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/io/StreamUtilsTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/io/StreamUtilsTest.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.InputStream; import java.io.PushbackInputStream; 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.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; class StreamUtilsTest { @Test void testMarkSupportedInputStream() throws Exception { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); assertEquals(10, is.available()); is = new PushbackInputStream(is); assertEquals(10, is.available()); assertFalse(is.markSupported()); is = StreamUtils.markSupportedInputStream(is); assertEquals(10, is.available()); is.mark(0); assertEquals((int) '0', is.read()); assertEquals((int) '1', is.read()); is.reset(); assertEquals((int) '0', is.read()); assertEquals((int) '1', is.read()); assertEquals((int) '2', is.read()); is.mark(0); assertEquals((int) '3', is.read()); assertEquals((int) '4', is.read()); assertEquals((int) '5', is.read()); is.reset(); assertEquals((int) '3', is.read()); assertEquals((int) '4', is.read()); is.mark(0); assertEquals((int) '5', is.read()); assertEquals((int) '6', is.read()); is.reset(); assertEquals((int) '5', is.read()); assertEquals((int) '6', is.read()); assertEquals((int) '7', is.read()); assertEquals((int) '8', is.read()); assertEquals((int) '9', is.read()); assertEquals(-1, is.read()); assertEquals(-1, is.read()); is.mark(0); assertEquals(-1, is.read()); assertEquals(-1, is.read()); is.reset(); assertEquals(-1, is.read()); assertEquals(-1, is.read()); is.close(); } @Test void testLimitedInputStream() throws Exception { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); assertThat(10, is(is.available())); is = StreamUtils.limitedInputStream(is, 2); assertThat(2, is(is.available())); assertThat(is.markSupported(), is(true)); is.mark(0); assertEquals((int) '0', is.read()); assertEquals((int) '1', is.read()); assertEquals(-1, is.read()); is.reset(); is.skip(1); assertEquals((int) '1', is.read()); is.reset(); is.skip(-1); assertEquals((int) '0', is.read()); is.reset(); byte[] bytes = new byte[2]; int read = is.read(bytes, 1, 1); assertThat(read, is(1)); is.reset(); StreamUtils.skipUnusedStream(is); assertEquals(-1, is.read()); is.close(); } @Test void testMarkInputSupport() { Assertions.assertThrows(IOException.class, () -> { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); try { is = StreamUtils.markSupportedInputStream(new PushbackInputStream(is), 1); is.mark(1); int read = is.read(); assertThat(read, is((int) '0')); is.skip(1); is.read(); } finally { if (is != null) { is.close(); } } }); } @Test void testSkipForOriginMarkSupportInput() throws IOException { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); InputStream newIs = StreamUtils.markSupportedInputStream(is, 1); assertThat(newIs, is(is)); is.close(); } @Test void testReadEmptyByteArray() { Assertions.assertThrows(NullPointerException.class, () -> { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); try { is = StreamUtils.limitedInputStream(is, 2); is.read(null, 0, 1); } finally { if (is != null) { is.close(); } } }); } @Test void testReadWithWrongOffset() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); try { is = StreamUtils.limitedInputStream(is, 2); is.read(new byte[1], -1, 1); } finally { if (is != null) { is.close(); } } }); } }
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/UnsafeStringWriterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringWriterTest.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 UnsafeStringWriterTest { @Test void testWrite() { UnsafeStringWriter writer = new UnsafeStringWriter(); writer.write("a"); writer.write("abc", 1, 1); writer.write(99); writer.flush(); writer.close(); assertThat(writer.toString(), is("abc")); } @Test void testNegativeSize() { Assertions.assertThrows(IllegalArgumentException.class, () -> new UnsafeStringWriter(-1)); } @Test void testAppend() { UnsafeStringWriter writer = new UnsafeStringWriter(); writer.append('a'); writer.append("abc", 1, 2); writer.append('c'); writer.flush(); writer.close(); assertThat(writer.toString(), is("abc")); } @Test void testAppendNull() { UnsafeStringWriter writer = new UnsafeStringWriter(); writer.append(null); writer.append(null, 0, 4); writer.flush(); writer.close(); assertThat(writer.toString(), is("nullnull")); } @Test void testWriteNull() throws IOException { UnsafeStringWriter writer = new UnsafeStringWriter(3); char[] chars = new char[2]; chars[0] = 'a'; chars[1] = 'b'; writer.write(chars); writer.write(chars, 0, 1); writer.flush(); writer.close(); assertThat(writer.toString(), is("aba")); } @Test void testWriteCharWithWrongLength() throws IOException { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { UnsafeStringWriter writer = new UnsafeStringWriter(); char[] chars = new char[0]; writer.write(chars, 0, 1); }); } @Test void testWriteCharWithWrongCombineLength() throws IOException { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { UnsafeStringWriter writer = new UnsafeStringWriter(); char[] chars = new char[1]; writer.write(chars, 1, 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/io/BytesTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/io/BytesTest.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.File; 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 BytesTest { private final byte[] b1 = "adpfioha;eoh;aldfadl;kfadslkfdajfio123431241235123davas;odvwe;lmzcoqpwoewqogineopwqihwqetup\n\tejqf;lajsfd中文字符0da0gsaofdsf==adfasdfs" .getBytes(); private final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. private byte[] bytes1 = {3, 12, 14, 41, 12, 2, 3, 12, 4, 67, 23}; private byte[] bytes2 = {3, 12, 14, 41, 12, 2, 3, 12, 4, 67}; @Test void testMain() { short s = (short) 0xabcd; assertThat(s, is(Bytes.bytes2short(Bytes.short2bytes(s)))); int i = 198284; assertThat(i, is(Bytes.bytes2int(Bytes.int2bytes(i)))); long l = 13841747174L; assertThat(l, is(Bytes.bytes2long(Bytes.long2bytes(l)))); float f = 1.3f; assertThat(f, is(Bytes.bytes2float(Bytes.float2bytes(f)))); double d = 11213.3; assertThat(d, is(Bytes.bytes2double(Bytes.double2bytes(d)))); assertThat(Bytes.int2bytes(i), is(int2bytes(i))); assertThat(Bytes.long2bytes(l), is(long2bytes(l))); String str = Bytes.bytes2base64("dubbo".getBytes()); byte[] bytes = Bytes.base642bytes(str, 0, str.length()); assertThat(bytes, is("dubbo".getBytes())); byte[] bytesWithC64 = Bytes.base642bytes(str, C64); assertThat(bytesWithC64, is(bytes)); byte[] emptyBytes = Bytes.base642bytes("dubbo", 0, 0); assertThat(emptyBytes, is("".getBytes())); assertThat(Bytes.base642bytes("dubbo", 0, 0, ""), is("".getBytes())); assertThat(Bytes.base642bytes("dubbo", 0, 0, new char[0]), is("".getBytes())); } @Test void testWrongBase64Code() { Assertions.assertThrows( IllegalArgumentException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 1, new char[] {'a'})); } @Test void testWrongOffSet() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), -1, 1)); } @Test void testLargeLength() { Assertions.assertThrows( IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 100000)); } @Test void testSmallLength() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, -1)); } @Test void testBase64S2b2sFailCaseLog() { String s1 = Bytes.bytes2base64(bytes1); byte[] out1 = Bytes.base642bytes(s1); assertThat(bytes1, is(out1)); String s2 = Bytes.bytes2base64(bytes2); byte[] out2 = Bytes.base642bytes(s2); assertThat(bytes2, is(out2)); } @Test void testBase642bCharArrCall() { byte[] stringCall = Bytes.base642bytes("ZHViYm8=", C64); byte[] charArrCall = Bytes.base642bytes("ZHViYm8=", C64.toCharArray()); assertThat(stringCall, is(charArrCall)); } @Test void testHex() { String str = Bytes.bytes2hex(b1); assertThat(b1, is(Bytes.hex2bytes(str))); } @Test void testMD5ForString() { byte[] md5 = Bytes.getMD5("dubbo"); assertThat(md5, is(Bytes.base642bytes("qk4bjCzJ3u2W/gEu8uB1Kg=="))); } @Test void testMD5ForFile() throws IOException { byte[] md5 = Bytes.getMD5(new File( getClass().getClassLoader().getResource("md5.testfile.txt").getFile())); assertThat(md5, is(Bytes.base642bytes("iNZ+5qHafVNPLJxHwLKJ3w=="))); } @Test void testZip() throws IOException { String s = "hello world"; byte[] zip = Bytes.zip(s.getBytes()); byte[] unzip = Bytes.unzip(zip); assertThat(unzip, is(s.getBytes())); } @Test void testBytes2HexWithWrongOffset() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2hex("hello".getBytes(), -1, 1)); } @Test void testBytes2HexWithWrongLength() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2hex("hello".getBytes(), 0, 6)); } private byte[] int2bytes(int x) { byte[] bb = new byte[4]; bb[0] = (byte) (x >> 24); bb[1] = (byte) (x >> 16); bb[2] = (byte) (x >> 8); bb[3] = (byte) (x >> 0); return bb; } private byte[] long2bytes(long x) { byte[] bb = new byte[8]; bb[0] = (byte) (x >> 56); bb[1] = (byte) (x >> 48); bb[2] = (byte) (x >> 40); bb[3] = (byte) (x >> 32); bb[4] = (byte) (x >> 24); bb[5] = (byte) (x >> 16); bb[6] = (byte) (x >> 8); bb[7] = (byte) (x >> 0); return bb; } }
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/function/StreamsTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/function/StreamsTest.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.function; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.apache.dubbo.common.function.Streams.filterList; import static org.apache.dubbo.common.function.Streams.filterSet; import static org.apache.dubbo.common.function.Streams.filterStream; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link Streams} Test * * @since 2.7.5 */ class StreamsTest { @Test void testFilterStream() { Stream<Integer> stream = filterStream(asList(1, 2, 3, 4, 5), i -> i % 2 == 0); assertEquals(asList(2, 4), stream.collect(toList())); } @Test void testFilterList() { List<Integer> list = filterList(asList(1, 2, 3, 4, 5), i -> i % 2 == 0); assertEquals(asList(2, 4), list); } @Test void testFilterSet() { Set<Integer> set = filterSet(asList(1, 2, 3, 4, 5), i -> i % 2 == 0); assertEquals(new LinkedHashSet<>(asList(2, 4)), 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/function/ThrowableActionTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableActionTest.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.function; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.function.ThrowableAction.execute; /** * {@link ThrowableAction} Test * * @since 2.7.5 */ class ThrowableActionTest { @Test void testExecute() { Assertions.assertThrows( RuntimeException.class, () -> execute(() -> { throw new Exception("Test"); }), "Test"); } }
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/function/ThrowableFunctionTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableFunctionTest.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.function; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.function.ThrowableConsumer.execute; import static org.junit.jupiter.api.Assertions.assertThrows; /** * {@link ThrowableFunction} Test * * @since 2.7.5 */ class ThrowableFunctionTest { @Test void testExecute() { assertThrows( RuntimeException.class, () -> execute("Hello,World", m -> { throw new Exception(m); }), "Hello,World"); } }
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/function/PredicatesTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/function/PredicatesTest.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.function; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.function.Predicates.alwaysFalse; import static org.apache.dubbo.common.function.Predicates.alwaysTrue; import static org.apache.dubbo.common.function.Predicates.and; import static org.apache.dubbo.common.function.Predicates.or; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link Predicates} Test * * @since 2.7.5 */ class PredicatesTest { @Test void testAlwaysTrue() { assertTrue(alwaysTrue().test(null)); } @Test void testAlwaysFalse() { assertFalse(alwaysFalse().test(null)); } @Test void testAnd() { assertTrue(and(alwaysTrue(), alwaysTrue(), alwaysTrue()).test(null)); assertFalse(and(alwaysFalse(), alwaysFalse(), alwaysFalse()).test(null)); assertFalse(and(alwaysTrue(), alwaysFalse(), alwaysFalse()).test(null)); assertFalse(and(alwaysTrue(), alwaysTrue(), alwaysFalse()).test(null)); } @Test void testOr() { assertTrue(or(alwaysTrue(), alwaysTrue(), alwaysTrue()).test(null)); assertTrue(or(alwaysTrue(), alwaysTrue(), alwaysFalse()).test(null)); assertTrue(or(alwaysTrue(), alwaysFalse(), alwaysFalse()).test(null)); assertFalse(or(alwaysFalse(), alwaysFalse(), alwaysFalse()).test(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/function/ThrowableConsumerTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableConsumerTest.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.function; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.function.ThrowableConsumer.execute; import static org.junit.jupiter.api.Assertions.assertThrows; /** * {@link ThrowableConsumer} Test * * @since 2.7.5 */ class ThrowableConsumerTest { @Test void testExecute() { assertThrows( RuntimeException.class, () -> execute("Hello,World", m -> { throw new Exception(m); }), "Hello,World"); } }
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/beanutil/Bean.java
dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.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.beanutil; import org.apache.dubbo.rpc.model.person.FullAddress; import org.apache.dubbo.rpc.model.person.PersonStatus; import org.apache.dubbo.rpc.model.person.Phone; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.Map; public class Bean implements Serializable { private Class<?> type; private PersonStatus status; private Date date; private Phone[] array; private Collection<Phone> collection; private Map<String, FullAddress> addresses; public Class<?> getType() { return type; } public void setType(Class<?> type) { this.type = type; } public PersonStatus getStatus() { return status; } public void setStatus(PersonStatus status) { this.status = status; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Phone[] getArray() { return array; } public void setArray(Phone[] array) { this.array = array; } public Collection<Phone> getCollection() { return collection; } public void setCollection(Collection<Phone> collection) { this.collection = collection; } public Map<String, FullAddress> getAddresses() { return addresses; } public void setAddresses(Map<String, FullAddress> addresses) { this.addresses = addresses; } }
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/beanutil/JavaBeanSerializeUtilTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.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.beanutil; import org.apache.dubbo.rpc.model.person.BigPerson; import org.apache.dubbo.rpc.model.person.FullAddress; import org.apache.dubbo.rpc.model.person.PersonInfo; import org.apache.dubbo.rpc.model.person.PersonStatus; import org.apache.dubbo.rpc.model.person.Phone; import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class JavaBeanSerializeUtilTest { @Test void testSerialize_Primitive() { JavaBeanDescriptor descriptor; descriptor = JavaBeanSerializeUtil.serialize(Integer.MAX_VALUE); Assertions.assertTrue(descriptor.isPrimitiveType()); Assertions.assertEquals(Integer.MAX_VALUE, descriptor.getPrimitiveProperty()); Date now = new Date(); descriptor = JavaBeanSerializeUtil.serialize(now); Assertions.assertTrue(descriptor.isPrimitiveType()); Assertions.assertEquals(now, descriptor.getPrimitiveProperty()); } @Test void testSerialize_Primitive_NUll() { JavaBeanDescriptor descriptor; descriptor = JavaBeanSerializeUtil.serialize(null); Assertions.assertNull(descriptor); } @Test void testDeserialize_Primitive() { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setPrimitiveProperty(Long.MAX_VALUE); Assertions.assertEquals(Long.MAX_VALUE, JavaBeanSerializeUtil.deserialize(descriptor)); BigDecimal decimal = BigDecimal.TEN; Assertions.assertEquals(Long.MAX_VALUE, descriptor.setPrimitiveProperty(decimal)); Assertions.assertEquals(decimal, JavaBeanSerializeUtil.deserialize(descriptor)); String string = UUID.randomUUID().toString(); Assertions.assertEquals(decimal, descriptor.setPrimitiveProperty(string)); Assertions.assertEquals(string, JavaBeanSerializeUtil.deserialize(descriptor)); } @Test void testDeserialize_Primitive0() { Assertions.assertThrows(IllegalArgumentException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_BEAN + 1); }); } @Test void testDeserialize_Null() { Assertions.assertThrows(IllegalArgumentException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(null, JavaBeanDescriptor.TYPE_BEAN); }); } @Test void testDeserialize_containsProperty() { Assertions.assertThrows(IllegalArgumentException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.containsProperty(null); }); } @Test void testSetEnumNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); }); JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_ENUM); String oldValueOrigin = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValueOrigin); String oldValueNext = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(oldValueNext, descriptor.getEnumPropertyName()); } @Test void testGetEnumNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.getEnumPropertyName(); }); } @Test void testSetClassNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); }); JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_CLASS); String oldValue1 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValue1); String oldValue2 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(oldValue2, descriptor.getClassNameProperty()); } @Test void testGetClassNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.getClassNameProperty(); }); } @Test void testSetPrimitiveProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_BEAN); descriptor.setPrimitiveProperty(JavaBeanDescriptor.class.getName()); }); } @Test void testGetPrimitiveProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_BEAN); descriptor.getPrimitiveProperty(); }); } @Test void testDeserialize_get_and_set() { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_BEAN); descriptor.setType(JavaBeanDescriptor.TYPE_PRIMITIVE); Assertions.assertEquals(descriptor.getType(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setClassName(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(JavaBeanDescriptor.class.getName(), descriptor.getClassName()); } @Test void testSerialize_Array() { int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(array, JavaBeanAccessor.METHOD); Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(int.class.getName(), descriptor.getClassName()); for (int i = 0; i < array.length; i++) { Assertions.assertEquals(array[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } Integer[] integers = new Integer[] {1, 2, 3, 4, null, null, null}; descriptor = JavaBeanSerializeUtil.serialize(integers, JavaBeanAccessor.METHOD); Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(Integer.class.getName(), descriptor.getClassName()); Assertions.assertEquals(integers.length, descriptor.propertySize()); for (int i = 0; i < integers.length; i++) { if (integers[i] == null) { Assertions.assertSame(integers[i], descriptor.getProperty(i)); } else { Assertions.assertEquals( integers[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } } int[][] second = {{1, 2}, {3, 4}}; descriptor = JavaBeanSerializeUtil.serialize(second, JavaBeanAccessor.METHOD); Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(int[].class.getName(), descriptor.getClassName()); for (int i = 0; i < second.length; i++) { for (int j = 0; j < second[i].length; j++) { JavaBeanDescriptor item = (((JavaBeanDescriptor) descriptor.getProperty(i))); Assertions.assertTrue(item.isArrayType()); Assertions.assertEquals(int.class.getName(), item.getClassName()); Assertions.assertEquals( second[i][j], ((JavaBeanDescriptor) item.getProperty(j)).getPrimitiveProperty()); } } BigPerson[] persons = new BigPerson[] {createBigPerson(), createBigPerson()}; descriptor = JavaBeanSerializeUtil.serialize(persons); Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(BigPerson.class.getName(), descriptor.getClassName()); for (int i = 0; i < persons.length; i++) { assertEqualsBigPerson(persons[i], descriptor.getProperty(i)); } } @Test void testConstructorArg() { Assertions.assertFalse((boolean) JavaBeanSerializeUtil.getConstructorArg(boolean.class)); Assertions.assertFalse((boolean) JavaBeanSerializeUtil.getConstructorArg(Boolean.class)); Assertions.assertEquals((byte) 0, JavaBeanSerializeUtil.getConstructorArg(byte.class)); Assertions.assertEquals((byte) 0, JavaBeanSerializeUtil.getConstructorArg(Byte.class)); Assertions.assertEquals((short) 0, JavaBeanSerializeUtil.getConstructorArg(short.class)); Assertions.assertEquals((short) 0, JavaBeanSerializeUtil.getConstructorArg(Short.class)); Assertions.assertEquals(0, JavaBeanSerializeUtil.getConstructorArg(int.class)); Assertions.assertEquals(0, JavaBeanSerializeUtil.getConstructorArg(Integer.class)); Assertions.assertEquals((long) 0, JavaBeanSerializeUtil.getConstructorArg(long.class)); Assertions.assertEquals((long) 0, JavaBeanSerializeUtil.getConstructorArg(Long.class)); Assertions.assertEquals((float) 0, JavaBeanSerializeUtil.getConstructorArg(float.class)); Assertions.assertEquals((float) 0, JavaBeanSerializeUtil.getConstructorArg(Float.class)); Assertions.assertEquals((double) 0, JavaBeanSerializeUtil.getConstructorArg(double.class)); Assertions.assertEquals((double) 0, JavaBeanSerializeUtil.getConstructorArg(Double.class)); Assertions.assertEquals((char) 0, JavaBeanSerializeUtil.getConstructorArg(char.class)); Assertions.assertEquals(new Character((char) 0), JavaBeanSerializeUtil.getConstructorArg(Character.class)); Assertions.assertNull(JavaBeanSerializeUtil.getConstructorArg(JavaBeanSerializeUtil.class)); } @Test void testDeserialize_Array() { final int len = 10; JavaBeanDescriptor descriptor = new JavaBeanDescriptor(int.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); for (int i = 0; i < len; i++) { descriptor.setProperty(i, i); } Object obj = JavaBeanSerializeUtil.deserialize(descriptor); Assertions.assertTrue(obj.getClass().isArray()); Assertions.assertSame(int.class, obj.getClass().getComponentType()); for (int i = 0; i < len; i++) { Assertions.assertEquals(i, Array.get(obj, i)); } descriptor = new JavaBeanDescriptor(int[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY); for (int i = 0; i < len; i++) { JavaBeanDescriptor innerItem = new JavaBeanDescriptor(int.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); for (int j = 0; j < len; j++) { innerItem.setProperty(j, j); } descriptor.setProperty(i, innerItem); } obj = JavaBeanSerializeUtil.deserialize(descriptor); Assertions.assertTrue(obj.getClass().isArray()); Assertions.assertEquals(int[].class, obj.getClass().getComponentType()); for (int i = 0; i < len; i++) { Object innerItem = Array.get(obj, i); Assertions.assertTrue(innerItem.getClass().isArray()); Assertions.assertEquals(int.class, innerItem.getClass().getComponentType()); for (int j = 0; j < len; j++) { Assertions.assertEquals(j, Array.get(innerItem, j)); } } descriptor = new JavaBeanDescriptor(BigPerson[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY); JavaBeanDescriptor innerDescriptor = new JavaBeanDescriptor(BigPerson.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); innerDescriptor.setProperty(0, JavaBeanSerializeUtil.serialize(createBigPerson(), JavaBeanAccessor.METHOD)); descriptor.setProperty(0, innerDescriptor); obj = JavaBeanSerializeUtil.deserialize(descriptor); Assertions.assertTrue(obj.getClass().isArray()); Assertions.assertEquals(BigPerson[].class, obj.getClass().getComponentType()); Assertions.assertEquals(1, Array.getLength(obj)); obj = Array.get(obj, 0); Assertions.assertTrue(obj.getClass().isArray()); Assertions.assertEquals(BigPerson.class, obj.getClass().getComponentType()); Assertions.assertEquals(1, Array.getLength(obj)); Assertions.assertEquals(createBigPerson(), Array.get(obj, 0)); } @Test void test_Circular_Reference() { Parent parent = new Parent(); parent.setAge(Integer.MAX_VALUE); parent.setEmail("a@b"); parent.setName("zhangsan"); Child child = new Child(); child.setAge(100); child.setName("lisi"); child.setParent(parent); parent.setChild(child); JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(parent, JavaBeanAccessor.METHOD); Assertions.assertTrue(descriptor.isBeanType()); assertEqualsPrimitive(parent.getAge(), descriptor.getProperty("age")); assertEqualsPrimitive(parent.getName(), descriptor.getProperty("name")); assertEqualsPrimitive(parent.getEmail(), descriptor.getProperty("email")); JavaBeanDescriptor childDescriptor = (JavaBeanDescriptor) descriptor.getProperty("child"); Assertions.assertSame(descriptor, childDescriptor.getProperty("parent")); assertEqualsPrimitive(child.getName(), childDescriptor.getProperty("name")); assertEqualsPrimitive(child.getAge(), childDescriptor.getProperty("age")); } public static class Parent { public String gender; public String email; String name; int age; Child child; private String securityEmail; public static Parent getNewParent() { return new Parent(); } public String getEmail() { return this.securityEmail; } public void setEmail(String email) { this.securityEmail = email; } 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 Child getChild() { return child; } public void setChild(Child child) { this.child = child; } } public static class Child { public String gender; public int age; String toy; Parent parent; private String name; 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 String getToy() { return toy; } public void setToy(String toy) { this.toy = toy; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } } @Test void testBeanSerialize() { Bean bean = new Bean(); bean.setDate(new Date()); bean.setStatus(PersonStatus.ENABLED); bean.setType(Bean.class); bean.setArray(new Phone[] {}); Collection<Phone> collection = new ArrayList<Phone>(); bean.setCollection(collection); Phone phone = new Phone(); collection.add(phone); Map<String, FullAddress> map = new HashMap<String, FullAddress>(); FullAddress address = new FullAddress(); map.put("first", address); bean.setAddresses(map); JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(bean, JavaBeanAccessor.METHOD); Assertions.assertTrue(descriptor.isBeanType()); assertEqualsPrimitive(bean.getDate(), descriptor.getProperty("date")); assertEqualsEnum(bean.getStatus(), descriptor.getProperty("status")); Assertions.assertTrue(((JavaBeanDescriptor) descriptor.getProperty("type")).isClassType()); Assertions.assertEquals( Bean.class.getName(), ((JavaBeanDescriptor) descriptor.getProperty("type")).getClassNameProperty()); Assertions.assertTrue(((JavaBeanDescriptor) descriptor.getProperty("array")).isArrayType()); Assertions.assertEquals(0, ((JavaBeanDescriptor) descriptor.getProperty("array")).propertySize()); JavaBeanDescriptor property = (JavaBeanDescriptor) descriptor.getProperty("collection"); Assertions.assertTrue(property.isCollectionType()); Assertions.assertEquals(1, property.propertySize()); property = (JavaBeanDescriptor) property.getProperty(0); Assertions.assertTrue(property.isBeanType()); Assertions.assertEquals(Phone.class.getName(), property.getClassName()); Assertions.assertEquals(0, property.propertySize()); property = (JavaBeanDescriptor) descriptor.getProperty("addresses"); Assertions.assertTrue(property.isMapType()); Assertions.assertEquals(bean.getAddresses().getClass().getName(), property.getClassName()); Assertions.assertEquals(1, property.propertySize()); Map.Entry<Object, Object> entry = property.iterator().next(); Assertions.assertTrue(((JavaBeanDescriptor) entry.getKey()).isPrimitiveType()); Assertions.assertEquals("first", ((JavaBeanDescriptor) entry.getKey()).getPrimitiveProperty()); Assertions.assertTrue(((JavaBeanDescriptor) entry.getValue()).isBeanType()); Assertions.assertEquals(FullAddress.class.getName(), ((JavaBeanDescriptor) entry.getValue()).getClassName()); Assertions.assertEquals(0, ((JavaBeanDescriptor) entry.getValue()).propertySize()); } @Test void testDeserializeBean() { Bean bean = new Bean(); bean.setDate(new Date()); bean.setStatus(PersonStatus.ENABLED); bean.setType(Bean.class); bean.setArray(new Phone[] {}); Collection<Phone> collection = new ArrayList<Phone>(); bean.setCollection(collection); Phone phone = new Phone(); collection.add(phone); Map<String, FullAddress> map = new HashMap<String, FullAddress>(); FullAddress address = new FullAddress(); map.put("first", address); bean.setAddresses(map); JavaBeanDescriptor beanDescriptor = JavaBeanSerializeUtil.serialize(bean, JavaBeanAccessor.METHOD); Object deser = JavaBeanSerializeUtil.deserialize(beanDescriptor); Assertions.assertTrue(deser instanceof Bean); Bean deserBean = (Bean) deser; Assertions.assertEquals(bean.getDate(), deserBean.getDate()); Assertions.assertEquals(bean.getStatus(), deserBean.getStatus()); Assertions.assertEquals(bean.getType(), deserBean.getType()); Assertions.assertEquals( bean.getCollection().size(), deserBean.getCollection().size()); Assertions.assertEquals( bean.getCollection().iterator().next().getClass(), deserBean.getCollection().iterator().next().getClass()); Assertions.assertEquals( bean.getAddresses().size(), deserBean.getAddresses().size()); Assertions.assertEquals( bean.getAddresses().entrySet().iterator().next().getKey(), deserBean.getAddresses().entrySet().iterator().next().getKey()); Assertions.assertEquals( bean.getAddresses().entrySet().iterator().next().getValue().getClass(), deserBean.getAddresses().entrySet().iterator().next().getValue().getClass()); } @Test @SuppressWarnings("unchecked") public void testSerializeJavaBeanDescriptor() { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(); JavaBeanDescriptor result = JavaBeanSerializeUtil.serialize(descriptor); Assertions.assertSame(descriptor, result); Map map = new HashMap(); map.put("first", descriptor); result = JavaBeanSerializeUtil.serialize(map); Assertions.assertTrue(result.isMapType()); Assertions.assertEquals(HashMap.class.getName(), result.getClassName()); Assertions.assertEquals(map.size(), result.propertySize()); Object object = result.iterator().next().getValue(); Assertions.assertTrue(object instanceof JavaBeanDescriptor); JavaBeanDescriptor actual = (JavaBeanDescriptor) object; Assertions.assertEquals(map.get("first"), actual); } static void assertEqualsEnum(Enum<?> expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assertions.assertTrue(descriptor.isEnumType()); Assertions.assertEquals(expected.getClass().getName(), descriptor.getClassName()); Assertions.assertEquals(expected.name(), descriptor.getEnumPropertyName()); } static void assertEqualsPrimitive(Object expected, Object obj) { if (expected == null) { return; } JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assertions.assertTrue(descriptor.isPrimitiveType()); Assertions.assertEquals(expected, descriptor.getPrimitiveProperty()); } static void assertEqualsBigPerson(BigPerson person, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assertions.assertTrue(descriptor.isBeanType()); assertEqualsPrimitive(person.getPersonId(), descriptor.getProperty("personId")); assertEqualsPrimitive(person.getLoginName(), descriptor.getProperty("loginName")); assertEqualsEnum(person.getStatus(), descriptor.getProperty("status")); assertEqualsPrimitive(person.getEmail(), descriptor.getProperty("email")); assertEqualsPrimitive(person.getPersonName(), descriptor.getProperty("personName")); JavaBeanDescriptor infoProfile = (JavaBeanDescriptor) descriptor.getProperty("infoProfile"); Assertions.assertTrue(infoProfile.isBeanType()); JavaBeanDescriptor phones = (JavaBeanDescriptor) infoProfile.getProperty("phones"); Assertions.assertTrue(phones.isCollectionType()); assertEqualsPhone(person.getInfoProfile().getPhones().get(0), phones.getProperty(0)); assertEqualsPhone(person.getInfoProfile().getPhones().get(1), phones.getProperty(1)); assertEqualsPhone(person.getInfoProfile().getFax(), infoProfile.getProperty("fax")); assertEqualsFullAddress(person.getInfoProfile().getFullAddress(), infoProfile.getProperty("fullAddress")); assertEqualsPrimitive(person.getInfoProfile().getMobileNo(), infoProfile.getProperty("mobileNo")); assertEqualsPrimitive(person.getInfoProfile().getName(), infoProfile.getProperty("name")); assertEqualsPrimitive(person.getInfoProfile().getDepartment(), infoProfile.getProperty("department")); assertEqualsPrimitive(person.getInfoProfile().getJobTitle(), infoProfile.getProperty("jobTitle")); assertEqualsPrimitive(person.getInfoProfile().getHomepageUrl(), infoProfile.getProperty("homepageUrl")); assertEqualsPrimitive(person.getInfoProfile().isFemale(), infoProfile.getProperty("female")); assertEqualsPrimitive(person.getInfoProfile().isMale(), infoProfile.getProperty("male")); } static void assertEqualsPhone(Phone expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assertions.assertTrue(descriptor.isBeanType()); if (expected.getArea() != null) { assertEqualsPrimitive(expected.getArea(), descriptor.getProperty("area")); } if (expected.getCountry() != null) { assertEqualsPrimitive(expected.getCountry(), descriptor.getProperty("country")); } if (expected.getExtensionNumber() != null) { assertEqualsPrimitive(expected.getExtensionNumber(), descriptor.getProperty("extensionNumber")); } if (expected.getNumber() != null) { assertEqualsPrimitive(expected.getNumber(), descriptor.getProperty("number")); } } static void assertEqualsFullAddress(FullAddress expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assertions.assertTrue(descriptor.isBeanType()); if (expected.getCityId() != null) { assertEqualsPrimitive(expected.getCityId(), descriptor.getProperty("cityId")); } if (expected.getCityName() != null) { assertEqualsPrimitive(expected.getCityName(), descriptor.getProperty("cityName")); } if (expected.getCountryId() != null) { assertEqualsPrimitive(expected.getCountryId(), descriptor.getProperty("countryId")); } if (expected.getCountryName() != null) { assertEqualsPrimitive(expected.getCountryName(), descriptor.getProperty("countryName")); } if (expected.getProvinceName() != null) { assertEqualsPrimitive(expected.getProvinceName(), descriptor.getProperty("provinceName")); } if (expected.getStreetAddress() != null) { assertEqualsPrimitive(expected.getStreetAddress(), descriptor.getProperty("streetAddress")); } if (expected.getZipCode() != null) { assertEqualsPrimitive(expected.getZipCode(), descriptor.getProperty("zipCode")); } } static BigPerson createBigPerson() { BigPerson bigPerson; bigPerson = new BigPerson(); bigPerson.setPersonId("superman111"); bigPerson.setLoginName("superman"); bigPerson.setStatus(PersonStatus.ENABLED); bigPerson.setEmail("sm@1.com"); bigPerson.setPersonName("pname"); ArrayList<Phone> phones = new ArrayList<Phone>(); Phone phone1 = new Phone("86", "0571", "87654321", "001"); Phone phone2 = new Phone("86", "0571", "87654322", "002"); phones.add(phone1); phones.add(phone2); PersonInfo pi = new PersonInfo(); pi.setPhones(phones); Phone fax = new Phone("86", "0571", "87654321", null); pi.setFax(fax); FullAddress addr = new FullAddress("CN", "zj", "3480", "wensanlu", "315000"); pi.setFullAddress(addr); pi.setMobileNo("13584652131"); pi.setMale(true); pi.setDepartment("b2b"); pi.setHomepageUrl("www.capcom.com"); pi.setJobTitle("qa"); pi.setName("superman"); bigPerson.setInfoProfile(pi); return bigPerson; } }
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/beanutil/JavaBeanAccessorTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanAccessorTest.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.beanutil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class JavaBeanAccessorTest { @Test void testIsAccessByMethod() { Assertions.assertTrue(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.METHOD)); Assertions.assertTrue(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.ALL)); Assertions.assertFalse(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.FIELD)); } @Test void testIsAccessByField() { Assertions.assertTrue(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.FIELD)); Assertions.assertTrue(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.ALL)); Assertions.assertFalse(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.METHOD)); } }
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/constants/CommonConstantsTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/constants/CommonConstantsTest.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.constants; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR; import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH; import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link CommonConstants} Test-Cases * * @since 2.7.8 */ class CommonConstantsTest { @Test void test() { assertEquals(',', COMMA_SEPARATOR_CHAR); assertEquals("composite", COMPOSITE_METADATA_STORAGE_TYPE); assertEquals("service-name-mapping.properties-path", SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY); assertEquals("META-INF/dubbo/service-name-mapping.properties", DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH); } }
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/convert/StringToStringConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToStringConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToStringConverter} Test * * @since 2.7.6 */ class StringToStringConverterTest { private StringToStringConverter converter; @BeforeEach public void init() { converter = (StringToStringConverter) getExtensionLoader(Converter.class).getExtension("string-to-string"); } @Test void testAccept() { assertTrue(converter.accept(String.class, String.class)); } @Test void testConvert() { assertEquals("1", converter.convert("1")); assertNull(converter.convert(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/convert/StringToDurationConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDurationConverterTest.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.convert; import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToDurationConverter} Test * * @since 3.2.3 */ class StringToDurationConverterTest { private StringToDurationConverter converter; @BeforeEach public void init() { converter = (StringToDurationConverter) getExtensionLoader(Converter.class).getExtension("string-to-duration"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Duration.class)); } @Test void testConvert() { assertEquals(Duration.ofMillis(1000), converter.convert("1000ms")); assertEquals(Duration.ofSeconds(1), converter.convert("1s")); assertEquals(Duration.ofMinutes(1), converter.convert("1m")); assertEquals(Duration.ofHours(1), converter.convert("1h")); assertEquals(Duration.ofDays(1), converter.convert("1d")); assertNull(converter.convert(null)); assertThrows(IllegalArgumentException.class, () -> { converter.convert("ttt"); }); } }
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/convert/StringToCharacterConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharacterConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToCharacterConverter} Test * * @since 2.7.6 */ class StringToCharacterConverterTest { private StringToCharacterConverter converter; @BeforeEach public void init() { converter = (StringToCharacterConverter) getExtensionLoader(Converter.class).getExtension("string-to-character"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Character.class)); } @Test void testConvert() { assertEquals('t', converter.convert("t")); assertNull(converter.convert(null)); assertThrows(IllegalArgumentException.class, () -> { converter.convert("ttt"); }); } }
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/convert/StringToIntegerConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToIntegerConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToIntegerConverter} Test * * @since 2.7.6 */ class StringToIntegerConverterTest { private StringToIntegerConverter converter; @BeforeEach public void init() { converter = (StringToIntegerConverter) getExtensionLoader(Converter.class).getExtension("string-to-integer"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Integer.class)); } @Test void testConvert() { assertEquals(Integer.valueOf("1"), converter.convert("1")); assertNull(converter.convert(null)); assertThrows(NumberFormatException.class, () -> { converter.convert("ttt"); }); } }
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/convert/ConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/ConverterTest.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.convert; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; /** * {@link Converter} Test-Cases * * @since 2.7.8 */ class ConverterTest { private ConverterUtil converterUtil; @BeforeEach public void setup() { converterUtil = FrameworkModel.defaultModel().getBeanFactory().getBean(ConverterUtil.class); } @AfterEach public void tearDown() { FrameworkModel.destroyAll(); } @Test void testGetConverter() { getExtensionLoader(Converter.class).getSupportedExtensionInstances().forEach(converter -> { assertSame(converter, converterUtil.getConverter(converter.getSourceType(), converter.getTargetType())); }); } @Test void testConvertIfPossible() { assertEquals(Integer.valueOf(2), converterUtil.convertIfPossible("2", Integer.class)); assertEquals(Boolean.FALSE, converterUtil.convertIfPossible("false", Boolean.class)); assertEquals(Double.valueOf(1), converterUtil.convertIfPossible("1", Double.class)); } 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/convert/StringToBooleanConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToBooleanConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToBooleanConverter} Test * * @since 2.7.6 */ class StringToBooleanConverterTest { private StringToBooleanConverter converter; @BeforeEach public void init() { converter = (StringToBooleanConverter) getExtensionLoader(Converter.class).getExtension("string-to-boolean"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Boolean.class)); } @Test void testConvert() { assertTrue(converter.convert("true")); assertTrue(converter.convert("true")); assertTrue(converter.convert("True")); assertFalse(converter.convert("a")); assertNull(converter.convert("")); assertNull(converter.convert(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/convert/StringToCharArrayConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharArrayConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToCharArrayConverter} Test * * @since 2.7.6 */ class StringToCharArrayConverterTest { private StringToCharArrayConverter converter; @BeforeEach public void init() { converter = (StringToCharArrayConverter) getExtensionLoader(Converter.class).getExtension("string-to-char-array"); } @Test void testAccept() { assertTrue(converter.accept(String.class, char[].class)); } @Test void testConvert() { assertArrayEquals(new char[] {'1', '2', '3'}, converter.convert("123")); assertNull(converter.convert(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/convert/StringToLongConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToLongConverterTest.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.convert; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.BeforeEach; 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToLongConverter} Test * * @since 2.7.6 */ class StringToLongConverterTest { private StringToLongConverter converter; @BeforeEach public void init() { converter = (StringToLongConverter) getExtensionLoader(Converter.class).getExtension("string-to-long"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Long.class)); } @Test void testConvert() { assertEquals(Long.valueOf("1"), converter.convert("1")); assertNull(converter.convert(null)); assertThrows(NumberFormatException.class, () -> { converter.convert("ttt"); }); } 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/convert/StringToShortConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToShortConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToShortConverter} Test * * @since 2.7.6 */ class StringToShortConverterTest { private StringToShortConverter converter; @BeforeEach public void init() { converter = (StringToShortConverter) getExtensionLoader(Converter.class).getExtension("string-to-short"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Short.class)); } @Test void testConvert() { assertEquals(Short.valueOf("1"), converter.convert("1")); assertNull(converter.convert(null)); assertThrows(NumberFormatException.class, () -> { converter.convert("ttt"); }); } }
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/convert/StringToOptionalConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.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.convert; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToOptionalConverter} Test * * @since 2.7.6 */ class StringToOptionalConverterTest { private StringToOptionalConverter converter; @BeforeEach public void init() { converter = (StringToOptionalConverter) getExtensionLoader(Converter.class).getExtension("string-to-optional"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Optional.class)); } @Test void testConvert() { assertEquals(Optional.of("1"), converter.convert("1")); assertEquals(Optional.empty(), converter.convert(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/convert/StringToFloatConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToFloatConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToFloatConverter} Test * * @since 2.7.6 */ class StringToFloatConverterTest { private StringToFloatConverter converter; @BeforeEach public void init() { converter = (StringToFloatConverter) getExtensionLoader(Converter.class).getExtension("string-to-float"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Float.class)); } @Test void testConvert() { assertEquals(Float.valueOf("1.0"), converter.convert("1.0")); assertNull(converter.convert(null)); assertThrows(NumberFormatException.class, () -> { converter.convert("ttt"); }); } }
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/convert/StringToDoubleConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDoubleConverterTest.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.convert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StringToDoubleConverter} Test * * @since 2.7.6 */ class StringToDoubleConverterTest { private StringToDoubleConverter converter; @BeforeEach public void init() { converter = (StringToDoubleConverter) getExtensionLoader(Converter.class).getExtension("string-to-double"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Double.class)); } @Test void testConvert() { assertEquals(Double.valueOf("1.0"), converter.convert("1.0")); assertNull(converter.convert(null)); assertThrows(NumberFormatException.class, () -> { converter.convert("ttt"); }); } }
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/convert/multiple/StringToTransferQueueConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToTransferQueueConverter} Test * * @since 2.7.6 */ class StringToTransferQueueConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-transfer-queue"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertFalse(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertFalse(converter.accept(String.class, NavigableSet.class)); assertFalse(converter.accept(String.class, TreeSet.class)); assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertFalse(converter.accept(String.class, BlockingDeque.class)); assertTrue(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { TransferQueue values = new LinkedTransferQueue(asList(1, 2, 3)); TransferQueue result = (TransferQueue) converter.convert("1,2,3", List.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values.clear(); values.addAll(asList("123")); result = (TransferQueue) converter.convert("123", NavigableSet.class, String.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { assertEquals(Integer.MAX_VALUE - 4, converter.getPriority()); } }
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/convert/multiple/StringToListConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToListConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToListConverter} Test * * @since 2.7.6 */ class StringToListConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-list"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertTrue(converter.accept(String.class, List.class)); assertTrue(converter.accept(String.class, AbstractList.class)); assertTrue(converter.accept(String.class, LinkedList.class)); assertTrue(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertFalse(converter.accept(String.class, NavigableSet.class)); assertFalse(converter.accept(String.class, TreeSet.class)); assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertFalse(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { List values = asList(1, 2, 3); List result = (List<Integer>) converter.convert("1,2,3", List.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values = asList("123"); result = (List<String>) converter.convert("123", List.class, String.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { // Since JDK21, add SequencedCollection assertEquals( Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 3 : 2), converter.getPriority()); } }
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/convert/multiple/StringToQueueConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; 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; /** * {@link StringToQueueConverter} Test * * @since 2.7.6 */ class StringToQueueConverterTest { private StringToQueueConverter converter; @BeforeEach public void init() { converter = new StringToQueueConverter(FrameworkModel.defaultModel()); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertTrue(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertTrue(converter.accept(String.class, Queue.class)); assertTrue(converter.accept(String.class, BlockingQueue.class)); assertTrue(converter.accept(String.class, TransferQueue.class)); assertTrue(converter.accept(String.class, Deque.class)); assertTrue(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertFalse(converter.accept(String.class, NavigableSet.class)); assertFalse(converter.accept(String.class, TreeSet.class)); assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { Queue values = new ArrayDeque(asList(1.0, 2.0, 3.0)); Queue result = (Queue<Double>) converter.convert("1.0,2.0,3.0", Queue.class, Double.class); assertTrue(CollectionUtils.equals(values, result)); values.clear(); values.add(123); result = (Queue) converter.convert("123", Queue.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { assertEquals(Integer.MAX_VALUE - 2, converter.getPriority()); } }
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/convert/multiple/StringToSortedSetConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToSortedSetConverter} Test * * @since 2.7.6 */ class StringToSortedSetConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-sorted-set"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertFalse(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, Set.class)); assertTrue(converter.accept(String.class, SortedSet.class)); assertTrue(converter.accept(String.class, NavigableSet.class)); assertTrue(converter.accept(String.class, TreeSet.class)); assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertFalse(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { Set values = new TreeSet(asList(1, 2, 3)); SortedSet result = (SortedSet) converter.convert("1,2,3", List.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values = new TreeSet(asList("123")); result = (SortedSet) converter.convert("123", NavigableSet.class, String.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { // Since JDK21, add SequencedCollection, SequencedSet assertEquals( Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 5 : 3), converter.getPriority()); } }
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/convert/multiple/StringToDequeConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToDequeConverter} Test * * @since 2.7.6 */ class StringToDequeConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-deque"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertTrue(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, TransferQueue.class)); assertTrue(converter.accept(String.class, Deque.class)); assertTrue(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertFalse(converter.accept(String.class, NavigableSet.class)); assertFalse(converter.accept(String.class, TreeSet.class)); assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { Deque values = new ArrayDeque(asList(1, 2, 3)); Deque result = (Deque) converter.convert("1,2,3", Deque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values = new ArrayDeque(asList("123")); result = (Deque) converter.convert("123", Deque.class, String.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { // Since JDK21, add SequencedCollection assertEquals( Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 4 : 3), converter.getPriority()); } }
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/convert/multiple/StringToBlockingDequeConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToBlockingDequeConverter} Test * * @see BlockingDeque * @since 2.7.6 */ class StringToBlockingDequeConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-blocking-deque"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertFalse(converter.accept(String.class, NavigableSet.class)); assertFalse(converter.accept(String.class, TreeSet.class)); assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertTrue(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() throws NoSuchFieldException { BlockingQueue<Integer> values = new LinkedBlockingDeque(asList(1, 2, 3)); BlockingDeque<Integer> result = (BlockingDeque<Integer>) converter.convert("1,2,3", BlockingDeque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values = new LinkedBlockingDeque(asList(123)); result = (BlockingDeque<Integer>) converter.convert("123", BlockingDeque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, null)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { // Since JDK21, add SequencedCollection assertEquals( Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 5), converter.getPriority()); } }
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/convert/multiple/StringToCollectionConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverterTest.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.convert.multiple; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToCollectionConverter} Test * * @since 2.7.6 */ class StringToCollectionConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-collection"); } @Test void testAccept() { assertTrue(converter.accept(String.class, Collection.class)); assertTrue(converter.accept(String.class, List.class)); assertTrue(converter.accept(String.class, AbstractList.class)); assertTrue(converter.accept(String.class, ArrayList.class)); assertTrue(converter.accept(String.class, LinkedList.class)); assertTrue(converter.accept(String.class, Set.class)); assertTrue(converter.accept(String.class, SortedSet.class)); assertTrue(converter.accept(String.class, NavigableSet.class)); assertTrue(converter.accept(String.class, TreeSet.class)); assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class)); assertTrue(converter.accept(String.class, Queue.class)); assertTrue(converter.accept(String.class, BlockingQueue.class)); assertTrue(converter.accept(String.class, TransferQueue.class)); assertTrue(converter.accept(String.class, Deque.class)); assertTrue(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { List values = asList(1L, 2L, 3L); Collection result = (Collection<Long>) converter.convert("1,2,3", Collection.class, Long.class); assertEquals(values, result); values = asList(123); result = (Collection<Integer>) converter.convert("123", Collection.class, Integer.class); assertEquals(values, result); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, Integer.class)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { assertEquals(Integer.MAX_VALUE - 1, converter.getPriority()); } }
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/convert/multiple/StringToSetConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSetConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; 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; /** * {@link StringToSetConverter} Test * * @since 2.7.6 */ class StringToSetConverterTest { private StringToSetConverter converter; @BeforeEach public void init() { converter = new StringToSetConverter(FrameworkModel.defaultModel()); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertFalse(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertTrue(converter.accept(String.class, Set.class)); assertTrue(converter.accept(String.class, SortedSet.class)); assertTrue(converter.accept(String.class, NavigableSet.class)); assertTrue(converter.accept(String.class, TreeSet.class)); assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertFalse(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { Set values = new HashSet(asList(1.0, 2.0, 3.0)); Set result = (Set<Double>) converter.convert("1.0,2.0,3.0", Queue.class, Double.class); assertTrue(CollectionUtils.equals(values, result)); values.clear(); values.add(123); result = (Set) converter.convert("123", Queue.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { assertEquals(Integer.MAX_VALUE - 2, converter.getPriority()); } }
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/convert/multiple/StringToArrayConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverterTest.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.convert.multiple; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Objects.deepEquals; 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; /** * {@link StringToArrayConverter} Test * * @since 2.7.6 */ class StringToArrayConverterTest { private StringToArrayConverter converter; @BeforeEach public void init() { converter = new StringToArrayConverter(FrameworkModel.defaultModel()); } @Test void testAccept() { assertTrue(converter.accept(String.class, char[].class)); assertTrue(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { assertTrue(deepEquals(new Integer[] {123}, converter.convert("123", Integer[].class, Integer.class))); assertTrue(deepEquals(new Integer[] {1, 2, 3}, converter.convert("1,2,3", Integer[].class, null))); assertNull(converter.convert("", Integer[].class, null)); assertNull(converter.convert(null, Integer[].class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { assertEquals(Integer.MAX_VALUE, converter.getPriority()); } }
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/convert/multiple/MultiValueConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/MultiValueConverterTest.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.convert.multiple; import java.util.Collection; import java.util.Deque; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link MultiValueConverter} Test * * @since 2.7.8 */ class MultiValueConverterTest { @Test void testFind() { MultiValueConverter converter = MultiValueConverter.find(String.class, String[].class); assertEquals(StringToArrayConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, BlockingDeque.class); assertEquals(StringToBlockingDequeConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, BlockingQueue.class); assertEquals(StringToBlockingQueueConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, Collection.class); assertEquals(StringToCollectionConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, Deque.class); assertEquals(StringToDequeConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, List.class); assertEquals(StringToListConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, NavigableSet.class); assertEquals(StringToNavigableSetConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, Queue.class); assertEquals(StringToQueueConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, Set.class); assertEquals(StringToSetConverter.class, converter.getClass()); converter = MultiValueConverter.find(String.class, TransferQueue.class); assertEquals(StringToTransferQueueConverter.class, converter.getClass()); } }
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/convert/multiple/StringToBlockingQueueConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToBlockingQueueConverter} Test * * @see BlockingDeque * @since 2.7.6 */ class StringToBlockingQueueConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-blocking-queue"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertFalse(converter.accept(String.class, NavigableSet.class)); assertFalse(converter.accept(String.class, TreeSet.class)); assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertTrue(converter.accept(String.class, BlockingQueue.class)); assertTrue(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertTrue(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { BlockingQueue values = new ArrayBlockingQueue(3); values.offer(1); values.offer(2); values.offer(3); BlockingQueue<Integer> result = (BlockingQueue<Integer>) converter.convert("1,2,3", BlockingDeque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values.clear(); values.offer(123); result = (BlockingQueue<Integer>) converter.convert("123", BlockingDeque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, null)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { assertEquals(Integer.MAX_VALUE - 3, converter.getPriority()); } }
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/convert/multiple/StringToNavigableSetConverterTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverterTest.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.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; 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; /** * {@link StringToNavigableSetConverter} Test * * @since 2.7.6 */ class StringToNavigableSetConverterTest { private MultiValueConverter converter; @BeforeEach public void init() { converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-navigable-set"); } @Test void testAccept() { assertFalse(converter.accept(String.class, Collection.class)); assertFalse(converter.accept(String.class, List.class)); assertFalse(converter.accept(String.class, AbstractList.class)); assertFalse(converter.accept(String.class, LinkedList.class)); assertFalse(converter.accept(String.class, ArrayList.class)); assertFalse(converter.accept(String.class, Set.class)); assertFalse(converter.accept(String.class, SortedSet.class)); assertTrue(converter.accept(String.class, NavigableSet.class)); assertTrue(converter.accept(String.class, TreeSet.class)); assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class)); assertFalse(converter.accept(String.class, Queue.class)); assertFalse(converter.accept(String.class, BlockingQueue.class)); assertFalse(converter.accept(String.class, TransferQueue.class)); assertFalse(converter.accept(String.class, Deque.class)); assertFalse(converter.accept(String.class, BlockingDeque.class)); assertFalse(converter.accept(null, char[].class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, String.class)); assertFalse(converter.accept(null, null)); } @Test void testConvert() { Set values = new TreeSet(asList(1, 2, 3)); NavigableSet result = (NavigableSet) converter.convert("1,2,3", List.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); values = new TreeSet(asList("123")); result = (NavigableSet) converter.convert("123", NavigableSet.class, String.class); assertTrue(CollectionUtils.equals(values, result)); assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, null)); } @Test void testGetSourceType() { assertEquals(String.class, converter.getSourceType()); } @Test void testGetPriority() { // Since JDK21, add SequencedCollection, SequencedSet assertEquals( Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 4), converter.getPriority()); } }
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/compiler/support/ClassUtilsTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/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.compiler.support; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ClassUtilsTest { @Test void testNewInstance() { HelloServiceImpl0 instance = (HelloServiceImpl0) ClassUtils.newInstance(HelloServiceImpl0.class.getName()); Assertions.assertEquals("Hello world!", instance.sayHello()); } @Test void testNewInstance0() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.newInstance(PrivateHelloServiceImpl.class.getName())); } @Test void testNewInstance1() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.newInstance( "org.apache.dubbo.common.compiler.support.internal.HelloServiceInternalImpl")); } @Test void testNewInstance2() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.newInstance("org.apache.dubbo.common.compiler.support.internal.NotExistsImpl")); } @Test void testForName() { ClassUtils.forName(new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImpl0"); } @Test void testForName1() { Assertions.assertThrows( IllegalStateException.class, () -> ClassUtils.forName( new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImplXX")); } @Test void testForName2() { Assertions.assertEquals(boolean.class, ClassUtils.forName("boolean")); Assertions.assertEquals(byte.class, ClassUtils.forName("byte")); Assertions.assertEquals(char.class, ClassUtils.forName("char")); Assertions.assertEquals(short.class, ClassUtils.forName("short")); Assertions.assertEquals(int.class, ClassUtils.forName("int")); Assertions.assertEquals(long.class, ClassUtils.forName("long")); Assertions.assertEquals(float.class, ClassUtils.forName("float")); Assertions.assertEquals(double.class, ClassUtils.forName("double")); Assertions.assertEquals(boolean[].class, ClassUtils.forName("boolean[]")); Assertions.assertEquals(byte[].class, ClassUtils.forName("byte[]")); Assertions.assertEquals(char[].class, ClassUtils.forName("char[]")); Assertions.assertEquals(short[].class, ClassUtils.forName("short[]")); Assertions.assertEquals(int[].class, ClassUtils.forName("int[]")); Assertions.assertEquals(long[].class, ClassUtils.forName("long[]")); Assertions.assertEquals(float[].class, ClassUtils.forName("float[]")); Assertions.assertEquals(double[].class, ClassUtils.forName("double[]")); } @Test void testGetBoxedClass() { Assertions.assertEquals(Boolean.class, ClassUtils.getBoxedClass(boolean.class)); Assertions.assertEquals(Character.class, ClassUtils.getBoxedClass(char.class)); Assertions.assertEquals(Byte.class, ClassUtils.getBoxedClass(byte.class)); Assertions.assertEquals(Short.class, ClassUtils.getBoxedClass(short.class)); Assertions.assertEquals(Integer.class, ClassUtils.getBoxedClass(int.class)); Assertions.assertEquals(Long.class, ClassUtils.getBoxedClass(long.class)); Assertions.assertEquals(Float.class, ClassUtils.getBoxedClass(float.class)); Assertions.assertEquals(Double.class, ClassUtils.getBoxedClass(double.class)); Assertions.assertEquals(ClassUtilsTest.class, ClassUtils.getBoxedClass(ClassUtilsTest.class)); } @Test void testBoxedAndUnboxed() { Assertions.assertEquals(Boolean.valueOf(true), ClassUtils.boxed(true)); Assertions.assertEquals(Character.valueOf('0'), ClassUtils.boxed('0')); Assertions.assertEquals(Byte.valueOf((byte) 0), ClassUtils.boxed((byte) 0)); Assertions.assertEquals(Short.valueOf((short) 0), ClassUtils.boxed((short) 0)); Assertions.assertEquals(Integer.valueOf((int) 0), ClassUtils.boxed((int) 0)); Assertions.assertEquals(Long.valueOf((long) 0), ClassUtils.boxed((long) 0)); Assertions.assertEquals(Float.valueOf((float) 0), ClassUtils.boxed((float) 0)); Assertions.assertEquals(Double.valueOf((double) 0), ClassUtils.boxed((double) 0)); Assertions.assertTrue(ClassUtils.unboxed(Boolean.valueOf(true))); Assertions.assertEquals('0', ClassUtils.unboxed(Character.valueOf('0'))); Assertions.assertEquals((byte) 0, ClassUtils.unboxed(Byte.valueOf((byte) 0))); Assertions.assertEquals((short) 0, ClassUtils.unboxed(Short.valueOf((short) 0))); Assertions.assertEquals(0, ClassUtils.unboxed(Integer.valueOf((int) 0))); Assertions.assertEquals((long) 0, ClassUtils.unboxed(Long.valueOf((long) 0))); // Assertions.assertEquals((float) 0, ClassUtils.unboxed(Float.valueOf((float) 0)), ((float) 0)); // Assertions.assertEquals((double) 0, ClassUtils.unboxed(Double.valueOf((double) 0)), ((double) 0)); } @Test void testGetSize() { Assertions.assertEquals(0, ClassUtils.getSize(null)); List<Integer> list = new ArrayList<>(); list.add(1); Assertions.assertEquals(1, ClassUtils.getSize(list)); Map map = new HashMap(); map.put(1, 1); Assertions.assertEquals(1, ClassUtils.getSize(map)); int[] array = new int[1]; Assertions.assertEquals(1, ClassUtils.getSize(array)); Assertions.assertEquals(-1, ClassUtils.getSize(new Object())); } @Test void testToUri() { Assertions.assertThrows(RuntimeException.class, () -> ClassUtils.toURI("#xx_abc#hello")); } @Test void testGetSizeMethod() { Assertions.assertEquals("getLength()", ClassUtils.getSizeMethod(GenericClass3.class)); } @Test void testGetSimpleClassName() { Assertions.assertNull(ClassUtils.getSimpleClassName(null)); Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getName())); Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getSimpleName())); } private interface GenericInterface<T> {} private class GenericClass<T> implements GenericInterface<T> {} private class GenericClass0 implements GenericInterface<String> {} private class GenericClass1 implements GenericInterface<Collection<String>> {} private class GenericClass2<T> implements GenericInterface<T[]> {} private class GenericClass3<T> implements GenericInterface<T[][]> { public int getLength() { return -1; } } private class PrivateHelloServiceImpl implements HelloService { private PrivateHelloServiceImpl() {} @Override public String sayHello() { return "Hello world!"; } } }
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/compiler/support/JavaCodeTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavaCodeTest.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.compiler.support; import java.util.concurrent.atomic.AtomicInteger; class JavaCodeTest { public static final AtomicInteger SUBFIX = new AtomicInteger(8); boolean shouldIgnoreWithoutPackage() { String jdkVersion = System.getProperty("java.specification.version"); try { return Integer.parseInt(jdkVersion) > 15; } catch (Throwable t) { return false; } } String getSimpleCode() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " implements HelloService {"); code.append(" public String sayHello() { "); code.append(" return \"Hello world!\"; "); code.append(" }"); code.append('}'); return code.toString(); } String getSimpleCodeWithoutPackage() { StringBuilder code = new StringBuilder(); code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + "implements org.apache.dubbo.common.compiler.support.HelloService.HelloService {"); code.append(" public String sayHello() { "); code.append(" return \"Hello world!\"; "); code.append(" }"); code.append('}'); return code.toString(); } String getSimpleCodeWithSyntax() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " implements HelloService {"); code.append(" public String sayHello() { "); code.append(" return \"Hello world!\"; "); // code.append(" }"); // } return code.toString(); } // only used for javassist String getSimpleCodeWithSyntax0() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); code.append("public class HelloServiceImpl_0 implements HelloService {"); code.append(" public String sayHello() { "); code.append(" return \"Hello world!\"; "); // code.append(" }"); // } return code.toString(); } String getSimpleCodeWithImports() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); code.append("import java.lang.*;\n"); code.append("import org.apache.dubbo.common.compiler.support;\n"); code.append("public class HelloServiceImpl2" + SUBFIX.getAndIncrement() + " implements HelloService {"); code.append(" public String sayHello() { "); code.append(" return \"Hello world!\"; "); code.append(" }"); code.append('}'); return code.toString(); } String getSimpleCodeWithWithExtends() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); code.append("import java.lang.*;\n"); code.append("import org.apache.dubbo.common.compiler.support;\n"); code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " extends org.apache.dubbo.common.compiler.support.HelloServiceImpl0 {\n"); code.append(" public String sayHello() { "); code.append(" return \"Hello world3!\"; "); code.append(" }"); code.append('}'); return code.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/compiler/support/HelloServiceImpl0.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloServiceImpl0.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.compiler.support; public class HelloServiceImpl0 implements HelloService { @Override public String sayHello() { return "Hello world!"; } }
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/compiler/support/JavassistCompilerTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavassistCompilerTest.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.compiler.support; import java.lang.reflect.Method; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; class JavassistCompilerTest extends JavaCodeTest { @Test void testCompileJavaClass() throws Exception { JavassistCompiler compiler = new JavassistCompiler(); Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), JavassistCompiler.class.getClassLoader()); // Because javassist compiles using the caller class loader, we shouldn't use HelloService directly Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); } /** * javassist compile will find HelloService in classpath */ @Test @DisabledForJreRange(min = JRE.JAVA_16) public void testCompileJavaClass0() throws Exception { boolean ignoreWithoutPackage = shouldIgnoreWithoutPackage(); JavassistCompiler compiler = new JavassistCompiler(); if (ignoreWithoutPackage) { Assertions.assertThrows( RuntimeException.class, () -> compiler.compile( null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader())); } else { Class<?> clazz = compiler.compile(null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); } } @Test void testCompileJavaClass1() { Assertions.assertThrows(IllegalStateException.class, () -> { JavassistCompiler compiler = new JavassistCompiler(); Class<?> clazz = compiler.compile( JavaCodeTest.class, getSimpleCodeWithSyntax0(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); }); } @Test void testCompileJavaClassWithImport() throws Exception { JavassistCompiler compiler = new JavassistCompiler(); Class<?> clazz = compiler.compile( JavaCodeTest.class, getSimpleCodeWithImports(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); } @Test void testCompileJavaClassWithExtends() throws Exception { JavassistCompiler compiler = new JavassistCompiler(); Class<?> clazz = compiler.compile( JavaCodeTest.class, getSimpleCodeWithWithExtends(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world3!", sayHello.invoke(instance)); } }
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/compiler/support/JdkCompilerTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JdkCompilerTest.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.compiler.support; import java.lang.reflect.Method; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class JdkCompilerTest extends JavaCodeTest { @Test void test_compileJavaClass() throws Exception { JdkCompiler compiler = new JdkCompiler(); Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); } @Test void test_compileJavaClass0() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler(); Class<?> clazz = compiler.compile( JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); }); } @Test void test_compileJavaClass1() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler(); Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); }); } @Test void test_compileJavaClass_java8() throws Exception { JdkCompiler compiler = new JdkCompiler("1.8"); Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); } @Test void test_compileJavaClass0_java8() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler("1.8"); Class<?> clazz = compiler.compile( JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); }); } @Test void test_compileJavaClass1_java8() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler("1.8"); Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); }); } }
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/compiler/support/AdaptiveCompilerTest.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/AdaptiveCompilerTest.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.compiler.support; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class AdaptiveCompilerTest extends JavaCodeTest { @Test void testAvailableCompiler() throws Exception { AdaptiveCompiler.setDefaultCompiler("jdk"); AdaptiveCompiler compiler = new AdaptiveCompiler(); compiler.setFrameworkModel(FrameworkModel.defaultModel()); Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), AdaptiveCompiler.class.getClassLoader()); HelloService helloService = (HelloService) clazz.getDeclaredConstructor().newInstance(); Assertions.assertEquals("Hello world!", helloService.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/compiler/support/HelloService.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloService.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.compiler.support; public interface HelloService { 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/compiler/support/internal/HelloServiceInternalImpl.java
dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/internal/HelloServiceInternalImpl.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.compiler.support.internal; final class HelloServiceInternalImpl {}
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/config/GreetingLocal1.java
dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal1.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.config; public class GreetingLocal1 {}
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/config/AbstractInterfaceConfigTest.java
dubbo-common/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.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.config; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import java.io.File; import java.nio.file.Path; import java.util.Collections; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; class AbstractInterfaceConfigTest { @BeforeAll public static void setUp(@TempDir Path folder) { File dubboProperties = folder.resolve(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY) .toFile(); SystemPropertyConfigUtils.setSystemProperty( CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath()); } @AfterAll public static void tearDown() { SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY); } @Test void checkStub1() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal1.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub2() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal2.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub3() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal3.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); } @Test void checkStub4() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal1.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub5() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal2.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub6() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal3.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); } @Test void testLocal() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal((Boolean) null); Assertions.assertNull(interfaceConfig.getLocal()); interfaceConfig.setLocal(true); Assertions.assertEquals("true", interfaceConfig.getLocal()); interfaceConfig.setLocal("GreetingMock"); Assertions.assertEquals("GreetingMock", interfaceConfig.getLocal()); } @Test void testStub() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub((Boolean) null); Assertions.assertNull(interfaceConfig.getStub()); interfaceConfig.setStub(true); Assertions.assertEquals("true", interfaceConfig.getStub()); interfaceConfig.setStub("GreetingMock"); Assertions.assertEquals("GreetingMock", interfaceConfig.getStub()); } @Test void testCluster() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setCluster("mockcluster"); Assertions.assertEquals("mockcluster", interfaceConfig.getCluster()); } @Test void testProxy() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setProxy("mockproxyfactory"); Assertions.assertEquals("mockproxyfactory", interfaceConfig.getProxy()); } @Test void testConnections() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setConnections(1); Assertions.assertEquals(1, interfaceConfig.getConnections().intValue()); } @Test void testFilter() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setFilter("mockfilter"); Assertions.assertEquals("mockfilter", interfaceConfig.getFilter()); } @Test void testListener() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setListener("mockinvokerlistener"); Assertions.assertEquals("mockinvokerlistener", interfaceConfig.getListener()); } @Test void testLayer() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLayer("layer"); Assertions.assertEquals("layer", interfaceConfig.getLayer()); } @Test void testApplication() { InterfaceConfig interfaceConfig = new InterfaceConfig(); ApplicationConfig applicationConfig = new ApplicationConfig("AbstractInterfaceConfigTest"); interfaceConfig.setApplication(applicationConfig); Assertions.assertSame(applicationConfig, interfaceConfig.getApplication()); } @Test void testModule() { InterfaceConfig interfaceConfig = new InterfaceConfig(); ModuleConfig moduleConfig = new ModuleConfig(); interfaceConfig.setModule(moduleConfig); Assertions.assertSame(moduleConfig, interfaceConfig.getModule()); } @Test void testRegistry() { InterfaceConfig interfaceConfig = new InterfaceConfig(); RegistryConfig registryConfig = new RegistryConfig(); interfaceConfig.setRegistry(registryConfig); Assertions.assertSame(registryConfig, interfaceConfig.getRegistry()); } @Test void testRegistries() { InterfaceConfig interfaceConfig = new InterfaceConfig(); RegistryConfig registryConfig = new RegistryConfig(); interfaceConfig.setRegistries(Collections.singletonList(registryConfig)); Assertions.assertEquals(1, interfaceConfig.getRegistries().size()); Assertions.assertSame(registryConfig, interfaceConfig.getRegistries().get(0)); } @Test void testMonitor() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMonitor("monitor-addr"); Assertions.assertEquals("monitor-addr", interfaceConfig.getMonitor().getAddress()); MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setAddress("monitor-addr"); interfaceConfig.setMonitor(monitorConfig); Assertions.assertSame(monitorConfig, interfaceConfig.getMonitor()); } @Test void testOwner() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setOwner("owner"); Assertions.assertEquals("owner", interfaceConfig.getOwner()); } @Test void testCallbacks() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setCallbacks(2); Assertions.assertEquals(2, interfaceConfig.getCallbacks().intValue()); } @Test void testOnconnect() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setOnconnect("onConnect"); Assertions.assertEquals("onConnect", interfaceConfig.getOnconnect()); } @Test void testOndisconnect() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setOndisconnect("onDisconnect"); Assertions.assertEquals("onDisconnect", interfaceConfig.getOndisconnect()); } @Test void testScope() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setScope("scope"); Assertions.assertEquals("scope", interfaceConfig.getScope()); } @Test void testVerifyMethod() { InterfaceConfig2 interfaceConfig2 = new InterfaceConfig2(); MethodConfig methodConfig = new MethodConfig(); methodConfig.setTimeout(5000); methodConfig.setName("sayHello"); Class<?> clazz = Greeting.class; boolean verifyResult = interfaceConfig2.verifyMethodConfig(methodConfig, clazz, false); Assertions.assertTrue(verifyResult); boolean verifyResult2 = interfaceConfig2.verifyMethodConfig(methodConfig, clazz, true); Assertions.assertFalse(verifyResult2); } public static class InterfaceConfig2 extends AbstractInterfaceConfig { @Override protected boolean isNeedCheckMethod() { return false; } } public static class InterfaceConfig extends AbstractInterfaceConfig {} }
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/config/Greeting.java
dubbo-common/src/test/java/org/apache/dubbo/config/Greeting.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.config; import org.apache.dubbo.common.extension.SPI; @SPI public interface Greeting { String hello(); }
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/config/GreetingLocal2.java
dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal2.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.config; public class GreetingLocal2 implements Greeting { @Override public String hello() { return "local"; } }
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/config/GreetingLocal3.java
dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal3.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.config; public class GreetingLocal3 implements Greeting { private Greeting greeting; public GreetingLocal3(Greeting greeting) { this.greeting = greeting; } @Override public String hello() { 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/config/context/ConfigConfigurationAdapterTest.java
dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigConfigurationAdapterTest.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.config.context; import org.apache.dubbo.config.RegistryConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link ConfigConfigurationAdapter} */ class ConfigConfigurationAdapterTest { @Test void test() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("127.0.0.1"); registryConfig.setPort(2181); String prefix = "dubbo.registry"; ConfigConfigurationAdapter configConfigurationAdapter = new ConfigConfigurationAdapter(registryConfig, prefix); Assertions.assertEquals(configConfigurationAdapter.getInternalProperty(prefix + "." + "address"), "127.0.0.1"); Assertions.assertEquals(configConfigurationAdapter.getInternalProperty(prefix + "." + "port"), "2181"); } }
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/config/context/ConfigManagerTest.java
dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.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.config.context; import org.apache.dubbo.common.serialization.PreferSerializationProvider; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Collection; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.config.context.ConfigManager.DUBBO_CONFIG_MODE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * {@link AbstractConfigManager} Test * {@link ConfigManager} Test * {@link ModuleConfigManager} Test * * @since 2.7.5 */ class ConfigManagerTest { private ConfigManager configManager; private ModuleConfigManager moduleConfigManager; @BeforeEach public void init() { ApplicationModel.defaultModel().destroy(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); configManager = applicationModel.getApplicationConfigManager(); moduleConfigManager = applicationModel.getDefaultModule().getConfigManager(); FrameworkModel.defaultModel().getBeanFactory().registerBean(TestPreferSerializationProvider.class); } @Test void testDestroy() { assertTrue(configManager.configsCache.isEmpty()); } @Test void testDefaultValues() { // assert single assertFalse(configManager.getApplication().isPresent()); assertFalse(configManager.getMonitor().isPresent()); assertFalse(configManager.getMetrics().isPresent()); // protocols assertTrue(configManager.getProtocols().isEmpty()); assertTrue(configManager.getDefaultProtocols().isEmpty()); // registries assertTrue(configManager.getRegistries().isEmpty()); assertTrue(configManager.getDefaultRegistries().isEmpty()); // config centers assertTrue(configManager.getConfigCenters().isEmpty()); // metadata assertTrue(configManager.getMetadataConfigs().isEmpty()); // services and references assertTrue(moduleConfigManager.getServices().isEmpty()); assertTrue(moduleConfigManager.getReferences().isEmpty()); // providers and consumers assertFalse(moduleConfigManager.getModule().isPresent()); assertFalse(moduleConfigManager.getDefaultProvider().isPresent()); assertFalse(moduleConfigManager.getDefaultConsumer().isPresent()); assertTrue(moduleConfigManager.getProviders().isEmpty()); assertTrue(moduleConfigManager.getConsumers().isEmpty()); } // Test ApplicationConfig correlative methods @Test void testApplicationConfig() { ApplicationConfig config = new ApplicationConfig("ConfigManagerTest"); configManager.setApplication(config); assertTrue(configManager.getApplication().isPresent()); assertEquals(config, configManager.getApplication().get()); assertEquals(config, moduleConfigManager.getApplication().get()); } // Test MonitorConfig correlative methods @Test void testMonitorConfig() { MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setGroup("test"); configManager.setMonitor(monitorConfig); assertTrue(configManager.getMonitor().isPresent()); assertEquals(monitorConfig, configManager.getMonitor().get()); assertEquals(monitorConfig, moduleConfigManager.getMonitor().get()); } // Test ModuleConfig correlative methods @Test void testModuleConfig() { ModuleConfig config = new ModuleConfig(); moduleConfigManager.setModule(config); assertTrue(moduleConfigManager.getModule().isPresent()); assertEquals(config, moduleConfigManager.getModule().get()); } // Test MetricsConfig correlative methods @Test void testMetricsConfig() { MetricsConfig config = new MetricsConfig(); config.setProtocol(PROTOCOL_PROMETHEUS); configManager.setMetrics(config); assertTrue(configManager.getMetrics().isPresent()); assertEquals(config, configManager.getMetrics().get()); assertEquals(config, moduleConfigManager.getMetrics().get()); } // Test ProviderConfig correlative methods @Test void testProviderConfig() { ProviderConfig config = new ProviderConfig(); moduleConfigManager.addProviders(asList(config, null)); Collection<ProviderConfig> configs = moduleConfigManager.getProviders(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertTrue(moduleConfigManager.getDefaultProvider().isPresent()); config = new ProviderConfig(); config.setId(DEFAULT_KEY); config.setQueues(10); moduleConfigManager.addProvider(config); assertTrue(moduleConfigManager.getDefaultProvider().isPresent()); configs = moduleConfigManager.getProviders(); assertEquals(2, configs.size()); } // Test ConsumerConfig correlative methods @Test void testConsumerConfig() { ConsumerConfig config = new ConsumerConfig(); moduleConfigManager.addConsumers(asList(config, null)); Collection<ConsumerConfig> configs = moduleConfigManager.getConsumers(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertTrue(moduleConfigManager.getDefaultConsumer().isPresent()); config = new ConsumerConfig(); config.setId(DEFAULT_KEY); config.setThreads(10); moduleConfigManager.addConsumer(config); assertTrue(moduleConfigManager.getDefaultConsumer().isPresent()); configs = moduleConfigManager.getConsumers(); assertEquals(2, configs.size()); } // Test ProtocolConfig correlative methods @Test void testProtocolConfig() { ProtocolConfig config = new ProtocolConfig(); configManager.addProtocols(asList(config, null)); Collection<ProtocolConfig> configs = configManager.getProtocols(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertFalse(configManager.getDefaultProtocols().isEmpty()); assertEquals(configs, moduleConfigManager.getProtocols()); assertNotEquals(20881, config.getPort()); assertNotEquals(config.getSerialization(), "fastjson2"); ProtocolConfig defaultConfig = new ProtocolConfig(); defaultConfig.setPort(20881); defaultConfig.setSerialization("fastjson2"); config.mergeProtocol(defaultConfig); assertEquals(config.getPort(), 20881); assertEquals(config.getSerialization(), "fastjson2"); } // Test RegistryConfig correlative methods @Test void testRegistryConfig() { RegistryConfig config = new RegistryConfig(); configManager.addRegistries(asList(config, null)); Collection<RegistryConfig> configs = configManager.getRegistries(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertFalse(configManager.getDefaultRegistries().isEmpty()); assertEquals(configs, moduleConfigManager.getRegistries()); } // Test ConfigCenterConfig correlative methods @Test void testConfigCenterConfig() { String address = "zookeeper://127.0.0.1:2181"; ConfigCenterConfig config = new ConfigCenterConfig(); config.setAddress(address); configManager.addConfigCenters(asList(config, null)); Collection<ConfigCenterConfig> configs = configManager.getConfigCenters(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); // add duplicated config, expecting ignore equivalent configs ConfigCenterConfig config2 = new ConfigCenterConfig(); config2.setAddress(address); configManager.addConfigCenter(config2); configs = configManager.getConfigCenters(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertEquals(configs, moduleConfigManager.getConfigCenters()); } @Test void testAddConfig() { configManager.addConfig(new ApplicationConfig("ConfigManagerTest")); configManager.addConfig(new ProtocolConfig()); moduleConfigManager.addConfig(new ProviderConfig()); assertTrue(configManager.getApplication().isPresent()); assertFalse(configManager.getProtocols().isEmpty()); assertFalse(moduleConfigManager.getProviders().isEmpty()); } @Test void testAddCustomConfig() { configManager.addConfig(new CustomRegistryConfig("CustomConfigManagerTest")); assertTrue(configManager.getRegistry("CustomConfigManagerTest").isPresent()); } static class CustomRegistryConfig extends RegistryConfig { CustomRegistryConfig(String id) { super(); this.setId(id); } } @Test void testRefreshAll() { configManager.refreshAll(); moduleConfigManager.refreshAll(); } @Test void testDefaultConfig() { ProviderConfig providerConfig = new ProviderConfig(); providerConfig.setDefault(false); assertFalse(ConfigManager.isDefaultConfig(providerConfig)); ProviderConfig providerConfig1 = new ProviderConfig(); assertNull(ConfigManager.isDefaultConfig(providerConfig1)); ProviderConfig providerConfig3 = new ProviderConfig(); providerConfig3.setDefault(true); assertTrue(ConfigManager.isDefaultConfig(providerConfig3)); ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setDefault(false); assertFalse(ConfigManager.isDefaultConfig(protocolConfig)); } @Test void testConfigMode() { ApplicationConfig applicationConfig1 = new ApplicationConfig("app1"); ApplicationConfig applicationConfig2 = new ApplicationConfig("app2"); try { // test strict mode ApplicationModel.reset(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.STRICT, configManager.getConfigMode()); System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.STRICT.name()); ApplicationModel.reset(); Assertions.assertEquals(ConfigMode.STRICT, configManager.getConfigMode()); configManager.addConfig(applicationConfig1); try { configManager.addConfig(applicationConfig2); fail("strict mode cannot add two application configs"); } catch (Exception e) { assertEquals(IllegalStateException.class, e.getClass()); assertTrue(e.getMessage().contains("please remove redundant configs and keep only one")); } // test override mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.OVERRIDE, configManager.getConfigMode()); configManager.addConfig(applicationConfig1); configManager.addConfig(applicationConfig2); assertEquals(applicationConfig2, configManager.getApplicationOrElseThrow()); // test ignore mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.IGNORE.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.IGNORE, configManager.getConfigMode()); configManager.addConfig(applicationConfig1); configManager.addConfig(applicationConfig2); assertEquals(applicationConfig1, configManager.getApplicationOrElseThrow()); // test OVERRIDE_ALL mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_ALL.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.OVERRIDE_ALL, configManager.getConfigMode()); ApplicationConfig applicationConfig11 = new ApplicationConfig("app11"); ApplicationConfig applicationConfig22 = new ApplicationConfig("app22"); applicationConfig11.setParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); applicationConfig22.setParameters(CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); configManager.addConfig(applicationConfig11); configManager.addConfig(applicationConfig22); assertEquals(applicationConfig11, configManager.getApplicationOrElseThrow()); assertEquals(applicationConfig11.getName(), "app22"); assertEquals( applicationConfig11.getParameters(), CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); // test OVERRIDE_IF_ABSENT mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_IF_ABSENT.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.OVERRIDE_IF_ABSENT, configManager.getConfigMode()); ApplicationConfig applicationConfig33 = new ApplicationConfig("app33"); ApplicationConfig applicationConfig44 = new ApplicationConfig("app44"); applicationConfig33.setParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); applicationConfig44.setParameters(CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); configManager.addConfig(applicationConfig33); configManager.addConfig(applicationConfig44); assertEquals(applicationConfig33, configManager.getApplicationOrElseThrow()); assertEquals("app33", applicationConfig33.getName()); assertEquals( CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "k3", "v3"), applicationConfig33.getParameters()); } finally { System.clearProperty(DUBBO_CONFIG_MODE); } } @Test void testGetConfigByIdOrName() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setId("registryID_1"); configManager.addRegistry(registryConfig); Optional<RegistryConfig> registryConfigOptional = configManager.getConfig(RegistryConfig.class, registryConfig.getId()); if (registryConfigOptional.isPresent()) { Assertions.assertEquals(registryConfigOptional.get(), registryConfig); } else { fail("registryConfigOptional is empty! "); } ProtocolConfig protocolConfig = new ProtocolConfig("dubbo"); configManager.addProtocol(protocolConfig); Optional<ProtocolConfig> protocolConfigOptional = configManager.getConfig(ProtocolConfig.class, protocolConfig.getName()); if (protocolConfigOptional.isPresent()) { Assertions.assertEquals(protocolConfigOptional.get(), protocolConfig); } else { fail("protocolConfigOptional is empty! "); } // test multi config has same name(dubbo) ProtocolConfig protocolConfig2 = new ProtocolConfig("dubbo"); protocolConfig2.setPort(9103); configManager.addProtocol(protocolConfig2); try { configManager.getConfig(ProtocolConfig.class, protocolConfig.getName()); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalStateException); String msg = e.getMessage(); Assertions.assertTrue( msg.startsWith("Found more than one config by name: dubbo, instances: "), "Unexpected message prefix: " + msg); Assertions.assertTrue( msg.contains("<dubbo:protocol port=\"9103\" name=\"dubbo\" />"), "Message should mention protocol with port 9103: " + msg); Assertions.assertTrue( msg.contains("<dubbo:protocol name=\"dubbo\" />"), "Message should mention protocol with default port: " + msg); Assertions.assertTrue( msg.endsWith("Please remove redundant configs or get config by id."), "Unexpected message suffix: " + msg); } ModuleConfig moduleConfig = new ModuleConfig(); moduleConfig.setId("moduleID_1"); moduleConfigManager.setModule(moduleConfig); Optional<ModuleConfig> moduleConfigOptional = moduleConfigManager.getConfig(ModuleConfig.class, moduleConfig.getId()); Assertions.assertEquals(moduleConfig, moduleConfigOptional.get()); Optional<RegistryConfig> config = moduleConfigManager.getConfig(RegistryConfig.class, registryConfig.getId()); Assertions.assertEquals(config.get(), registryConfig); } @Test void testLoadConfigsOfTypeFromProps() { try { // dubbo.application.enable-file-cache = false configManager.loadConfigsOfTypeFromProps(ApplicationConfig.class); Optional<ApplicationConfig> application = configManager.getApplication(); Assertions.assertTrue(application.isPresent()); configManager.removeConfig(application.get()); System.setProperty("dubbo.protocols.dubbo1.port", "20880"); System.setProperty("dubbo.protocols.dubbo2.port", "20881"); System.setProperty("dubbo.protocols.rest1.port", "8080"); System.setProperty("dubbo.protocols.rest2.port", "8081"); configManager.loadConfigsOfTypeFromProps(ProtocolConfig.class); Collection<ProtocolConfig> protocols = configManager.getProtocols(); Assertions.assertEquals(4, protocols.size()); System.setProperty("dubbo.applications.app1.name", "app-demo1"); System.setProperty("dubbo.applications.app2.name", "app-demo2"); try { configManager.loadConfigsOfTypeFromProps(ApplicationConfig.class); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e.getMessage().contains("load config failed")); } } finally { System.clearProperty("dubbo.protocols.dubbo1.port"); System.clearProperty("dubbo.protocols.dubbo2.port"); System.clearProperty("dubbo.protocols.rest1.port"); System.clearProperty("dubbo.protocols.rest2.port"); System.clearProperty("dubbo.applications.app1.name"); System.clearProperty("dubbo.applications.app2.name"); } } @Test void testLoadConfig() { configManager.loadConfigs(); Assertions.assertTrue(configManager.getApplication().isPresent()); Assertions.assertTrue(configManager.getSsl().isPresent()); Assertions.assertFalse(configManager.getProtocols().isEmpty()); int port = 20880; ProtocolConfig config1 = new ProtocolConfig(); config1.setName("dubbo"); config1.setPort(port); ProtocolConfig config2 = new ProtocolConfig(); config2.setName("rest"); config2.setPort(port); configManager.addProtocols(asList(config1, config2)); try { configManager.loadConfigs(); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalStateException); Assertions.assertTrue(e.getMessage().contains("Duplicated port used by protocol configs, port: " + port)); } moduleConfigManager.loadConfigs(); Assertions.assertTrue(moduleConfigManager.getModule().isPresent()); Assertions.assertFalse(moduleConfigManager.getProviders().isEmpty()); Assertions.assertFalse(moduleConfigManager.getConsumers().isEmpty()); } public static class TestPreferSerializationProvider implements PreferSerializationProvider { @Override public String getPreferSerialization() { return "hessian2"; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.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.metadata.definition; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.metadata.definition.builder.DefaultTypeBuilder; import org.apache.dubbo.metadata.definition.builder.TypeBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.rpc.model.FrameworkModel; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * 2015/1/27. */ public class TypeDefinitionBuilder { private static final Logger logger = LoggerFactory.getLogger(TypeDefinitionBuilder.class); public static List<TypeBuilder> BUILDERS; public static void initBuilders(FrameworkModel model) { Set<TypeBuilder> tbs = model.getExtensionLoader(TypeBuilder.class).getSupportedExtensionInstances(); BUILDERS = new ArrayList<>(tbs); } public static TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) { TypeBuilder builder = getGenericTypeBuilder(clazz); TypeDefinition td; if (clazz.isPrimitive() || ClassUtils.isSimpleType(clazz)) { // changed since 2.7.6 td = new TypeDefinition(clazz.getCanonicalName()); typeCache.put(clazz.getCanonicalName(), td); } else if (builder != null) { td = builder.build(type, clazz, typeCache); } else { td = DefaultTypeBuilder.build(clazz, typeCache); } return td; } private static TypeBuilder getGenericTypeBuilder(Class<?> clazz) { for (TypeBuilder builder : BUILDERS) { try { if (builder.accept(clazz)) { return builder; } } catch (NoClassDefFoundError cnfe) { // ignore logger.info("Throw classNotFound (" + cnfe.getMessage() + ") in " + builder.getClass()); } } return null; } private final Map<String, TypeDefinition> typeCache = new HashMap<>(); public TypeDefinition build(Type type, Class<?> clazz) { return build(type, clazz, typeCache); } public List<TypeDefinition> getTypeDefinitions() { return new ArrayList<>(typeCache.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/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.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.metadata.definition; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.definition.model.MethodDefinition; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.util.ClassUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * 2015/1/27. */ public final class ServiceDefinitionBuilder { /** * Describe a Java interface in {@link ServiceDefinition}. * * @return Service description */ public static ServiceDefinition build(final Class<?> interfaceClass) { ServiceDefinition sd = new ServiceDefinition(); build(sd, interfaceClass); return sd; } public static FullServiceDefinition buildFullDefinition(final Class<?> interfaceClass) { FullServiceDefinition sd = new FullServiceDefinition(); build(sd, interfaceClass); return sd; } public static FullServiceDefinition buildFullDefinition(final Class<?> interfaceClass, Map<String, String> params) { FullServiceDefinition sd = new FullServiceDefinition(); build(sd, interfaceClass); sd.setParameters(params); return sd; } public static <T extends ServiceDefinition> void build(T sd, final Class<?> interfaceClass) { sd.setCanonicalName(interfaceClass.getCanonicalName()); sd.setCodeSource(ClassUtils.getCodeSource(interfaceClass)); Annotation[] classAnnotations = interfaceClass.getAnnotations(); sd.setAnnotations(annotationToStringList(classAnnotations)); TypeDefinitionBuilder builder = new TypeDefinitionBuilder(); List<Method> methods = ClassUtils.getPublicNonStaticMethods(interfaceClass); for (Method method : methods) { MethodDefinition md = new MethodDefinition(); md.setName(method.getName()); Annotation[] methodAnnotations = method.getAnnotations(); md.setAnnotations(annotationToStringList(methodAnnotations)); // Process parameter types. Class<?>[] paramTypes = method.getParameterTypes(); Type[] genericParamTypes = method.getGenericParameterTypes(); String[] parameterTypes = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { TypeDefinition td = builder.build(genericParamTypes[i], paramTypes[i]); parameterTypes[i] = td.getType(); } md.setParameterTypes(parameterTypes); // Process return type. TypeDefinition td = builder.build(method.getGenericReturnType(), method.getReturnType()); md.setReturnType(td.getType()); sd.getMethods().add(md); } sd.setTypes(builder.getTypeDefinitions()); } private static List<String> annotationToStringList(Annotation[] annotations) { if (annotations == null) { return Collections.emptyList(); } List<String> list = new ArrayList<>(); for (Annotation annotation : annotations) { list.add(annotation.toString()); } return list; } /** * Describe a Java interface in Json schema. * * @return Service description */ public static String schema(final Class<?> clazz) { ServiceDefinition sd = build(clazz); return JsonUtils.toJson(sd); } private ServiceDefinitionBuilder() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.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.metadata.definition; import org.apache.dubbo.metadata.definition.model.MethodDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * {@link MethodDefinition} Builder based on Java Reflection * * @since 2.7.6 */ public class MethodDefinitionBuilder { private final TypeDefinitionBuilder builder; public MethodDefinitionBuilder(TypeDefinitionBuilder builder) { this.builder = builder; } public MethodDefinitionBuilder() { this.builder = new TypeDefinitionBuilder(); } /** * Build the instance of {@link MethodDefinition} * * @param method {@link Method} * @return non-null */ public MethodDefinition build(Method method) { MethodDefinition md = new MethodDefinition(); md.setName(method.getName()); // Process the parameters Class<?>[] paramTypes = method.getParameterTypes(); Type[] genericParamTypes = method.getGenericParameterTypes(); int paramSize = paramTypes.length; String[] parameterTypes = new String[paramSize]; List<TypeDefinition> parameters = new ArrayList<>(paramSize); for (int i = 0; i < paramSize; i++) { TypeDefinition parameter = builder.build(genericParamTypes[i], paramTypes[i]); parameterTypes[i] = parameter.getType(); parameters.add(parameter); } md.setParameterTypes(parameterTypes); md.setParameters(parameters); // Process return type. TypeDefinition td = builder.build(method.getGenericReturnType(), method.getReturnType()); md.setReturnType(td.getType()); return md; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.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.metadata.definition.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.List; /** * 2015/1/27. */ public final class ClassUtils { /** * Get the code source file or class path of the Class passed in. * * @param clazz * @return Jar file name or class path. */ public static String getCodeSource(Class<?> clazz) { ProtectionDomain protectionDomain = clazz.getProtectionDomain(); if (protectionDomain == null || protectionDomain.getCodeSource() == null) { return null; } CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); URL location = codeSource.getLocation(); if (location == null) { return null; } String path = location.toExternalForm(); if (path.endsWith(".jar") && path.contains("/")) { return path.substring(path.lastIndexOf('/') + 1); } return path; } /** * Get all non-static fields of the Class passed in or its super classes. * <p> * * @param clazz Class to parse. * @return field list */ public static List<Field> getNonStaticFields(final Class<?> clazz) { List<Field> result = new ArrayList<>(); Class<?> target = clazz; while (target != null) { if (JaketConfigurationUtils.isExcludedType(target)) { break; } Field[] fields = target.getDeclaredFields(); for (Field field : fields) { int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) { continue; } result.add(field); } target = target.getSuperclass(); } return result; } /** * Get all public, non-static methods of the Class passed in. * <p> * * @param clazz Class to parse. * @return methods list */ public static List<Method> getPublicNonStaticMethods(final Class<?> clazz) { List<Method> result = new ArrayList<>(); Method[] methods = clazz.getMethods(); for (Method method : methods) { int mod = method.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) { result.add(method); } } return result; } public static String getCanonicalNameForParameterizedType(ParameterizedType parameterizedType) { StringBuilder sb = new StringBuilder(); Type ownerType = parameterizedType.getOwnerType(); Class<?> rawType = (Class) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (ownerType != null) { if (ownerType instanceof Class) { sb.append(((Class) ownerType).getName()); } else { sb.append(ownerType); } sb.append('.'); if (ownerType instanceof ParameterizedType) { // Find simple name of nested type by removing the // shared prefix with owner. sb.append(rawType.getName() .replace(((Class) ((ParameterizedType) ownerType).getRawType()).getName() + "$", "")); } else { sb.append(rawType.getSimpleName()); } } else { sb.append(rawType.getCanonicalName()); } if (actualTypeArguments != null && actualTypeArguments.length > 0) { sb.append('<'); boolean first = true; for (Type t : actualTypeArguments) { if (!first) { sb.append(", "); } if (t instanceof Class) { Class c = (Class) t; sb.append(c.getCanonicalName()); } else if (t instanceof ParameterizedType) { sb.append(getCanonicalNameForParameterizedType((ParameterizedType) t)); } else { sb.append(t.toString()); } first = false; } sb.append('>'); } return sb.toString(); } private ClassUtils() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.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.metadata.definition.util; import org.apache.dubbo.common.utils.StringUtils; import java.io.InputStream; import java.util.Properties; /** * 2015/1/27. */ public class JaketConfigurationUtils { private static final String CONFIGURATION_FILE = "jaket.properties"; private static String[] includedInterfacePackages; private static String[] includedTypePackages; private static String[] closedTypes; static { Properties props = new Properties(); InputStream inStream = JaketConfigurationUtils.class.getClassLoader().getResourceAsStream(CONFIGURATION_FILE); try { props.load(inStream); String value = (String) props.get("included_interface_packages"); if (StringUtils.isNotEmpty(value)) { includedInterfacePackages = value.split(","); } value = props.getProperty("included_type_packages"); if (StringUtils.isNotEmpty(value)) { includedTypePackages = value.split(","); } value = props.getProperty("closed_types"); if (StringUtils.isNotEmpty(value)) { closedTypes = value.split(","); } } catch (Throwable e) { // Ignore it. } } public static boolean isExcludedInterface(Class<?> clazz) { if (includedInterfacePackages == null || includedInterfacePackages.length == 0) { return false; } for (String packagePrefix : includedInterfacePackages) { if (clazz.getCanonicalName().startsWith(packagePrefix)) { return false; } } return true; } public static boolean isExcludedType(Class<?> clazz) { if (includedTypePackages == null || includedTypePackages.length == 0) { return false; } for (String packagePrefix : includedTypePackages) { if (clazz.getCanonicalName().startsWith(packagePrefix)) { return false; } } return true; } public static boolean needAnalyzing(Class<?> clazz) { String canonicalName = clazz.getCanonicalName(); if (closedTypes != null && closedTypes.length > 0) { for (String type : closedTypes) { if (canonicalName.startsWith(type)) { return false; } } } return !isExcludedType(clazz); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.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.metadata.definition.builder; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.util.ClassUtils; import org.apache.dubbo.metadata.definition.util.JaketConfigurationUtils; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.List; import java.util.Map; /** * 2015/1/27. */ public final class DefaultTypeBuilder { public static TypeDefinition build(Class<?> clazz, Map<String, TypeDefinition> typeCache) { String className = clazz.getCanonicalName(); if (className == null) { className = clazz.getName(); } // Try to get a cached definition TypeDefinition td = typeCache.get(className); if (td != null) { return td; } td = new TypeDefinition(className); typeCache.put(className, td); // Primitive type if (!JaketConfigurationUtils.needAnalyzing(clazz)) { return td; } // Custom type List<Field> fields = ClassUtils.getNonStaticFields(clazz); for (Field field : fields) { String fieldName = field.getName(); Class<?> fieldClass = field.getType(); Type fieldType = field.getGenericType(); TypeDefinition fieldTd = TypeDefinitionBuilder.build(fieldType, fieldClass, typeCache); td.getProperties().put(fieldName, fieldTd.getType()); } return td; } private DefaultTypeBuilder() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.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.metadata.definition.builder; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.util.ClassUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collection; import java.util.Map; /** * 2015/1/27. */ public class CollectionTypeBuilder implements TypeBuilder { @Override public boolean accept(Class<?> clazz) { if (clazz == null) { return false; } return Collection.class.isAssignableFrom(clazz); } @Override public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) { if (!(type instanceof ParameterizedType)) { return new TypeDefinition(clazz.getCanonicalName()); } ParameterizedType parameterizedType = (ParameterizedType) type; Type[] actualTypeArgs = parameterizedType.getActualTypeArguments(); if (actualTypeArgs == null || actualTypeArgs.length != 1) { throw new IllegalArgumentException(MessageFormat.format( "[ServiceDefinitionBuilder] Collection type [{0}] with unexpected amount of arguments [{1}]." + Arrays.toString(actualTypeArgs), type, actualTypeArgs)); } String colType = ClassUtils.getCanonicalNameForParameterizedType(parameterizedType); TypeDefinition td = typeCache.get(colType); if (td != null) { return td; } td = new TypeDefinition(colType); typeCache.put(colType, td); Type actualType = actualTypeArgs[0]; TypeDefinition itemTd = null; if (actualType instanceof ParameterizedType) { // Nested collection or map. Class<?> rawType = (Class<?>) ((ParameterizedType) actualType).getRawType(); itemTd = TypeDefinitionBuilder.build(actualType, rawType, typeCache); } else if (actualType instanceof Class<?>) { Class<?> actualClass = (Class<?>) actualType; itemTd = TypeDefinitionBuilder.build(null, actualClass, typeCache); } if (itemTd != null) { td.getItems().add(itemTd.getType()); } return td; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.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.metadata.definition.builder; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import java.lang.reflect.Type; import java.util.Map; /** * 2015/1/27. */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface TypeBuilder extends Prioritized { /** * Whether the build accept the class passed in. */ boolean accept(Class<?> clazz); /** * Build type definition with the type or class. */ TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.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.metadata.definition.builder; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Map; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * 2015/1/27. */ public class EnumTypeBuilder implements TypeBuilder { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TypeDefinitionBuilder.class); @Override public boolean accept(Class<?> clazz) { if (clazz == null) { return false; } return clazz.isEnum(); } @Override public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) { String canonicalName = clazz.getCanonicalName(); TypeDefinition td = typeCache.get(canonicalName); if (td != null) { return td; } td = new TypeDefinition(canonicalName); typeCache.put(canonicalName, td); try { Method methodValues = clazz.getDeclaredMethod("values"); methodValues.setAccessible(true); Object[] values = (Object[]) methodValues.invoke(clazz, new Object[0]); int length = values.length; for (int i = 0; i < length; i++) { Object value = values[i]; td.getEnums().add(value.toString()); } return td; } catch (Throwable t) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "There is an error while process class " + clazz, t); } return td; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.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.metadata.definition.builder; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.util.ClassUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Map; import static org.apache.dubbo.common.utils.TypeUtils.getRawClass; import static org.apache.dubbo.common.utils.TypeUtils.isClass; import static org.apache.dubbo.common.utils.TypeUtils.isParameterizedType; /** * 2015/1/27. */ public class MapTypeBuilder implements TypeBuilder { @Override public boolean accept(Class<?> clazz) { if (clazz == null) { return false; } return Map.class.isAssignableFrom(clazz); } @Override public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) { if (!(type instanceof ParameterizedType)) { return new TypeDefinition(clazz.getCanonicalName()); } ParameterizedType parameterizedType = (ParameterizedType) type; Type[] actualTypeArgs = parameterizedType.getActualTypeArguments(); int actualTypeArgsLength = actualTypeArgs == null ? 0 : actualTypeArgs.length; String mapType = ClassUtils.getCanonicalNameForParameterizedType(parameterizedType); TypeDefinition td = typeCache.get(mapType); if (td != null) { return td; } td = new TypeDefinition(mapType); typeCache.put(mapType, td); for (int i = 0; i < actualTypeArgsLength; i++) { Type actualType = actualTypeArgs[i]; TypeDefinition item = null; Class<?> rawType = getRawClass(actualType); if (isParameterizedType(actualType)) { // Nested collection or map. item = TypeDefinitionBuilder.build(actualType, rawType, typeCache); } else if (isClass(actualType)) { item = TypeDefinitionBuilder.build(null, rawType, typeCache); } if (item != null) { td.getItems().add(item.getType()); } } return td; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.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.metadata.definition.builder; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import java.lang.reflect.Type; import java.util.Map; /** * 2015/1/27. */ public class ArrayTypeBuilder implements TypeBuilder { @Override public boolean accept(Class<?> clazz) { if (clazz == null) { return false; } return clazz.isArray(); } @Override public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) { final String canonicalName = clazz.getCanonicalName(); TypeDefinition td = typeCache.get(canonicalName); if (td != null) { return td; } td = new TypeDefinition(canonicalName); typeCache.put(canonicalName, td); // Process the component type of array. Class<?> componentType = clazz.getComponentType(); TypeDefinition itemTd = TypeDefinitionBuilder.build(componentType, componentType, typeCache); if (itemTd != null) { td.getItems().add(itemTd.getType()); } return td; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.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.metadata.definition.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import static org.apache.dubbo.metadata.definition.model.TypeDefinition.formatType; import static org.apache.dubbo.metadata.definition.model.TypeDefinition.formatTypes; /** * 2015/1/27. */ public class MethodDefinition implements Serializable { private String name; private String[] parameterTypes; private String returnType; /** * @deprecated please use parameterTypes, * and find TypeDefinition in org.apache.dubbo.metadata.definition.model.ServiceDefinition#types */ @Deprecated private List<TypeDefinition> parameters; private List<String> annotations; public String getName() { return name; } public List<TypeDefinition> getParameters() { if (parameters == null) { parameters = new ArrayList<>(); } return parameters; } public String[] getParameterTypes() { return parameterTypes; } public String getReturnType() { return returnType; } public void setName(String name) { this.name = name; } public void setParameters(List<TypeDefinition> parameters) { this.parameters = parameters; } public void setParameterTypes(String[] parameterTypes) { this.parameterTypes = formatTypes(parameterTypes); } public void setReturnType(String returnType) { this.returnType = formatType(returnType); } public List<String> getAnnotations() { if (annotations == null) { annotations = Collections.emptyList(); } return annotations; } public void setAnnotations(List<String> annotations) { this.annotations = annotations; } @Override public String toString() { return "MethodDefinition [name=" + name + ", parameterTypes=" + Arrays.toString(parameterTypes) + ", returnType=" + returnType + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MethodDefinition)) { return false; } MethodDefinition that = (MethodDefinition) o; return Objects.equals(getName(), that.getName()) && Arrays.equals(getParameterTypes(), that.getParameterTypes()) && Objects.equals(getReturnType(), that.getReturnType()); } @Override public int hashCode() { return Objects.hash(getName(), getReturnType(), Arrays.toString(getParameterTypes())); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.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.metadata.definition.model; import org.apache.dubbo.metadata.definition.util.ClassUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; /** * 2015/1/27. */ public class ServiceDefinition implements Serializable { /** * the canonical name of interface * * @see Class#getCanonicalName() */ private String canonicalName; /** * the location of class file * * @see ClassUtils#getCodeSource(Class) */ private String codeSource; private List<MethodDefinition> methods; /** * the definitions of type */ private List<TypeDefinition> types; /** * the definitions of annotations */ private List<String> annotations; public String getCanonicalName() { return canonicalName; } public String getCodeSource() { return codeSource; } public List<MethodDefinition> getMethods() { if (methods == null) { methods = new ArrayList<>(); } return methods; } public List<TypeDefinition> getTypes() { if (types == null) { types = new ArrayList<>(); } return types; } public String getUniqueId() { return canonicalName + "@" + codeSource; } public void setCanonicalName(String canonicalName) { this.canonicalName = canonicalName; } public void setCodeSource(String codeSource) { this.codeSource = codeSource; } public void setMethods(List<MethodDefinition> methods) { this.methods = methods; } public void setTypes(List<TypeDefinition> types) { this.types = types; } public List<String> getAnnotations() { if (annotations == null) { annotations = Collections.emptyList(); } return annotations; } public void setAnnotations(List<String> annotations) { this.annotations = annotations; } @Override public String toString() { return "ServiceDefinition [canonicalName=" + canonicalName + ", codeSource=" + codeSource + ", methods=" + methods + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ServiceDefinition)) { return false; } ServiceDefinition that = (ServiceDefinition) o; return Objects.equals(getCanonicalName(), that.getCanonicalName()) && Objects.equals(getCodeSource(), that.getCodeSource()) && Objects.equals(getMethods(), that.getMethods()) && Objects.equals(getTypes(), that.getTypes()); } @Override public int hashCode() { return Objects.hash(getCanonicalName(), getCodeSource(), getMethods(), getTypes()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.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.metadata.definition.model; import java.util.Map; /** * 2018/10/25 */ public class FullServiceDefinition extends ServiceDefinition { private Map<String, String> parameters; public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } @Override public String toString() { return "FullServiceDefinition{" + "parameters=" + parameters + "} " + super.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/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java
dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.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.metadata.definition.model; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.utils.StringUtils.replace; /** * 2015/1/27. */ public class TypeDefinition implements Serializable { /** * the name of type * * @see Class#getCanonicalName() * @see org.apache.dubbo.metadata.definition.util.ClassUtils#getCanonicalNameForParameterizedType(ParameterizedType) */ private String type; /** * the items(generic parameter) of Map/List(ParameterizedType) * <p> * if this type is not ParameterizedType, the items is null or empty */ private List<String> items; /** * the enum's value * <p> * If this type is not enum, enums is null or empty */ private List<String> enums; /** * the key is property name, * the value is property's type name */ private Map<String, String> properties; public TypeDefinition() {} public TypeDefinition(String type) { this.setType(type); } /** * Format the {@link String} array presenting Java types * * @param types the strings presenting Java types * @return new String array of Java types after be formatted * @since 2.7.9 */ public static String[] formatTypes(String[] types) { String[] newTypes = new String[types.length]; for (int i = 0; i < types.length; i++) { newTypes[i] = formatType(types[i]); } return newTypes; } /** * Format the {@link String} presenting Java type * * @param type the String presenting type * @return new String presenting Java type after be formatted * @since 2.7.9 */ public static String formatType(String type) { if (isGenericType(type)) { return formatGenericType(type); } return type; } /** * Replacing <code>", "</code> to <code>","</code> will not change the semantic of * {@link ParameterizedType#toString()} * * @param type * @return formatted type * @see sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl */ private static String formatGenericType(String type) { return replace(type, ", ", ","); } private static boolean isGenericType(String type) { return type.contains("<") && type.contains(">"); } public List<String> getEnums() { if (enums == null) { enums = new ArrayList<>(); } return enums; } public List<String> getItems() { if (items == null) { items = new ArrayList<>(); } return items; } public Map<String, String> getProperties() { if (properties == null) { properties = new HashMap<>(); } return properties; } public String getType() { return type; } public void setEnums(List<String> enums) { this.enums = enums; } public void setItems(List<String> items) { this.items = items; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public void setType(String type) { this.type = formatType(type); } @Override public String toString() { return "TypeDefinition [type=" + type + ", properties=" + properties + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TypeDefinition)) { return false; } TypeDefinition that = (TypeDefinition) o; return Objects.equals(getType(), that.getType()) && Objects.equals(getItems(), that.getItems()) && Objects.equals(getEnums(), that.getEnums()) && Objects.equals(getProperties(), that.getProperties()); } @Override public int hashCode() { return Objects.hash(getType(), getItems(), getEnums(), getProperties()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.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.rpc.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_RAW_RETURN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_GSON; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_PROTOBUF; public class ProtocolUtils { private static final ConcurrentMap<String, GroupServiceKeyCache> groupServiceKeyCacheMap = new ConcurrentHashMap<>(); private ProtocolUtils() {} public static String serviceKey(URL url) { return serviceKey(url.getPort(), url.getPath(), url.getVersion(), url.getGroup()); } public static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { serviceGroup = serviceGroup == null ? "" : serviceGroup; GroupServiceKeyCache groupServiceKeyCache = groupServiceKeyCacheMap.get(serviceGroup); if (groupServiceKeyCache == null) { groupServiceKeyCacheMap.putIfAbsent(serviceGroup, new GroupServiceKeyCache(serviceGroup)); groupServiceKeyCache = groupServiceKeyCacheMap.get(serviceGroup); } return groupServiceKeyCache.getServiceKey(serviceName, serviceVersion, port); } public static boolean isGeneric(String generic) { return StringUtils.isNotEmpty(generic) && (GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */ || GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase( generic) /* Streaming generalization call supporting jdk serialization */ || GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic) || GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic) || GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic) || GENERIC_RAW_RETURN.equalsIgnoreCase(generic)); } public static boolean isValidGenericValue(String generic) { return isGeneric(generic) || Boolean.FALSE.toString().equalsIgnoreCase(generic); } public static boolean isDefaultGenericSerialization(String generic) { return isGeneric(generic) && GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic); } public static boolean isJavaGenericSerialization(String generic) { return isGeneric(generic) && GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic); } public static boolean isGsonGenericSerialization(String generic) { return isGeneric(generic) && GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic); } public static boolean isBeanGenericSerialization(String generic) { return isGeneric(generic) && GENERIC_SERIALIZATION_BEAN.equals(generic); } public static boolean isProtobufGenericSerialization(String generic) { return isGeneric(generic) && GENERIC_SERIALIZATION_PROTOBUF.equals(generic); } public static boolean isGenericReturnRawResult(String generic) { return GENERIC_RAW_RETURN.equals(generic); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.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.rpc.support; import org.apache.dubbo.common.utils.StringUtils; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class GroupServiceKeyCache { private final String serviceGroup; // ConcurrentMap<serviceName, ConcurrentMap<serviceVersion, ConcurrentMap<port, String>>> private final ConcurrentMap<String, ConcurrentMap<String, ConcurrentMap<Integer, String>>> serviceKeyMap; public GroupServiceKeyCache(String serviceGroup) { this.serviceGroup = serviceGroup; this.serviceKeyMap = new ConcurrentHashMap<>(512); } public String getServiceKey(String serviceName, String serviceVersion, int port) { ConcurrentMap<String, ConcurrentMap<Integer, String>> versionMap = serviceKeyMap.get(serviceName); if (versionMap == null) { serviceKeyMap.putIfAbsent(serviceName, new ConcurrentHashMap<>()); versionMap = serviceKeyMap.get(serviceName); } serviceVersion = serviceVersion == null ? "" : serviceVersion; ConcurrentMap<Integer, String> portMap = versionMap.get(serviceVersion); if (portMap == null) { versionMap.putIfAbsent(serviceVersion, new ConcurrentHashMap<>()); portMap = versionMap.get(serviceVersion); } String serviceKey = portMap.get(port); if (serviceKey == null) { serviceKey = createServiceKey(serviceName, serviceVersion, port); portMap.put(port, serviceKey); } return serviceKey; } private String createServiceKey(String serviceName, String serviceVersion, int port) { StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(serviceGroup)) { buf.append(serviceGroup).append('/'); } buf.append(serviceName); if (StringUtils.isNotEmpty(serviceVersion) && !"0.0.0".equals(serviceVersion) && !"*".equals(serviceVersion)) { buf.append(':').append(serviceVersion); } buf.append(':').append(port); return buf.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/main/java/org/apache/dubbo/rpc/service/GenericService.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericService.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.rpc.service; import java.util.concurrent.CompletableFuture; /** * Generic service interface * * @export */ public interface GenericService { /** * Generic invocation * * @param method Method name, e.g. findPerson. If there are overridden methods, parameter info is * required, e.g. findPerson(java.lang.String) * @param parameterTypes Parameter types * @param args Arguments * @return invocation return value * @throws GenericException potential exception thrown from the invocation */ Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; default CompletableFuture<Object> $invokeAsync(String method, String[] parameterTypes, Object[] args) throws GenericException { Object object = $invoke(method, parameterTypes, args); if (object instanceof CompletableFuture) { return (CompletableFuture<Object>) object; } return CompletableFuture.completedFuture(object); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.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.rpc.service; import org.apache.dubbo.rpc.model.BuiltinServiceDetector; public class GenericServiceDetector implements BuiltinServiceDetector { @Override public Class<?> getService() { return GenericService.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/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.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.rpc.service; import org.apache.dubbo.rpc.model.ReflectionServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; public class ServiceDescriptorInternalCache { private static final ServiceDescriptor genericServiceDescriptor = new ReflectionServiceDescriptor(GenericService.class); private static final ServiceDescriptor echoServiceDescriptor = new ReflectionServiceDescriptor(EchoService.class); public static ServiceDescriptor genericService() { return genericServiceDescriptor; } public static ServiceDescriptor echoService() { return echoServiceDescriptor; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.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.rpc.service; import org.apache.dubbo.rpc.model.BuiltinServiceDetector; public class EchoServiceDetector implements BuiltinServiceDetector { @Override public Class<?> getService() { return EchoService.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/main/java/org/apache/dubbo/rpc/service/Destroyable.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/Destroyable.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.rpc.service; public interface Destroyable { void $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/main/java/org/apache/dubbo/rpc/service/GenericException.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericException.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.rpc.service; import org.apache.dubbo.common.utils.StringUtils; /** * GenericException * * @export */ public class GenericException extends RuntimeException { private static final long serialVersionUID = -1182299763306599962L; private String exceptionClass; private String exceptionMessage; public GenericException() {} public GenericException(String exceptionMessage) { super(exceptionMessage); this.exceptionMessage = exceptionMessage; } public GenericException(String exceptionClass, String exceptionMessage) { super(exceptionMessage); this.exceptionClass = exceptionClass; this.exceptionMessage = exceptionMessage; } public GenericException(Throwable cause) { super(StringUtils.toString(cause)); this.exceptionClass = cause.getClass().getName(); this.exceptionMessage = cause.getMessage(); } public GenericException(String message, Throwable cause, String exceptionClass, String exceptionMessage) { super(message, cause); this.exceptionClass = exceptionClass; this.exceptionMessage = exceptionMessage; } public String getExceptionClass() { return exceptionClass; } public void setExceptionClass(String exceptionClass) { this.exceptionClass = exceptionClass; } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.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.rpc.service; /** * Echo service. * @export */ public interface EchoService { /** * echo test. * * @param message message. * @return message. */ Object $echo(Object 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/main/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessor.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.rpc.model; import org.apache.dubbo.common.extension.ExtensionPostProcessor; public class ScopeModelAwareExtensionProcessor implements ExtensionPostProcessor, ScopeModelAccessor { private ScopeModel scopeModel; private FrameworkModel frameworkModel; private ApplicationModel applicationModel; private ModuleModel moduleModel; public ScopeModelAwareExtensionProcessor(ScopeModel scopeModel) { this.scopeModel = scopeModel; initialize(); } private void initialize() { // NOTE: Do not create a new model or use the default application/module model here! // Only the visible and only matching scope model can be injected, that is, module -> application -> framework. // The converse is a one-to-many relationship and cannot be injected. // One framework may have multiple applications, and one application may have multiple modules. // So, the spi extension/bean of application scope can be injected its application model and framework model, // but the spi extension/bean of framework scope cannot be injected an application or module model. if (scopeModel instanceof FrameworkModel) { frameworkModel = (FrameworkModel) scopeModel; } else if (scopeModel instanceof ApplicationModel) { applicationModel = (ApplicationModel) scopeModel; frameworkModel = applicationModel.getFrameworkModel(); } else if (scopeModel instanceof ModuleModel) { moduleModel = (ModuleModel) scopeModel; applicationModel = moduleModel.getApplicationModel(); frameworkModel = applicationModel.getFrameworkModel(); } } @Override public Object postProcessAfterInitialization(Object instance, String name) throws Exception { if (instance instanceof ScopeModelAware) { ScopeModelAware modelAware = (ScopeModelAware) instance; modelAware.setScopeModel(scopeModel); if (this.moduleModel != null) { modelAware.setModuleModel(this.moduleModel); } if (this.applicationModel != null) { modelAware.setApplicationModel(this.applicationModel); } if (this.frameworkModel != null) { modelAware.setFrameworkModel(this.frameworkModel); } } return instance; } @Override public ScopeModel getScopeModel() { return scopeModel; } @Override public FrameworkModel getFrameworkModel() { return frameworkModel; } @Override public ApplicationModel getApplicationModel() { return applicationModel; } @Override public ModuleModel getModuleModel() { return moduleModel; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/AsyncMethodInfo.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/AsyncMethodInfo.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.rpc.model; import java.lang.reflect.Method; public class AsyncMethodInfo { // callback instance when async-call is invoked private Object oninvokeInstance; // callback method when async-call is invoked private Method oninvokeMethod; // callback instance when async-call is returned private Object onreturnInstance; // callback method when async-call is returned private Method onreturnMethod; // callback instance when async-call has exception thrown private Object onthrowInstance; // callback method when async-call has exception thrown private Method onthrowMethod; public Object getOninvokeInstance() { return oninvokeInstance; } public void setOninvokeInstance(Object oninvokeInstance) { this.oninvokeInstance = oninvokeInstance; } public Method getOninvokeMethod() { return oninvokeMethod; } public void setOninvokeMethod(Method oninvokeMethod) { this.oninvokeMethod = oninvokeMethod; } public Object getOnreturnInstance() { return onreturnInstance; } public void setOnreturnInstance(Object onreturnInstance) { this.onreturnInstance = onreturnInstance; } public Method getOnreturnMethod() { return onreturnMethod; } public void setOnreturnMethod(Method onreturnMethod) { this.onreturnMethod = onreturnMethod; } public Object getOnthrowInstance() { return onthrowInstance; } public void setOnthrowInstance(Object onthrowInstance) { this.onthrowInstance = onthrowInstance; } public Method getOnthrowMethod() { return onthrowMethod; } public void setOnthrowMethod(Method onthrowMethod) { this.onthrowMethod = onthrowMethod; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.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.rpc.model; import org.apache.dubbo.common.BaseServiceMetadata; import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ReferenceConfigBase; import org.apache.dubbo.config.ServiceConfigBase; import java.util.Objects; import java.util.Set; public class ServiceModel { private String serviceKey; private Object proxyObject; private Runnable destroyRunner; private ClassLoader classLoader; private final ClassLoader interfaceClassLoader; private final ModuleModel moduleModel; private final ServiceDescriptor serviceModel; private AbstractInterfaceConfig config; private final ServiceMetadata serviceMetadata; public ServiceModel( Object proxyObject, String serviceKey, ServiceDescriptor serviceModel, ModuleModel moduleModel, ClassLoader interfaceClassLoader) { this(proxyObject, serviceKey, serviceModel, moduleModel, null, interfaceClassLoader); } public ServiceModel( Object proxyObject, String serviceKey, ServiceDescriptor serviceModel, ModuleModel moduleModel, ServiceMetadata serviceMetadata, ClassLoader interfaceClassLoader) { this.proxyObject = proxyObject; this.serviceKey = serviceKey; this.serviceModel = serviceModel; this.moduleModel = ScopeModelUtil.getModuleModel(moduleModel); this.serviceMetadata = serviceMetadata; this.interfaceClassLoader = interfaceClassLoader; if (serviceMetadata != null) { serviceMetadata.setServiceModel(this); } if (interfaceClassLoader != null) { this.classLoader = interfaceClassLoader; } if (this.classLoader == null) { this.classLoader = Thread.currentThread().getContextClassLoader(); } } @Deprecated public AbstractInterfaceConfig getConfig() { return config; } @Deprecated public void setConfig(AbstractInterfaceConfig config) { this.config = config; } /** * ServiceModel should be decoupled from AbstractInterfaceConfig and removed in a future version * @return */ @Deprecated public ReferenceConfigBase<?> getReferenceConfig() { if (config == null) { return null; } if (config instanceof ReferenceConfigBase) { return (ReferenceConfigBase<?>) config; } else { throw new IllegalArgumentException("Current ServiceModel is not a ConsumerModel"); } } /** * ServiceModel should be decoupled from AbstractInterfaceConfig and removed in a future version * @return */ @Deprecated public ServiceConfigBase<?> getServiceConfig() { if (config == null) { return null; } if (config instanceof ServiceConfigBase) { return (ServiceConfigBase<?>) config; } else { throw new IllegalArgumentException("Current ServiceModel is not a ProviderModel"); } } public String getServiceKey() { return serviceKey; } public void setProxyObject(Object proxyObject) { this.proxyObject = proxyObject; } public Object getProxyObject() { return proxyObject; } public ServiceDescriptor getServiceModel() { return serviceModel; } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } public ClassLoader getClassLoader() { return classLoader; } /** * Return all method models for the current service * * @return method model list */ public Set<MethodDescriptor> getAllMethods() { return serviceModel.getAllMethods(); } public Class<?> getServiceInterfaceClass() { return serviceModel.getServiceInterfaceClass(); } public void setServiceKey(String serviceKey) { this.serviceKey = serviceKey; if (serviceMetadata != null) { serviceMetadata.setServiceKey(serviceKey); serviceMetadata.setGroup(BaseServiceMetadata.groupFromServiceKey(serviceKey)); } } public String getServiceName() { return this.serviceMetadata.getServiceKey(); } /** * @return serviceMetadata */ public ServiceMetadata getServiceMetadata() { return serviceMetadata; } public ModuleModel getModuleModel() { return moduleModel; } public Runnable getDestroyRunner() { return destroyRunner; } public void setDestroyRunner(Runnable destroyRunner) { this.destroyRunner = destroyRunner; } public ClassLoader getInterfaceClassLoader() { return interfaceClassLoader; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServiceModel that = (ServiceModel) o; return Objects.equals(serviceKey, that.serviceKey) && Objects.equals(proxyObject, that.proxyObject) && Objects.equals(destroyRunner, that.destroyRunner) && Objects.equals(classLoader, that.classLoader) && Objects.equals(interfaceClassLoader, that.interfaceClassLoader) && Objects.equals(moduleModel, that.moduleModel) && Objects.equals(serviceModel, that.serviceModel) && Objects.equals(serviceMetadata, that.serviceMetadata); } @Override public int hashCode() { return Objects.hash( serviceKey, proxyObject, destroyRunner, classLoader, interfaceClassLoader, moduleModel, serviceModel, serviceMetadata); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.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.rpc.model; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import java.util.List; import java.util.Set; /** * ServiceModel and ServiceMetadata are to some extent duplicated with each other. We should merge them in the future. */ public interface ServiceDescriptor { FullServiceDefinition getFullServiceDefinition(String serviceKey); String getInterfaceName(); Class<?> getServiceInterfaceClass(); Set<MethodDescriptor> getAllMethods(); /** * Does not use Optional as return type to avoid potential performance decrease. * */ MethodDescriptor getMethod(String methodName, String params); /** * Does not use Optional as return type to avoid potential performance decrease. * */ MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes); List<MethodDescriptor> getMethods(String methodName); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.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.rpc.model; import org.apache.dubbo.common.URL; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; /** * ProviderModel is about published services */ public class ProviderModel extends ServiceModel { private final List<RegisterStatedURL> urls; private final Map<String, List<ProviderMethodModel>> methods = new HashMap<>(); /** * The url of the reference service */ private List<URL> serviceUrls = new ArrayList<>(); private volatile long lastInvokeTime = 0; public ProviderModel( String serviceKey, Object serviceInstance, ServiceDescriptor serviceDescriptor, ClassLoader interfaceClassLoader) { super(serviceInstance, serviceKey, serviceDescriptor, null, interfaceClassLoader); if (null == serviceInstance) { throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); } this.urls = new CopyOnWriteArrayList<>(); } public ProviderModel( String serviceKey, Object serviceInstance, ServiceDescriptor serviceDescriptor, ServiceMetadata serviceMetadata, ClassLoader interfaceClassLoader) { super(serviceInstance, serviceKey, serviceDescriptor, null, serviceMetadata, interfaceClassLoader); if (null == serviceInstance) { throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); } initMethod(serviceDescriptor.getServiceInterfaceClass()); this.urls = new ArrayList<>(1); } public ProviderModel( String serviceKey, Object serviceInstance, ServiceDescriptor serviceModel, ModuleModel moduleModel, ServiceMetadata serviceMetadata, ClassLoader interfaceClassLoader) { super(serviceInstance, serviceKey, serviceModel, moduleModel, serviceMetadata, interfaceClassLoader); if (null == serviceInstance) { throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); } initMethod(serviceModel.getServiceInterfaceClass()); this.urls = new ArrayList<>(1); } public Object getServiceInstance() { return getProxyObject(); } public List<RegisterStatedURL> getStatedUrl() { return urls; } public void addStatedUrl(RegisterStatedURL url) { this.urls.add(url); } public static class RegisterStatedURL { private volatile URL registryUrl; private volatile URL providerUrl; private volatile boolean registered; public RegisterStatedURL(URL providerUrl, URL registryUrl, boolean registered) { this.providerUrl = providerUrl; this.registered = registered; this.registryUrl = registryUrl; } public URL getProviderUrl() { return providerUrl; } public void setProviderUrl(URL providerUrl) { this.providerUrl = providerUrl; } public boolean isRegistered() { return registered; } public void setRegistered(boolean registered) { this.registered = registered; } public URL getRegistryUrl() { return registryUrl; } public void setRegistryUrl(URL registryUrl) { this.registryUrl = registryUrl; } } public List<ProviderMethodModel> getAllMethodModels() { List<ProviderMethodModel> result = new ArrayList<>(); for (List<ProviderMethodModel> models : methods.values()) { result.addAll(models); } return result; } public ProviderMethodModel getMethodModel(String methodName, String[] argTypes) { List<ProviderMethodModel> methodModels = methods.get(methodName); if (methodModels != null) { for (ProviderMethodModel methodModel : methodModels) { if (Arrays.equals(argTypes, methodModel.getMethodArgTypes())) { return methodModel; } } } return null; } public List<ProviderMethodModel> getMethodModelList(String methodName) { List<ProviderMethodModel> resultList = methods.get(methodName); return resultList == null ? Collections.emptyList() : resultList; } private void initMethod(Class<?> serviceInterfaceClass) { Method[] methodsToExport = serviceInterfaceClass.getMethods(); for (Method method : methodsToExport) { method.setAccessible(true); List<ProviderMethodModel> methodModels = methods.computeIfAbsent(method.getName(), k -> new ArrayList<>()); methodModels.add(new ProviderMethodModel(method)); } } public List<URL> getServiceUrls() { return serviceUrls; } public void setServiceUrls(List<URL> urls) { this.serviceUrls = urls; } public long getLastInvokeTime() { return lastInvokeTime; } public void updateLastInvokeTime() { this.lastInvokeTime = System.currentTimeMillis(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ProviderModel that = (ProviderModel) o; return Objects.equals(urls, that.urls) && Objects.equals(methods, that.methods); } @Override public int hashCode() { return Objects.hash(super.hashCode(), urls, methods); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.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.rpc.model; import java.lang.reflect.Method; import java.lang.reflect.Type; public interface MethodDescriptor { /** * Retrieves the method name. * <p> * In Protobuf scenarios, this name may start with an uppercase letter. * * @return the method name */ String getMethodName(); /** * Retrieves the Java method name. * <p> * In Protobuf scenarios, This name is typically converted to start with a lowercase letter for Java naming conventions. * * @return the Java method name as a String */ String getJavaMethodName(); String getParamDesc(); /** * duplicate filed as paramDesc, but with different format. */ String[] getCompatibleParamSignatures(); Class<?>[] getParameterClasses(); Class<?> getReturnClass(); Type[] getReturnTypes(); RpcType getRpcType(); boolean isGeneric(); /** * Only available for ReflectionMethod * * @return method */ Method getMethod(); void addAttribute(String key, Object value); Object getAttribute(String key); Class<?>[] getActualRequestTypes(); Class<?> getActualResponseType(); enum RpcType { UNARY, CLIENT_STREAM, SERVER_STREAM, BI_STREAM } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.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.rpc.model; public interface UnPack { /** * @param data byte array * @return object instance * @throws Exception exception */ Object unpack(byte[] data) throws Exception; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.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.rpc.model; /** * An accessor for scope model, it can be use in interface default methods to get scope model. */ public interface ScopeModelAccessor { ScopeModel getScopeModel(); default FrameworkModel getFrameworkModel() { return ScopeModelUtil.getFrameworkModel(getScopeModel()); } default ApplicationModel getApplicationModel() { return ScopeModelUtil.getApplicationModel(getScopeModel()); } default ModuleModel getModuleModel() { return ScopeModelUtil.getModuleModel(getScopeModel()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.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.rpc.model; import org.apache.dubbo.common.BaseServiceMetadata; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Notice, this class currently has no usage inside Dubbo. * * data related to service level such as name, version, classloader of business service, * security info, etc. Also, with a AttributeMap for extension. */ public class ServiceMetadata extends BaseServiceMetadata { private String defaultGroup; private Class<?> serviceType; private Object target; /** * will be transferred to remote side */ private final Map<String, Object> attachments = new ConcurrentHashMap<>(); /** * used locally */ private final ConcurrentHashMap<String, Object> attributeMap = new ConcurrentHashMap<>(); public ServiceMetadata(String serviceInterfaceName, String group, String version, Class<?> serviceType) { this.serviceInterfaceName = serviceInterfaceName; this.defaultGroup = group; this.group = group; this.version = version; this.serviceKey = buildServiceKey(serviceInterfaceName, group, version); this.serviceType = serviceType; } public ServiceMetadata() {} @Override public String getServiceKey() { return serviceKey; } public Map<String, Object> getAttachments() { return attachments; } public ConcurrentHashMap<String, Object> getAttributeMap() { return attributeMap; } public Object getAttribute(String key) { return attributeMap.get(key); } public void addAttribute(String key, Object value) { this.attributeMap.put(key, value); } public void addAttachment(String key, Object value) { this.attachments.put(key, value); } public Class<?> getServiceType() { return serviceType; } public String getDefaultGroup() { return defaultGroup; } public void setDefaultGroup(String defaultGroup) { this.defaultGroup = defaultGroup; } public void setServiceType(Class<?> serviceType) { this.serviceType = serviceType; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.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.rpc.model; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; /** * Model of dubbo framework, it can be shared with multiple applications. */ public class FrameworkModel extends ScopeModel { // ========================= Static Fields Start =================================== protected static final Logger LOGGER = LoggerFactory.getLogger(FrameworkModel.class); public static final String NAME = "FrameworkModel"; private static final AtomicLong index = new AtomicLong(1); private static final Object globalLock = new Object(); private static volatile FrameworkModel defaultInstance; private static final List<FrameworkModel> allInstances = new CopyOnWriteArrayList<>(); // ========================= Static Fields End =================================== // internal app index is 0, default app index is 1 private final AtomicLong appIndex = new AtomicLong(0); private volatile ApplicationModel defaultAppModel; private final List<ApplicationModel> applicationModels = new CopyOnWriteArrayList<>(); private final List<ApplicationModel> pubApplicationModels = new CopyOnWriteArrayList<>(); private final FrameworkServiceRepository serviceRepository; private final ApplicationModel internalApplicationModel; private final ReentrantLock destroyLock = new ReentrantLock(); /** * Use {@link FrameworkModel#newModel()} to create a new model */ public FrameworkModel() { super(null, ExtensionScope.FRAMEWORK, false); synchronized (globalLock) { synchronized (instLock) { this.setInternalId(String.valueOf(index.getAndIncrement())); // register FrameworkModel instance early allInstances.add(this); if (LOGGER.isInfoEnabled()) { LOGGER.info(getDesc() + " is created"); } initialize(); TypeDefinitionBuilder.initBuilders(this); serviceRepository = new FrameworkServiceRepository(this); ExtensionLoader<ScopeModelInitializer> initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set<ScopeModelInitializer> initializers = initializerExtensionLoader.getSupportedExtensionInstances(); for (ScopeModelInitializer initializer : initializers) { initializer.initializeFrameworkModel(this); } internalApplicationModel = new ApplicationModel(this, true); internalApplicationModel .getApplicationConfigManager() .setApplication(new ApplicationConfig( internalApplicationModel, CommonConstants.DUBBO_INTERNAL_APPLICATION)); internalApplicationModel.setModelName(CommonConstants.DUBBO_INTERNAL_APPLICATION); } } } @Override protected void onDestroy() { synchronized (instLock) { if (defaultInstance == this) { // NOTE: During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or // ApplicationModel.defaultModel() // will return a broken model, maybe cause unpredictable problem. if (LOGGER.isInfoEnabled()) { LOGGER.info("Destroying default framework model: " + getDesc()); } } if (LOGGER.isInfoEnabled()) { LOGGER.info(getDesc() + " is destroying ..."); } // destroy all application model for (ApplicationModel applicationModel : new ArrayList<>(applicationModels)) { applicationModel.destroy(); } // check whether all application models are destroyed checkApplicationDestroy(); // notify destroy and clean framework resources // see org.apache.dubbo.config.deploy.FrameworkModelCleaner notifyDestroy(); if (LOGGER.isInfoEnabled()) { LOGGER.info(getDesc() + " is destroyed"); } // remove from allInstances and reset default FrameworkModel synchronized (globalLock) { allInstances.remove(this); resetDefaultFrameworkModel(); } // if all FrameworkModels are destroyed, clean global static resources, shutdown dubbo completely destroyGlobalResources(); } } private void checkApplicationDestroy() { synchronized (instLock) { if (applicationModels.size() > 0) { List<String> remainApplications = applicationModels.stream().map(ScopeModel::getDesc).collect(Collectors.toList()); throw new IllegalStateException( "Not all application models are completely destroyed, remaining " + remainApplications.size() + " application models may be created during destruction: " + remainApplications); } } } private void destroyGlobalResources() { synchronized (globalLock) { if (allInstances.isEmpty()) { GlobalResourcesRepository.getInstance().destroy(); } } } /** * During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or ApplicationModel.defaultModel() * will return a broken model, maybe cause unpredictable problem. * Recommendation: Avoid using the default model as much as possible. * @return the global default FrameworkModel */ public static FrameworkModel defaultModel() { FrameworkModel instance = defaultInstance; if (instance == null) { synchronized (globalLock) { resetDefaultFrameworkModel(); if (defaultInstance == null) { defaultInstance = new FrameworkModel(); } instance = defaultInstance; } } Assert.notNull(instance, "Default FrameworkModel is null"); return instance; } /** * Get all framework model instances * @return */ public static List<FrameworkModel> getAllInstances() { synchronized (globalLock) { return Collections.unmodifiableList(new ArrayList<>(allInstances)); } } /** * Destroy all framework model instances, shutdown dubbo engine completely. */ public static void destroyAll() { synchronized (globalLock) { for (FrameworkModel frameworkModel : new ArrayList<>(allInstances)) { frameworkModel.destroy(); } } } public ApplicationModel newApplication() { synchronized (instLock) { return new ApplicationModel(this); } } /** * Get or create default application model * @return */ public ApplicationModel defaultApplication() { ApplicationModel appModel = this.defaultAppModel; if (appModel == null) { // check destroyed before acquire inst lock, avoid blocking during destroying checkDestroyed(); resetDefaultAppModel(); if ((appModel = this.defaultAppModel) == null) { synchronized (instLock) { if (this.defaultAppModel == null) { this.defaultAppModel = newApplication(); } appModel = this.defaultAppModel; } } } Assert.notNull(appModel, "Default ApplicationModel is null"); return appModel; } ApplicationModel getDefaultAppModel() { return defaultAppModel; } void addApplication(ApplicationModel applicationModel) { // can not add new application if it's destroying checkDestroyed(); synchronized (instLock) { if (!this.applicationModels.contains(applicationModel)) { applicationModel.setInternalId(buildInternalId(getInternalId(), appIndex.getAndIncrement())); this.applicationModels.add(applicationModel); if (!applicationModel.isInternal()) { this.pubApplicationModels.add(applicationModel); } } } } void removeApplication(ApplicationModel model) { synchronized (instLock) { this.applicationModels.remove(model); if (!model.isInternal()) { this.pubApplicationModels.remove(model); } resetDefaultAppModel(); } } /** * Protocols are special resources that need to be destroyed as soon as possible. * * Since connections inside protocol are not classified by applications, trying to destroy protocols in advance might only work for singleton application scenario. */ void tryDestroyProtocols() { synchronized (instLock) { if (pubApplicationModels.size() == 0) { notifyProtocolDestroy(); } } } void tryDestroy() { synchronized (instLock) { if (pubApplicationModels.size() == 0) { destroy(); } } } private void checkDestroyed() { if (isDestroyed()) { throw new IllegalStateException("FrameworkModel is destroyed"); } } private void resetDefaultAppModel() { synchronized (instLock) { if (this.defaultAppModel != null && !this.defaultAppModel.isDestroyed()) { return; } ApplicationModel oldDefaultAppModel = this.defaultAppModel; if (pubApplicationModels.size() > 0) { this.defaultAppModel = pubApplicationModels.get(0); } else { this.defaultAppModel = null; } if (defaultInstance == this && oldDefaultAppModel != this.defaultAppModel) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Reset global default application from " + safeGetModelDesc(oldDefaultAppModel) + " to " + safeGetModelDesc(this.defaultAppModel)); } } } } private static void resetDefaultFrameworkModel() { synchronized (globalLock) { if (defaultInstance != null && !defaultInstance.isDestroyed()) { return; } FrameworkModel oldDefaultFrameworkModel = defaultInstance; if (allInstances.size() > 0) { defaultInstance = allInstances.get(0); } else { defaultInstance = null; } if (oldDefaultFrameworkModel != defaultInstance) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Reset global default framework from " + safeGetModelDesc(oldDefaultFrameworkModel) + " to " + safeGetModelDesc(defaultInstance)); } } } } private static String safeGetModelDesc(ScopeModel scopeModel) { return scopeModel != null ? scopeModel.getDesc() : null; } /** * Get all application models except for the internal application model. */ public List<ApplicationModel> getApplicationModels() { synchronized (globalLock) { return Collections.unmodifiableList(pubApplicationModels); } } /** * Get all application models including the internal application model. */ public List<ApplicationModel> getAllApplicationModels() { synchronized (globalLock) { return Collections.unmodifiableList(applicationModels); } } public ApplicationModel getInternalApplicationModel() { return internalApplicationModel; } public FrameworkServiceRepository getServiceRepository() { return serviceRepository; } @Override protected Lock acquireDestroyLock() { return destroyLock; } @Override public Environment modelEnvironment() { throw new UnsupportedOperationException("Environment is inaccessible for FrameworkModel"); } @Override protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) { return super.checkIfClassLoaderCanRemoved(classLoader) && applicationModels.stream() .noneMatch(applicationModel -> applicationModel.containsClassLoader(classLoader)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelUtil.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelUtil.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.rpc.model; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; public class ScopeModelUtil { public static <T> ScopeModel getOrDefault(ScopeModel scopeModel, Class<T> type) { if (scopeModel != null) { return scopeModel; } return getDefaultScopeModel(type); } private static <T> ScopeModel getDefaultScopeModel(Class<T> type) { SPI spi = type.getAnnotation(SPI.class); if (spi == null) { throw new IllegalArgumentException("SPI annotation not found for class: " + type.getName()); } switch (spi.scope()) { case FRAMEWORK: return FrameworkModel.defaultModel(); case APPLICATION: return ApplicationModel.defaultModel(); case MODULE: return ApplicationModel.defaultModel().getDefaultModule(); default: throw new IllegalStateException("Unable to get default scope model for type: " + type.getName()); } } public static ModuleModel getModuleModel(ScopeModel scopeModel) { if (scopeModel == null) { return ApplicationModel.defaultModel().getDefaultModule(); } if (scopeModel instanceof ModuleModel) { return (ModuleModel) scopeModel; } else { throw new IllegalArgumentException("Unable to get ModuleModel from " + scopeModel); } } public static ApplicationModel getApplicationModel(ScopeModel scopeModel) { return getOrDefaultApplicationModel(scopeModel); } public static ApplicationModel getOrDefaultApplicationModel(ScopeModel scopeModel) { if (scopeModel == null) { return ApplicationModel.defaultModel(); } return getOrNullApplicationModel(scopeModel); } public static ApplicationModel getOrNullApplicationModel(ScopeModel scopeModel) { if (scopeModel == null) { return null; } if (scopeModel instanceof ApplicationModel) { return (ApplicationModel) scopeModel; } else if (scopeModel instanceof ModuleModel) { ModuleModel moduleModel = (ModuleModel) scopeModel; return moduleModel.getApplicationModel(); } else { throw new IllegalArgumentException("Unable to get ApplicationModel from " + scopeModel); } } public static FrameworkModel getFrameworkModel(ScopeModel scopeModel) { if (scopeModel == null) { return FrameworkModel.defaultModel(); } if (scopeModel instanceof ApplicationModel) { return ((ApplicationModel) scopeModel).getFrameworkModel(); } else if (scopeModel instanceof ModuleModel) { ModuleModel moduleModel = (ModuleModel) scopeModel; return moduleModel.getApplicationModel().getFrameworkModel(); } else if (scopeModel instanceof FrameworkModel) { return (FrameworkModel) scopeModel; } else { throw new IllegalArgumentException("Unable to get FrameworkModel from " + scopeModel); } } public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type, ScopeModel scopeModel) { if (scopeModel != null) { return scopeModel.getExtensionLoader(type); } else { SPI spi = type.getAnnotation(SPI.class); if (spi == null) { throw new IllegalArgumentException("SPI annotation not found for class: " + type.getName()); } switch (spi.scope()) { case FRAMEWORK: return FrameworkModel.defaultModel().getExtensionLoader(type); case APPLICATION: return ApplicationModel.defaultModel().getExtensionLoader(type); case MODULE: return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(type); default: throw new IllegalArgumentException("Unable to get ExtensionLoader for type: " + type.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/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.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.rpc.model; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collections; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; import static org.apache.dubbo.common.utils.MethodUtils.toShortString; public class ReflectionMethodDescriptor implements MethodDescriptor { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReflectionMethodDescriptor.class); private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>(); public final String methodName; private final String[] compatibleParamSignatures; private final Class<?>[] parameterClasses; private final Class<?> returnClass; private final Type[] returnTypes; private final String paramDesc; private final Method method; private final boolean generic; private final RpcType rpcType; private Class<?>[] actualRequestTypes; private Class<?> actualResponseType; public ReflectionMethodDescriptor(Method method) { this.method = method; this.methodName = method.getName(); this.parameterClasses = method.getParameterTypes(); this.returnClass = method.getReturnType(); Type[] returnTypesResult; try { returnTypesResult = ReflectUtils.getReturnTypes(method); } catch (Throwable throwable) { logger.error( COMMON_REFLECTIVE_OPERATION_FAILED, "", "", "fail to get return types. Method name: " + methodName + " Declaring class:" + method.getDeclaringClass().getName(), throwable); returnTypesResult = new Type[] {returnClass, returnClass}; } this.returnTypes = returnTypesResult; this.paramDesc = ReflectUtils.getDesc(parameterClasses); this.compatibleParamSignatures = Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new); this.generic = (methodName.equals($INVOKE) || methodName.equals($INVOKE_ASYNC)) && parameterClasses.length == 3; this.rpcType = determineRpcType(); } private RpcType determineRpcType() { if (generic) { return RpcType.UNARY; } if (parameterClasses.length > 2) { return RpcType.UNARY; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (parameterClasses.length == 1 && isStreamType(parameterClasses[0]) && isStreamType(returnClass)) { this.actualRequestTypes = new Class<?>[] { obtainActualTypeInStreamObserver( ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]) }; actualResponseType = obtainActualTypeInStreamObserver( ((ParameterizedType) genericParameterTypes[0]).getActualTypeArguments()[0]); return RpcType.BI_STREAM; } boolean returnIsVoid = returnClass.getName().equals(void.class.getName()); if (returnIsVoid && parameterClasses.length == 1 && isStreamType(parameterClasses[0])) { actualRequestTypes = Collections.emptyList().toArray(new Class<?>[0]); actualResponseType = obtainActualTypeInStreamObserver( ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]); return RpcType.SERVER_STREAM; } if (returnIsVoid && parameterClasses.length == 2 && !isStreamType(parameterClasses[0]) && isStreamType(parameterClasses[1])) { actualRequestTypes = parameterClasses; actualResponseType = obtainActualTypeInStreamObserver( ((ParameterizedType) method.getGenericParameterTypes()[1]).getActualTypeArguments()[0]); return RpcType.SERVER_STREAM; } if (Arrays.stream(parameterClasses).anyMatch(this::isStreamType) || isStreamType(returnClass)) { throw new IllegalStateException( "Bad stream method signature. method(" + methodName + ":" + paramDesc + ")"); } // Can not determine client stream because it has same signature with bi_stream return RpcType.UNARY; } private boolean isStreamType(Class<?> classType) { return StreamObserver.class.isAssignableFrom(classType); } @Override public String getMethodName() { return methodName; } @Override public String getJavaMethodName() { return method.getName(); } @Override public Method getMethod() { return method; } @Override public String[] getCompatibleParamSignatures() { return compatibleParamSignatures; } @Override public Class<?>[] getParameterClasses() { return parameterClasses; } @Override public String getParamDesc() { return paramDesc; } @Override public Class<?> getReturnClass() { return returnClass; } @Override public Type[] getReturnTypes() { return returnTypes; } @Override public RpcType getRpcType() { return rpcType; } @Override public boolean isGeneric() { return generic; } public void addAttribute(String key, Object value) { this.attributeMap.put(key, value); } public Object getAttribute(String key) { return this.attributeMap.get(key); } @Override public Class<?>[] getActualRequestTypes() { return actualRequestTypes; } @Override public Class<?> getActualResponseType() { return actualResponseType; } private Class<?> obtainActualTypeInStreamObserver(Type typeInStreamObserver) { return (Class<?>) (typeInStreamObserver instanceof ParameterizedType ? ((ParameterizedType) typeInStreamObserver).getRawType() : typeInStreamObserver); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReflectionMethodDescriptor that = (ReflectionMethodDescriptor) o; return generic == that.generic && Objects.equals(method, that.method) && Objects.equals(paramDesc, that.paramDesc) && Arrays.equals(compatibleParamSignatures, that.compatibleParamSignatures) && Arrays.equals(parameterClasses, that.parameterClasses) && Objects.equals(returnClass, that.returnClass) && Arrays.equals(returnTypes, that.returnTypes) && Objects.equals(methodName, that.methodName) && Objects.equals(attributeMap, that.attributeMap); } @Override public int hashCode() { int result = Objects.hash(method, paramDesc, returnClass, methodName, generic, attributeMap); result = 31 * result + Arrays.hashCode(compatibleParamSignatures); result = 31 * result + Arrays.hashCode(parameterClasses); result = 31 * result + Arrays.hashCode(returnTypes); return result; } @Override public String toString() { return "ReflectionMethodDescriptor{method='" + toShortString(method) + "', rpcType=" + rpcType + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.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.rpc.model; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.config.ReferenceConfigBase; import org.apache.dubbo.config.ServiceConfigBase; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; /** * Service repository for module */ public class ModuleServiceRepository { private final ModuleModel moduleModel; /** * services */ private final ConcurrentMap<String, List<ServiceDescriptor>> services = new ConcurrentHashMap<>(); /** * consumers ( key - group/interface:version value - consumerModel list) */ private final ConcurrentMap<String, List<ConsumerModel>> consumers = new ConcurrentHashMap<>(); /** * providers */ private final ConcurrentMap<String, ProviderModel> providers = new ConcurrentHashMap<>(); private final FrameworkServiceRepository frameworkServiceRepository; public ModuleServiceRepository(ModuleModel moduleModel) { this.moduleModel = moduleModel; frameworkServiceRepository = ScopeModelUtil.getFrameworkModel(moduleModel).getServiceRepository(); } public ModuleModel getModuleModel() { return moduleModel; } /** * @deprecated Replaced to {@link ModuleServiceRepository#registerConsumer(ConsumerModel)} */ @Deprecated public void registerConsumer( String serviceKey, ServiceDescriptor serviceDescriptor, ReferenceConfigBase<?> rc, Object proxy, ServiceMetadata serviceMetadata) { ClassLoader classLoader = null; if (rc != null) { classLoader = rc.getInterfaceClassLoader(); } ConsumerModel consumerModel = new ConsumerModel( serviceMetadata.getServiceKey(), proxy, serviceDescriptor, serviceMetadata, null, classLoader); this.registerConsumer(consumerModel); } public void registerConsumer(ConsumerModel consumerModel) { ConcurrentHashMapUtils.computeIfAbsent( consumers, consumerModel.getServiceKey(), (serviceKey) -> new CopyOnWriteArrayList<>()) .add(consumerModel); } /** * @deprecated Replaced to {@link ModuleServiceRepository#registerProvider(ProviderModel)} */ @Deprecated public void registerProvider( String serviceKey, Object serviceInstance, ServiceDescriptor serviceModel, ServiceConfigBase<?> serviceConfig, ServiceMetadata serviceMetadata) { ClassLoader classLoader = null; Class<?> cla = null; if (serviceConfig != null) { classLoader = serviceConfig.getInterfaceClassLoader(); cla = serviceConfig.getInterfaceClass(); } ProviderModel providerModel = new ProviderModel(serviceKey, serviceInstance, serviceModel, serviceMetadata, classLoader); this.registerProvider(providerModel); } public void registerProvider(ProviderModel providerModel) { providers.putIfAbsent(providerModel.getServiceKey(), providerModel); frameworkServiceRepository.registerProvider(providerModel); } public ServiceDescriptor registerService(ServiceDescriptor serviceDescriptor) { return registerService(serviceDescriptor.getServiceInterfaceClass(), serviceDescriptor); } public ServiceDescriptor registerService(Class<?> interfaceClazz) { ServiceDescriptor serviceDescriptor = new ReflectionServiceDescriptor(interfaceClazz); return registerService(interfaceClazz, serviceDescriptor); } public ServiceDescriptor registerService(Class<?> interfaceClazz, ServiceDescriptor serviceDescriptor) { List<ServiceDescriptor> serviceDescriptors = ConcurrentHashMapUtils.computeIfAbsent( services, interfaceClazz.getName(), k -> new CopyOnWriteArrayList<>()); synchronized (serviceDescriptors) { Optional<ServiceDescriptor> previous = serviceDescriptors.stream() .filter(s -> s.getServiceInterfaceClass().equals(interfaceClazz)) .findFirst(); if (previous.isPresent()) { return previous.get(); } else { serviceDescriptors.add(serviceDescriptor); return serviceDescriptor; } } } /** * See {@link #registerService(Class)} * <p> * we assume: * 1. services with different interfaces are not allowed to have the same path. * 2. services share the same interface but has different group/version can share the same path. * 3. path's default value is the name of the interface. * * @param path * @param interfaceClass * @return */ public ServiceDescriptor registerService(String path, Class<?> interfaceClass) { ServiceDescriptor serviceDescriptor = registerService(interfaceClass); // if path is different with interface name, add extra path mapping if (!interfaceClass.getName().equals(path)) { List<ServiceDescriptor> serviceDescriptors = ConcurrentHashMapUtils.computeIfAbsent(services, path, _k -> new CopyOnWriteArrayList<>()); synchronized (serviceDescriptors) { Optional<ServiceDescriptor> previous = serviceDescriptors.stream() .filter(s -> s.getServiceInterfaceClass().equals(serviceDescriptor.getServiceInterfaceClass())) .findFirst(); if (previous.isPresent()) { return previous.get(); } else { serviceDescriptors.add(serviceDescriptor); return serviceDescriptor; } } } return serviceDescriptor; } @Deprecated public void reRegisterProvider(String newServiceKey, String serviceKey) { ProviderModel providerModel = this.providers.get(serviceKey); frameworkServiceRepository.unregisterProvider(providerModel); providerModel.setServiceKey(newServiceKey); this.providers.putIfAbsent(newServiceKey, providerModel); frameworkServiceRepository.registerProvider(providerModel); this.providers.remove(serviceKey); } @Deprecated public void reRegisterConsumer(String newServiceKey, String serviceKey) { List<ConsumerModel> consumerModel = this.consumers.get(serviceKey); consumerModel.forEach(c -> c.setServiceKey(newServiceKey)); ConcurrentHashMapUtils.computeIfAbsent(this.consumers, newServiceKey, (k) -> new CopyOnWriteArrayList<>()) .addAll(consumerModel); this.consumers.remove(serviceKey); } public void unregisterService(Class<?> interfaceClazz) { // TODO remove unregisterService(interfaceClazz.getName()); } public void unregisterService(String path) { services.remove(path); } public void unregisterProvider(ProviderModel providerModel) { frameworkServiceRepository.unregisterProvider(providerModel); providers.remove(providerModel.getServiceKey()); } public void unregisterConsumer(ConsumerModel consumerModel) { consumers.get(consumerModel.getServiceKey()).remove(consumerModel); } public List<ServiceDescriptor> getAllServices() { List<ServiceDescriptor> serviceDescriptors = services.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); return Collections.unmodifiableList(serviceDescriptors); } public ServiceDescriptor getService(String serviceName) { // TODO, may need to distinguish service by class loader. List<ServiceDescriptor> serviceDescriptors = services.get(serviceName); if (CollectionUtils.isEmpty(serviceDescriptors)) { return null; } return serviceDescriptors.get(0); } public ServiceDescriptor lookupService(String interfaceName) { if (interfaceName != null && services.containsKey(interfaceName)) { List<ServiceDescriptor> serviceDescriptors = services.get(interfaceName); return serviceDescriptors.size() > 0 ? serviceDescriptors.get(0) : null; } else { return null; } } public MethodDescriptor lookupMethod(String interfaceName, String methodName) { ServiceDescriptor serviceDescriptor = lookupService(interfaceName); if (serviceDescriptor == null) { return null; } List<MethodDescriptor> methods = serviceDescriptor.getMethods(methodName); if (CollectionUtils.isEmpty(methods)) { return null; } return methods.iterator().next(); } public List<ProviderModel> getExportedServices() { return Collections.unmodifiableList(new ArrayList<>(providers.values())); } public ProviderModel lookupExportedService(String serviceKey) { return providers.get(serviceKey); } public List<ConsumerModel> getReferredServices() { List<ConsumerModel> consumerModels = consumers.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); return Collections.unmodifiableList(consumerModels); } /** * @deprecated Replaced to {@link ModuleServiceRepository#lookupReferredServices(String)} */ @Deprecated public ConsumerModel lookupReferredService(String serviceKey) { if (consumers.containsKey(serviceKey)) { List<ConsumerModel> consumerModels = consumers.get(serviceKey); return consumerModels.size() > 0 ? consumerModels.get(0) : null; } else { return null; } } public List<ConsumerModel> lookupReferredServices(String serviceKey) { return consumers.get(serviceKey); } public void destroy() { for (ProviderModel providerModel : providers.values()) { frameworkServiceRepository.unregisterProvider(providerModel); } providers.clear(); consumers.clear(); services.clear(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelDestroyListener.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelDestroyListener.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.rpc.model; public interface ScopeModelDestroyListener<T extends ScopeModel> { void onDestroy(T scopeModel); default boolean isProtocol() { return false; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.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.rpc.model; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; public class StubMethodDescriptor implements MethodDescriptor, PackableMethod { private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>(); private final String methodName; private final String javaMethodName; private final String[] compatibleParamSignatures; private final Class<?>[] parameterClasses; private final Class<?> returnClass; private final Type[] returnTypes; private final String paramDesc; private final RpcType rpcType; private final Pack requestPack; private final Pack responsePack; private final UnPack requestUnpack; private final UnPack responseUnpack; public StubMethodDescriptor( String methodName, Class<?> requestClass, Class<?> responseClass, RpcType rpcType, Pack requestPack, Pack responsePack, UnPack requestUnpack, UnPack responseUnpack) { this.methodName = methodName; this.javaMethodName = toJavaMethodName(methodName); this.rpcType = rpcType; this.requestPack = requestPack; this.responsePack = responsePack; this.responseUnpack = responseUnpack; this.requestUnpack = requestUnpack; this.parameterClasses = new Class<?>[] {requestClass}; this.returnClass = responseClass; this.paramDesc = ReflectUtils.getDesc(parameterClasses); this.compatibleParamSignatures = Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new); this.returnTypes = new Type[] {responseClass, responseClass}; } @Override public String getMethodName() { return methodName; } @Override public String getJavaMethodName() { return javaMethodName; } @Override public String getParamDesc() { return paramDesc; } @Override public String[] getCompatibleParamSignatures() { return compatibleParamSignatures; } @Override public Class<?>[] getParameterClasses() { return parameterClasses; } @Override public Class<?> getReturnClass() { return returnClass; } @Override public Type[] getReturnTypes() { return returnTypes; } @Override public RpcType getRpcType() { return rpcType; } @Override public boolean isGeneric() { return false; } @Override public Method getMethod() { return null; } @Override public void addAttribute(String key, Object value) { this.attributeMap.put(key, value); } @Override public Object getAttribute(String key) { return this.attributeMap.get(key); } @Override public Class<?>[] getActualRequestTypes() { return this.parameterClasses; } @Override public Class<?> getActualResponseType() { return this.returnClass; } @Override public Pack getRequestPack() { return requestPack; } @Override public Pack getResponsePack() { return responsePack; } @Override public UnPack getResponseUnpack() { return responseUnpack; } @Override public UnPack getRequestUnpack() { return requestUnpack; } @Override public String toString() { return "StubMethodDescriptor{" + "method=" + methodName + '(' + (parameterClasses.length > 0 ? parameterClasses[0].getSimpleName() : "") + "), rpcType='" + rpcType + "'}"; } private static String toJavaMethodName(String methodName) { char ch = methodName.charAt(0); return Character.isUpperCase(ch) ? Character.toLowerCase(ch) + methodName.substring(1) : methodName; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.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.rpc.model; /** * An interface to inject FrameworkModel/ApplicationModel/ModuleModel for SPI extensions and internal beans. */ public interface ScopeModelAware { /** * Override this method if you need get the scope model (maybe one of FrameworkModel/ApplicationModel/ModuleModel). * @param scopeModel */ default void setScopeModel(ScopeModel scopeModel) {} /** * Override this method if you just need framework model * @param frameworkModel */ default void setFrameworkModel(FrameworkModel frameworkModel) {} /** * Override this method if you just need application model * @param applicationModel */ default void setApplicationModel(ApplicationModel applicationModel) {} /** * Override this method if you just need module model * @param moduleModel */ default void setModuleModel(ModuleModel moduleModel) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.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.rpc.model; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.FRAMEWORK) public interface PackableMethodFactory { PackableMethod create(MethodDescriptor methodDescriptor, URL url, String contentType); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeClassLoaderListener.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeClassLoaderListener.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.rpc.model; public interface ScopeClassLoaderListener<T extends ScopeModel> { void onAddClassLoader(T scopeModel, ClassLoader classLoader); void onRemoveClassLoader(T scopeModel, ClassLoader classLoader); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.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.rpc.model; public interface WrapperUnPack extends UnPack { default Object unpack(byte[] data) throws Exception { return unpack(data, false); } Object unpack(byte[] data, boolean isReturnTriException) throws Exception; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.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.rpc.model; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; /** * Replaced with {@link MethodDescriptor} */ @Deprecated public class ConsumerMethodModel { private final Method method; // private final boolean isCallBack; // private final boolean isFuture; private final String[] parameterTypes; private final Class<?>[] parameterClasses; private final Class<?> returnClass; private final String methodName; private final boolean generic; private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>(); public ConsumerMethodModel(Method method) { this.method = method; this.parameterClasses = method.getParameterTypes(); this.returnClass = method.getReturnType(); this.parameterTypes = this.createParamSignature(parameterClasses); this.methodName = method.getName(); this.generic = methodName.equals($INVOKE) && parameterTypes != null && parameterTypes.length == 3; } public Method getMethod() { return method; } // public ConcurrentMap<String, Object> getAttributeMap() { // return attributeMap; // } public void addAttribute(String key, Object value) { this.attributeMap.put(key, value); } public Object getAttribute(String key) { return this.attributeMap.get(key); } public Class<?> getReturnClass() { return returnClass; } public String getMethodName() { return methodName; } public String[] getParameterTypes() { return parameterTypes; } private String[] createParamSignature(Class<?>[] args) { if (args == null || args.length == 0) { return new String[] {}; } String[] paramSig = new String[args.length]; for (int x = 0; x < args.length; x++) { paramSig[x] = args[x].getName(); } return paramSig; } public boolean isGeneric() { return generic; } public Class<?>[] getParameterClasses() { return parameterClasses; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.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.rpc.model; /** * A packable method is used to customize serialization for methods. It can provide a common wrapper * for RESP / Protobuf. */ public interface PackableMethod { default Object parseRequest(byte[] data) throws Exception { return getRequestUnpack().unpack(data); } default Object parseResponse(byte[] data) throws Exception { return parseResponse(data, false); } default Object parseResponse(byte[] data, boolean isReturnTriException) throws Exception { UnPack unPack = getResponseUnpack(); if (unPack instanceof WrapperUnPack) { return ((WrapperUnPack) unPack).unpack(data, isReturnTriException); } return unPack.unpack(data); } default byte[] packRequest(Object request) throws Exception { return getRequestPack().pack(request); } default byte[] packResponse(Object response) throws Exception { return getResponsePack().pack(response); } default boolean needWrapper() { return false; } Pack getRequestPack(); Pack getResponsePack(); UnPack getResponseUnpack(); UnPack getRequestUnpack(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderMethodModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderMethodModel.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.rpc.model; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Replaced with {@link MethodDescriptor} */ @Deprecated public class ProviderMethodModel { private final Method method; private final String methodName; private final Class<?>[] parameterClasses; private final String[] methodArgTypes; private final Type[] genericParameterTypes; private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>(); public ProviderMethodModel(Method method) { this.method = method; this.methodName = method.getName(); this.parameterClasses = method.getParameterTypes(); this.methodArgTypes = getArgTypes(method); this.genericParameterTypes = method.getGenericParameterTypes(); } public Method getMethod() { return method; } public String getMethodName() { return methodName; } public String[] getMethodArgTypes() { return methodArgTypes; } public ConcurrentMap<String, Object> getAttributeMap() { return attributeMap; } private static String[] getArgTypes(Method method) { String[] methodArgTypes = new String[0]; Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length > 0) { methodArgTypes = new String[parameterTypes.length]; int index = 0; for (Class<?> paramType : parameterTypes) { methodArgTypes[index++] = paramType.getName(); } } return methodArgTypes; } public Class<?>[] getParameterClasses() { return parameterClasses; } public Type[] getGenericParameterTypes() { return genericParameterTypes; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.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.rpc.model; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.FRAMEWORK) public interface BuiltinServiceDetector { Class<?> getService(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.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.rpc.model; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.StringUtils; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNABLE_DESTROY_MODEL; @SuppressWarnings({"unchecked", "rawtypes"}) public abstract class ScopeModel implements ExtensionAccessor { protected static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ScopeModel.class); /** * The internal id is used to represent the hierarchy of the model tree, such as: * <ol> * <li>1</li> * FrameworkModel (index=1) * <li>1.2</li> * FrameworkModel (index=1) -> ApplicationModel (index=2) * <li>1.2.0</li> * FrameworkModel (index=1) -> ApplicationModel (index=2) -> ModuleModel (index=0, internal module) * <li>1.2.1</li> * FrameworkModel (index=1) -> ApplicationModel (index=2) -> ModuleModel (index=1, first user module) * </ol> */ private String internalId; /** * Public Model Name, can be set from user */ private String modelName; private String desc; private final Set<ClassLoader> classLoaders = new ConcurrentHashSet<>(); private final ScopeModel parent; private final ExtensionScope scope; private volatile ExtensionDirector extensionDirector; private volatile ScopeBeanFactory beanFactory; private final List<ScopeModelDestroyListener> destroyListeners = new CopyOnWriteArrayList<>(); private final List<ScopeClassLoaderListener> classLoaderListeners = new CopyOnWriteArrayList<>(); private final Map<String, Object> attributes = new ConcurrentHashMap<>(); private final AtomicBoolean destroyed = new AtomicBoolean(false); private final boolean internalScope; protected final Object instLock = new Object(); protected ScopeModel(ScopeModel parent, ExtensionScope scope, boolean isInternal) { this.parent = parent; this.scope = scope; this.internalScope = isInternal; } /** * NOTE: * <ol> * <li>The initialize method only be called in subclass.</li> * <li> * In subclass, the extensionDirector and beanFactory are available in initialize but not available in constructor. * </li> * </ol> */ protected void initialize() { synchronized (instLock) { this.extensionDirector = new ExtensionDirector(parent != null ? parent.getExtensionDirector() : null, scope, this); this.extensionDirector.addExtensionPostProcessor(new ScopeModelAwareExtensionProcessor(this)); this.beanFactory = new ScopeBeanFactory(parent != null ? parent.getBeanFactory() : null, extensionDirector); // Add Framework's ClassLoader by default ClassLoader dubboClassLoader = ScopeModel.class.getClassLoader(); if (dubboClassLoader != null) { this.addClassLoader(dubboClassLoader); } } } protected abstract Lock acquireDestroyLock(); public void destroy() { Lock lock = acquireDestroyLock(); try { lock.lock(); if (destroyed.compareAndSet(false, true)) { try { onDestroy(); HashSet<ClassLoader> copyOfClassLoaders = new HashSet<>(classLoaders); for (ClassLoader classLoader : copyOfClassLoaders) { removeClassLoader(classLoader); } if (beanFactory != null) { beanFactory.destroy(); } if (extensionDirector != null) { extensionDirector.destroy(); } } catch (Throwable t) { LOGGER.error(CONFIG_UNABLE_DESTROY_MODEL, "", "", "Error happened when destroying ScopeModel.", t); } } } finally { lock.unlock(); } } public boolean isDestroyed() { return destroyed.get(); } protected void notifyDestroy() { for (ScopeModelDestroyListener destroyListener : destroyListeners) { destroyListener.onDestroy(this); } } protected void notifyProtocolDestroy() { for (ScopeModelDestroyListener destroyListener : destroyListeners) { if (destroyListener.isProtocol()) { destroyListener.onDestroy(this); } } } protected void notifyClassLoaderAdd(ClassLoader classLoader) { for (ScopeClassLoaderListener classLoaderListener : classLoaderListeners) { classLoaderListener.onAddClassLoader(this, classLoader); } } protected void notifyClassLoaderDestroy(ClassLoader classLoader) { for (ScopeClassLoaderListener classLoaderListener : classLoaderListeners) { classLoaderListener.onRemoveClassLoader(this, classLoader); } } protected abstract void onDestroy(); public final void addDestroyListener(ScopeModelDestroyListener listener) { destroyListeners.add(listener); } public final void addClassLoaderListener(ScopeClassLoaderListener listener) { classLoaderListeners.add(listener); } public Map<String, Object> getAttributes() { return attributes; } public <T> T getAttribute(String key, Class<T> type) { return (T) attributes.get(key); } public Object getAttribute(String key) { return attributes.get(key); } public void setAttribute(String key, Object value) { attributes.put(key, value); } @Override public ExtensionDirector getExtensionDirector() { return extensionDirector; } public final ScopeBeanFactory getBeanFactory() { return beanFactory; } public final <T> T getOrRegisterBean(Class<T> type) { return beanFactory.getOrRegisterBean(type); } public final <T> T getBean(Class<T> type) { return beanFactory.getBean(type); } public ScopeModel getParent() { return parent; } public ExtensionScope getScope() { return scope; } public void addClassLoader(ClassLoader classLoader) { synchronized (instLock) { this.classLoaders.add(classLoader); if (parent != null) { parent.addClassLoader(classLoader); } extensionDirector.removeAllCachedLoader(); notifyClassLoaderAdd(classLoader); } } public void removeClassLoader(ClassLoader classLoader) { synchronized (instLock) { if (checkIfClassLoaderCanRemoved(classLoader)) { this.classLoaders.remove(classLoader); if (parent != null) { parent.removeClassLoader(classLoader); } extensionDirector.removeAllCachedLoader(); notifyClassLoaderDestroy(classLoader); } } } protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) { return classLoader != null && !classLoader.equals(ScopeModel.class.getClassLoader()); } public Set<ClassLoader> getClassLoaders() { return Collections.unmodifiableSet(classLoaders); } /** * Get current model's environment. * </br> * Note: This method should not start with `get` or it would be invoked due to Spring boot refresh. * @see <a href="https://github.com/apache/dubbo/issues/12542">Configuration refresh issue</a> */ public abstract Environment modelEnvironment(); /** * Get current model's environment. * * @see <a href="https://github.com/apache/dubbo/issues/12542">Configuration refresh issue</a> * @deprecated use modelEnvironment() instead */ @Deprecated @SuppressWarnings("DeprecatedIsStillUsed") public final Environment getModelEnvironment() { try { return modelEnvironment(); } catch (Exception ex) { return null; } } public String getInternalId() { return this.internalId; } void setInternalId(String internalId) { this.internalId = internalId; } protected String buildInternalId(String parentInternalId, long childIndex) { // FrameworkModel 1 // ApplicationModel 1.1 // ModuleModel 1.1.1 if (StringUtils.hasText(parentInternalId)) { return parentInternalId + "." + childIndex; } else { return "" + childIndex; } } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; this.desc = buildDesc(); } public boolean isInternal() { return internalScope; } /** * @return to describe string of this scope model */ public String getDesc() { if (this.desc == null) { this.desc = buildDesc(); } return this.desc; } private String buildDesc() { // Dubbo Framework[1] // Dubbo Application[1.1](appName) // Dubbo Module[1.1.1](appName/moduleName) String type = this.getClass().getSimpleName().replace("Model", ""); String desc = "Dubbo " + type + "[" + this.getInternalId() + "]"; // append model name path String modelNamePath = this.getModelNamePath(); if (StringUtils.hasText(modelNamePath)) { desc += "(" + modelNamePath + ")"; } return desc; } private String getModelNamePath() { if (this instanceof ApplicationModel) { return safeGetAppName((ApplicationModel) this); } else if (this instanceof ModuleModel) { String modelName = this.getModelName(); if (StringUtils.hasText(modelName)) { // appName/moduleName return safeGetAppName(((ModuleModel) this).getApplicationModel()) + "/" + modelName; } } return null; } private static String safeGetAppName(ApplicationModel applicationModel) { String modelName = applicationModel.getModelName(); if (StringUtils.isBlank(modelName)) { modelName = "unknown"; // unknown application } return modelName; } @Override public String toString() { return getDesc(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.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.rpc.model; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; public class ServiceRepository { public static final String NAME = "repository"; private final AtomicBoolean initialized = new AtomicBoolean(false); private final ApplicationModel applicationModel; public ServiceRepository(ApplicationModel applicationModel) { this.applicationModel = applicationModel; initialize(); } private void initialize() { if (initialized.compareAndSet(false, true)) { Set<BuiltinServiceDetector> builtinServices = applicationModel .getExtensionLoader(BuiltinServiceDetector.class) .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(builtinServices)) { for (BuiltinServiceDetector service : builtinServices) { Class<?> serviceClass = service.getService(); if (serviceClass == null) { continue; } applicationModel.getInternalModule().getServiceRepository().registerService(serviceClass); } } } } public void destroy() { // TODO destroy application service repository } public Collection<ConsumerModel> allConsumerModels() { // aggregate from sub modules List<ConsumerModel> allConsumerModels = new ArrayList<>(); for (ModuleModel moduleModel : applicationModel.getModuleModels()) { allConsumerModels.addAll(moduleModel.getServiceRepository().getReferredServices()); } return allConsumerModels; } public Collection<ProviderModel> allProviderModels() { // aggregate from sub modules List<ProviderModel> allProviderModels = new ArrayList<>(); for (ModuleModel moduleModel : applicationModel.getModuleModels()) { allProviderModels.addAll(moduleModel.getServiceRepository().getExportedServices()); } return allProviderModels; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false