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-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.java
dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.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.serialize.fastjson2; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.time.LocalDate; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import com.example.test.TestPojo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class FastJson2SerializationTest { @Test void testReadString() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read string { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject("hello"); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals("hello", objectInput.readUTF()); } // write string, read string { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(null); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertNull(objectInput.readUTF()); } // write date, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readUTF); } // write pojo, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new TrustedPojo(ThreadLocalRandom.current().nextDouble())); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(String.class, objectInput.readUTF()); } // write map, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readUTF); } // write list, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new LinkedList<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(String.class, objectInput.readUTF()); } frameworkModel.destroy(); } @Test void testReadEvent() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read event { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject("hello"); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals("hello", objectInput.readEvent()); } // write date, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readEvent); } // write pojo, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new TrustedPojo(ThreadLocalRandom.current().nextDouble())); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(String.class, objectInput.readEvent()); } // write map, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readEvent); } // write list, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new LinkedList<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(String.class, objectInput.readEvent()); } frameworkModel.destroy(); } @Test void testReadByte() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write byte, read byte { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject((byte) 11); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals((byte) 11, objectInput.readByte()); } // write date, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); // fastjson2 could not read byte from the serialization of LocalDate by now. 2025/04/02 objectOutput.writeObject(LocalDate.now()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } // write pojo, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new TrustedPojo(ThreadLocalRandom.current().nextDouble())); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } // write map, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } // write list, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new LinkedList<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } frameworkModel.destroy(); } @Test void testReadObject() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read pojo { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(trustedPojo, objectInput.readObject()); } // write list, read list { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(pojos, objectInput.readObject()); } // write pojo, read pojo { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(trustedPojo, objectInput.readObject(TrustedPojo.class)); } // write list, read list { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(pojos, objectInput.readObject(List.class)); } // write list, read list { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(pojos, objectInput.readObject(LinkedList.class)); } frameworkModel.destroy(); } @Test void testReadObjectNotMatched() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckStatus(SerializeCheckStatus.STRICT); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read list failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(List.class)); } // write pojo, read list failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(LinkedList.class)); } // write pojo, read string failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(String.class, objectInput.readObject(String.class)); } // write pojo, read other failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(TrustedNotSerializable.class)); } // write pojo, read same field failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(TrustedPojo2.class)); } // write pojo, read map failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(Map.class)); } // write list, read pojo failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(TrustedPojo.class)); } // write list, read map failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(Map.class)); } frameworkModel.destroy(); } @Test void testLimit1() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write trusted, read trusted TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(trustedPojo, objectInput.readObject()); frameworkModel.destroy(); } @Test void testLimit4() throws IOException, ClassNotFoundException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // write force untrusted, read failed { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); TestPojo trustedPojo = new TestPojo("12345"); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .addToAllowed(trustedPojo.getClass().getName()); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); frameworkModel.destroy(); } { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckStatus(SerializeCheckStatus.STRICT); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readObject); frameworkModel.destroy(); } } @Test void testLimit5() throws IOException, ClassNotFoundException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // write force un-serializable, read failed { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); TrustedNotSerializable trustedPojo = new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckSerializable(false); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); frameworkModel.destroy(); } { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckStatus(SerializeCheckStatus.STRICT); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readObject); frameworkModel.destroy(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TrustedPojo2.java
dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TrustedPojo2.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.serialize.fastjson2; import java.io.Serializable; import java.util.Objects; public class TrustedPojo2 implements Serializable { private final double data; public TrustedPojo2(double data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustedPojo2 that = (TrustedPojo2) o; return Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TrustedNotSerializable.java
dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TrustedNotSerializable.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.serialize.fastjson2; import java.util.Objects; public class TrustedNotSerializable { private final double data; public TrustedNotSerializable(double data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustedNotSerializable that = (TrustedNotSerializable) o; return Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TypeMatchTest.java
dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TypeMatchTest.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.serialize.fastjson2; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.DataInput; import org.apache.dubbo.common.serialize.DataOutput; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; class TypeMatchTest { static class DataProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception { List<Object> datas = new LinkedList<>(); List<Method> readMethods = new LinkedList<>(); List<Method> writeMethods = new LinkedList<>(); datas.add(true); datas.add(false); datas.add((byte) 123); datas.add((byte) 234); datas.add((short) 12345); datas.add((short) 23456); datas.add(123456); datas.add(234567); datas.add(1234567L); datas.add(2345678L); datas.add(0.123F); datas.add(1.234F); datas.add(0.1234D); datas.add(1.2345D); datas.add("hello"); datas.add("world"); datas.add("hello".getBytes()); datas.add("world".getBytes()); for (Method method : ObjectInput.class.getMethods()) { if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : DataInput.class.getMethods()) { if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : ObjectOutput.class.getMethods()) { if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } for (Method method : DataOutput.class.getMethods()) { if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new HashMap<>(16); primitiveWrapperTypeMap.put(Boolean.class, boolean.class); primitiveWrapperTypeMap.put(Byte.class, byte.class); primitiveWrapperTypeMap.put(Character.class, char.class); primitiveWrapperTypeMap.put(Double.class, double.class); primitiveWrapperTypeMap.put(Float.class, float.class); primitiveWrapperTypeMap.put(Integer.class, int.class); primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); primitiveWrapperTypeMap.put(Void.class, void.class); List<Arguments> argumentsList = new LinkedList<>(); for (Object data : datas) { for (Method input : readMethods) { for (Method output : writeMethods) { if (output.getParameterTypes()[0].isAssignableFrom(data.getClass())) { argumentsList.add(Arguments.arguments(data, input, output)); } if (primitiveWrapperTypeMap.containsKey(data.getClass()) && output.getParameterTypes()[0].isAssignableFrom( primitiveWrapperTypeMap.get(data.getClass()))) { argumentsList.add(Arguments.arguments(data, input, output)); } } } } return argumentsList.stream(); } } @ParameterizedTest @ArgumentsSource(DataProvider.class) void test(Object data, Method input, Method output) throws Exception { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); output.invoke(objectOutput, data); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); if (output.getParameterTypes()[0].equals(input.getReturnType())) { Object result = input.invoke(objectInput); if (data.getClass().isArray()) { Assertions.assertArrayEquals((byte[]) data, (byte[]) result); } else { Assertions.assertEquals(data, result); } } else { try { Object result = input.invoke(objectInput); if (data.getClass().isArray()) { Assertions.assertNotEquals(data.getClass(), result.getClass()); } else { Assertions.assertNotEquals(data, result); } } catch (Exception e) { // ignore } } frameworkModel.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TrustedPojo.java
dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TrustedPojo.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.serialize.fastjson2; import java.io.Serializable; import java.util.Objects; public class TrustedPojo implements Serializable { private final double data; public TrustedPojo(double data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustedPojo that = (TrustedPojo) o; return Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.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.serialize.fastjson2; import org.apache.dubbo.common.serialize.ObjectOutput; import java.io.IOException; import java.io.OutputStream; import com.alibaba.fastjson2.JSONB; import com.alibaba.fastjson2.JSONWriter; /** * FastJson object output implementation */ public class FastJson2ObjectOutput implements ObjectOutput { private final Fastjson2CreatorManager fastjson2CreatorManager; private final Fastjson2SecurityManager fastjson2SecurityManager; private volatile ClassLoader classLoader; private final OutputStream os; public FastJson2ObjectOutput( Fastjson2CreatorManager fastjson2CreatorManager, Fastjson2SecurityManager fastjson2SecurityManager, OutputStream out) { this.fastjson2CreatorManager = fastjson2CreatorManager; this.fastjson2SecurityManager = fastjson2SecurityManager; this.classLoader = Thread.currentThread().getContextClassLoader(); this.os = out; fastjson2CreatorManager.setCreator(classLoader); } @Override public void writeBool(boolean v) throws IOException { writeObject(v); } @Override public void writeByte(byte v) throws IOException { writeObject(v); } @Override public void writeShort(short v) throws IOException { writeObject(v); } @Override public void writeInt(int v) throws IOException { writeObject(v); } @Override public void writeLong(long v) throws IOException { writeObject(v); } @Override public void writeFloat(float v) throws IOException { writeObject(v); } @Override public void writeDouble(double v) throws IOException { writeObject(v); } @Override public void writeUTF(String v) throws IOException { writeObject(v); } @Override public void writeBytes(byte[] b) throws IOException { writeLength(b.length); os.write(b); } @Override public void writeBytes(byte[] b, int off, int len) throws IOException { writeLength(len); os.write(b, off, len); } @Override public void writeObject(Object obj) throws IOException { updateClassLoaderIfNeed(); byte[] bytes; if (fastjson2SecurityManager.getSecurityFilter().isCheckSerializable()) { bytes = JSONB.toBytes( obj, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ErrorOnNoneSerializable, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.WriteNameAsSymbol); } else { bytes = JSONB.toBytes( obj, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.WriteNameAsSymbol); } writeLength(bytes.length); os.write(bytes); os.flush(); } private void updateClassLoaderIfNeed() { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); if (currentClassLoader != classLoader) { fastjson2CreatorManager.setCreator(currentClassLoader); classLoader = currentClassLoader; } } private void writeLength(int value) throws IOException { byte[] bytes = new byte[Integer.BYTES]; int length = bytes.length; for (int i = 0; i < length; i++) { bytes[length - i - 1] = (byte) (value & 0xFF); value >>= 8; } os.write(bytes); } @Override public void flushBuffer() throws IOException { os.flush(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.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.serialize.fastjson2; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.AllowClassNotifyListener; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.fastjson2.filter.ContextAutoTypeBeforeHandler; import com.alibaba.fastjson2.util.TypeUtils; import static com.alibaba.fastjson2.util.TypeUtils.loadClass; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNTRUSTED_SERIALIZE_CLASS; import static org.apache.dubbo.common.utils.SerializeCheckStatus.STRICT; public class Fastjson2SecurityManager implements AllowClassNotifyListener { private volatile Handler securityFilter; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Fastjson2SecurityManager.class); private final SerializeSecurityManager securityManager; private volatile SerializeCheckStatus status = AllowClassNotifyListener.DEFAULT_STATUS; private volatile boolean checkSerializable = true; private volatile Set<String> allowedList = new ConcurrentHashSet<>(1); private volatile Set<String> disAllowedList = new ConcurrentHashSet<>(1); public Fastjson2SecurityManager(FrameworkModel frameworkModel) { securityManager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class); securityManager.registerListener(this); securityFilter = new Handler( AllowClassNotifyListener.DEFAULT_STATUS, securityManager, true, new String[0], new ConcurrentHashSet<>()); } @Override public synchronized void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) { this.allowedList = allowedList; this.disAllowedList = disAllowedList; this.securityFilter = new Handler( this.status, this.securityManager, this.checkSerializable, this.allowedList.toArray(new String[0]), this.disAllowedList); } @Override public synchronized void notifyCheckStatus(SerializeCheckStatus status) { this.status = status; this.securityFilter = new Handler( this.status, this.securityManager, this.checkSerializable, this.allowedList.toArray(new String[0]), this.disAllowedList); } @Override public synchronized void notifyCheckSerializable(boolean checkSerializable) { this.checkSerializable = checkSerializable; this.securityFilter = new Handler( this.status, this.securityManager, this.checkSerializable, this.allowedList.toArray(new String[0]), this.disAllowedList); } public Handler getSecurityFilter() { return securityFilter; } public static class Handler extends ContextAutoTypeBeforeHandler { final SerializeCheckStatus status; final SerializeSecurityManager serializeSecurityManager; final Map<String, Class<?>> classCache = new ConcurrentHashMap<>(16, 0.75f, 1); final Set<String> disAllowedList; final boolean checkSerializable; public Handler( SerializeCheckStatus status, SerializeSecurityManager serializeSecurityManager, boolean checkSerializable, String[] acceptNames, Set<String> disAllowedList) { super(true, acceptNames); this.status = status; this.serializeSecurityManager = serializeSecurityManager; this.checkSerializable = checkSerializable; this.disAllowedList = disAllowedList; } @Override public Class<?> apply(String typeName, Class<?> expectClass, long features) { Class<?> tryLoad = super.apply(typeName, expectClass, features); // 1. in allow list, return if (tryLoad != null) { return tryLoad; } // 2. check if in strict mode if (status == STRICT) { String msg = "[Serialization Security] Serialized class " + typeName + " is not in allow list. " + "Current mode is `STRICT`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(typeName)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } // 3. try load Class<?> localClass = loadClassDirectly(typeName); if (localClass != null) { if (status == SerializeCheckStatus.WARN && serializeSecurityManager.getWarnedClasses().add(typeName)) { logger.warn( PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", "[Serialization Security] Serialized class " + localClass.getName() + " is not in allow list. " + "Current mode is `WARN`, will allow to deserialize it by default. " + "Dubbo will set to `STRICT` mode by default in the future. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."); } return localClass; } // 4. class not found return null; } public boolean checkIfDisAllow(String typeName) { return disAllowedList.stream().anyMatch(typeName::startsWith); } public boolean isCheckSerializable() { return checkSerializable; } public Class<?> loadClassDirectly(String typeName) { Class<?> clazz = classCache.get(typeName); if (clazz == null && checkIfDisAllow(typeName)) { clazz = DenyClass.class; String msg = "[Serialization Security] Serialized class " + typeName + " is in disAllow list. " + "Current mode is `WARN`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(typeName)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } } if (clazz == null) { clazz = TypeUtils.getMapping(typeName); } if (clazz == null) { clazz = loadClass(typeName); } if (clazz != null) { Class<?> origin = classCache.putIfAbsent(typeName, clazz); if (origin != null) { clazz = origin; } } if (clazz == DenyClass.class) { return null; } return clazz; } } private static class DenyClass { // To indicate that the target class has been reject } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2Serialization.java
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2Serialization.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.serialize.fastjson2; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Optional; import static org.apache.dubbo.common.serialize.Constants.FASTJSON2_SERIALIZATION_ID; /** * FastJson serialization implementation * * <pre> * e.g. &lt;dubbo:protocol serialization="fastjson" /&gt; * </pre> */ public class FastJson2Serialization implements Serialization { private static final Logger logger = LoggerFactory.getLogger(FastJson2Serialization.class); static { Class<?> aClass = null; try { aClass = com.alibaba.fastjson2.JSONB.class; } catch (Throwable ignored) { } if (aClass == null) { logger.info("Failed to load com.alibaba.fastjson2.JSONB, fastjson2 serialization will be disabled."); throw new IllegalStateException("The fastjson2 is not in classpath."); } } @Override public byte getContentTypeId() { return FASTJSON2_SERIALIZATION_ID; } @Override public String getContentType() { return "text/jsonb"; } @Override public ObjectOutput serialize(URL url, OutputStream output) throws IOException { Fastjson2CreatorManager fastjson2CreatorManager = Optional.ofNullable(url) .map(URL::getOrDefaultFrameworkModel) .orElseGet(FrameworkModel::defaultModel) .getBeanFactory() .getBean(Fastjson2CreatorManager.class); Fastjson2SecurityManager fastjson2SecurityManager = Optional.ofNullable(url) .map(URL::getOrDefaultFrameworkModel) .orElseGet(FrameworkModel::defaultModel) .getBeanFactory() .getBean(Fastjson2SecurityManager.class); return new FastJson2ObjectOutput(fastjson2CreatorManager, fastjson2SecurityManager, output); } @Override public ObjectInput deserialize(URL url, InputStream input) throws IOException { Fastjson2CreatorManager fastjson2CreatorManager = Optional.ofNullable(url) .map(URL::getOrDefaultFrameworkModel) .orElseGet(FrameworkModel::defaultModel) .getBeanFactory() .getBean(Fastjson2CreatorManager.class); Fastjson2SecurityManager fastjson2SecurityManager = Optional.ofNullable(url) .map(URL::getOrDefaultFrameworkModel) .orElseGet(FrameworkModel::defaultModel) .getBeanFactory() .getBean(Fastjson2SecurityManager.class); return new FastJson2ObjectInput(fastjson2CreatorManager, fastjson2SecurityManager, input); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2ScopeModelInitializer.java
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2ScopeModelInitializer.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.serialize.fastjson2; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; import java.util.Arrays; public class Fastjson2ScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { boolean classExist = false; try { for (String className : Arrays.asList( "com.alibaba.fastjson2.JSONB", "com.alibaba.fastjson2.reader.ObjectReaderCreatorASM", "com.alibaba.fastjson2.writer.ObjectWriterCreatorASM", "com.alibaba.fastjson2.JSONValidator", "com.alibaba.fastjson2.JSONFactory", "com.alibaba.fastjson2.JSONWriter", "com.alibaba.fastjson2.util.TypeUtils", "com.alibaba.fastjson2.filter.ContextAutoTypeBeforeHandler")) { Class<?> aClass = ClassUtils.forName(className, Thread.currentThread().getContextClassLoader()); if (aClass == null) { throw new ClassNotFoundException(className); } } classExist = true; } catch (Throwable ignored) { } if (classExist) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); beanFactory.registerBean(Fastjson2CreatorManager.class); beanFactory.registerBean(Fastjson2SecurityManager.class); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2CreatorManager.java
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2CreatorManager.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.serialize.fastjson2; import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeClassLoaderListener; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.fastjson2.JSONFactory; import com.alibaba.fastjson2.reader.ObjectReaderCreator; import com.alibaba.fastjson2.reader.ObjectReaderCreatorASM; import com.alibaba.fastjson2.writer.ObjectWriterCreator; import com.alibaba.fastjson2.writer.ObjectWriterCreatorASM; public class Fastjson2CreatorManager implements ScopeClassLoaderListener<FrameworkModel> { /** * An empty classLoader used when classLoader is system classLoader. Prevent the NPE. */ private static final ClassLoader SYSTEM_CLASSLOADER_KEY = new ClassLoader() {}; private final ConcurrentHashMap<ClassLoader, ObjectReaderCreator> readerMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<ClassLoader, ObjectWriterCreator> writerMap = new ConcurrentHashMap<>(); public Fastjson2CreatorManager(FrameworkModel frameworkModel) { frameworkModel.addClassLoaderListener(this); } public void setCreator(ClassLoader classLoader) { if (classLoader == null) { classLoader = SYSTEM_CLASSLOADER_KEY; } if (NativeDetector.inNativeImage()) { JSONFactory.setContextReaderCreator(readerMap.putIfAbsent(classLoader, ObjectReaderCreator.INSTANCE)); JSONFactory.setContextWriterCreator(writerMap.putIfAbsent(classLoader, ObjectWriterCreator.INSTANCE)); } else { JSONFactory.setContextReaderCreator( ConcurrentHashMapUtils.computeIfAbsent(readerMap, classLoader, ObjectReaderCreatorASM::new)); JSONFactory.setContextWriterCreator( ConcurrentHashMapUtils.computeIfAbsent(writerMap, classLoader, ObjectWriterCreatorASM::new)); } } @Override public void onAddClassLoader(FrameworkModel scopeModel, ClassLoader classLoader) { // nop } @Override public void onRemoveClassLoader(FrameworkModel scopeModel, ClassLoader classLoader) { readerMap.remove(classLoader); writerMap.remove(classLoader); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.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.serialize.fastjson2; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.ClassUtils; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import com.alibaba.fastjson2.JSONB; import com.alibaba.fastjson2.JSONReader; /** * FastJson object input implementation */ public class FastJson2ObjectInput implements ObjectInput { private final Fastjson2CreatorManager fastjson2CreatorManager; private final Fastjson2SecurityManager fastjson2SecurityManager; private volatile ClassLoader classLoader; private final InputStream is; public FastJson2ObjectInput( Fastjson2CreatorManager fastjson2CreatorManager, Fastjson2SecurityManager fastjson2SecurityManager, InputStream in) { this.fastjson2CreatorManager = fastjson2CreatorManager; this.fastjson2SecurityManager = fastjson2SecurityManager; this.classLoader = Thread.currentThread().getContextClassLoader(); this.is = in; fastjson2CreatorManager.setCreator(classLoader); } @Override public boolean readBool() throws IOException { return readObject(boolean.class); } @Override public byte readByte() throws IOException { return readObject(byte.class); } @Override public short readShort() throws IOException { return readObject(short.class); } @Override public int readInt() throws IOException { return readObject(int.class); } @Override public long readLong() throws IOException { return readObject(long.class); } @Override public float readFloat() throws IOException { return readObject(float.class); } @Override public double readDouble() throws IOException { return readObject(double.class); } @Override public String readUTF() throws IOException { return readObject(String.class); } @Override public byte[] readBytes() throws IOException { int length = readLength(); byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { throw new IllegalArgumentException( "deserialize failed. expected read length: " + length + " but actual read: " + read); } return bytes; } @Override public Object readObject() throws IOException, ClassNotFoundException { return readObject(Object.class); } @Override public <T> T readObject(Class<T> cls) throws IOException { updateClassLoaderIfNeed(); int length = readLength(); byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { throw new IllegalArgumentException( "deserialize failed. expected read length: " + length + " but actual read: " + read); } Fastjson2SecurityManager.Handler securityFilter = fastjson2SecurityManager.getSecurityFilter(); T result; if (securityFilter.isCheckSerializable()) { result = JSONB.parseObject( bytes, cls, securityFilter, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.ErrorOnNoneSerializable, JSONReader.Feature.IgnoreAutoTypeNotMatch, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased); } else { result = JSONB.parseObject( bytes, cls, securityFilter, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.IgnoreAutoTypeNotMatch, JSONReader.Feature.FieldBased); } if (result != null && cls != null && !ClassUtils.isMatch(result.getClass(), cls)) { throw new IllegalArgumentException( "deserialize failed. expected class: " + cls + " but actual class: " + result.getClass()); } return result; } @Override public <T> T readObject(Class<T> cls, Type type) throws IOException, ClassNotFoundException { updateClassLoaderIfNeed(); int length = readLength(); byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { throw new IllegalArgumentException( "deserialize failed. expected read length: " + length + " but actual read: " + read); } Fastjson2SecurityManager.Handler securityFilter = fastjson2SecurityManager.getSecurityFilter(); T result; if (securityFilter.isCheckSerializable()) { result = JSONB.parseObject( bytes, cls, securityFilter, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.ErrorOnNoneSerializable, JSONReader.Feature.IgnoreAutoTypeNotMatch, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased); } else { result = JSONB.parseObject( bytes, cls, securityFilter, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.IgnoreAutoTypeNotMatch, JSONReader.Feature.FieldBased); } if (result != null && cls != null && !ClassUtils.isMatch(result.getClass(), cls)) { throw new IllegalArgumentException( "deserialize failed. expected class: " + cls + " but actual class: " + result.getClass()); } return result; } private void updateClassLoaderIfNeed() { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); if (currentClassLoader != classLoader) { fastjson2CreatorManager.setCreator(currentClassLoader); classLoader = currentClassLoader; } } private int readLength() throws IOException { byte[] bytes = new byte[Integer.BYTES]; int read = is.read(bytes, 0, Integer.BYTES); if (read != Integer.BYTES) { throw new IllegalArgumentException( "deserialize failed. expected read length: " + Integer.BYTES + " but actual read: " + read); } int value = 0; for (byte b : bytes) { value = (value << 8) + (b & 0xFF); } return value; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/com/example/test/TestPojo.java
dubbo-serialization/dubbo-serialization-hessian2/src/test/java/com/example/test/TestPojo.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 com.example.test; import java.io.Serializable; import java.util.Objects; public class TestPojo implements Serializable { private final String data; public TestPojo(String data) { this.data = data; } @Override public String toString() { throw new IllegalAccessError(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestPojo testPojo = (TestPojo) o; return Objects.equals(data, testPojo.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TrustedPojo2.java
dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TrustedPojo2.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.serialize.hessian2; import java.io.Serializable; import java.util.Objects; public class TrustedPojo2 implements Serializable { private final double data; public TrustedPojo2(double data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustedPojo2 that = (TrustedPojo2) o; return Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TrustedNotSerializable.java
dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TrustedNotSerializable.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.serialize.hessian2; import java.util.Objects; public class TrustedNotSerializable { private final double data; public TrustedNotSerializable(double data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustedNotSerializable that = (TrustedNotSerializable) o; return Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.java
dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.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.serialize.hessian2; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import com.example.test.TestPojo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE; class Hessian2SerializationTest { @Test void testReadString() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read string { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject("hello"); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals("hello", objectInput.readUTF()); } // write string, read string { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(null); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertNull(objectInput.readUTF()); } // write date, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new Date()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readUTF); } // write pojo, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new TrustedPojo(ThreadLocalRandom.current().nextDouble())); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readUTF); } // write map, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readUTF); } // write list, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new LinkedList<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readUTF); } frameworkModel.destroy(); } @Test void testReadEvent() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read event { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject("hello"); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals("hello", objectInput.readEvent()); } // write date, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new Date()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readEvent); } // write pojo, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new TrustedPojo(ThreadLocalRandom.current().nextDouble())); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readEvent); } // write map, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readEvent); } // write list, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new LinkedList<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readEvent); } frameworkModel.destroy(); } @Test void testReadByte() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write byte, read byte { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject((byte) 11); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals((byte) 11, objectInput.readByte()); } // write date, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new Date()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } // write pojo, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new TrustedPojo(ThreadLocalRandom.current().nextDouble())); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } // write map, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new HashMap<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } // write list, read failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(new LinkedList<>()); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readByte); } frameworkModel.destroy(); } @Test void testReadObject() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read pojo { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(trustedPojo, objectInput.readObject()); } // write list, read list { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(pojos, objectInput.readObject()); } // write pojo, read pojo { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(trustedPojo, objectInput.readObject(TrustedPojo.class)); } // write list, read list { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(pojos, objectInput.readObject(List.class)); } // write list, read list { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(pojos, objectInput.readObject(LinkedList.class)); } frameworkModel.destroy(); } @Test void testReadObjectNotMatched() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read list failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(List.class)); } // write pojo, read list failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(LinkedList.class)); } // write pojo, read string failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(String.class)); } // write pojo, read other failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(TrustedNotSerializable.class)); } // write pojo, read same field failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(TrustedPojo2.class, objectInput.readObject(TrustedPojo2.class)); } // write pojo, read map failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(Map.class, objectInput.readObject(Map.class)); } // write list, read pojo failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(TrustedPojo.class)); } // write list, read map failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList<TrustedPojo> pojos = new LinkedList<>(); pojos.add(trustedPojo); objectOutput.writeObject(pojos); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, () -> objectInput.readObject(Map.class)); } frameworkModel.destroy(); } @Test void testLimit1() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write trusted, read trusted TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertEquals(trustedPojo, objectInput.readObject()); frameworkModel.destroy(); } @Test void testLimit2() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckStatus(SerializeCheckStatus.STRICT); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write untrusted failed TestPojo trustedPojo = new TestPojo("12345"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); Assertions.assertThrows(IOException.class, () -> objectOutput.writeObject(trustedPojo)); frameworkModel.destroy(); } @Test void testLimit3() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write un-serializable failed TrustedNotSerializable trustedPojo = new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); Assertions.assertThrows(IOException.class, () -> objectOutput.writeObject(trustedPojo)); frameworkModel.destroy(); } @Test void testLimit4() throws IOException, ClassNotFoundException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // write force untrusted, read failed { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); TestPojo trustedPojo = new TestPojo("12345"); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .addToAllowed(trustedPojo.getClass().getName()); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); frameworkModel.destroy(); } { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckStatus(SerializeCheckStatus.STRICT); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(Map.class, objectInput.readObject()); frameworkModel.destroy(); } } @Test void testLimit5() throws IOException, ClassNotFoundException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // write force un-serializable, read failed { SystemPropertyConfigUtils.setSystemProperty(DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE, "true"); FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); TrustedNotSerializable trustedPojo = new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); frameworkModel .getBeanFactory() .getBean(SerializeSecurityManager.class) .setCheckSerializable(false); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); frameworkModel.destroy(); SystemPropertyConfigUtils.clearSystemProperty(DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE); } { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(Map.class, objectInput.readObject()); frameworkModel.destroy(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TypeMatchTest.java
dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TypeMatchTest.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.serialize.hessian2; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.DataInput; import org.apache.dubbo.common.serialize.DataOutput; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; class TypeMatchTest { static class DataProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception { List<Object> datas = new LinkedList<>(); List<Method> readMethods = new LinkedList<>(); List<Method> writeMethods = new LinkedList<>(); datas.add(true); datas.add(false); datas.add((byte) 123); datas.add((byte) 234); datas.add((short) 12345); datas.add((short) 23456); datas.add(123456); datas.add(234567); datas.add(1234567L); datas.add(2345678L); datas.add(0.123F); datas.add(1.234F); datas.add(0.1234D); datas.add(1.2345D); datas.add("hello"); datas.add("world"); datas.add("hello".getBytes()); datas.add("world".getBytes()); for (Method method : ObjectInput.class.getMethods()) { if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : DataInput.class.getMethods()) { if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : ObjectOutput.class.getMethods()) { if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } for (Method method : DataOutput.class.getMethods()) { if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new HashMap<>(16); primitiveWrapperTypeMap.put(Boolean.class, boolean.class); primitiveWrapperTypeMap.put(Byte.class, byte.class); primitiveWrapperTypeMap.put(Character.class, char.class); primitiveWrapperTypeMap.put(Double.class, double.class); primitiveWrapperTypeMap.put(Float.class, float.class); primitiveWrapperTypeMap.put(Integer.class, int.class); primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); primitiveWrapperTypeMap.put(Void.class, void.class); List<Arguments> argumentsList = new LinkedList<>(); for (Object data : datas) { for (Method input : readMethods) { for (Method output : writeMethods) { if (output.getParameterTypes()[0].isAssignableFrom(data.getClass())) { argumentsList.add(Arguments.arguments(data, input, output)); } if (primitiveWrapperTypeMap.containsKey(data.getClass()) && output.getParameterTypes()[0].isAssignableFrom( primitiveWrapperTypeMap.get(data.getClass()))) { argumentsList.add(Arguments.arguments(data, input, output)); } } } } return argumentsList.stream(); } } @ParameterizedTest @ArgumentsSource(DataProvider.class) void test(Object data, Method input, Method output) throws Exception { FrameworkModel frameworkModel = new FrameworkModel(); Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); output.invoke(objectOutput, data); objectOutput.flushBuffer(); byte[] bytes = outputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); if (output.getParameterTypes()[0].equals(input.getReturnType())) { Object result = input.invoke(objectInput); if (data.getClass().isArray()) { Assertions.assertArrayEquals((byte[]) data, (byte[]) result); } else { Assertions.assertEquals(data, result); } } else { try { Object result = input.invoke(objectInput); if (data.getClass().isArray()) { Assertions.assertNotEquals(data.getClass(), result.getClass()); } else { Assertions.assertNotEquals(data, result); } } catch (Exception e) { // ignore } } frameworkModel.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TrustedPojo.java
dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TrustedPojo.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.serialize.hessian2; import java.io.Serializable; import java.util.Objects; public class TrustedPojo implements Serializable { private final double data; public TrustedPojo(double data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustedPojo that = (TrustedPojo) o; return Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(data); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.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.serialize.hessian2; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Optional; import static org.apache.dubbo.common.serialize.Constants.HESSIAN2_SERIALIZATION_ID; /** * Hessian2 serialization implementation, hessian2 is the default serialization protocol for dubbo * * <pre> * e.g. &lt;dubbo:protocol serialization="hessian2" /&gt; * </pre> */ public class Hessian2Serialization implements Serialization { private static final Logger logger = LoggerFactory.getLogger(Hessian2Serialization.class); static { Class<?> aClass = null; try { aClass = com.alibaba.com.caucho.hessian.io.Hessian2Output.class; } catch (Throwable ignored) { } if (aClass == null) { logger.info( "Failed to load com.alibaba.com.caucho.hessian.io.Hessian2Output, hessian2 serialization will be disabled."); throw new IllegalStateException("The hessian2 is not in classpath."); } } @Override public byte getContentTypeId() { return HESSIAN2_SERIALIZATION_ID; } @Override public String getContentType() { return "x-application/hessian2"; } @Override public ObjectOutput serialize(URL url, OutputStream out) throws IOException { Hessian2FactoryManager hessian2FactoryManager = Optional.ofNullable(url) .map(URL::getOrDefaultFrameworkModel) .orElseGet(FrameworkModel::defaultModel) .getBeanFactory() .getBean(Hessian2FactoryManager.class); return new Hessian2ObjectOutput(out, hessian2FactoryManager); } @Override public ObjectInput deserialize(URL url, InputStream is) throws IOException { Hessian2FactoryManager hessian2FactoryManager = Optional.ofNullable(url) .map(URL::getOrDefaultFrameworkModel) .orElseGet(FrameworkModel::defaultModel) .getBeanFactory() .getBean(Hessian2FactoryManager.class); return new Hessian2ObjectInput(is, hessian2FactoryManager); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializerFactory.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializerFactory.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.serialize.hessian2; import org.apache.dubbo.common.utils.DefaultSerializeClassChecker; import java.io.InputStream; import java.io.Serializable; import com.alibaba.com.caucho.hessian.io.Deserializer; import com.alibaba.com.caucho.hessian.io.InputStreamDeserializer; import com.alibaba.com.caucho.hessian.io.JavaDeserializer; import com.alibaba.com.caucho.hessian.io.JavaSerializer; import com.alibaba.com.caucho.hessian.io.RecordDeserializer; import com.alibaba.com.caucho.hessian.io.RecordUtil; import com.alibaba.com.caucho.hessian.io.Serializer; import com.alibaba.com.caucho.hessian.io.SerializerFactory; import com.alibaba.com.caucho.hessian.io.UnsafeDeserializer; import com.alibaba.com.caucho.hessian.io.UnsafeSerializer; public class Hessian2SerializerFactory extends SerializerFactory { private final DefaultSerializeClassChecker defaultSerializeClassChecker; public Hessian2SerializerFactory( ClassLoader classLoader, DefaultSerializeClassChecker defaultSerializeClassChecker) { super(classLoader); this.defaultSerializeClassChecker = defaultSerializeClassChecker; } @Override public Class<?> loadSerializedClass(String className) throws ClassNotFoundException { return defaultSerializeClassChecker.loadClass(getClassLoader(), className); } @Override protected Serializer getDefaultSerializer(Class cl) { if (_defaultSerializer != null) return _defaultSerializer; try { // pre-check if class is allow defaultSerializeClassChecker.loadClass(getClassLoader(), cl.getName()); } catch (ClassNotFoundException e) { // ignore } checkSerializable(cl); if (isEnableUnsafeSerializer() && JavaSerializer.getWriteReplace(cl) == null) { return UnsafeSerializer.create(cl); } else return JavaSerializer.create(cl); } @Override protected Deserializer getDefaultDeserializer(Class cl) { if (InputStream.class.equals(cl)) { return InputStreamDeserializer.DESER; } try { // pre-check if class is allow defaultSerializeClassChecker.loadClass(getClassLoader(), cl.getName()); } catch (ClassNotFoundException e) { // ignore } checkSerializable(cl); if (RecordUtil.isRecord(cl)) { return new RecordDeserializer(cl, getFieldDeserializerFactory()); } else { if (isEnableUnsafeSerializer()) { return new UnsafeDeserializer(cl, getFieldDeserializerFactory()); } else return new JavaDeserializer(cl, getFieldDeserializerFactory()); } } private void checkSerializable(Class<?> cl) { // If class is Serializable => ok // If class has not implement Serializable // If hessian check serializable => fail // If dubbo class checker check serializable => fail // If both hessian and dubbo class checker allow non-serializable => ok if (!Serializable.class.isAssignableFrom(cl) && (!isAllowNonSerializable() || defaultSerializeClassChecker.isCheckSerializable())) { throw new IllegalStateException( "Serialized class " + cl.getName() + " must implement java.io.Serializable"); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2FactoryManager.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2FactoryManager.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.serialize.hessian2; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.DefaultSerializeClassChecker; import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.com.caucho.hessian.io.SerializerFactory; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_HESSIAN_ALLOW; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_HESSIAN_DENY; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_HESSIAN_WHITELIST; public class Hessian2FactoryManager { private volatile SerializerFactory SYSTEM_SERIALIZER_FACTORY; private volatile SerializerFactory stickySerializerFactory = null; private final ConcurrentHashMap<ClassLoader, SerializerFactory> CL_2_SERIALIZER_FACTORY = new ConcurrentHashMap<>(); private final SerializeSecurityManager serializeSecurityManager; private final DefaultSerializeClassChecker defaultSerializeClassChecker; public Hessian2FactoryManager(FrameworkModel frameworkModel) { serializeSecurityManager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class); defaultSerializeClassChecker = frameworkModel.getBeanFactory().getOrRegisterBean(DefaultSerializeClassChecker.class); } public SerializerFactory getSerializerFactory(ClassLoader classLoader) { SerializerFactory sticky = stickySerializerFactory; if (sticky != null && Objects.equals(sticky.getClassLoader(), classLoader)) { return sticky; } if (classLoader == null) { // system classloader if (SYSTEM_SERIALIZER_FACTORY == null) { synchronized (this) { if (SYSTEM_SERIALIZER_FACTORY == null) { SYSTEM_SERIALIZER_FACTORY = createSerializerFactory(null); } } } stickySerializerFactory = SYSTEM_SERIALIZER_FACTORY; return SYSTEM_SERIALIZER_FACTORY; } SerializerFactory factory = ConcurrentHashMapUtils.computeIfAbsent( CL_2_SERIALIZER_FACTORY, classLoader, this::createSerializerFactory); stickySerializerFactory = factory; return factory; } private SerializerFactory createSerializerFactory(ClassLoader classLoader) { String whitelist = SystemPropertyConfigUtils.getSystemProperty(DUBBO_HESSIAN_WHITELIST); if (StringUtils.isNotEmpty(whitelist)) { return createWhiteListSerializerFactory(classLoader); } return createDefaultSerializerFactory(classLoader); } private SerializerFactory createDefaultSerializerFactory(ClassLoader classLoader) { Hessian2SerializerFactory hessian2SerializerFactory = new Hessian2SerializerFactory(classLoader, defaultSerializeClassChecker); hessian2SerializerFactory.setAllowNonSerializable(Boolean.parseBoolean( SystemPropertyConfigUtils.getSystemProperty(DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE, "false"))); hessian2SerializerFactory.getClassFactory().allow("org.apache.dubbo.*"); return hessian2SerializerFactory; } public SerializerFactory createWhiteListSerializerFactory(ClassLoader classLoader) { SerializerFactory serializerFactory = new Hessian2SerializerFactory(classLoader, defaultSerializeClassChecker); String whiteList = SystemPropertyConfigUtils.getSystemProperty(DUBBO_HESSIAN_WHITELIST); if ("true".equals(whiteList)) { serializerFactory.getClassFactory().setWhitelist(true); String allowPattern = SystemPropertyConfigUtils.getSystemProperty(DUBBO_HESSIAN_ALLOW); if (StringUtils.isNotEmpty(allowPattern)) { for (String pattern : allowPattern.split(";")) { serializerFactory.getClassFactory().allow(pattern); serializeSecurityManager.addToAlwaysAllowed(pattern); } } serializeSecurityManager.setCheckStatus(SerializeCheckStatus.STRICT); } else { serializerFactory.getClassFactory().setWhitelist(false); String denyPattern = SystemPropertyConfigUtils.getSystemProperty(DUBBO_HESSIAN_DENY); if (StringUtils.isNotEmpty(denyPattern)) { for (String pattern : denyPattern.split(";")) { serializerFactory.getClassFactory().deny(pattern); serializeSecurityManager.addToDisAllowed(pattern); } } } serializerFactory.setAllowNonSerializable(Boolean.parseBoolean( SystemPropertyConfigUtils.getSystemProperty(DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE, "false"))); serializerFactory.getClassFactory().allow("org.apache.dubbo.*"); return serializerFactory; } public void onRemoveClassLoader(ClassLoader classLoader) { CL_2_SERIALIZER_FACTORY.remove(classLoader); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ClassLoaderListener.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ClassLoaderListener.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.serialize.hessian2; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeClassLoaderListener; public class Hessian2ClassLoaderListener implements ScopeClassLoaderListener<FrameworkModel> { @Override public void onAddClassLoader(FrameworkModel scopeModel, ClassLoader classLoader) { // noop } @Override public void onRemoveClassLoader(FrameworkModel scopeModel, ClassLoader classLoader) { Hessian2FactoryManager hessian2FactoryManager = scopeModel.getBeanFactory().getBean(Hessian2FactoryManager.class); hessian2FactoryManager.onRemoveClassLoader(classLoader); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ScopeModelInitializer.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ScopeModelInitializer.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.serialize.hessian2; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class Hessian2ScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { Class<?> aClass = null; try { aClass = com.alibaba.com.caucho.hessian.io.Hessian2Output.class; } catch (Throwable ignored) { } if (aClass != null) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); beanFactory.registerBean(Hessian2FactoryManager.class); frameworkModel.addClassLoaderListener(new Hessian2ClassLoaderListener()); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.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.serialize.hessian2; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.Objects; import com.alibaba.com.caucho.hessian.io.Hessian2Input; /** * Hessian2 object input implementation */ public class Hessian2ObjectInput implements ObjectInput, Cleanable { private final Hessian2Input mH2i; private final Hessian2FactoryManager hessian2FactoryManager; @Deprecated public Hessian2ObjectInput(InputStream is) { mH2i = new Hessian2Input(is); this.hessian2FactoryManager = FrameworkModel.defaultModel().getBeanFactory().getOrRegisterBean(Hessian2FactoryManager.class); mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } public Hessian2ObjectInput(InputStream is, Hessian2FactoryManager hessian2FactoryManager) { mH2i = new Hessian2Input(is); this.hessian2FactoryManager = hessian2FactoryManager; mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } @Override public boolean readBool() throws IOException { return mH2i.readBoolean(); } @Override public byte readByte() throws IOException { return (byte) mH2i.readInt(); } @Override public short readShort() throws IOException { return (short) mH2i.readInt(); } @Override public int readInt() throws IOException { return mH2i.readInt(); } @Override public long readLong() throws IOException { return mH2i.readLong(); } @Override public float readFloat() throws IOException { return (float) mH2i.readDouble(); } @Override public double readDouble() throws IOException { return mH2i.readDouble(); } @Override public byte[] readBytes() throws IOException { return mH2i.readBytes(); } @Override public String readUTF() throws IOException { return mH2i.readString(); } @Override public Object readObject() throws IOException { if (!Objects.equals( mH2i.getSerializerFactory().getClassLoader(), Thread.currentThread().getContextClassLoader())) { mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } return mH2i.readObject(); } @Override @SuppressWarnings("unchecked") public <T> T readObject(Class<T> cls) throws IOException, ClassNotFoundException { if (!Objects.equals( mH2i.getSerializerFactory().getClassLoader(), Thread.currentThread().getContextClassLoader())) { mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } return (T) mH2i.readObject(cls); } @Override public <T> T readObject(Class<T> cls, Type type) throws IOException, ClassNotFoundException { if (!Objects.equals( mH2i.getSerializerFactory().getClassLoader(), Thread.currentThread().getContextClassLoader())) { mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } return readObject(cls); } public InputStream readInputStream() throws IOException { return mH2i.readInputStream(); } @Override public void cleanup() { if (mH2i != null) { mH2i.reset(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.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.serialize.hessian2; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import java.io.OutputStream; import com.alibaba.com.caucho.hessian.io.Hessian2Output; /** * Hessian2 object output implementation */ public class Hessian2ObjectOutput implements ObjectOutput, Cleanable { private final Hessian2Output mH2o; @Deprecated public Hessian2ObjectOutput(OutputStream os) { mH2o = new Hessian2Output(os); Hessian2FactoryManager hessian2FactoryManager = FrameworkModel.defaultModel().getBeanFactory().getOrRegisterBean(Hessian2FactoryManager.class); mH2o.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } public Hessian2ObjectOutput(OutputStream os, Hessian2FactoryManager hessian2FactoryManager) { mH2o = new Hessian2Output(os); mH2o.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( Thread.currentThread().getContextClassLoader())); } @Override public void writeBool(boolean v) throws IOException { mH2o.writeBoolean(v); } @Override public void writeByte(byte v) throws IOException { mH2o.writeInt(v); } @Override public void writeShort(short v) throws IOException { mH2o.writeInt(v); } @Override public void writeInt(int v) throws IOException { mH2o.writeInt(v); } @Override public void writeLong(long v) throws IOException { mH2o.writeLong(v); } @Override public void writeFloat(float v) throws IOException { mH2o.writeDouble(v); } @Override public void writeDouble(double v) throws IOException { mH2o.writeDouble(v); } @Override public void writeBytes(byte[] b) throws IOException { mH2o.writeBytes(b); } @Override public void writeBytes(byte[] b, int off, int len) throws IOException { mH2o.writeBytes(b, off, len); } @Override public void writeUTF(String v) throws IOException { mH2o.writeString(v); } @Override public void writeObject(Object obj) throws IOException { mH2o.writeObject(obj); } @Override public void flushBuffer() throws IOException { mH2o.flushBuffer(); } public OutputStream getOutputStream() throws IOException { return mH2o.getBytesOutputStream(); } @Override public void cleanup() { if (mH2o != null) { mH2o.reset(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/aot/HessianReflectionTypeDescriberRegistrar.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/aot/HessianReflectionTypeDescriberRegistrar.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.serialize.hessian2.aot; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.TypeDescriber; import java.net.URL; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; public class HessianReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override public List<TypeDescriber> getTypeDescribers() { List<TypeDescriber> typeDescribers = new ArrayList<>(); loadFile("META-INF/dubbo/hessian/deserializers", typeDescribers); loadFile("META-INF/dubbo/hessian/serializers", typeDescribers); typeDescribers.add(buildTypeDescriberWithDeclared(Date.class)); typeDescribers.add(buildTypeDescriberWithDeclared(Time.class)); typeDescribers.add(buildTypeDescriberWithDeclared(Timestamp.class)); return typeDescribers; } private void loadFile(String path, List<TypeDescriber> typeDescribers) { try { Enumeration<URL> resources = this.getClass().getClassLoader().getResources(path); while (resources.hasMoreElements()) { URL url = resources.nextElement(); Properties props = new Properties(); props.load(url.openStream()); for (Object value : props.values()) { String className = (String) value; typeDescribers.add(buildTypeDescriberWithDeclared(className)); } } } catch (Throwable t) { // ignore } } private TypeDescriber buildTypeDescriberWithDeclared(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithDeclared(String cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber(cl, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/aot/HessianResourceDescriberRegistrar.java
dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/aot/HessianResourceDescriberRegistrar.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.serialize.hessian2.aot; import org.apache.dubbo.aot.api.ResourceBundleDescriber; import org.apache.dubbo.aot.api.ResourceDescriberRegistrar; import org.apache.dubbo.aot.api.ResourcePatternDescriber; import java.util.Collections; import java.util.List; public class HessianResourceDescriberRegistrar implements ResourceDescriberRegistrar { @Override public List<ResourcePatternDescriber> getResourcePatternDescribers() { return Collections.singletonList(new ResourcePatternDescriber("DENY_CLASS", null)); } @Override public List<ResourceBundleDescriber> getResourceBundleDescribers() { return Collections.emptyList(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.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.springboot.demo.provider; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.springboot.demo.DemoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @DubboService public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); @Override public String sayHello(String name) { logger.info("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); return "Hello " + name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.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.springboot.demo.provider; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import java.util.concurrent.CountDownLatch; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableDubbo(scanBasePackages = {"org.apache.dubbo.springboot.demo.provider"}) public class ProviderApplication { public static void main(String[] args) throws Exception { SpringApplication.run(ProviderApplication.class, args); new CountDownLatch(1).await(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.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.springboot.demo.consumer; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.springboot.demo.DemoService; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Service; @SpringBootApplication @Service @EnableDubbo public class ConsumerApplication { private static final Logger logger = LoggerFactory.getLogger(ConsumerApplication.class); @DubboReference private DemoService demoService; public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args); ConsumerApplication application = context.getBean(ConsumerApplication.class); String result = application.doSayHello("world"); logger.info("result: {}", result); CompletableFuture<String> future = application.doSayHelloAsync("world"); try { logger.info("async call returned: {}", future.get()); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } public String doSayHello(String name) { return demoService.sayHello(name); } public CompletableFuture<String> doSayHelloAsync(String name) { CompletableFuture<String> sayHelloAsyncFuture = demoService.sayHelloAsync(name); return sayHelloAsyncFuture; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.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.springboot.demo; import java.util.concurrent.CompletableFuture; public interface DemoService { String sayHello(String name); default CompletableFuture<String> sayHelloAsync(String name) { return CompletableFuture.completedFuture(sayHello(name)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/GreeterService.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/GreeterService.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.springboot.demo.servlet; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import java.util.concurrent.CompletableFuture; public interface GreeterService { /** * Sends a greeting */ HelloReply sayHello(HelloRequest request); /** * Sends a greeting asynchronously */ CompletableFuture<String> sayHelloAsync(String request); /** * Sends a greeting with server streaming */ void sayHelloServerStream(HelloRequest request, StreamObserver<HelloReply> responseObserver); void sayHelloServerStreamNoParameter(StreamObserver<HelloReply> responseObserver); void sayHelloServerStreamSSE(StreamObserver<ServerSentEvent<HelloReply>> responseObserver); /** * Sends greetings with bi streaming */ StreamObserver<HelloRequest> sayHelloBiStream(StreamObserver<HelloReply> responseObserver); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/HelloReply.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/HelloReply.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.springboot.demo.servlet; import java.io.Serializable; public class HelloReply implements Serializable { private static final long serialVersionUID = 1L; private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/GreeterServiceImpl.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/GreeterServiceImpl.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.springboot.demo.servlet; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import java.time.Duration; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @DubboService public class GreeterServiceImpl implements GreeterService { private static final Logger LOGGER = LoggerFactory.getLogger(GreeterServiceImpl.class); @Override public HelloReply sayHello(HelloRequest request) { LOGGER.info("Received sayHello request: {}", request.getName()); return toReply("Hello " + request.getName()); } @Override public CompletableFuture<String> sayHelloAsync(String name) { LOGGER.info("Received sayHelloAsync request: {}", name); return CompletableFuture.supplyAsync(() -> "Hello " + name); } @Override public void sayHelloServerStream(HelloRequest request, StreamObserver<HelloReply> responseObserver) { LOGGER.info("Received sayHelloServerStream request"); for (int i = 1; i < 6; i++) { LOGGER.info("sayHelloServerStream onNext: {} {} times", request.getName(), i); responseObserver.onNext(toReply("Hello " + request.getName() + ' ' + i + " times")); } LOGGER.info("sayHelloServerStream onCompleted"); responseObserver.onCompleted(); } @Override public void sayHelloServerStreamNoParameter(StreamObserver<HelloReply> responseObserver) { LOGGER.info("Received sayHelloServerStreamNoParameter request"); for (int i = 1; i < 6; i++) { LOGGER.info("sayHelloServerStreamNoParameter onNext: {} times", i); responseObserver.onNext(toReply("Hello " + ' ' + i + " times")); } LOGGER.info("sayHelloServerStreamNoParameter onCompleted"); responseObserver.onCompleted(); } @Override public void sayHelloServerStreamSSE(StreamObserver<ServerSentEvent<HelloReply>> responseObserver) { LOGGER.info("Received sayHelloServerStreamSSE request"); responseObserver.onNext(ServerSentEvent.<HelloReply>builder() .retry(Duration.ofSeconds(20)) .build()); responseObserver.onNext(ServerSentEvent.<HelloReply>builder() .event("say") .comment("hello world") .build()); for (int i = 1; i < 6; i++) { LOGGER.info("sayHelloServerStreamSSE onNext: {} times", i); responseObserver.onNext(ServerSentEvent.<HelloReply>builder() .data(toReply("Hello " + ' ' + i + " times")) .build()); } LOGGER.info("sayHelloServerStreamSSE onCompleted"); responseObserver.onCompleted(); } @Override public StreamObserver<HelloRequest> sayHelloBiStream(StreamObserver<HelloReply> responseObserver) { LOGGER.info("Received sayHelloBiStream request"); return new StreamObserver<HelloRequest>() { @Override public void onNext(HelloRequest request) { LOGGER.info("sayHelloBiStream onNext: {}", request.getName()); responseObserver.onNext(toReply("Hello " + request.getName())); } @Override public void onError(Throwable throwable) { LOGGER.error("sayHelloBiStream onError", throwable); } @Override public void onCompleted() { LOGGER.info("sayHelloBiStream onCompleted"); } }; } private static HelloReply toReply(String message) { HelloReply reply = new HelloReply(); reply.setMessage(message); return reply; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/HelloRequest.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/HelloRequest.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.springboot.demo.servlet; import java.io.Serializable; public class HelloRequest implements Serializable { private static final long serialVersionUID = 1L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/ProviderApplication.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/ProviderApplication.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.springboot.demo.servlet; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableDubbo public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/ApiConsumer.java
dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-servlet/src/main/java/org/apache/dubbo/springboot/demo/servlet/ApiConsumer.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.springboot.demo.servlet; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApiConsumer { private static final Logger logger = LoggerFactory.getLogger(ApiConsumer.class); public static void main(String[] args) throws InterruptedException { ReferenceConfig<GreeterService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(GreeterService.class); referenceConfig.setCheck(false); referenceConfig.setProtocol(CommonConstants.TRIPLE); referenceConfig.setLazy(true); referenceConfig.setTimeout(100000); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap .application(new ApplicationConfig("dubbo-demo-triple-api-consumer")) .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) .reference(referenceConfig) .start(); GreeterService greeterService = referenceConfig.get(); logger.info("dubbo referenceConfig started"); logger.info("Call sayHello"); HelloReply reply = greeterService.sayHello(buildRequest("triple")); logger.info("sayHello reply: {}", reply.getMessage()); logger.info("Call sayHelloAsync"); CompletableFuture<String> sayHelloAsync = greeterService.sayHelloAsync("triple"); sayHelloAsync.thenAccept(value -> logger.info("sayHelloAsync reply: {}", value)); StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() { @Override public void onNext(HelloReply reply) { logger.info("sayHelloServerStream onNext: {}", reply.getMessage()); } @Override public void onError(Throwable t) { logger.info("sayHelloServerStream onError: {}", t.getMessage()); } @Override public void onCompleted() { logger.info("sayHelloServerStream onCompleted"); } }; logger.info("Call sayHelloServerStream"); greeterService.sayHelloServerStream(buildRequest("triple"), responseObserver); StreamObserver<HelloReply> sayHelloServerStreamNoParameterResponseObserver = new StreamObserver<HelloReply>() { @Override public void onNext(HelloReply reply) { logger.info("sayHelloServerStreamNoParameter onNext: {}", reply.getMessage()); } @Override public void onError(Throwable t) { logger.info("sayHelloServerStreamNoParameter onError: {}", t.getMessage()); } @Override public void onCompleted() { logger.info("sayHelloServerStreamNoParameter onCompleted"); } }; greeterService.sayHelloServerStreamNoParameter(sayHelloServerStreamNoParameterResponseObserver); StreamObserver<HelloReply> biResponseObserver = new StreamObserver<HelloReply>() { @Override public void onNext(HelloReply reply) { logger.info("biRequestObserver onNext: {}", reply.getMessage()); } @Override public void onError(Throwable t) { logger.info("biResponseObserver onError: {}", t.getMessage()); } @Override public void onCompleted() { logger.info("biResponseObserver onCompleted"); } }; logger.info("Call biRequestObserver"); StreamObserver<HelloRequest> biRequestObserver = greeterService.sayHelloBiStream(biResponseObserver); for (int i = 0; i < 5; i++) { biRequestObserver.onNext(buildRequest("triple" + i)); } biRequestObserver.onCompleted(); Thread.sleep(2000); } private static HelloRequest buildRequest(String name) { HelloRequest request = new HelloRequest(); request.setName(name); return request; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/McpDemoApplication.java
dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/McpDemoApplication.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.mcp.server.demo; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableDubbo public class McpDemoApplication { public static void main(String[] args) { SpringApplication.run(McpDemoApplication.class, args); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/NestedDetail.java
dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/NestedDetail.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.mcp.server.demo.demo; public class NestedDetail { private String detailInfo; private Double value; // Default constructor public NestedDetail() {} // Getters and Setters public String getDetailInfo() { return detailInfo; } public void setDetailInfo(String detailInfo) { this.detailInfo = detailInfo; } public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } @Override public String toString() { return "NestedDetail{" + "detailInfo='" + detailInfo + '\'' + ", value=" + value + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/ComplexResponse.java
dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/ComplexResponse.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.mcp.server.demo.demo; public class ComplexResponse { private String message; private boolean success; private int code; // Default constructor public ComplexResponse() {} public ComplexResponse(String message, boolean success, int code) { this.message = message; this.success = success; this.code = code; } // Getters and Setters public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } @Override public String toString() { return "ComplexResponse{" + "message='" + message + '\'' + ", success=" + success + ", code=" + code + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/ComplexRequest.java
dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/ComplexRequest.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.mcp.server.demo.demo; import java.util.List; import java.util.Map; public class ComplexRequest { private String greeting; private int count; private boolean active; private NestedDetail nestedDetail; private List<String> tags; private Map<String, String> attributes; // Default constructor (important for deserialization) public ComplexRequest() {} // Getters and Setters public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public NestedDetail getNestedDetail() { return nestedDetail; } public void setNestedDetail(NestedDetail nestedDetail) { this.nestedDetail = nestedDetail; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public Map<String, String> getAttributes() { return attributes; } public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; } @Override public String toString() { return "ComplexRequest{" + "greeting='" + greeting + '\'' + ", count=" + count + ", active=" + active + ", nestedDetail=" + nestedDetail + ", tags=" + tags + ", attributes=" + attributes + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/HelloServiceImpl.java
dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/HelloServiceImpl.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.mcp.server.demo.demo; import org.apache.dubbo.config.annotation.DubboService; @DubboService(mcpEnabled = true) public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { System.out.println("HelloServiceImpl.sayHello called with: " + name); if (name == null || name.trim().isEmpty()) { return "Hello, guest!"; } return "Hello, " + name + "!"; } @Override public ComplexResponse greetComplex(ComplexRequest request) { System.out.println("HelloServiceImpl.greetComplex called with: " + request); if (request == null) { return new ComplexResponse("Error: Request was null", false, 400); } String message = "Received: " + request.getGreeting() + ". Count: " + request.getCount() + ". Active: " + request.isActive() + ". Detail: " + (request.getNestedDetail() != null ? request.getNestedDetail().getDetailInfo() : "N/A") + ". Tags: " + (request.getTags() != null ? String.join(", ", request.getTags()) : "None") + ". Attributes: " + (request.getAttributes() != null ? request.getAttributes().toString() : "None"); return new ComplexResponse(message, true, 200); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/HelloService.java
dubbo-demo/dubbo-demo-mcp-server/src/main/java/org/apache/dubbo/mcp/server/demo/demo/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.mcp.server.demo.demo; import org.apache.dubbo.mcp.annotations.McpTool; import org.apache.dubbo.remoting.http12.rest.Mapping; @Mapping("") public interface HelloService { @McpTool @Mapping("/hello") String sayHello(String name); @McpTool @Mapping("/greetComplex") ComplexResponse greetComplex(ComplexRequest request); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-consumer/src/main/java/org/apache/dubbo/springboot/idl/demo/consumer/ConsumerApplication.java
dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-consumer/src/main/java/org/apache/dubbo/springboot/idl/demo/consumer/ConsumerApplication.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.springboot.idl.demo.consumer; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.demo.hello.GreeterService; import org.apache.dubbo.demo.hello.HelloReply; import org.apache.dubbo.demo.hello.HelloRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Service; @SpringBootApplication @Service @EnableDubbo public class ConsumerApplication { private static final Logger logger = LoggerFactory.getLogger(ConsumerApplication.class); @DubboReference private GreeterService demoService; public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args); ConsumerApplication application = context.getBean(ConsumerApplication.class); HelloReply result = application.doSayHello("world"); logger.info("result: {}", result.getMessage()); } public HelloReply doSayHello(String name) { return demoService.sayHello(HelloRequest.newBuilder().setName(name).build()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/test/java/org/apache/dubbo/springboot/idl/demo/MessageServiceTest.java
dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/test/java/org/apache/dubbo/springboot/idl/demo/MessageServiceTest.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.springboot.idl.demo; import org.apache.dubbo.demo.message.DubboMessageServiceTriple; import org.apache.dubbo.rpc.protocol.tri.service.SchemaDescriptorRegistry; import com.google.protobuf.Descriptors.FileDescriptor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class MessageServiceTest { @Test public void testMessageGenerator() { try { // load class Class.forName(DubboMessageServiceTriple.class.getName()); } catch (ClassNotFoundException ignored) { } FileDescriptor schemaDescriptor = SchemaDescriptorRegistry.getSchemaDescriptor(DubboMessageServiceTriple.SERVICE_NAME); Assertions.assertNotNull(schemaDescriptor); Assertions.assertEquals("message.proto", schemaDescriptor.getName()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/main/java/org/apache/dubbo/springboot/idl/demo/provider/GreeterServiceImpl.java
dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/main/java/org/apache/dubbo/springboot/idl/demo/provider/GreeterServiceImpl.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.springboot.idl.demo.provider; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.demo.hello.GreeterService; import org.apache.dubbo.demo.hello.HelloReply; import org.apache.dubbo.demo.hello.HelloRequest; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @DubboService public class GreeterServiceImpl implements GreeterService { private static final Logger LOGGER = LoggerFactory.getLogger(GreeterServiceImpl.class); @Override public HelloReply sayHello(HelloRequest request) { LOGGER.info("Received sayHello request: {}", request.getName()); return toReply("Hello " + request.getName()); } @Override public CompletableFuture<HelloReply> sayHelloAsync(HelloRequest request) { LOGGER.info("Received sayHelloAsync request: {}", request.getName()); HelloReply.newBuilder().setMessage("Hello " + request.getName()); return CompletableFuture.supplyAsync(() -> HelloReply.newBuilder().setMessage("Hello " + request.getName()).build()); } @Override public void sayHelloStream(HelloRequest request, StreamObserver<HelloReply> responseObserver) { LOGGER.info("Received sayHelloStream request: {}", request.getName()); for (int i = 0; i < 5; i++) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { responseObserver.onError(e); } responseObserver.onNext(HelloReply.newBuilder() .setMessage(i + "# Hello " + request.getName()) .build()); } responseObserver.onCompleted(); } private static HelloReply toReply(String message) { return HelloReply.newBuilder().setMessage(message).build(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/main/java/org/apache/dubbo/springboot/idl/demo/provider/ProviderApplication.java
dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/main/java/org/apache/dubbo/springboot/idl/demo/provider/ProviderApplication.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.springboot.idl.demo.provider; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import java.util.concurrent.CountDownLatch; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableDubbo public class ProviderApplication { public static void main(String[] args) throws Exception { SpringApplication.run(ProviderApplication.class, args); new CountDownLatch(1).await(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java
dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.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.demo.provider; import org.apache.dubbo.api.demo.DemoService; import org.apache.dubbo.rpc.RpcContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); @Override public String sayHello(String name) { logger.info("Hello " + name + ", request from consumer: " + RpcContext.getServiceContext().getRemoteAddress()); return "Hello " + name + ", response from provider: " + RpcContext.getServiceContext().getLocalAddress(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java
dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.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.demo.provider; import org.apache.dubbo.api.demo.DemoService; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; public class Application { private static final String ZOOKEEPER_URL = "zookeeper://127.0.0.1:2181"; public static void main(String[] args) { startWithBootstrap(); } private static void startWithBootstrap() { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress(ZOOKEEPER_URL); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap .application(new ApplicationConfig("dubbo-demo-api-provider")) .configCenter(configCenterConfig) .registry(new RegistryConfig(ZOOKEEPER_URL)) .metadataReport(new MetadataReportConfig(ZOOKEEPER_URL)) .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) .service(service) .start() .await(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-api/dubbo-demo-api-interface/src/main/java/org/apache/dubbo/api/demo/DemoService.java
dubbo-demo/dubbo-demo-api/dubbo-demo-api-interface/src/main/java/org/apache/dubbo/api/demo/DemoService.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.api.demo; import java.util.concurrent.CompletableFuture; public interface DemoService { String sayHello(String name); /** * Asynchronous method example. * <p> * This method returns a {@link CompletableFuture<String>} to demonstrate Dubbo's asynchronous invocation capability. * Developers are recommended to refer to the official sample project for complete usage: * <a href="https://github.com/lqscript/dubbo-samples/tree/master/2-advanced/dubbo-samples-async/dubbo-samples-async-original-future"> * Dubbo Async Invocation Sample</a> * </p> * * @param name Input name parameter * @return Asynchronous result wrapped in CompletableFuture */ default CompletableFuture<String> sayHelloAsync(String name) { return CompletableFuture.completedFuture(sayHello(name)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java
dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.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.demo.consumer; import org.apache.dubbo.api.demo.DemoService; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.service.GenericService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); private static final String ZOOKEEPER_URL = "zookeeper://127.0.0.1:2181"; public static void main(String[] args) { runWithBootstrap(); } private static void runWithBootstrap() { ReferenceConfig<DemoService> reference = new ReferenceConfig<>(); reference.setInterface(DemoService.class); reference.setGeneric("true"); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress(ZOOKEEPER_URL); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap .application(new ApplicationConfig("dubbo-demo-api-consumer")) .configCenter(configCenterConfig) .registry(new RegistryConfig(ZOOKEEPER_URL)) .metadataReport(new MetadataReportConfig(ZOOKEEPER_URL)) .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) .reference(reference) .start(); DemoService demoService = bootstrap.getCache().get(reference); String message = demoService.sayHello("dubbo"); logger.info(message); // generic invoke GenericService genericService = (GenericService) demoService; Object genericInvokeResult = genericService.$invoke( "sayHello", new String[] {String.class.getName()}, new Object[] {"dubbo generic invoke"}); logger.info(genericInvokeResult.toString()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/Type.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/Type.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.service; public enum Type { High, Normal, Lower }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/ComplexObject.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/ComplexObject.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.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * ON 2018/11/5 */ public class ComplexObject { public ComplexObject() {} public ComplexObject( String var1, int var2, long l, String[] var3, List<Integer> var4, ComplexObject.TestEnum testEnum) { this.setInnerObject(new ComplexObject.InnerObject()); this.getInnerObject().setInnerA(var1); this.getInnerObject().setInnerB(var2); this.setIntList(var4); this.setStrArrays(var3); this.setTestEnum(testEnum); this.setV(l); InnerObject2 io21 = new InnerObject2(); io21.setInnerA2(var1 + "_21"); io21.setInnerB2(var2 + 100000); InnerObject2 io22 = new InnerObject2(); io22.setInnerA2(var1 + "_22"); io22.setInnerB2(var2 + 200000); this.setInnerObject2(new ArrayList<>(Arrays.asList(io21, io22))); InnerObject3 io31 = new InnerObject3(); io31.setInnerA3(var1 + "_31"); InnerObject3 io32 = new InnerObject3(); io32.setInnerA3(var1 + "_32"); InnerObject3 io33 = new InnerObject3(); io33.setInnerA3(var1 + "_33"); this.setInnerObject3(new InnerObject3[] {io31, io32, io33}); this.maps = new HashMap<>(4); this.maps.put(var1 + "_k1", var1 + "_v1"); this.maps.put(var1 + "_k2", var1 + "_v2"); } private InnerObject innerObject; private List<InnerObject2> innerObject2; private InnerObject3[] innerObject3; private String[] strArrays; private List<Integer> intList; private long v; private TestEnum testEnum; private Map<String, String> maps; public InnerObject getInnerObject() { return innerObject; } public void setInnerObject(InnerObject innerObject) { this.innerObject = innerObject; } public String[] getStrArrays() { return strArrays; } public void setStrArrays(String[] strArrays) { this.strArrays = strArrays; } public List<Integer> getIntList() { return intList; } public void setIntList(List<Integer> intList) { this.intList = intList; } public long getV() { return v; } public void setV(long v) { this.v = v; } public TestEnum getTestEnum() { return testEnum; } public void setTestEnum(TestEnum testEnum) { this.testEnum = testEnum; } public List<InnerObject2> getInnerObject2() { return innerObject2; } public void setInnerObject2(List<InnerObject2> innerObject2) { this.innerObject2 = innerObject2; } public InnerObject3[] getInnerObject3() { return innerObject3; } public void setInnerObject3(InnerObject3[] innerObject3) { this.innerObject3 = innerObject3; } public Map<String, String> getMaps() { return maps; } public void setMaps(Map<String, String> maps) { this.maps = maps; } @Override public String toString() { return "ComplexObject{" + "innerObject=" + innerObject + ", innerObject2=" + innerObject2 + ", innerObject3=" + Arrays.toString(innerObject3) + ", strArrays=" + Arrays.toString(strArrays) + ", intList=" + intList + ", v=" + v + ", testEnum=" + testEnum + ", maps=" + maps + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ComplexObject)) return false; ComplexObject that = (ComplexObject) o; return getV() == that.getV() && Objects.equals(getInnerObject(), that.getInnerObject()) && Objects.equals(getInnerObject2(), that.getInnerObject2()) && Arrays.equals(getInnerObject3(), that.getInnerObject3()) && Arrays.equals(getStrArrays(), that.getStrArrays()) && Objects.equals(getIntList(), that.getIntList()) && getTestEnum() == that.getTestEnum() && Objects.equals(getMaps(), that.getMaps()); } @Override public int hashCode() { int result = Objects.hash(getInnerObject(), getInnerObject2(), getIntList(), getV(), getTestEnum(), getMaps()); result = 31 * result + Arrays.hashCode(getInnerObject3()); result = 31 * result + Arrays.hashCode(getStrArrays()); return result; } public enum TestEnum { VALUE1, VALUE2 } public static class InnerObject { String innerA; int innerB; public String getInnerA() { return innerA; } public void setInnerA(String innerA) { this.innerA = innerA; } public int getInnerB() { return innerB; } public void setInnerB(int innerB) { this.innerB = innerB; } @Override public String toString() { return "InnerObject{" + "innerA='" + innerA + '\'' + ", innerB=" + innerB + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InnerObject)) return false; InnerObject that = (InnerObject) o; return getInnerB() == that.getInnerB() && Objects.equals(getInnerA(), that.getInnerA()); } @Override public int hashCode() { return Objects.hash(getInnerA(), getInnerB()); } } public static class InnerObject2 { String innerA2; int innerB2; public String getInnerA2() { return innerA2; } public void setInnerA2(String innerA2) { this.innerA2 = innerA2; } public int getInnerB2() { return innerB2; } public void setInnerB2(int innerB2) { this.innerB2 = innerB2; } @Override public String toString() { return "InnerObject{" + "innerA='" + innerA2 + '\'' + ", innerB=" + innerB2 + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InnerObject2)) return false; InnerObject2 that = (InnerObject2) o; return getInnerB2() == that.getInnerB2() && Objects.equals(getInnerA2(), that.getInnerA2()); } @Override public int hashCode() { return Objects.hash(getInnerA2(), getInnerB2()); } } public static class InnerObject3 { String innerA3; public String getInnerA3() { return innerA3; } public void setInnerA3(String innerA3) { this.innerA3 = innerA3; } @Override public String toString() { return "InnerObject3{" + "innerA3='" + innerA3 + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InnerObject3)) return false; InnerObject3 that = (InnerObject3) o; return Objects.equals(getInnerA3(), that.getInnerA3()); } @Override public int hashCode() { return Objects.hash(getInnerA3()); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/Person.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/Person.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.service; import java.io.Serializable; /** * Person.java */ public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; 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; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoServiceImpl.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoServiceImpl.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.service; import org.apache.dubbo.rpc.RpcContext; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); public DemoServiceImpl() { super(); } public String sayHello(String name) { return "hello " + name; } public long timestamp() { return System.currentTimeMillis(); } public String getThreadName() { return Thread.currentThread().getName(); } public int getSize(String[] strs) { if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { logger.info( "RpcContext.getServerAttachment().getRemoteHost()={}", RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { if (types.length == 0) return Type.Lower; return types[0]; } public Type enumlength(Type type) { return type; } public int stringLength(String str) { return str.length(); } public String get(CustomArgument arg1) { return arg1.toString(); } public byte getbyte(byte arg) { return arg; } @Override public String complexCompute(String input, ComplexObject co) { return input + "###" + co.toString(); } @Override public ComplexObject findComplexObject( String var1, int var2, long l, String[] var3, List<Integer> var4, ComplexObject.TestEnum testEnum) { return new ComplexObject(var1, var2, l, var3, var4, testEnum); } public Person gerPerson(Person person) { return person; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoService.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoService.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.service; import java.util.List; public interface DemoService { String sayHello(String name); long timestamp(); String getThreadName(); int getSize(String[] strs); int getSize(Object[] os); Object invoke(String service, String method) throws Exception; int stringLength(String str); Type enumlength(Type... types); // Type enumlength(Type type); String get(CustomArgument arg1); byte getbyte(byte arg); String complexCompute(String input, ComplexObject co); ComplexObject findComplexObject( String var1, int var2, long l, String[] var3, List<Integer> var4, ComplexObject.TestEnum testEnum); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.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.service; import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ public class MockInvocation implements Invocation { private String arg0; private Map<String, Object> attachments; public MockInvocation(String arg0) { this.arg0 = arg0; attachments = new HashMap<>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } @Override public String getServiceName() { return "DemoService"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {arg0}; } public Map<String, String> getAttachments() { return new AttachmentsAdapter.ObjectToStringMap(attachments); } @Override public Map<String, Object> getObjectAttachments() { return attachments; } @Override public Map<String, Object> copyObjectAttachments() { return new HashMap<>(attachments); } @Override public void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) { attachments.entrySet().forEach(consumer); } @Override public void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override public void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { attachments.put(key, value); } @Override public void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setObjectAttachmentIfAbsent(String key, Object value) { attachments.put(key, value); } public Invoker<?> getInvoker() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key) { return attachments.get(key); } public String getAttachment(String key, String defaultValue) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key, Object defaultValue) { Object result = attachments.get(key); if (result == null) { return defaultValue; } return result; } @Override public void addInvokedInvoker(Invoker<?> invoker) {} @Override public List<Invoker<?>> getInvokedInvokers() { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/service/CustomArgument.java
dubbo-compatible/src/test/java/org/apache/dubbo/service/CustomArgument.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.service; import java.io.Serializable; @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; public CustomArgument() {} public CustomArgument(Type type, String name) { super(); this.type = type; this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/filter/MyFilter.java
dubbo-compatible/src/test/java/org/apache/dubbo/filter/MyFilter.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.filter; import com.alibaba.dubbo.rpc.Filter; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcResult; public class MyFilter implements Filter { public static int count = 0; @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { count++; if (invocation.getArguments()[0].equals("aa")) { throw new RpcException(new IllegalArgumentException("arg0 illegal")); } if (invocation.getArguments()[0].equals("cc")) { return new RpcResult("123test"); } Result tmp = invoker.invoke(invocation); return tmp; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/filter/FilterTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/filter/FilterTest.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.filter; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.Filter; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; class FilterTest { Filter myFilter = new MyFilter(); @Test void testInvokeException() { try { Invoker<FilterTest> invoker = new LegacyInvoker<FilterTest>(null); Invocation invocation = new LegacyInvocation("aa"); myFilter.invoke(invoker, invocation); fail(); } catch (RpcException e) { Assertions.assertTrue(e.getMessage().contains("arg0 illegal")); } } @Test void testDefault() throws Throwable { Invoker<FilterTest> invoker = new LegacyInvoker<FilterTest>(null); org.apache.dubbo.rpc.Invocation invocation = new RpcInvocation( null, "echo", "DemoService", "DemoService", new Class[] {String.class}, new Object[] {"bbb"}); org.apache.dubbo.rpc.Result res = myFilter.invoke(invoker, invocation); Assertions.assertEquals("alibaba", res.recreate()); } @Test void testRecreate() throws Throwable { Invoker<FilterTest> invoker = new LegacyInvoker<FilterTest>(null); org.apache.dubbo.rpc.Invocation invocation = new RpcInvocation( null, "echo", "DemoService", "DemoService", new Class[] {String.class}, new Object[] {"cc"}); org.apache.dubbo.rpc.Result res = myFilter.invoke(invoker, invocation); Assertions.assertEquals("123test", res.recreate()); } @AfterAll public static void tear() { Assertions.assertEquals(3, MyFilter.count); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java
dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.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.filter; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ public class LegacyInvocation implements Invocation { private String arg0; public LegacyInvocation(String arg0) { this.arg0 = arg0; } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {arg0}; } public Map<String, String> getAttachments() { Map<String, String> attachments = new HashMap<String, String>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); return attachments; } public Invoker<?> getInvoker() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return getAttachments().get(key); } public String getAttachment(String key, String defaultValue) { return getAttachments().get(key); } @Override public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker<?> invoker) {} @Override public List<org.apache.dubbo.rpc.Invoker<?>> getInvokedInvokers() { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java
dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.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.filter; import org.apache.dubbo.service.DemoService; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcResult; public class LegacyInvoker<T> implements Invoker<T> { URL url; Class<T> type; boolean hasException = false; public LegacyInvoker(URL url) { this.url = url; type = (Class<T>) DemoService.class; } public LegacyInvoker(URL url, boolean hasException) { this.url = url; type = (Class<T>) DemoService.class; this.hasException = hasException; } @Override public Class<T> getInterface() { return type; } public URL getUrl() { return url; } @Override public boolean isAvailable() { return false; } public Result invoke(Invocation invocation) throws RpcException { RpcResult result = new RpcResult(); if (!hasException) { result.setValue("alibaba"); } else { result.setException(new RuntimeException("mocked exception")); } return result; } @Override public void destroy() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.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.generic; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.definition.model.MethodDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.service.ComplexObject; import org.apache.dubbo.service.DemoService; import org.apache.dubbo.service.DemoServiceImpl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.dubbo.config.ReferenceConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class GenericServiceTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @Test void testGeneric() { DemoService server = new DemoServiceImpl(); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0"); Exporter<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); Invoker<DemoService> invoker = protocol.refer(DemoService.class, url); GenericService client = (GenericService) proxyFactory.getProxy(invoker, true); Object result = client.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result); org.apache.dubbo.rpc.service.GenericService newClient = (org.apache.dubbo.rpc.service.GenericService) proxyFactory.getProxy(invoker, true); Object res = newClient.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"hehe"}); Assertions.assertEquals("hello hehe", res); invoker.destroy(); exporter.unexport(); } @Test void testGeneric2() { DemoService server = new DemoServiceImpl(); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf( "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); Invoker<GenericService> invoker = protocol.refer(GenericService.class, url); GenericService client = proxyFactory.getProxy(invoker, true); Object result = client.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result); Invoker<DemoService> invoker2 = protocol.refer(DemoService.class, url); GenericService client2 = (GenericService) proxyFactory.getProxy(invoker2, true); Object result2 = client2.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result2); invoker.destroy(); exporter.unexport(); } @Test void testGenericCompatible() { DubboBootstrap.getInstance().application("test-app").initialize(); DemoService server = new DemoServiceImpl(); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf( "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); // simulate normal invoke ReferenceConfig oldReferenceConfig = new ReferenceConfig<>(); oldReferenceConfig.setGeneric(true); oldReferenceConfig.setInterface(DemoService.class.getName()); oldReferenceConfig.refresh(); Invoker invoker = protocol.refer(oldReferenceConfig.getInterfaceClass(), url); GenericService client = (GenericService) proxyFactory.getProxy(invoker, true); Assertions.assertInstanceOf(Dubbo2CompactUtils.getGenericServiceClass(), client); Object result = client.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result); invoker.destroy(); exporter.unexport(); } @Test void testGenericComplexCompute4FullServiceMetadata() { DemoService server = new DemoServiceImpl(); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf( "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); String var1 = "v1"; int var2 = 234; long l = 555; String[] var3 = {"var31", "var32"}; List<Integer> var4 = Arrays.asList(2, 4, 8); ComplexObject.TestEnum testEnum = ComplexObject.TestEnum.VALUE2; FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(DemoService.class); MethodDefinition methodDefinition = getMethod("complexCompute", fullServiceDefinition.getMethods()); Map mapObject = createComplexObject(fullServiceDefinition, var1, var2, l, var3, var4, testEnum); ComplexObject complexObject = map2bean(mapObject); Invoker<GenericService> invoker = protocol.refer(GenericService.class, url); GenericService client = proxyFactory.getProxy(invoker, true); Object result = client.$invoke( methodDefinition.getName(), methodDefinition.getParameterTypes(), new Object[] {"haha", mapObject}); String r1 = (String) result; Assertions.assertTrue(r1.startsWith("haha###")); Assertions.assertTrue(r1.contains("v1_k1=v1_v1")); Assertions.assertTrue(r1.contains("v1_k2=v1_v2")); Invoker<DemoService> invoker2 = protocol.refer(DemoService.class, url); GenericService client2 = (GenericService) proxyFactory.getProxy(invoker2, true); Object result2 = client2.$invoke( "complexCompute", methodDefinition.getParameterTypes(), new Object[] {"haha2", mapObject}); String r2 = (String) result2; Assertions.assertTrue(r2.startsWith("haha2###")); Assertions.assertTrue(r2.contains("v1_k1=v1_v1")); Assertions.assertTrue(r2.contains("v1_k2=v1_v2")); invoker.destroy(); exporter.unexport(); } @Test void testGenericFindComplexObject4FullServiceMetadata() { DemoService server = new DemoServiceImpl(); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf( "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); String var1 = "v1"; int var2 = 234; long l = 555; String[] var3 = {"var31", "var32"}; List<Integer> var4 = Arrays.asList(2, 4, 8); ComplexObject.TestEnum testEnum = ComplexObject.TestEnum.VALUE2; // ComplexObject complexObject = createComplexObject(var1, var2, l, var3, var4, testEnum); Invoker<GenericService> invoker = protocol.refer(GenericService.class, url); GenericService client = proxyFactory.getProxy(invoker, true); Object result = client.$invoke( "findComplexObject", new String[] { "java.lang.String", "int", "long", "java.lang.String[]", "java.util.List", "org.apache.dubbo.service.ComplexObject$TestEnum" }, new Object[] {var1, var2, l, var3, var4, testEnum}); Assertions.assertNotNull(result); ComplexObject r = map2bean((Map) result); Assertions.assertEquals(r, createComplexObject(var1, var2, l, var3, var4, testEnum)); invoker.destroy(); exporter.unexport(); } MethodDefinition getMethod(String methodName, List<MethodDefinition> list) { for (MethodDefinition methodDefinition : list) { if (methodDefinition.getName().equals(methodName)) { return methodDefinition; } } return null; } Map<String, Object> createComplexObject( FullServiceDefinition fullServiceDefinition, String var1, int var2, long l, String[] var3, List<Integer> var4, ComplexObject.TestEnum testEnum) { List<TypeDefinition> typeDefinitions = fullServiceDefinition.getTypes(); TypeDefinition topTypeDefinition = null; TypeDefinition innerTypeDefinition = null; TypeDefinition inner2TypeDefinition = null; TypeDefinition inner3TypeDefinition = null; for (TypeDefinition typeDefinition : typeDefinitions) { if (typeDefinition.getType().equals(ComplexObject.class.getCanonicalName())) { topTypeDefinition = typeDefinition; } else if (typeDefinition.getType().equals(ComplexObject.InnerObject.class.getCanonicalName())) { innerTypeDefinition = typeDefinition; } else if (typeDefinition.getType().equals(ComplexObject.InnerObject2.class.getCanonicalName())) { inner2TypeDefinition = typeDefinition; } else if (typeDefinition.getType().equals(ComplexObject.InnerObject3.class.getCanonicalName())) { inner3TypeDefinition = typeDefinition; } } Assertions.assertEquals("long", topTypeDefinition.getProperties().get("v")); Assertions.assertEquals( "java.util.Map<java.lang.String,java.lang.String>", topTypeDefinition.getProperties().get("maps")); Assertions.assertEquals( "org.apache.dubbo.service.ComplexObject.InnerObject", topTypeDefinition.getProperties().get("innerObject")); Assertions.assertEquals( "java.util.List<java.lang.Integer>", topTypeDefinition.getProperties().get("intList")); Assertions.assertEquals( "java.lang.String[]", topTypeDefinition.getProperties().get("strArrays")); Assertions.assertEquals( "org.apache.dubbo.service.ComplexObject.InnerObject3[]", topTypeDefinition.getProperties().get("innerObject3")); Assertions.assertEquals( "org.apache.dubbo.service.ComplexObject.TestEnum", topTypeDefinition.getProperties().get("testEnum")); Assertions.assertEquals( "java.util.List<org.apache.dubbo.service.ComplexObject.InnerObject2>", topTypeDefinition.getProperties().get("innerObject2")); Assertions.assertSame( "java.lang.String", innerTypeDefinition.getProperties().get("innerA")); Assertions.assertSame("int", innerTypeDefinition.getProperties().get("innerB")); Assertions.assertSame( "java.lang.String", inner2TypeDefinition.getProperties().get("innerA2")); Assertions.assertSame("int", inner2TypeDefinition.getProperties().get("innerB2")); Assertions.assertSame( "java.lang.String", inner3TypeDefinition.getProperties().get("innerA3")); Map<String, Object> result = new HashMap<>(); result.put("v", l); Map maps = new HashMap<>(4); maps.put(var1 + "_k1", var1 + "_v1"); maps.put(var1 + "_k2", var1 + "_v2"); result.put("maps", maps); result.put("intList", var4); result.put("strArrays", var3); result.put("testEnum", testEnum.name()); Map innerObjectMap = new HashMap<>(4); result.put("innerObject", innerObjectMap); innerObjectMap.put("innerA", var1); innerObjectMap.put("innerB", var2); List<Map> innerObject2List = new ArrayList<>(); result.put("innerObject2", innerObject2List); Map innerObject2Tmp1 = new HashMap<>(4); innerObject2Tmp1.put("innerA2", var1 + "_21"); innerObject2Tmp1.put("innerB2", var2 + 100000); Map innerObject2Tmp2 = new HashMap<>(4); innerObject2Tmp2.put("innerA2", var1 + "_22"); innerObject2Tmp2.put("innerB2", var2 + 200000); innerObject2List.add(innerObject2Tmp1); innerObject2List.add(innerObject2Tmp2); Map innerObject3Tmp1 = new HashMap<>(4); innerObject3Tmp1.put("innerA3", var1 + "_31"); Map innerObject3Tmp2 = new HashMap<>(4); innerObject3Tmp2.put("innerA3", var1 + "_32"); Map innerObject3Tmp3 = new HashMap<>(4); innerObject3Tmp3.put("innerA3", var1 + "_32"); result.put("innerObject3", new Map[] {innerObject3Tmp1, innerObject3Tmp2, innerObject3Tmp3}); return result; } Map<String, Object> bean2Map(ComplexObject complexObject) { return JsonUtils.toJavaObject(JsonUtils.toJson(complexObject), Map.class); } ComplexObject map2bean(Map<String, Object> map) { return JsonUtils.toJavaObject(JsonUtils.toJson(map), ComplexObject.class); } ComplexObject createComplexObject( String var1, int var2, long l, String[] var3, List<Integer> var4, ComplexObject.TestEnum testEnum) { return new ComplexObject(var1, var2, l, var3, var4, testEnum); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.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.tools; import org.apache.dubbo.config.annotation.Service; import java.io.Serializable; /** * {@link TestService} Implementation * * @since 2.7.6 */ @com.alibaba.dubbo.config.annotation.Service( interfaceName = "org.apache.dubbo.metadata.tools.TestService", interfaceClass = TestService.class, version = "3.0.0", group = "test") @Service( interfaceName = "org.apache.dubbo.metadata.tools.TestService", interfaceClass = TestService.class, version = "3.0.0", group = "test") public class TestServiceImpl extends GenericTestService implements TestService, AutoCloseable, Serializable { @Override public String echo(String message) { return "[ECHO] " + message; } @Override public void close() throws Exception {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.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.tools; import java.util.EventListener; import com.alibaba.dubbo.config.annotation.Service; /** * {@link TestService} Implementation * * @since 2.7.6 */ @Service(version = "2.0.0", group = "generic") public class GenericTestService extends DefaultTestService implements TestService, EventListener { @Override public String echo(String message) { return "[ECHO] " + message; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.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.tools; import java.io.Serializable; public class Ancestor implements Serializable { private boolean z; public boolean isZ() { return z; } public void setZ(boolean z) { this.z = z; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.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.tools; import org.apache.dubbo.metadata.annotation.processing.model.Model; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import java.util.concurrent.TimeUnit; /** * Test Service * * @since 2.7.6 */ @Path("/echo") public interface TestService { @GET <T> String echo(@PathParam("message") @DefaultValue("mercyblitz") String message); @POST Model model(@PathParam("model") Model model); // Test primitive @PUT String testPrimitive(boolean z, int i); // Test enumeration @PUT Model testEnum(TimeUnit timeUnit); // Test Array @GET String testArray(String[] strArray, int[] intArray, Model[] modelArray); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.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.tools; import java.io.IOException; import org.junit.jupiter.api.Test; /** * The Compiler test case */ class CompilerTest { @Test void testCompile() throws IOException { Compiler compiler = new Compiler(); compiler.compile(TestServiceImpl.class, DefaultTestService.class, GenericTestService.class); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.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.tools; import javax.annotation.processing.Processor; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import static java.util.Arrays.asList; /** * The Java Compiler */ public class Compiler { private final File sourceDirectory; private final JavaCompiler javaCompiler; private final StandardJavaFileManager javaFileManager; private final Set<Processor> processors = new LinkedHashSet<>(); public Compiler() throws IOException { this(defaultTargetDirectory()); } public Compiler(File targetDirectory) throws IOException { this(defaultSourceDirectory(), targetDirectory); } public Compiler(File sourceDirectory, File targetDirectory) throws IOException { this.sourceDirectory = sourceDirectory; this.javaCompiler = ToolProvider.getSystemJavaCompiler(); this.javaFileManager = javaCompiler.getStandardFileManager(null, null, null); this.javaFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(targetDirectory)); this.javaFileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(targetDirectory)); } private static File defaultSourceDirectory() { return new File(defaultRootDirectory(), "src/test/java"); } private static File defaultRootDirectory() { return detectClassPath(Compiler.class).getParentFile().getParentFile(); } private static File defaultTargetDirectory() { File dir = new File(defaultRootDirectory(), "target/generated-classes"); dir.mkdirs(); return dir; } private static File detectClassPath(Class<?> targetClass) { URL classFileURL = targetClass.getProtectionDomain().getCodeSource().getLocation(); if ("file".equals(classFileURL.getProtocol())) { return new File(classFileURL.getPath()); } else { throw new RuntimeException("No support"); } } public Compiler processors(Processor... processors) { this.processors.addAll(asList(processors)); return this; } private Iterable<? extends JavaFileObject> getJavaFileObjects(Class<?>... sourceClasses) { int size = sourceClasses == null ? 0 : sourceClasses.length; File[] javaSourceFiles = new File[size]; for (int i = 0; i < size; i++) { File javaSourceFile = javaSourceFile(sourceClasses[i].getName()); javaSourceFiles[i] = javaSourceFile; } return javaFileManager.getJavaFileObjects(javaSourceFiles); } private File javaSourceFile(String sourceClassName) { String javaSourceFilePath = sourceClassName.replace('.', '/').concat(".java"); return new File(sourceDirectory, javaSourceFilePath); } public boolean compile(Class<?>... sourceClasses) { JavaCompiler.CompilationTask task = javaCompiler.getTask( null, this.javaFileManager, null, asList("-parameters", "-Xlint:unchecked", "-nowarn", "-Xlint:deprecation"), // null, null, getJavaFileObjects(sourceClasses)); if (!processors.isEmpty()) { task.setProcessors(processors); } return task.call(); } public JavaCompiler getJavaCompiler() { return javaCompiler; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.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.tools; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.metadata.annotation.processing.model.Model; import java.util.concurrent.TimeUnit; /** * {@link TestService} Implementation * * @since 2.7.6 */ @Service(interfaceName = "org.apache.dubbo.metadata.tools.TestService", version = "1.0.0", group = "default") public class DefaultTestService implements TestService { private String name; @Override public String echo(String message) { return "[ECHO] " + message; } @Override public Model model(Model model) { return model; } @Override public String testPrimitive(boolean z, int i) { return null; } @Override public Model testEnum(TimeUnit timeUnit) { return null; } @Override public String testArray(String[] strArray, int[] intArray, Model[] modelArray) { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Parent.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Parent.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.tools; public class Parent extends Ancestor { private byte b; private short s; private int i; private long l; public byte getB() { return b; } public void setB(byte b) { this.b = b; } public short getS() { return s; } public void setS(short s) { this.s = s; } public int getI() { return i; } public void setI(int i) { this.i = i; } public long getL() { return l; } public void setL(long l) { this.l = l; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.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.tools; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; import java.util.Set; import static javax.lang.model.SourceVersion.latestSupported; /** * {@link Processor} for test * * @since 2.7.6 */ @SupportedAnnotationTypes("*") public class TestProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { return false; } public ProcessingEnvironment getProcessingEnvironment() { return super.processingEnv; } public SourceVersion getSupportedSourceVersion() { return latestSupported(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.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.annotation.processing; import org.apache.dubbo.metadata.tools.Compiler; import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Set; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.InvocationInterceptor; import org.junit.jupiter.api.extension.ReflectiveInvocationContext; import static org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest.testInstanceHolder; public class CompilerInvocationInterceptor implements InvocationInterceptor { @Override public void interceptTestMethod( Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable { Set<Class<?>> classesToBeCompiled = new LinkedHashSet<>(); AbstractAnnotationProcessingTest abstractAnnotationProcessingTest = testInstanceHolder.get(); classesToBeCompiled.add(getClass()); abstractAnnotationProcessingTest.addCompiledClasses(classesToBeCompiled); Compiler compiler = new Compiler(); compiler.processors(new AnnotationProcessingTestProcessor( abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext)); compiler.compile(classesToBeCompiled.toArray(new Class[0])); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.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.annotation.processing; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; import java.lang.reflect.Method; import java.util.Set; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.InvocationInterceptor; import org.junit.jupiter.api.extension.ReflectiveInvocationContext; import static javax.lang.model.SourceVersion.latestSupported; @SupportedAnnotationTypes("*") public class AnnotationProcessingTestProcessor extends AbstractProcessor { private final AbstractAnnotationProcessingTest abstractAnnotationProcessingTest; private final InvocationInterceptor.Invocation<Void> invocation; private final ReflectiveInvocationContext<Method> invocationContext; private final ExtensionContext extensionContext; public AnnotationProcessingTestProcessor( AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, InvocationInterceptor.Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) { this.abstractAnnotationProcessingTest = abstractAnnotationProcessingTest; this.invocation = invocation; this.invocationContext = invocationContext; this.extensionContext = extensionContext; } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver()) { prepare(); abstractAnnotationProcessingTest.beforeEach(); try { invocation.proceed(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } return false; } private void prepare() { abstractAnnotationProcessingTest.processingEnv = super.processingEnv; abstractAnnotationProcessingTest.elements = super.processingEnv.getElementUtils(); abstractAnnotationProcessingTest.types = super.processingEnv.getTypeUtils(); } @Override public SourceVersion getSupportedSourceVersion() { return latestSupported(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.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.annotation.processing; import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; /** * Abstract {@link Annotation} Processing Test case * * @since 2.7.6 */ @ExtendWith(CompilerInvocationInterceptor.class) public abstract class AbstractAnnotationProcessingTest { static ThreadLocal<AbstractAnnotationProcessingTest> testInstanceHolder = new ThreadLocal<>(); protected ProcessingEnvironment processingEnv; protected Elements elements; protected Types types; @BeforeEach public final void init() { testInstanceHolder.set(this); } @AfterEach public final void destroy() { testInstanceHolder.remove(); } protected abstract void addCompiledClasses(Set<Class<?>> classesToBeCompiled); protected abstract void beforeEach(); protected TypeElement getType(Class<?> type) { return TypeUtils.getType(processingEnv, type); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.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.annotation.processing.util; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info; import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link LoggerUtils} Test * * @since 2.7.6 */ class LoggerUtilsTest { @Test void testLogger() { assertNotNull(LoggerUtils.LOGGER); } @Test void testInfo() { info("Hello,World"); info("Hello,%s", "World"); info("%s,%s", "Hello", "World"); } @Test void testWarn() { warn("Hello,World"); warn("Hello,%s", "World"); warn("%s,%s", "Hello", "World"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.util; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.ws.rs.Path; import java.util.Iterator; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAllAnnotations; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotations; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * The {@link AnnotationUtils} Test * * @since 2.7.6 */ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {} @Override protected void beforeEach() { testType = getType(TestServiceImpl.class); } @Test void testGetAnnotation() { AnnotationMirror serviceAnnotation = getAnnotation(testType, Service.class); assertEquals("3.0.0", getAttribute(serviceAnnotation, "version")); assertEquals("test", getAttribute(serviceAnnotation, "group")); assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(serviceAnnotation, "interfaceName")); assertNull(getAnnotation(testType, (Class) null)); assertNull(getAnnotation(testType, (String) null)); assertNull(getAnnotation(testType.asType(), (Class) null)); assertNull(getAnnotation(testType.asType(), (String) null)); assertNull(getAnnotation((Element) null, (Class) null)); assertNull(getAnnotation((Element) null, (String) null)); assertNull(getAnnotation((TypeElement) null, (Class) null)); assertNull(getAnnotation((TypeElement) null, (String) null)); } @Test void testGetAnnotations() { List<AnnotationMirror> annotations = getAnnotations(testType); Iterator<AnnotationMirror> iterator = annotations.iterator(); assertEquals(2, annotations.size()); assertEquals( "com.alibaba.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); assertEquals( "org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Service.class); iterator = annotations.iterator(); assertEquals(1, annotations.size()); assertEquals( "org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType.asType(), Service.class); iterator = annotations.iterator(); assertEquals(1, annotations.size()); assertEquals( "org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType.asType(), Service.class.getTypeName()); iterator = annotations.iterator(); assertEquals(1, annotations.size()); assertEquals( "org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Override.class); assertEquals(0, annotations.size()); annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class); assertEquals(1, annotations.size()); assertTrue(getAnnotations(null, (Class) null).isEmpty()); assertTrue(getAnnotations(null, (String) null).isEmpty()); assertTrue(getAnnotations(testType, (Class) null).isEmpty()); assertTrue(getAnnotations(testType, (String) null).isEmpty()); assertTrue(getAnnotations(null, Service.class).isEmpty()); assertTrue(getAnnotations(null, Service.class.getTypeName()).isEmpty()); } @Test void testGetAllAnnotations() { List<AnnotationMirror> annotations = getAllAnnotations(testType); assertEquals(5, annotations.size()); annotations = getAllAnnotations(testType.asType(), annotation -> true); assertEquals(5, annotations.size()); annotations = getAllAnnotations(processingEnv, TestServiceImpl.class); assertEquals(5, annotations.size()); annotations = getAllAnnotations(testType.asType(), Service.class); assertEquals(2, annotations.size()); annotations = getAllAnnotations(testType, Override.class); assertEquals(0, annotations.size()); annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); assertEquals(2, annotations.size()); assertTrue(getAllAnnotations((Element) null, (Class) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null, (String) null).isEmpty()); assertTrue(getAllAnnotations((ProcessingEnvironment) null, (Class) null).isEmpty()); assertTrue( getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty()); assertTrue(getAllAnnotations((Element) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null).isEmpty()); assertTrue(getAllAnnotations(processingEnv, (Class) null).isEmpty()); assertTrue(getAllAnnotations(processingEnv, (String) null).isEmpty()); assertTrue(getAllAnnotations(testType, (Class) null).isEmpty()); assertTrue(getAllAnnotations(testType.asType(), (Class) null).isEmpty()); assertTrue(getAllAnnotations(testType, (String) null).isEmpty()); assertTrue(getAllAnnotations(testType.asType(), (String) null).isEmpty()); assertTrue(getAllAnnotations((Element) null, Service.class).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName()) .isEmpty()); } @Test void testFindAnnotation() { assertEquals( "org.apache.dubbo.config.annotation.Service", findAnnotation(testType, Service.class).getAnnotationType().toString()); assertEquals( "com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class) .getAnnotationType() .toString()); assertEquals( "javax.ws.rs.Path", findAnnotation(testType, Path.class).getAnnotationType().toString()); assertEquals( "javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class) .getAnnotationType() .toString()); assertEquals( "javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class.getTypeName()) .getAnnotationType() .toString()); assertNull(findAnnotation(testType, Override.class)); assertNull(findAnnotation((Element) null, (Class) null)); assertNull(findAnnotation((Element) null, (String) null)); assertNull(findAnnotation((TypeMirror) null, (Class) null)); assertNull(findAnnotation((TypeMirror) null, (String) null)); assertNull(findAnnotation(testType, (Class) null)); assertNull(findAnnotation(testType, (String) null)); assertNull(findAnnotation(testType.asType(), (Class) null)); assertNull(findAnnotation(testType.asType(), (String) null)); } @Test void testFindMetaAnnotation() { getAllDeclaredMethods(getType(TestService.class)).forEach(method -> { assertEquals( "javax.ws.rs.HttpMethod", findMetaAnnotation(method, "javax.ws.rs.HttpMethod") .getAnnotationType() .toString()); }); } @Test void testGetAttribute() { assertEquals( "org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class), "interfaceName")); assertEquals( "org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName")); assertEquals("/echo", getAttribute(findAnnotation(testType, Path.class), "value")); assertNull(getAttribute(findAnnotation(testType, Path.class), null)); assertNull(getAttribute(findAnnotation(testType, (Class) null), null)); } @Test void testGetValue() { AnnotationMirror pathAnnotation = getAnnotation(getType(TestService.class), Path.class); assertEquals("/echo", getValue(pathAnnotation)); } @Test void testIsAnnotationPresent() { assertTrue(isAnnotationPresent(testType, "org.apache.dubbo.config.annotation.Service")); assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service")); assertTrue(isAnnotationPresent(testType, "javax.ws.rs.Path")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.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.annotation.processing.util; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.tools.DefaultTestService; import org.apache.dubbo.metadata.tools.GenericTestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.lang.model.element.TypeElement; import java.util.LinkedHashSet; import java.util.Set; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.DUBBO_SERVICE_ANNOTATION_TYPE; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.GROUP_ATTRIBUTE_NAME; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.INTERFACE_CLASS_ATTRIBUTE_NAME; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.INTERFACE_NAME_ATTRIBUTE_NAME; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.LEGACY_SERVICE_ANNOTATION_TYPE; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SERVICE_ANNOTATION_TYPE; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SUPPORTED_ANNOTATION_TYPES; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.VERSION_ATTRIBUTE_NAME; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getGroup; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getVersion; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.isServiceAnnotationPresent; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link ServiceAnnotationUtils} Test * * @since 2.7.6 */ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {} @Override protected void beforeEach() {} @Test void testConstants() { assertEquals("org.apache.dubbo.config.annotation.DubboService", DUBBO_SERVICE_ANNOTATION_TYPE); assertEquals("org.apache.dubbo.config.annotation.Service", SERVICE_ANNOTATION_TYPE); assertEquals("com.alibaba.dubbo.config.annotation.Service", LEGACY_SERVICE_ANNOTATION_TYPE); assertEquals("interfaceClass", INTERFACE_CLASS_ATTRIBUTE_NAME); assertEquals("interfaceName", INTERFACE_NAME_ATTRIBUTE_NAME); assertEquals("group", GROUP_ATTRIBUTE_NAME); assertEquals("version", VERSION_ATTRIBUTE_NAME); assertEquals( new LinkedHashSet<>(asList( "org.apache.dubbo.config.annotation.DubboService", "org.apache.dubbo.config.annotation.Service", "com.alibaba.dubbo.config.annotation.Service")), SUPPORTED_ANNOTATION_TYPES); } @Test void testIsServiceAnnotationPresent() { assertTrue(isServiceAnnotationPresent(getType(TestServiceImpl.class))); assertTrue(isServiceAnnotationPresent(getType(GenericTestService.class))); assertTrue(isServiceAnnotationPresent(getType(DefaultTestService.class))); assertFalse(isServiceAnnotationPresent(getType(TestService.class))); } @Test void testGetAnnotation() { TypeElement type = getType(TestServiceImpl.class); assertEquals( "org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); type = getType(GenericTestService.class); assertEquals( "com.alibaba.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); type = getType(DefaultTestService.class); assertEquals( "org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); assertThrows(IllegalArgumentException.class, () -> getAnnotation(getType(TestService.class))); } @Test void testResolveServiceInterfaceName() { TypeElement type = getType(TestServiceImpl.class); assertEquals( "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); type = getType(GenericTestService.class); assertEquals( "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); type = getType(DefaultTestService.class); assertEquals( "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); } @Test void testGetVersion() { TypeElement type = getType(TestServiceImpl.class); assertEquals("3.0.0", getVersion(getAnnotation(type))); type = getType(GenericTestService.class); assertEquals("2.0.0", getVersion(getAnnotation(type))); type = getType(DefaultTestService.class); assertEquals("1.0.0", getVersion(getAnnotation(type))); } @Test void testGetGroup() { TypeElement type = getType(TestServiceImpl.class); assertEquals("test", getGroup(getAnnotation(type))); type = getType(GenericTestService.class); assertEquals("generic", getGroup(getAnnotation(type))); type = getType(DefaultTestService.class); assertEquals("default", getGroup(getAnnotation(type))); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.util; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getDeclaredMethods; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodName; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodParameterTypes; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getOverrideMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getPublicNonStaticMethods; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getReturnType; import static org.junit.jupiter.api.Assertions.assertArrayEquals; 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 MethodUtils} Test * * @since 2.7.6 */ class MethodUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {} @Override protected void beforeEach() { testType = getType(TestServiceImpl.class); } @Test void testDeclaredMethods() { TypeElement type = getType(Model.class); List<ExecutableElement> methods = getDeclaredMethods(type); assertEquals(12, methods.size()); methods = getAllDeclaredMethods(type); // registerNatives() no provided in JDK 17 assertTrue(methods.size() >= 33); assertTrue(getAllDeclaredMethods((TypeElement) null).isEmpty()); assertTrue(getAllDeclaredMethods((TypeMirror) null).isEmpty()); } private List<? extends ExecutableElement> doGetAllDeclaredMethods() { return getAllDeclaredMethods(testType, Object.class); } @Test void testGetAllDeclaredMethods() { List<? extends ExecutableElement> methods = doGetAllDeclaredMethods(); assertEquals(14, methods.size()); } @Test void testGetPublicNonStaticMethods() { List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class); assertEquals(14, methods.size()); methods = getPublicNonStaticMethods(testType.asType(), Object.class); assertEquals(14, methods.size()); } @Test void testIsMethod() { List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class); assertEquals(14, methods.stream().map(MethodUtils::isMethod).count()); } @Test void testIsPublicNonStaticMethod() { List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class); assertEquals( 14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count()); } @Test void testFindMethod() { TypeElement type = getType(Model.class); // Test methods from java.lang.Object // Object#toString() String methodName = "toString"; ExecutableElement method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#hashCode() methodName = "hashCode"; method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#getClass() methodName = "getClass"; method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#finalize() methodName = "finalize"; method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#clone() methodName = "clone"; method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#notify() methodName = "notify"; method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#notifyAll() methodName = "notifyAll"; method = findMethod(type.asType(), methodName); assertEquals(method.getSimpleName().toString(), methodName); // Object#wait(long) methodName = "wait"; method = findMethod(type.asType(), methodName, long.class); assertEquals(method.getSimpleName().toString(), methodName); // Object#wait(long,int) methodName = "wait"; method = findMethod(type.asType(), methodName, long.class, int.class); assertEquals(method.getSimpleName().toString(), methodName); // Object#equals(Object) methodName = "equals"; method = findMethod(type.asType(), methodName, Object.class); assertEquals(method.getSimpleName().toString(), methodName); } @Test void testGetOverrideMethod() { List<? extends ExecutableElement> methods = doGetAllDeclaredMethods(); ExecutableElement overrideMethod = getOverrideMethod(processingEnv, testType, methods.get(0)); assertNull(overrideMethod); ExecutableElement declaringMethod = findMethod(getType(TestService.class), "echo", "java.lang.String"); overrideMethod = getOverrideMethod(processingEnv, testType, declaringMethod); assertEquals(methods.get(0), overrideMethod); } @Test void testGetMethodName() { ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); assertEquals("echo", getMethodName(method)); assertNull(getMethodName(null)); } @Test void testReturnType() { ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); assertEquals("java.lang.String", getReturnType(method)); assertNull(getReturnType(null)); } @Test void testMatchParameterTypes() { ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); assertArrayEquals(new String[] {"java.lang.String"}, getMethodParameterTypes(method)); assertTrue(getMethodParameterTypes(null).length == 0); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.util; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.util.ElementFilter.fieldsIn; import static javax.lang.model.util.ElementFilter.methodsIn; import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getAllDeclaredMembers; import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getDeclaredMembers; import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.hasModifiers; import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.isPublicNonStatic; import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.matchParameterTypes; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link MemberUtils} Test * * @since 2.7.6 */ class MemberUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {} @Override protected void beforeEach() { testType = getType(TestServiceImpl.class); } @Test void testIsPublicNonStatic() { assertFalse(isPublicNonStatic(null)); methodsIn(getDeclaredMembers(testType.asType())).forEach(method -> assertTrue(isPublicNonStatic(method))); } @Test void testHasModifiers() { assertFalse(hasModifiers(null)); List<? extends Element> members = getAllDeclaredMembers(testType.asType()); List<VariableElement> fields = fieldsIn(members); assertTrue(hasModifiers(fields.get(0), PRIVATE)); } @Test void testDeclaredMembers() { TypeElement type = getType(Model.class); List<? extends Element> members = getDeclaredMembers(type.asType()); List<VariableElement> fields = fieldsIn(members); assertEquals(19, members.size()); assertEquals(6, fields.size()); assertEquals("f", fields.get(0).getSimpleName().toString()); assertEquals("d", fields.get(1).getSimpleName().toString()); assertEquals("tu", fields.get(2).getSimpleName().toString()); assertEquals("str", fields.get(3).getSimpleName().toString()); assertEquals("bi", fields.get(4).getSimpleName().toString()); assertEquals("bd", fields.get(5).getSimpleName().toString()); members = getAllDeclaredMembers(type.asType()); fields = fieldsIn(members); assertEquals(11, fields.size()); assertEquals("f", fields.get(0).getSimpleName().toString()); assertEquals("d", fields.get(1).getSimpleName().toString()); assertEquals("tu", fields.get(2).getSimpleName().toString()); assertEquals("str", fields.get(3).getSimpleName().toString()); assertEquals("bi", fields.get(4).getSimpleName().toString()); assertEquals("bd", fields.get(5).getSimpleName().toString()); assertEquals("b", fields.get(6).getSimpleName().toString()); assertEquals("s", fields.get(7).getSimpleName().toString()); assertEquals("i", fields.get(8).getSimpleName().toString()); assertEquals("l", fields.get(9).getSimpleName().toString()); assertEquals("z", fields.get(10).getSimpleName().toString()); } @Test void testMatchParameterTypes() { ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); assertTrue(matchParameterTypes(method.getParameters(), "java.lang.String")); assertFalse(matchParameterTypes(method.getParameters(), "java.lang.Object")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.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.annotation.processing.util; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.tools.DefaultTestService; import org.apache.dubbo.metadata.tools.GenericTestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import java.io.File; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URISyntaxException; import java.net.URL; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getAllInterfaces; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getAllSuperTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getInterfaces; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResource; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResourceName; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getSuperType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isAnnotationType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isArrayType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isClassType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isDeclaredType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isInterfaceType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isPrimitiveType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSameType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isTypeElement; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.listDeclaredTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.listTypeElements; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * The {@link TypeUtils} Test * * @since 2.7.6 */ class TypeUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(ArrayTypeModel.class); classesToBeCompiled.add(Color.class); } @Override protected void beforeEach() { testType = getType(TestServiceImpl.class); } @Test void testIsSimpleType() { assertTrue(isSimpleType(getType(Void.class))); assertTrue(isSimpleType(getType(Boolean.class))); assertTrue(isSimpleType(getType(Character.class))); assertTrue(isSimpleType(getType(Byte.class))); assertTrue(isSimpleType(getType(Short.class))); assertTrue(isSimpleType(getType(Integer.class))); assertTrue(isSimpleType(getType(Long.class))); assertTrue(isSimpleType(getType(Float.class))); assertTrue(isSimpleType(getType(Double.class))); assertTrue(isSimpleType(getType(String.class))); assertTrue(isSimpleType(getType(BigDecimal.class))); assertTrue(isSimpleType(getType(BigInteger.class))); assertTrue(isSimpleType(getType(Date.class))); assertTrue(isSimpleType(getType(Object.class))); assertFalse(isSimpleType(getType(getClass()))); assertFalse(isSimpleType((TypeElement) null)); assertFalse(isSimpleType((TypeMirror) null)); } @Test void testIsSameType() { assertTrue(isSameType(getType(Void.class).asType(), "java.lang.Void")); assertFalse(isSameType(getType(String.class).asType(), "java.lang.Void")); assertFalse(isSameType(getType(Void.class).asType(), (Type) null)); assertFalse(isSameType(null, (Type) null)); assertFalse(isSameType(getType(Void.class).asType(), (String) null)); assertFalse(isSameType(null, (String) null)); } @Test void testIsArrayType() { TypeElement type = getType(ArrayTypeModel.class); assertTrue(isArrayType(findField(type.asType(), "integers").asType())); assertTrue(isArrayType(findField(type.asType(), "strings").asType())); assertTrue(isArrayType(findField(type.asType(), "primitiveTypeModels").asType())); assertTrue(isArrayType(findField(type.asType(), "models").asType())); assertTrue(isArrayType(findField(type.asType(), "colors").asType())); assertFalse(isArrayType((Element) null)); assertFalse(isArrayType((TypeMirror) null)); } @Test void testIsEnumType() { TypeElement type = getType(Color.class); assertTrue(isEnumType(type.asType())); type = getType(ArrayTypeModel.class); assertFalse(isEnumType(type.asType())); assertFalse(isEnumType((Element) null)); assertFalse(isEnumType((TypeMirror) null)); } @Test void testIsClassType() { TypeElement type = getType(ArrayTypeModel.class); assertTrue(isClassType(type.asType())); type = getType(Model.class); assertTrue(isClassType(type.asType())); assertFalse(isClassType((Element) null)); assertFalse(isClassType((TypeMirror) null)); } @Test void testIsPrimitiveType() { TypeElement type = getType(PrimitiveTypeModel.class); getDeclaredFields(type.asType()).stream() .map(VariableElement::asType) .forEach(t -> assertTrue(isPrimitiveType(t))); assertFalse(isPrimitiveType(getType(ArrayTypeModel.class))); assertFalse(isPrimitiveType((Element) null)); assertFalse(isPrimitiveType((TypeMirror) null)); } @Test void testIsInterfaceType() { TypeElement type = getType(CharSequence.class); assertTrue(isInterfaceType(type)); assertTrue(isInterfaceType(type.asType())); type = getType(Model.class); assertFalse(isInterfaceType(type)); assertFalse(isInterfaceType(type.asType())); assertFalse(isInterfaceType((Element) null)); assertFalse(isInterfaceType((TypeMirror) null)); } @Test void testIsAnnotationType() { TypeElement type = getType(Override.class); assertTrue(isAnnotationType(type)); assertTrue(isAnnotationType(type.asType())); type = getType(Model.class); assertFalse(isAnnotationType(type)); assertFalse(isAnnotationType(type.asType())); assertFalse(isAnnotationType((Element) null)); assertFalse(isAnnotationType((TypeMirror) null)); } @Test void testGetHierarchicalTypes() { Set hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, true); Iterator iterator = hierarchicalTypes.iterator(); assertEquals(8, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType); iterator = hierarchicalTypes.iterator(); assertEquals(8, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), Object.class); iterator = hierarchicalTypes.iterator(); assertEquals(7, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, false); iterator = hierarchicalTypes.iterator(); assertEquals(4, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, true); iterator = hierarchicalTypes.iterator(); assertEquals(5, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); assertEquals( "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, true); iterator = hierarchicalTypes.iterator(); assertEquals(4, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, false); iterator = hierarchicalTypes.iterator(); assertEquals(1, hierarchicalTypes.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, false); assertEquals(0, hierarchicalTypes.size()); assertTrue(getHierarchicalTypes((TypeElement) null).isEmpty()); assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty()); } @Test void testGetInterfaces() { TypeElement type = getType(Model.class); List<TypeMirror> interfaces = getInterfaces(type); assertTrue(interfaces.isEmpty()); interfaces = getInterfaces(testType.asType()); assertEquals(3, interfaces.size()); assertEquals( "org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString()); assertEquals("java.lang.AutoCloseable", interfaces.get(1).toString()); assertEquals("java.io.Serializable", interfaces.get(2).toString()); assertTrue(getInterfaces((TypeElement) null).isEmpty()); assertTrue(getInterfaces((TypeMirror) null).isEmpty()); } @Test void testGetAllInterfaces() { Set<? extends TypeMirror> interfaces = getAllInterfaces(testType.asType()); assertEquals(4, interfaces.size()); Iterator<? extends TypeMirror> iterator = interfaces.iterator(); assertEquals( "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); Set<TypeElement> allInterfaces = getAllInterfaces(testType); assertEquals(4, interfaces.size()); Iterator<TypeElement> allIterator = allInterfaces.iterator(); assertEquals( "org.apache.dubbo.metadata.tools.TestService", allIterator.next().toString()); assertEquals("java.lang.AutoCloseable", allIterator.next().toString()); assertEquals("java.io.Serializable", allIterator.next().toString()); assertEquals("java.util.EventListener", allIterator.next().toString()); assertTrue(getAllInterfaces((TypeElement) null).isEmpty()); assertTrue(getAllInterfaces((TypeMirror) null).isEmpty()); } @Test void testGetType() { TypeElement element = TypeUtils.getType(processingEnv, String.class); assertEquals(element, TypeUtils.getType(processingEnv, element.asType())); assertEquals(element, TypeUtils.getType(processingEnv, "java.lang.String")); assertNull(TypeUtils.getType(processingEnv, (Type) null)); assertNull(TypeUtils.getType(processingEnv, (TypeMirror) null)); assertNull(TypeUtils.getType(processingEnv, (CharSequence) null)); assertNull(TypeUtils.getType(null, (CharSequence) null)); } @Test void testGetSuperType() { TypeElement gtsTypeElement = getSuperType(testType); assertEquals(gtsTypeElement, getType(GenericTestService.class)); TypeElement dtsTypeElement = getSuperType(gtsTypeElement); assertEquals(dtsTypeElement, getType(DefaultTestService.class)); TypeMirror gtsType = getSuperType(testType.asType()); assertEquals(gtsType, getType(GenericTestService.class).asType()); TypeMirror dtsType = getSuperType(gtsType); assertEquals(dtsType, getType(DefaultTestService.class).asType()); assertNull(getSuperType((TypeElement) null)); assertNull(getSuperType((TypeMirror) null)); } @Test void testGetAllSuperTypes() { Set<?> allSuperTypes = getAllSuperTypes(testType); Iterator<?> iterator = allSuperTypes.iterator(); assertEquals(3, allSuperTypes.size()); assertEquals(iterator.next(), getType(GenericTestService.class)); assertEquals(iterator.next(), getType(DefaultTestService.class)); assertEquals(iterator.next(), getType(Object.class)); allSuperTypes = getAllSuperTypes(testType); iterator = allSuperTypes.iterator(); assertEquals(3, allSuperTypes.size()); assertEquals(iterator.next(), getType(GenericTestService.class)); assertEquals(iterator.next(), getType(DefaultTestService.class)); assertEquals(iterator.next(), getType(Object.class)); assertTrue(getAllSuperTypes((TypeElement) null).isEmpty()); assertTrue(getAllSuperTypes((TypeMirror) null).isEmpty()); } @Test void testIsDeclaredType() { assertTrue(isDeclaredType(testType)); assertTrue(isDeclaredType(testType.asType())); assertFalse(isDeclaredType((Element) null)); assertFalse(isDeclaredType((TypeMirror) null)); assertFalse(isDeclaredType(types.getNullType())); assertFalse(isDeclaredType(types.getPrimitiveType(TypeKind.BYTE))); assertFalse(isDeclaredType(types.getArrayType(types.getPrimitiveType(TypeKind.BYTE)))); } @Test void testOfDeclaredType() { assertEquals(testType.asType(), ofDeclaredType(testType)); assertEquals(testType.asType(), ofDeclaredType(testType.asType())); assertEquals(ofDeclaredType(testType), ofDeclaredType(testType.asType())); assertNull(ofDeclaredType((Element) null)); assertNull(ofDeclaredType((TypeMirror) null)); } @Test void testIsTypeElement() { assertTrue(isTypeElement(testType)); assertTrue(isTypeElement(testType.asType())); assertFalse(isTypeElement((Element) null)); assertFalse(isTypeElement((TypeMirror) null)); } @Test void testOfTypeElement() { assertEquals(testType, ofTypeElement(testType)); assertEquals(testType, ofTypeElement(testType.asType())); assertNull(ofTypeElement((Element) null)); assertNull(ofTypeElement((TypeMirror) null)); } @Test void testOfDeclaredTypes() { Set<DeclaredType> declaredTypes = ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class))); assertTrue(declaredTypes.contains(getType(String.class).asType())); assertTrue(declaredTypes.contains(getType(TestServiceImpl.class).asType())); assertTrue(declaredTypes.contains(getType(Color.class).asType())); assertTrue(ofDeclaredTypes(null).isEmpty()); } @Test void testListDeclaredTypes() { List<DeclaredType> types = listDeclaredTypes(asList(testType, testType, testType)); assertEquals(1, types.size()); assertEquals(ofDeclaredType(testType), types.get(0)); types = listDeclaredTypes(asList(new Element[] {null})); assertTrue(types.isEmpty()); } @Test void testListTypeElements() { List<TypeElement> typeElements = listTypeElements(asList(testType.asType(), ofDeclaredType(testType))); assertEquals(1, typeElements.size()); assertEquals(testType, typeElements.get(0)); typeElements = listTypeElements( asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE))); assertTrue(typeElements.isEmpty()); typeElements = listTypeElements(asList(new TypeMirror[] {null})); assertTrue(typeElements.isEmpty()); typeElements = listTypeElements(null); assertTrue(typeElements.isEmpty()); } @Test @Disabled public void testGetResource() throws URISyntaxException { URL resource = getResource(processingEnv, testType); assertNotNull(resource); assertTrue(new File(resource.toURI()).exists()); assertEquals(resource, getResource(processingEnv, testType.asType())); assertEquals(resource, getResource(processingEnv, "org.apache.dubbo.metadata.tools.TestServiceImpl")); assertThrows(RuntimeException.class, () -> getResource(processingEnv, "NotFound")); } @Test void testGetResourceName() { assertEquals("java/lang/String.class", getResourceName("java.lang.String")); assertNull(getResourceName(null)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.util; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getAllDeclaredFields; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getAllNonStaticFields; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getNonStaticFields; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isEnumMemberField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isNonStaticField; 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 FieldUtils} Test * * @since 2.7.6 */ class FieldUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {} @Override protected void beforeEach() { testType = getType(TestServiceImpl.class); } @Test void testGetDeclaredFields() { TypeElement type = getType(Model.class); List<VariableElement> fields = getDeclaredFields(type); assertModelFields(fields); fields = getDeclaredFields(type.asType()); assertModelFields(fields); assertTrue(getDeclaredFields((Element) null).isEmpty()); assertTrue(getDeclaredFields((TypeMirror) null).isEmpty()); fields = getDeclaredFields(type, f -> "f".equals(f.getSimpleName().toString())); assertEquals(1, fields.size()); assertEquals("f", fields.get(0).getSimpleName().toString()); } @Test void testGetAllDeclaredFields() { TypeElement type = getType(Model.class); List<VariableElement> fields = getAllDeclaredFields(type); assertModelAllFields(fields); assertTrue(getAllDeclaredFields((Element) null).isEmpty()); assertTrue(getAllDeclaredFields((TypeMirror) null).isEmpty()); fields = getAllDeclaredFields(type, f -> "f".equals(f.getSimpleName().toString())); assertEquals(1, fields.size()); assertEquals("f", fields.get(0).getSimpleName().toString()); } @Test void testGetDeclaredField() { TypeElement type = getType(Model.class); testGetDeclaredField(type, "f", float.class); testGetDeclaredField(type, "d", double.class); testGetDeclaredField(type, "tu", TimeUnit.class); testGetDeclaredField(type, "str", String.class); testGetDeclaredField(type, "bi", BigInteger.class); testGetDeclaredField(type, "bd", BigDecimal.class); assertNull(getDeclaredField(type, "b")); assertNull(getDeclaredField(type, "s")); assertNull(getDeclaredField(type, "i")); assertNull(getDeclaredField(type, "l")); assertNull(getDeclaredField(type, "z")); assertNull(getDeclaredField((Element) null, "z")); assertNull(getDeclaredField((TypeMirror) null, "z")); } @Test void testFindField() { TypeElement type = getType(Model.class); testFindField(type, "f", float.class); testFindField(type, "d", double.class); testFindField(type, "tu", TimeUnit.class); testFindField(type, "str", String.class); testFindField(type, "bi", BigInteger.class); testFindField(type, "bd", BigDecimal.class); testFindField(type, "b", byte.class); testFindField(type, "s", short.class); testFindField(type, "i", int.class); testFindField(type, "l", long.class); testFindField(type, "z", boolean.class); assertNull(findField((Element) null, "f")); assertNull(findField((Element) null, null)); assertNull(findField((TypeMirror) null, "f")); assertNull(findField((TypeMirror) null, null)); assertNull(findField(type, null)); assertNull(findField(type.asType(), null)); } @Test void testIsEnumField() { TypeElement type = getType(Color.class); VariableElement field = findField(type, "RED"); assertTrue(isEnumMemberField(field)); field = findField(type, "YELLOW"); assertTrue(isEnumMemberField(field)); field = findField(type, "BLUE"); assertTrue(isEnumMemberField(field)); type = getType(Model.class); field = findField(type, "f"); assertFalse(isEnumMemberField(field)); assertFalse(isEnumMemberField(null)); } @Test void testIsNonStaticField() { TypeElement type = getType(Model.class); assertTrue(isNonStaticField(findField(type, "f"))); type = getType(Color.class); assertFalse(isNonStaticField(findField(type, "BLUE"))); } @Test void testIsField() { TypeElement type = getType(Model.class); assertTrue(isField(findField(type, "f"))); assertTrue(isField(findField(type, "f"), PRIVATE)); type = getType(Color.class); assertTrue(isField(findField(type, "BLUE"), PUBLIC, STATIC, FINAL)); assertFalse(isField(null)); assertFalse(isField(null, PUBLIC, STATIC, FINAL)); } @Test void testGetNonStaticFields() { TypeElement type = getType(Model.class); List<VariableElement> fields = getNonStaticFields(type); assertModelFields(fields); fields = getNonStaticFields(type.asType()); assertModelFields(fields); assertTrue(getAllNonStaticFields((Element) null).isEmpty()); assertTrue(getAllNonStaticFields((TypeMirror) null).isEmpty()); } @Test void testGetAllNonStaticFields() { TypeElement type = getType(Model.class); List<VariableElement> fields = getAllNonStaticFields(type); assertModelAllFields(fields); fields = getAllNonStaticFields(type.asType()); assertModelAllFields(fields); assertTrue(getAllNonStaticFields((Element) null).isEmpty()); assertTrue(getAllNonStaticFields((TypeMirror) null).isEmpty()); } private void assertModelFields(List<VariableElement> fields) { assertEquals(6, fields.size()); assertEquals("d", fields.get(1).getSimpleName().toString()); assertEquals("tu", fields.get(2).getSimpleName().toString()); assertEquals("str", fields.get(3).getSimpleName().toString()); assertEquals("bi", fields.get(4).getSimpleName().toString()); assertEquals("bd", fields.get(5).getSimpleName().toString()); } private void assertModelAllFields(List<VariableElement> fields) { assertEquals(11, fields.size()); assertEquals("f", fields.get(0).getSimpleName().toString()); assertEquals("d", fields.get(1).getSimpleName().toString()); assertEquals("tu", fields.get(2).getSimpleName().toString()); assertEquals("str", fields.get(3).getSimpleName().toString()); assertEquals("bi", fields.get(4).getSimpleName().toString()); assertEquals("bd", fields.get(5).getSimpleName().toString()); assertEquals("b", fields.get(6).getSimpleName().toString()); assertEquals("s", fields.get(7).getSimpleName().toString()); assertEquals("i", fields.get(8).getSimpleName().toString()); assertEquals("l", fields.get(9).getSimpleName().toString()); assertEquals("z", fields.get(10).getSimpleName().toString()); } private void testGetDeclaredField(TypeElement type, String fieldName, Type fieldType) { VariableElement field = getDeclaredField(type, fieldName); assertField(field, fieldName, fieldType); } private void testFindField(TypeElement type, String fieldName, Type fieldType) { VariableElement field = findField(type, fieldName); assertField(field, fieldName, fieldType); } private void assertField(VariableElement field, String fieldName, Type fieldType) { assertEquals(fieldName, field.getSimpleName().toString()); assertEquals(fieldType.getTypeName(), field.asType().toString()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.lang.model.element.TypeElement; import java.util.HashMap; import java.util.Map; import java.util.Set; 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.assertTrue; /** * {@link EnumTypeDefinitionBuilder} Test * * @since 2.7.6 */ class EnumTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private EnumTypeDefinitionBuilder builder; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(Color.class); } @Override protected void beforeEach() { builder = new EnumTypeDefinitionBuilder(); } @Test void testAccept() { TypeElement typeElement = getType(Color.class); assertTrue(builder.accept(processingEnv, typeElement.asType())); } @Test void testBuild() { TypeElement typeElement = getType(Color.class); Map<String, TypeDefinition> typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache); assertEquals(Color.class.getName(), typeDefinition.getType()); assertEquals(asList("RED", "YELLOW", "BLUE"), typeDefinition.getEnums()); // assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link PrimitiveTypeDefinitionBuilder} Test * * @since 2.7.6 */ class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private PrimitiveTypeDefinitionBuilder builder; private VariableElement zField; private VariableElement bField; private VariableElement cField; private VariableElement sField; private VariableElement iField; private VariableElement lField; private VariableElement fField; private VariableElement dField; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(PrimitiveTypeModel.class); } @Override protected void beforeEach() { builder = new PrimitiveTypeDefinitionBuilder(); TypeElement testType = getType(PrimitiveTypeModel.class); zField = findField(testType, "z"); bField = findField(testType, "b"); cField = findField(testType, "c"); sField = findField(testType, "s"); iField = findField(testType, "i"); lField = findField(testType, "l"); fField = findField(testType, "f"); dField = findField(testType, "d"); assertEquals("boolean", zField.asType().toString()); assertEquals("byte", bField.asType().toString()); assertEquals("char", cField.asType().toString()); assertEquals("short", sField.asType().toString()); assertEquals("int", iField.asType().toString()); assertEquals("long", lField.asType().toString()); assertEquals("float", fField.asType().toString()); assertEquals("double", dField.asType().toString()); } @Test void testAccept() { assertTrue(builder.accept(processingEnv, zField.asType())); assertTrue(builder.accept(processingEnv, bField.asType())); assertTrue(builder.accept(processingEnv, cField.asType())); assertTrue(builder.accept(processingEnv, sField.asType())); assertTrue(builder.accept(processingEnv, iField.asType())); assertTrue(builder.accept(processingEnv, lField.asType())); assertTrue(builder.accept(processingEnv, fField.asType())); assertTrue(builder.accept(processingEnv, dField.asType())); } @Test void testBuild() { buildAndAssertTypeDefinition(processingEnv, zField, builder); buildAndAssertTypeDefinition(processingEnv, bField, builder); buildAndAssertTypeDefinition(processingEnv, cField, builder); buildAndAssertTypeDefinition(processingEnv, sField, builder); buildAndAssertTypeDefinition(processingEnv, iField, builder); buildAndAssertTypeDefinition(processingEnv, lField, builder); buildAndAssertTypeDefinition(processingEnv, zField, builder); buildAndAssertTypeDefinition(processingEnv, fField, builder); buildAndAssertTypeDefinition(processingEnv, dField, builder); } static void buildAndAssertTypeDefinition( ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) { Map<String, TypeDefinition> typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); assertBasicTypeDefinition(typeDefinition, field.asType().toString(), builder); // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); } static void assertBasicTypeDefinition(TypeDefinition typeDefinition, String type, TypeBuilder builder) { assertEquals(type, typeDefinition.getType()); // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); assertTrue(typeDefinition.getProperties().isEmpty()); assertTrue(typeDefinition.getItems().isEmpty()); assertTrue(typeDefinition.getEnums().isEmpty()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel; import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; import java.util.Set; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link GeneralTypeDefinitionBuilder} Test * * @since 2.7.6 */ class GeneralTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private GeneralTypeDefinitionBuilder builder; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(Model.class); } @Override protected void beforeEach() { builder = new GeneralTypeDefinitionBuilder(); } @Test void testAccept() { assertTrue(builder.accept(processingEnv, getType(Model.class).asType())); assertTrue( builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType())); assertTrue(builder.accept(processingEnv, getType(SimpleTypeModel.class).asType())); assertTrue(builder.accept(processingEnv, getType(ArrayTypeModel.class).asType())); assertTrue( builder.accept(processingEnv, getType(CollectionTypeModel.class).asType())); assertFalse(builder.accept(processingEnv, getType(Color.class).asType())); } @Test void testBuild() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.Set; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.builder.PrimitiveTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link SimpleTypeDefinitionBuilder} Test * * @since 2.7.6 */ class SimpleTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private SimpleTypeDefinitionBuilder builder; private VariableElement vField; private VariableElement zField; private VariableElement cField; private VariableElement bField; private VariableElement sField; private VariableElement iField; private VariableElement lField; private VariableElement fField; private VariableElement dField; private VariableElement strField; private VariableElement bdField; private VariableElement biField; private VariableElement dtField; private VariableElement invalidField; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(SimpleTypeModel.class); } @Override protected void beforeEach() { builder = new SimpleTypeDefinitionBuilder(); TypeElement testType = getType(SimpleTypeModel.class); vField = findField(testType, "v"); zField = findField(testType, "z"); cField = findField(testType, "c"); bField = findField(testType, "b"); sField = findField(testType, "s"); iField = findField(testType, "i"); lField = findField(testType, "l"); fField = findField(testType, "f"); dField = findField(testType, "d"); strField = findField(testType, "str"); bdField = findField(testType, "bd"); biField = findField(testType, "bi"); dtField = findField(testType, "dt"); invalidField = findField(testType, "invalid"); assertEquals("java.lang.Void", vField.asType().toString()); assertEquals("java.lang.Boolean", zField.asType().toString()); assertEquals("java.lang.Character", cField.asType().toString()); assertEquals("java.lang.Byte", bField.asType().toString()); assertEquals("java.lang.Short", sField.asType().toString()); assertEquals("java.lang.Integer", iField.asType().toString()); assertEquals("java.lang.Long", lField.asType().toString()); assertEquals("java.lang.Float", fField.asType().toString()); assertEquals("java.lang.Double", dField.asType().toString()); assertEquals("java.lang.String", strField.asType().toString()); assertEquals("java.math.BigDecimal", bdField.asType().toString()); assertEquals("java.math.BigInteger", biField.asType().toString()); assertEquals("java.util.Date", dtField.asType().toString()); assertEquals("int", invalidField.asType().toString()); } @Test void testAccept() { assertTrue(builder.accept(processingEnv, vField.asType())); assertTrue(builder.accept(processingEnv, zField.asType())); assertTrue(builder.accept(processingEnv, cField.asType())); assertTrue(builder.accept(processingEnv, bField.asType())); assertTrue(builder.accept(processingEnv, sField.asType())); assertTrue(builder.accept(processingEnv, iField.asType())); assertTrue(builder.accept(processingEnv, lField.asType())); assertTrue(builder.accept(processingEnv, fField.asType())); assertTrue(builder.accept(processingEnv, dField.asType())); assertTrue(builder.accept(processingEnv, strField.asType())); assertTrue(builder.accept(processingEnv, bdField.asType())); assertTrue(builder.accept(processingEnv, biField.asType())); assertTrue(builder.accept(processingEnv, dtField.asType())); // false condition assertFalse(builder.accept(processingEnv, invalidField.asType())); } @Test void testBuild() { buildAndAssertTypeDefinition(processingEnv, vField, builder); buildAndAssertTypeDefinition(processingEnv, zField, builder); buildAndAssertTypeDefinition(processingEnv, cField, builder); buildAndAssertTypeDefinition(processingEnv, sField, builder); buildAndAssertTypeDefinition(processingEnv, iField, builder); buildAndAssertTypeDefinition(processingEnv, lField, builder); buildAndAssertTypeDefinition(processingEnv, fField, builder); buildAndAssertTypeDefinition(processingEnv, dField, builder); buildAndAssertTypeDefinition(processingEnv, strField, builder); buildAndAssertTypeDefinition(processingEnv, bdField, builder); buildAndAssertTypeDefinition(processingEnv, biField, builder); buildAndAssertTypeDefinition(processingEnv, dtField, builder); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.Set; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.builder.ArrayTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link CollectionTypeDefinitionBuilder} Test * * @since 2.7.6 */ class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private CollectionTypeDefinitionBuilder builder; private VariableElement stringsField; private VariableElement colorsField; private VariableElement primitiveTypeModelsField; private VariableElement modelsField; private VariableElement modelArraysField; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(CollectionTypeModel.class); } @Override protected void beforeEach() { builder = new CollectionTypeDefinitionBuilder(); TypeElement testType = getType(CollectionTypeModel.class); stringsField = findField(testType, "strings"); colorsField = findField(testType, "colors"); primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); modelsField = findField(testType, "models"); modelArraysField = findField(testType, "modelArrays"); assertEquals("strings", stringsField.getSimpleName().toString()); assertEquals("colors", colorsField.getSimpleName().toString()); assertEquals( "primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); assertEquals("models", modelsField.getSimpleName().toString()); assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); } @Test void testAccept() { assertTrue(builder.accept(processingEnv, stringsField.asType())); assertTrue(builder.accept(processingEnv, colorsField.asType())); assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType())); assertTrue(builder.accept(processingEnv, modelsField.asType())); assertTrue(builder.accept(processingEnv, modelArraysField.asType())); } @Test void testBuild() { buildAndAssertTypeDefinition( processingEnv, stringsField, "java.util.Collection<java.lang.String>", "java.lang.String", builder); buildAndAssertTypeDefinition( processingEnv, colorsField, "java.util.List<org.apache.dubbo.metadata.annotation.processing.model.Color>", "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); buildAndAssertTypeDefinition( processingEnv, primitiveTypeModelsField, "java.util.Queue<org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel>", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); buildAndAssertTypeDefinition( processingEnv, modelsField, "java.util.Deque<org.apache.dubbo.metadata.annotation.processing.model.Model>", "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); buildAndAssertTypeDefinition( processingEnv, modelArraysField, "java.util.Set<org.apache.dubbo.metadata.annotation.processing.model.Model[]>", "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.tools.TestServiceImpl; import java.util.Arrays; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link ServiceDefinitionBuilder} Test * * @since 2.7.6 */ class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest { @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(TestServiceImpl.class); } @Override protected void beforeEach() {} @Test void testBuild() { ServiceDefinition serviceDefinition = build(processingEnv, getType(TestServiceImpl.class)); assertEquals(TestServiceImpl.class.getTypeName(), serviceDefinition.getCanonicalName()); assertEquals("org/apache/dubbo/metadata/tools/TestServiceImpl.class", serviceDefinition.getCodeSource()); // types List<String> typeNames = Arrays.asList( "org.apache.dubbo.metadata.tools.TestServiceImpl", "org.apache.dubbo.metadata.tools.GenericTestService", "org.apache.dubbo.metadata.tools.DefaultTestService", "org.apache.dubbo.metadata.tools.TestService", "java.lang.AutoCloseable", "java.io.Serializable", "java.util.EventListener"); for (String typeName : typeNames) { String gotTypeName = getTypeName(typeName, serviceDefinition.getTypes()); assertEquals(typeName, gotTypeName); } // methods assertEquals(14, serviceDefinition.getMethods().size()); } private static String getTypeName(String type, List<TypeDefinition> types) { for (TypeDefinition typeDefinition : types) { if (type.equals(typeDefinition.getType())) { return typeDefinition.getType(); } } return type; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link ArrayTypeDefinitionBuilder} Test * * @since 2.7.6 */ class ArrayTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private ArrayTypeDefinitionBuilder builder; private TypeElement testType; private VariableElement integersField; private VariableElement stringsField; private VariableElement primitiveTypeModelsField; private VariableElement modelsField; private VariableElement colorsField; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(ArrayTypeModel.class); } @Override protected void beforeEach() { builder = new ArrayTypeDefinitionBuilder(); testType = getType(ArrayTypeModel.class); integersField = findField(testType, "integers"); stringsField = findField(testType, "strings"); primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); modelsField = findField(testType, "models"); colorsField = findField(testType, "colors"); } @Test void testAccept() { assertTrue(builder.accept(processingEnv, integersField.asType())); assertTrue(builder.accept(processingEnv, stringsField.asType())); assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType())); assertTrue(builder.accept(processingEnv, modelsField.asType())); assertTrue(builder.accept(processingEnv, colorsField.asType())); } @Test void testBuild() { buildAndAssertTypeDefinition(processingEnv, integersField, "int[]", "int", builder); buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder); buildAndAssertTypeDefinition( processingEnv, primitiveTypeModelsField, "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel[]", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); buildAndAssertTypeDefinition( processingEnv, modelsField, "org.apache.dubbo.metadata.annotation.processing.model.Model[]", "org.apache.dubbo.metadata.annotation.processing.model.Model", builder, (def, subDef) -> { TypeElement subType = elements.getTypeElement(subDef.getType()); assertEquals(ElementKind.CLASS, subType.getKind()); }); buildAndAssertTypeDefinition( processingEnv, colorsField, "org.apache.dubbo.metadata.annotation.processing.model.Color[]", "org.apache.dubbo.metadata.annotation.processing.model.Color", builder, (def, subDef) -> { TypeElement subType = elements.getTypeElement(subDef.getType()); assertEquals(ElementKind.ENUM, subType.getKind()); }); } static void buildAndAssertTypeDefinition( ProcessingEnvironment processingEnv, VariableElement field, String expectedType, String compositeType, TypeBuilder builder, BiConsumer<TypeDefinition, TypeDefinition>... assertions) { Map<String, TypeDefinition> typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); String subTypeName = typeDefinition.getItems().get(0); TypeDefinition subTypeDefinition = typeCache.get(subTypeName); assertEquals(expectedType, typeDefinition.getType()); // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); assertEquals(compositeType, subTypeDefinition.getType()); // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, subTypeDefinition)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.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.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.MapTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link MapTypeDefinitionBuilder} Test * * @since 2.7.6 */ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private MapTypeDefinitionBuilder builder; private VariableElement stringsField; private VariableElement colorsField; private VariableElement primitiveTypeModelsField; private VariableElement modelsField; private VariableElement modelArraysField; @Override protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) { classesToBeCompiled.add(MapTypeModel.class); } @Override protected void beforeEach() { builder = new MapTypeDefinitionBuilder(); TypeElement testType = getType(MapTypeModel.class); stringsField = findField(testType, "strings"); colorsField = findField(testType, "colors"); primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); modelsField = findField(testType, "models"); modelArraysField = findField(testType, "modelArrays"); assertEquals("strings", stringsField.getSimpleName().toString()); assertEquals("colors", colorsField.getSimpleName().toString()); assertEquals( "primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); assertEquals("models", modelsField.getSimpleName().toString()); assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); } @Test void testAccept() { assertTrue(builder.accept(processingEnv, stringsField.asType())); assertTrue(builder.accept(processingEnv, colorsField.asType())); assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType())); assertTrue(builder.accept(processingEnv, modelsField.asType())); assertTrue(builder.accept(processingEnv, modelArraysField.asType())); } @Test void testBuild() { buildAndAssertTypeDefinition( processingEnv, stringsField, "java.util.Map<java.lang.String,java.lang.String>", "java.lang.String", "java.lang.String", builder); buildAndAssertTypeDefinition( processingEnv, colorsField, "java.util.SortedMap<java.lang.String,org.apache.dubbo.metadata.annotation.processing.model.Color>", "java.lang.String", "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); buildAndAssertTypeDefinition( processingEnv, primitiveTypeModelsField, "java.util.NavigableMap<org.apache.dubbo.metadata.annotation.processing.model.Color,org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel>", "org.apache.dubbo.metadata.annotation.processing.model.Color", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); buildAndAssertTypeDefinition( processingEnv, modelsField, "java.util.HashMap<java.lang.String,org.apache.dubbo.metadata.annotation.processing.model.Model>", "java.lang.String", "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); buildAndAssertTypeDefinition( processingEnv, modelArraysField, "java.util.TreeMap<org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel,org.apache.dubbo.metadata.annotation.processing.model.Model[]>", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); } static void buildAndAssertTypeDefinition( ProcessingEnvironment processingEnv, VariableElement field, String expectedType, String keyType, String valueType, TypeBuilder builder, BiConsumer<TypeDefinition, TypeDefinition>... assertions) { Map<String, TypeDefinition> typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); String keyTypeName = typeDefinition.getItems().get(0); TypeDefinition keyTypeDefinition = typeCache.get(keyTypeName); String valueTypeName = typeDefinition.getItems().get(1); TypeDefinition valueTypeDefinition = typeCache.get(valueTypeName); assertEquals(expectedType, typeDefinition.getType()); // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); assertEquals(keyType, keyTypeDefinition.getType()); assertEquals(valueType, valueTypeDefinition.getType()); // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, keyTypeDefinition)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.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.annotation.processing.model; import java.util.HashMap; import java.util.Map; import java.util.NavigableMap; import java.util.SortedMap; import java.util.TreeMap; /** * {@link Map} Type model * * @since 2.7.6 */ public class MapTypeModel { private Map<String, String> strings; // The composite element is simple type private SortedMap<String, Color> colors; // The composite element is Enum type private NavigableMap<Color, PrimitiveTypeModel> primitiveTypeModels; // The composite element is POJO type private HashMap<String, Model> models; // The composite element is hierarchical POJO type private TreeMap<PrimitiveTypeModel, Model[]> modelArrays; // The composite element is hierarchical POJO type }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.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.annotation.processing.model; import org.apache.dubbo.metadata.tools.Parent; import java.math.BigDecimal; import java.math.BigInteger; import java.util.concurrent.TimeUnit; /** * Model Object */ public class Model extends Parent { private float f; private double d; private TimeUnit tu; private String str; private BigInteger bi; private BigDecimal bd; public float getF() { return f; } public void setF(float f) { this.f = f; } public double getD() { return d; } public void setD(double d) { this.d = d; } public TimeUnit getTu() { return tu; } public void setTu(TimeUnit tu) { this.tu = tu; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public BigInteger getBi() { return bi; } public void setBi(BigInteger bi) { this.bi = bi; } public BigDecimal getBd() { return bd; } public void setBd(BigDecimal bd) { this.bd = bd; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.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.annotation.processing.model; /** * Primitive Type model * * @since 2.7.6 */ public class PrimitiveTypeModel { private boolean z; private byte b; private char c; private short s; private int i; private long l; private float f; private double d; public boolean isZ() { return z; } public byte getB() { return b; } public char getC() { return c; } public short getS() { return s; } public int getI() { return i; } public long getL() { return l; } public float getF() { return f; } public double getD() { return d; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.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.annotation.processing.model; /** * Array Type Model * * @since 2.7.6 */ public class ArrayTypeModel { private int[] integers; // Primitive type array private String[] strings; // Simple type array private PrimitiveTypeModel[] primitiveTypeModels; // Complex type array private Model[] models; // Hierarchical Complex type array private Color[] colors; // Enum type array }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.model; /** * Color enumeration * * @since 2.7.6 */ public enum Color { RED(1), YELLOW(2), BLUE(3); private final int value; Color(int value) { this.value = value; } @Override public String toString() { return "Color{" + "value=" + value + "} " + super.toString(); } public int getValue() { return value; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.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.annotation.processing.model; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; /** * Simple Type model * * @since 2.7.6 */ public class SimpleTypeModel { private Void v; private Boolean z; private Character c; private Byte b; private Short s; private Integer i; private Long l; private Float f; private Double d; private String str; private BigDecimal bd; private BigInteger bi; private Date dt; private int invalid; public Void getV() { return v; } public void setV(Void v) { this.v = v; } public Boolean getZ() { return z; } public void setZ(Boolean z) { this.z = z; } public Character getC() { return c; } public void setC(Character c) { this.c = c; } public Byte getB() { return b; } public void setB(Byte b) { this.b = b; } public Short getS() { return s; } public void setS(Short s) { this.s = s; } public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } public Long getL() { return l; } public void setL(Long l) { this.l = l; } public Float getF() { return f; } public void setF(Float f) { this.f = f; } public Double getD() { return d; } public void setD(Double d) { this.d = d; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public BigDecimal getBd() { return bd; } public void setBd(BigDecimal bd) { this.bd = bd; } public BigInteger getBi() { return bi; } public void setBi(BigInteger bi) { this.bi = bi; } public Date getDt() { return dt; } public void setDt(Date dt) { this.dt = dt; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.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.annotation.processing.model; import java.util.Collection; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; /** * {@link Collection} Type Model * * @since 2.7.6 */ public class CollectionTypeModel { private Collection<String> strings; // The composite element is simple type private List<Color> colors; // The composite element is Enum type private Queue<PrimitiveTypeModel> primitiveTypeModels; // The composite element is POJO type private Deque<Model> models; // The composite element is hierarchical POJO type private Set<Model[]> modelArrays; // The composite element is hierarchical POJO type }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.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.rest; import org.apache.dubbo.config.annotation.DubboService; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import java.util.HashMap; import java.util.Map; /** * JAX-RS {@link RestService} */ @DubboService( version = "3.0.0", protocol = {"dubbo", "rest"}, group = "standard") @Path("/") public class StandardRestService implements RestService { @Override @Path("param") @GET public String param(@QueryParam("param") String param) { return param; } @Override @Path("params") @POST public String params(@QueryParam("a") int a, @QueryParam("b") String b) { return a + b; } @Override @Path("headers") @GET public String headers( @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { String result = header + " , " + header2 + " , " + param; return result; } @Override @Path("path-variables/{p1}/{p2}") @GET public String pathVariables( @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { String result = path1 + " , " + path2 + " , " + param; return result; } // @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913 // @CookieValue also does not support @Override @Path("form") @POST public String form(@FormParam("f") String form) { return String.valueOf(form); } @Override @Path("request/body/map") @POST @Produces("application/json;charset=UTF-8") public User requestBodyMap(Map<String, Object> data, @QueryParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); user.setAge((Integer) data.get("age")); return user; } @Path("request/body/user") @POST @Override @Consumes("application/json;charset=UTF-8") public Map<String, Object> requestBodyUser(User user) { Map<String, Object> map = new HashMap<>(); map.put("id", user.getId()); map.put("name", user.getName()); map.put("age", user.getAge()); return map; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.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.rest; import org.apache.dubbo.config.annotation.DubboService; import java.util.HashMap; import java.util.Map; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * Spring MVC {@link RestService} * * @since 2.7.6 */ @DubboService(version = "2.0.0", group = "spring") @RestController public class SpringRestService implements RestService { @Override @GetMapping(value = "/param") public String param(@RequestParam(defaultValue = "value-param") String param) { return null; } @Override @PostMapping("/params") public String params( @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { return null; } @Override @GetMapping("/headers") public String headers( @RequestHeader(name = "h", defaultValue = "value-h") String header, @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, @RequestParam(value = "v", defaultValue = "1") Integer param) { return null; } @Override @GetMapping("/path-variables/{p1}/{p2}") public String pathVariables( @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { return null; } @Override @PostMapping("/form") public String form(@RequestParam("f") String form) { return String.valueOf(form); } @Override @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public User requestBodyMap(@RequestBody Map<String, Object> data, @RequestParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); user.setAge((Integer) data.get("age")); return user; } @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @Override public Map<String, Object> requestBodyUser(@RequestBody User user) { Map<String, Object> map = new HashMap<>(); map.put("id", user.getId()); map.put("name", user.getName()); map.put("age", user.getAge()); return map; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.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.rest; import org.apache.dubbo.config.annotation.DubboService; import java.util.Map; /** * The default implementation of {@link RestService} * * @since 2.7.6 */ @DubboService(version = "1.0.0", group = "default") public class DefaultRestService implements RestService { @Override public String param(String param) { return null; } @Override public String params(int a, String b) { return null; } @Override public String headers(String header, String header2, Integer param) { return null; } @Override public String pathVariables(String path1, String path2, String param) { return null; } @Override public String form(String form) { return null; } @Override public User requestBodyMap(Map<String, Object> data, String param) { return null; } @Override public Map<String, Object> requestBodyUser(User user) { return null; } public User user(User user) { return user; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/User.java
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/User.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.rest; import java.io.Serializable; /** * User Entity * * @since 2.7.6 */ public class User implements Serializable { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false