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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.Profiler; import org.apache.dubbo.common.profiler.ProfilerEntry; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcServiceContext; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST; public class InvocationUtil { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(InvokerInvocationHandler.class); public static Object invoke(Invoker<?> invoker, RpcInvocation rpcInvocation) throws Throwable { RpcContext.RestoreServiceContext originServiceContext = RpcContext.storeServiceContext(); try { URL url = invoker.getUrl(); String serviceKey = url.getServiceKey(); rpcInvocation.setTargetServiceUniqueName(serviceKey); // invoker.getUrl() returns consumer url. RpcServiceContext.getServiceContext().setConsumerUrl(url); if (ProfilerSwitch.isEnableSimpleProfiler()) { ProfilerEntry parentProfiler = Profiler.getBizProfiler(); ProfilerEntry bizProfiler; if (parentProfiler != null) { bizProfiler = Profiler.enter( parentProfiler, "Receive request. Client invoke begin. ServiceKey: " + serviceKey + " MethodName:" + rpcInvocation.getMethodName()); } else { bizProfiler = Profiler.start("Receive request. Client invoke begin. ServiceKey: " + serviceKey + " " + "MethodName:" + rpcInvocation.getMethodName()); } rpcInvocation.put(Profiler.PROFILER_KEY, bizProfiler); try { return invoker.invoke(rpcInvocation).recreate(); } finally { Profiler.release(bizProfiler); Long timeout = RpcUtils.convertToNumber(rpcInvocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY)); if (timeout == null) { timeout = (long) url.getMethodPositiveParameter( rpcInvocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); } long usage = bizProfiler.getEndTime() - bizProfiler.getStartTime(); if ((usage / (1000_000L * ProfilerSwitch.getWarnPercent())) > timeout) { StringBuilder attachment = new StringBuilder(); rpcInvocation.foreachAttachment((entry) -> { attachment .append(entry.getKey()) .append("=") .append(entry.getValue()) .append(";\n"); }); logger.warn( PROXY_TIMEOUT_REQUEST, "", "", String.format( "[Dubbo-Consumer] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + "invocation context:\n%s" + "thread info: \n%s", rpcInvocation.getProtocolServiceKey(), rpcInvocation.getMethodName(), usage / 1000_000, usage % 1000_000, timeout, attachment, Profiler.buildDetail(bizProfiler))); } } } return invoker.invoke(rpcInvocation).recreate(); } finally { RpcContext.restoreServiceContext(originServiceContext); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.Profiler; import org.apache.dubbo.common.profiler.ProfilerEntry; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncContextImpl; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_ASYNC_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_ERROR_ASYNC_RESPONSE; /** * This Invoker works on provider side, delegates RPC to interface implementation. */ public abstract class AbstractProxyInvoker<T> implements Invoker<T> { ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyInvoker.class); private final T proxy; private final Class<T> type; private final URL url; public AbstractProxyInvoker(T proxy, Class<T> type, URL url) { if (proxy == null) { throw new IllegalArgumentException("proxy == null"); } if (type == null) { throw new IllegalArgumentException("interface == null"); } if (!type.isInstance(proxy)) { throw new IllegalArgumentException(proxy.getClass().getName() + " not implement interface " + type); } this.proxy = proxy; this.type = type; this.url = url; } @Override public Class<T> getInterface() { return type; } @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} @Override public Result invoke(Invocation invocation) throws RpcException { ProfilerEntry originEntry = null; try { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); if (fromInvocation instanceof ProfilerEntry) { ProfilerEntry profiler = Profiler.enter( (ProfilerEntry) fromInvocation, "Receive request. Server biz impl invoke begin."); invocation.put(Profiler.PROFILER_KEY, profiler); originEntry = Profiler.setToBizProfiler(profiler); } } Object value = doInvoke( proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); CompletableFuture<Object> future = wrapWithFuture(value, invocation); CompletableFuture<AppResponse> appResponseFuture = future.handle((obj, t) -> { AppResponse result = new AppResponse(invocation); if (t != null) { if (t instanceof CompletionException) { result.setException(t.getCause()); } else { result.setException(t); } } else { result.setValue(obj); } return result; }); return new AsyncRpcResult(appResponseFuture, invocation); } catch (InvocationTargetException e) { if (RpcContext.getServiceContext().isAsyncStarted() && !RpcContext.getServiceContext().stopAsync()) { logger.error( PROXY_ERROR_ASYNC_RESPONSE, "", "", "Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", e); } return AsyncRpcResult.newDefaultAsyncResult(null, e.getTargetException(), invocation); } catch (Throwable e) { throw new RpcException( "Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl() + ", cause: " + e.getMessage(), e); } finally { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); if (fromInvocation instanceof ProfilerEntry) { ProfilerEntry profiler = Profiler.release((ProfilerEntry) fromInvocation); invocation.put(Profiler.PROFILER_KEY, profiler); } } Profiler.removeBizProfiler(); if (originEntry != null) { Profiler.setToBizProfiler(originEntry); } } } private CompletableFuture<Object> wrapWithFuture(Object value, Invocation invocation) { if (value instanceof CompletableFuture) { invocation.put(PROVIDER_ASYNC_KEY, Boolean.TRUE); return (CompletableFuture<Object>) value; } else if (RpcContext.getServerAttachment().isAsyncStarted()) { invocation.put(PROVIDER_ASYNC_KEY, Boolean.TRUE); return ((AsyncContextImpl) (RpcContext.getServerAttachment().getAsyncContext())).getInternalFuture(); } return CompletableFuture.completedFuture(value); } protected abstract Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable; @Override public String toString() { return getInterface() + " -> " + (getUrl() == null ? " " : getUrl().toString()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.service.Destroyable; import org.apache.dubbo.rpc.service.EchoService; import org.apache.dubbo.rpc.service.GenericService; import java.util.Arrays; import java.util.LinkedHashSet; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_UNSUPPORTED_INVOKER; import static org.apache.dubbo.rpc.Constants.INTERFACES; public abstract class AbstractProxyFactory implements ProxyFactory { private static final Class<?>[] INTERNAL_INTERFACES = new Class<?>[] {EchoService.class, Destroyable.class}; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyFactory.class); @Override public <T> T getProxy(Invoker<T> invoker) throws RpcException { return getProxy(invoker, false); } @Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { // when compiling with native image, ensure that the order of the interfaces remains unchanged LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>(); ClassLoader classLoader = getClassLoader(invoker); String config = invoker.getUrl().getParameter(INTERFACES); if (StringUtils.isNotEmpty(config)) { String[] types = COMMA_SPLIT_PATTERN.split(config); for (String type : types) { try { interfaces.add(ReflectUtils.forName(classLoader, type)); } catch (Throwable e) { // ignore } } } Class<?> realInterfaceClass = null; if (generic) { try { // find the real interface from url String realInterface = invoker.getUrl().getParameter(Constants.INTERFACE); realInterfaceClass = ReflectUtils.forName(classLoader, realInterface); interfaces.add(realInterfaceClass); } catch (Throwable e) { // ignore } if (GenericService.class.isAssignableFrom(invoker.getInterface()) && Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()) { interfaces.add(Dubbo2CompactUtils.getGenericServiceClass()); } if (!GenericService.class.isAssignableFrom(invoker.getInterface())) { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()) { interfaces.add(Dubbo2CompactUtils.getGenericServiceClass()); } else { interfaces.add(org.apache.dubbo.rpc.service.GenericService.class); } } } interfaces.add(invoker.getInterface()); interfaces.addAll(Arrays.asList(INTERNAL_INTERFACES)); try { return getProxy(invoker, interfaces.toArray(new Class<?>[0])); } catch (Throwable t) { if (generic) { if (realInterfaceClass != null) { interfaces.remove(realInterfaceClass); } interfaces.remove(invoker.getInterface()); logger.error( PROXY_UNSUPPORTED_INVOKER, "", "", "Error occur when creating proxy. Invoker is in generic mode. Trying to create proxy without real interface class.", t); return getProxy(invoker, interfaces.toArray(new Class<?>[0])); } else { throw t; } } } private <T> ClassLoader getClassLoader(Invoker<T> invoker) { ServiceModel serviceModel = invoker.getUrl().getServiceModel(); ClassLoader classLoader = null; if (serviceModel != null && serviceModel.getInterfaceClassLoader() != null) { classLoader = serviceModel.getInterfaceClassLoader(); } if (classLoader == null) { classLoader = ClassUtils.getClassLoader(); } return classLoader; } public static Class<?>[] getInternalInterfaces() { return INTERNAL_INTERFACES.clone(); } public abstract <T> T getProxy(Invoker<T> invoker, Class<?>[] types); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public interface MethodInvoker { Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable; /** * no overload method invoker */ class SingleMethodInvoker implements MethodInvoker { private final Method method; SingleMethodInvoker(Method method) { this.method = method; } @Override public Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { return method.invoke(instance, arguments); } } /** * overload method invoker */ class OverloadMethodInvoker implements MethodInvoker { private final MethodMeta[] methods; OverloadMethodInvoker(List<Method> methods) { this.methods = methods.stream().map(MethodMeta::new).toArray(MethodMeta[]::new); } @Override public Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { for (MethodMeta meta : methods) { if (Arrays.equals(meta.getParametersType(), parameterTypes)) { return meta.getMethod().invoke(instance, arguments); } } throw new NoSuchMethodException( instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes)); } private static class MethodMeta { private final Method method; private final Class<?>[] parametersType; private MethodMeta(Method method) { this.method = method; this.parametersType = method.getParameterTypes(); } public Method getMethod() { return method; } public Class<?>[] getParametersType() { return parametersType; } } } class CompositeMethodInvoker implements MethodInvoker { private final Map<String, MethodInvoker> invokers; public CompositeMethodInvoker(Map<String, MethodInvoker> invokers) { this.invokers = invokers; } /** * for test * * @return all MethodInvoker */ Map<String, MethodInvoker> getInvokers() { return invokers; } @Override public Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { MethodInvoker invoker = invokers.get(methodName); if (invoker == null) { throw new NoSuchMethodException( instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes)); } return invoker.invoke(instance, methodName, parameterTypes, arguments); } } static MethodInvoker newInstance(Class<?> clazz) { Method[] methods = clazz.getMethods(); Map<String, MethodInvoker> invokers = new HashMap<>(); Map<String, List<Method>> map = new HashMap<>(); for (Method method : methods) { map.computeIfAbsent(method.getName(), name -> new ArrayList<>()).add(method); } Set<Map.Entry<String, List<Method>>> entries = map.entrySet(); for (Map.Entry<String, List<Method>> entry : entries) { String methodName = entry.getKey(); List<Method> ms = entry.getValue(); if (ms.size() == 1) { invokers.put(methodName, new SingleMethodInvoker(ms.get(0))); continue; } invokers.put(methodName, new OverloadMethodInvoker(ms)); } return new CompositeMethodInvoker(invokers); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * InvokerHandler */ public class InvokerInvocationHandler implements InvocationHandler { private static final Logger logger = LoggerFactory.getLogger(InvokerInvocationHandler.class); private final Invoker<?> invoker; private final ServiceModel serviceModel; private final String protocolServiceKey; public InvokerInvocationHandler(Invoker<?> handler) { this.invoker = handler; URL url = invoker.getUrl(); this.protocolServiceKey = url.getProtocolServiceKey(); this.serviceModel = url.getServiceModel(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(invoker, args); } String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { if ("toString".equals(methodName)) { return invoker.toString(); } else if ("$destroy".equals(methodName)) { invoker.destroy(); return null; } else if ("hashCode".equals(methodName)) { return invoker.hashCode(); } } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return invoker.equals(args[0]); } RpcInvocation rpcInvocation = new RpcInvocation( serviceModel, method.getName(), invoker.getInterface().getName(), protocolServiceKey, method.getParameterTypes(), args); if (serviceModel instanceof ConsumerModel) { rpcInvocation.put(Constants.CONSUMER_MODEL, serviceModel); rpcInvocation.put(Constants.METHOD_MODEL, ((ConsumerModel) serviceModel).getMethodModel(method)); } return InvocationUtil.invoke(invoker, rpcInvocation); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.proxy.jdk.JdkProxyFactory; import java.util.Arrays; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED; public abstract class AbstractFallbackJdkProxyFactory extends AbstractProxyFactory { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(this.getClass()); private final JdkProxyFactory jdkProxyFactory = new JdkProxyFactory(); @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { try { return doGetInvoker(proxy, type, url); } catch (Throwable throwable) { // try fall back to JDK proxy factory String factoryName = getClass().getSimpleName(); try { Invoker<T> invoker = jdkProxyFactory.getInvoker(proxy, type, url); logger.error( PROXY_FAILED, "", "", "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy success. " + "Interfaces: " + type, throwable); // log out error return invoker; } catch (Throwable fromJdk) { logger.error( PROXY_FAILED, "", "", "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + " Javassist Error.", throwable); logger.error( PROXY_FAILED, "", "", "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + " JDK Error.", fromJdk); throw throwable; } } } @Override public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) { try { return doGetProxy(invoker, interfaces); } catch (Throwable throwable) { // try fall back to JDK proxy factory String factoryName = getClass().getSimpleName(); try { T proxy = jdkProxyFactory.getProxy(invoker, interfaces); logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy success. " + "Interfaces: " + Arrays.toString(interfaces), throwable); return proxy; } catch (Throwable fromJdk) { logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.", throwable); logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.", fromJdk); throw throwable; } } } protected abstract <T> Invoker<T> doGetInvoker(T proxy, Class<T> type, URL url); protected abstract <T> T doGetProxy(Invoker<T> invoker, Class<?>[] types); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy.jdk; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.proxy.AbstractProxyFactory; import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker; import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * JdkRpcProxyFactory */ public class JdkProxyFactory extends AbstractProxyFactory { @Override @SuppressWarnings("unchecked") public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) { return (T) Proxy.newProxyInstance( invoker.getInterface().getClassLoader(), interfaces, new InvokerInvocationHandler(invoker)); } @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) { return new AbstractProxyInvoker<T>(proxy, type, url) { @Override protected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { Method method = proxy.getClass().getMethod(methodName, parameterTypes); return method.invoke(proxy, arguments); } }; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy.wrapper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; 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.RpcException; import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Constructor; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; import static org.apache.dubbo.rpc.Constants.STUB_EVENT_METHODS_KEY; import static org.apache.dubbo.rpc.Constants.STUB_KEY; public class StubProxyFactoryWrapper implements ProxyFactory { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(StubProxyFactoryWrapper.class); private final ProxyFactory proxyFactory; private Protocol protocol; public StubProxyFactoryWrapper(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } public void setProtocol(Protocol protocol) { this.protocol = protocol; } @Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { T proxy = proxyFactory.getProxy(invoker, generic); if (GenericService.class != invoker.getInterface()) { URL url = invoker.getUrl(); String stub = url.getParameter(STUB_KEY, url.getParameter(LOCAL_KEY)); if (ConfigUtils.isNotEmpty(stub)) { Class<?> serviceType = invoker.getInterface(); if (ConfigUtils.isDefault(stub)) { if (url.hasParameter(STUB_KEY)) { stub = serviceType.getName() + "Stub"; } else { stub = serviceType.getName() + "Local"; } } try { Class<?> stubClass = ReflectUtils.forName(stub); if (!serviceType.isAssignableFrom(stubClass)) { throw new IllegalStateException("The stub implementation class " + stubClass.getName() + " not implement interface " + serviceType.getName()); } try { Constructor<?> constructor = ReflectUtils.findConstructor(stubClass, serviceType); proxy = (T) constructor.newInstance(new Object[] {proxy}); // export stub service URLBuilder urlBuilder = URLBuilder.from(url); if (url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT)) { urlBuilder.addParameter( STUB_EVENT_METHODS_KEY, StringUtils.join( Wrapper.getWrapper(proxy.getClass()).getDeclaredMethodNames(), ",")); urlBuilder.addParameter(IS_SERVER_KEY, Boolean.FALSE.toString()); try { export(proxy, invoker.getInterface(), urlBuilder.build()); } catch (Exception e) { LOGGER.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "export a stub service error.", e); } } } catch (NoSuchMethodException e) { throw new IllegalStateException( "No such constructor \"public " + stubClass.getSimpleName() + "(" + serviceType.getName() + ")\" in stub implementation class " + stubClass.getName(), e); } } catch (Throwable t) { LOGGER.error( PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to create stub implementation class " + stub + " in consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", cause: " + t.getMessage(), t); // ignore } } } return proxy; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public <T> T getProxy(Invoker<T> invoker) throws RpcException { return getProxy(invoker, false); } @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { return proxyFactory.getInvoker(proxy, type, url); } private <T> Exporter<T> export(T instance, Class<T> type, URL url) { return protocol.export(proxyFactory.getInvoker(instance, type, url)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.proxy.javassist; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.bytecode.Proxy; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.proxy.AbstractProxyFactory; import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker; import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; import org.apache.dubbo.rpc.proxy.jdk.JdkProxyFactory; import java.util.Arrays; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED; /** * JavassistRpcProxyFactory */ public class JavassistProxyFactory extends AbstractProxyFactory { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JavassistProxyFactory.class); private final JdkProxyFactory jdkProxyFactory = new JdkProxyFactory(); @Override @SuppressWarnings("unchecked") public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) { try { return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker)); } catch (Throwable fromJavassist) { // try fall back to JDK proxy factory try { T proxy = jdkProxyFactory.getProxy(invoker, interfaces); logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + "Interfaces: " + Arrays.toString(interfaces), fromJavassist); return proxy; } catch (Throwable fromJdk) { logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.", fromJavassist); logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.", fromJdk); throw fromJavassist; } } } @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) { try { // TODO Wrapper cannot handle this scenario correctly: the classname contains '$' final Wrapper wrapper = Wrapper.getWrapper(proxy.getClass().getName().indexOf('$') < 0 ? proxy.getClass() : type); return new AbstractProxyInvoker<T>(proxy, type, url) { @Override protected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { return wrapper.invokeMethod(proxy, methodName, parameterTypes, arguments); } }; } catch (Throwable fromJavassist) { // try fall back to JDK proxy factory try { Invoker<T> invoker = jdkProxyFactory.getInvoker(proxy, type, url); logger.error( PROXY_FAILED, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy success. " + "Interfaces: " + type, fromJavassist); // log out error return invoker; } catch (Throwable fromJdk) { logger.error( PROXY_FAILED, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + " Javassist Error.", fromJavassist); logger.error( PROXY_FAILED, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + " JDK Error.", fromJdk); throw fromJavassist; } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; public class FutureToObserverAdaptor<T> implements StreamObserver<T> { private final CompletableFuture<T> future; public FutureToObserverAdaptor(CompletableFuture<T> future) { this.future = future; } @Override public void onNext(T data) { if (future.isDone() || future.isCancelled() || future.isCompletedExceptionally()) { throw new IllegalStateException("Too many response for unary method"); } future.complete(data); } @Override public void onError(Throwable throwable) { if (future.isDone() || future.isCancelled() || future.isCompletedExceptionally()) { throw new IllegalStateException("Too many response for unary method"); } future.completeExceptionally(throwable); } @Override public void onCompleted() { if (future.isDone() || future.isCancelled() || future.isCompletedExceptionally()) { return; } throw new IllegalStateException("Completed without value or exception "); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.ServerService; /** * Stub proxy factory is used to generate non-reflection invoker and proxy. It relies on Dubbo3 * Triple compiler. */ public class StubProxyFactory implements ProxyFactory { @Override public <T> T getProxy(Invoker<T> invoker) throws RpcException { return StubSuppliers.createStub(invoker.getUrl().getServiceInterface(), invoker); } @Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { return getProxy(invoker); } @Override @SuppressWarnings("all") public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { return ((ServerService) proxy).getInvoker(url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; import java.util.function.Function; public class BiStreamMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<StreamObserver<R>, StreamObserver<T>> func; public BiStreamMethodHandler(Function<StreamObserver<R>, StreamObserver<T>> func) { this.func = func; } @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = func.apply(responseObserver); return CompletableFuture.completedFuture(requestObserver); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; public class ServerStreamMethodHandler<T, R> implements StubMethodHandler<T, R> { private final BiConsumer<T, StreamObserver<R>> func; public ServerStreamMethodHandler(BiConsumer<T, StreamObserver<R>> func) { this.func = func; } @Override public CompletableFuture<?> invoke(Object[] arguments) { T request = (T) arguments[0]; StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[1]; func.accept(request, responseObserver); return CompletableFuture.completedFuture(null); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; public class UnaryStubMethodHandler<T, R> implements StubMethodHandler<T, R> { private final BiConsumer<T, StreamObserver<R>> func; public UnaryStubMethodHandler(BiConsumer<T, StreamObserver<R>> func) { this.func = func; } @Override public CompletableFuture<R> invoke(Object[] arguments) { T request = (T) arguments[0]; CompletableFuture<R> future = new CompletableFuture<>(); StreamObserver<R> responseObserver = new FutureToObserverAdaptor<>(future); try { func.accept(request, responseObserver); } catch (Throwable e) { future.completeExceptionally(e); } return future; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import java.util.concurrent.CompletableFuture; /** * A generic methodHandler for stub invocation * * @param <T> Request Type * @param <R> Response Type */ public interface StubMethodHandler<T, R> { /** * Invoke method * * @param arguments may contain {@link org.apache.dubbo.common.stream.StreamObserver} or just * single request instance. * @return an Async or Sync future */ CompletableFuture<?> invoke(Object[] arguments); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker; import java.util.Map; public class StubInvoker<T> extends AbstractProxyInvoker<T> { private final Map<String, StubMethodHandler<?, ?>> handlers; public StubInvoker(T proxy, URL url, Class<T> type, Map<String, StubMethodHandler<?, ?>> handlers) { super(proxy, type, url); this.handlers = handlers; } @Override protected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { return handlers.get(methodName).invoke(arguments); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; public class StubSuppliers { private static final Map<String, Function<Invoker<?>, Object>> STUB_SUPPLIERS = new ConcurrentHashMap<>(); private static final Map<String, ServiceDescriptor> SERVICE_DESCRIPTOR_MAP = new ConcurrentHashMap<>(); public static void addDescriptor(String interfaceName, ServiceDescriptor serviceDescriptor) { SERVICE_DESCRIPTOR_MAP.put(interfaceName, serviceDescriptor); } public static void addSupplier(String interfaceName, Function<Invoker<?>, Object> supplier) { STUB_SUPPLIERS.put(interfaceName, supplier); } public static <T> T createStub(String interfaceName, Invoker<T> invoker) { // TODO DO not hack here if (!STUB_SUPPLIERS.containsKey(interfaceName)) { ReflectUtils.forName(stubClassName(interfaceName)); if (!STUB_SUPPLIERS.containsKey(interfaceName)) { throw new IllegalStateException("Can not find any stub supplier for " + interfaceName); } } return (T) STUB_SUPPLIERS.get(interfaceName).apply(invoker); } private static String stubClassName(String interfaceName) { int idx = interfaceName.lastIndexOf('.'); String pkg = interfaceName.substring(0, idx + 1); String name = interfaceName.substring(idx + 1); return pkg + "Dubbo" + name + "Triple"; } public static ServiceDescriptor getServiceDescriptor(String interfaceName) { // TODO DO not hack here if (!SERVICE_DESCRIPTOR_MAP.containsKey(interfaceName)) { ReflectUtils.forName(stubClassName(interfaceName)); if (!SERVICE_DESCRIPTOR_MAP.containsKey(interfaceName)) { throw new IllegalStateException("Can not find any stub supplier for " + interfaceName); } } return SERVICE_DESCRIPTOR_MAP.get(interfaceName); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/annotations/GRequest.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/annotations/GRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface GRequest { String value() default ""; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/aot/GenericProxyDescriberRegistrar.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/aot/GenericProxyDescriberRegistrar.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.aot; import org.apache.dubbo.aot.api.JdkProxyDescriber; import org.apache.dubbo.aot.api.ProxyDescriberRegistrar; import org.apache.dubbo.rpc.service.Destroyable; import org.apache.dubbo.rpc.service.EchoService; import org.apache.dubbo.rpc.service.GenericService; import java.util.ArrayList; import java.util.List; public class GenericProxyDescriberRegistrar implements ProxyDescriberRegistrar { @Override public List<JdkProxyDescriber> getJdkProxyDescribers() { List<JdkProxyDescriber> describers = new ArrayList<>(); List<String> proxiedInterfaces = new ArrayList<>(); proxiedInterfaces.add(GenericService.class.getName()); proxiedInterfaces.add(EchoService.class.getName()); proxiedInterfaces.add(Destroyable.class.getName()); describers.add(new JdkProxyDescriber(proxiedInterfaces, null)); return describers; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.BaseFilter; @SPI(scope = ExtensionScope.MODULE) public interface ClusterFilter extends BaseFilter {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.RpcException; public abstract class InvokerListenerAdapter implements InvokerListener { @Override public void referred(Invoker<?> invoker) throws RpcException {} @Override public void destroyed(Invoker<?> invoker) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterChangeListener.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterChangeListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.rpc.Exporter; /** * An interface for listening to changes in the export state of an Exporter object. */ public interface ExporterChangeListener { /** * This method is called when an Exporter object is exported. * * @param exporter The Exporter object that has been exported. */ void onExporterChangeExport(Exporter<?> exporter); /** * This method is called when an Exporter object is unexported. * * @param exporter The Exporter object that has been unexported. */ void onExporterChangeUnExport(Exporter<?> exporter); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.RpcException; public abstract class ExporterListenerAdapter implements ExporterListener { @Override public void exported(Exporter<?> exporter) throws RpcException {} @Override public void unexported(Exporter<?> exporter) throws RpcException {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_UNSUPPORTED_INVOKER; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** * DeprecatedProtocolFilter */ @Activate(DEPRECATED_KEY) public class DeprecatedInvokerListener extends InvokerListenerAdapter { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedInvokerListener.class); @Override public void referred(Invoker<?> invoker) throws RpcException { if (invoker.getUrl().getParameter(DEPRECATED_KEY, false)) { LOGGER.error( PROXY_UNSUPPORTED_INVOKER, "", "", "The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from " + invoker.getUrl()); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.RpcException; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * The InjvmExporterListener class is an implementation of the ExporterListenerAdapter abstract class, * <p> * which is used to listen for changes to the InjvmExporter instances. * <p> * It maintains two ConcurrentHashMaps, one to keep track of the ExporterChangeListeners registered for each service, * <p> * and another to keep track of the currently exported services and their associated Exporter instances. * <p> * It overrides the exported and unexported methods to add or remove the corresponding Exporter instances to/from * <p> * the exporters ConcurrentHashMap, and to notify all registered ExporterChangeListeners of the change. * <p> * It also provides methods to add or remove ExporterChangeListeners for a specific service, and to retrieve the * <p> * currently exported Exporter instance for a given service. */ public class InjvmExporterListener extends ExporterListenerAdapter { /* * A ConcurrentHashMap to keep track of the ExporterChangeListeners registered for each service. */ private final Map<String, Set<ExporterChangeListener>> exporterChangeListeners = new ConcurrentHashMap<>(); /* * A ConcurrentHashMap to keep track of the currently exported services and their associated Exporter instances */ private final Map<String, Exporter<?>> exporters = new ConcurrentHashMap<>(); /** * Overrides the exported method to add the given exporter to the exporters ConcurrentHashMap, * <p> * and to notify all registered ExporterChangeListeners of the export event. * * @param exporter The Exporter instance that has been exported. * @throws RpcException If there is an error during the export process. */ @Override public void exported(Exporter<?> exporter) throws RpcException { String serviceKey = exporter.getInvoker().getUrl().getServiceKey(); exporters.putIfAbsent(serviceKey, exporter); Set<ExporterChangeListener> listeners = exporterChangeListeners.get(serviceKey); if (!CollectionUtils.isEmpty(listeners)) { for (ExporterChangeListener listener : listeners) { listener.onExporterChangeExport(exporter); } } super.exported(exporter); } /** * Overrides the unexported method to remove the given exporter from the exporters ConcurrentHashMap, * <p> * and to notify all registered ExporterChangeListeners of the unexport event. * * @param exporter The Exporter instance that has been unexported. * @throws RpcException If there is an error during the unexport process. */ @Override public void unexported(Exporter<?> exporter) throws RpcException { String serviceKey = exporter.getInvoker().getUrl().getServiceKey(); exporters.remove(serviceKey, exporter); Set<ExporterChangeListener> listeners = exporterChangeListeners.get(serviceKey); if (!CollectionUtils.isEmpty(listeners)) { for (ExporterChangeListener listener : listeners) { listener.onExporterChangeUnExport(exporter); } } super.unexported(exporter); } /** * Adds an ExporterChangeListener for a specific service, and notifies the listener of the current Exporter instance * <p> * if it exists. * * @param listener The ExporterChangeListener to add. * @param serviceKey The service key for the service to listen for changes on. */ public synchronized void addExporterChangeListener(ExporterChangeListener listener, String serviceKey) { exporterChangeListeners.putIfAbsent(serviceKey, new ConcurrentHashSet<>()); exporterChangeListeners.get(serviceKey).add(listener); if (exporters.get(serviceKey) != null) { Exporter<?> exporter = exporters.get(serviceKey); listener.onExporterChangeExport(exporter); } } /** * Removes an ExporterChangeListener for a specific service. * * @param listener The ExporterChangeListener to remove. * @param listenerKey The service key for the service to remove the listener from. */ public synchronized void removeExporterChangeListener(ExporterChangeListener listener, String listenerKey) { Set<ExporterChangeListener> listeners = exporterChangeListeners.get(listenerKey); if (CollectionUtils.isEmpty(listeners)) { return; } listeners.remove(listener); if (CollectionUtils.isEmpty(listeners)) { exporterChangeListeners.remove(listenerKey); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import java.util.List; import java.util.function.Consumer; /** * ListenerInvoker */ public class ListenerInvokerWrapper<T> implements Invoker<T> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerInvokerWrapper.class); private final Invoker<T> invoker; private final List<InvokerListener> listeners; public ListenerInvokerWrapper(Invoker<T> invoker, List<InvokerListener> listeners) { if (invoker == null) { throw new IllegalArgumentException("invoker == null"); } this.invoker = invoker; this.listeners = listeners; listenerEvent(listener -> listener.referred(invoker)); } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public URL getUrl() { return invoker.getUrl(); } @Override public boolean isAvailable() { return invoker.isAvailable(); } @Override public Result invoke(Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public String toString() { return getInterface() + " -> " + (getUrl() == null ? " " : getUrl().toString()); } @Override public void destroy() { try { invoker.destroy(); } finally { listenerEvent(listener -> listener.destroyed(invoker)); } } public Invoker<T> getInvoker() { return invoker; } public List<InvokerListener> getListeners() { return listeners; } private void listenerEvent(Consumer<InvokerListener> consumer) { if (CollectionUtils.isNotEmpty(listeners)) { RuntimeException exception = null; for (InvokerListener listener : listeners) { if (listener != null) { try { consumer.accept(listener); } catch (RuntimeException t) { logger.error( LoggerCodeConstants.INTERNAL_ERROR, "wrapped listener internal error", "", t.getMessage(), t); exception = t; } } } if (exception != null) { throw exception; } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.listener; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Invoker; import java.util.List; import java.util.function.Consumer; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT; /** * ListenerExporter */ public class ListenerExporterWrapper<T> implements Exporter<T> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerExporterWrapper.class); private final Exporter<T> exporter; private final List<ExporterListener> listeners; public ListenerExporterWrapper(Exporter<T> exporter, List<ExporterListener> listeners) { if (exporter == null) { throw new IllegalArgumentException("exporter == null"); } this.exporter = exporter; this.listeners = listeners; listenerEvent(listener -> listener.exported(this)); } @Override public Invoker<T> getInvoker() { return exporter.getInvoker(); } @Override public void unexport() { try { exporter.unexport(); } finally { listenerEvent(listener -> listener.unexported(this)); } } @Override public void register() { exporter.register(); } @Override public void unregister() { exporter.unregister(); } private void listenerEvent(Consumer<ExporterListener> consumer) { if (CollectionUtils.isNotEmpty(listeners)) { RuntimeException exception = null; for (ExporterListener listener : listeners) { if (listener != null) { try { consumer.accept(listener); } catch (RuntimeException t) { logger.error(COMMON_FAILED_NOTIFY_EVENT, "", "", t.getMessage(), t); exception = t; } } } if (exception != null) { throw exception; } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; /** * AbstractExporter. */ public abstract class AbstractExporter<T> implements Exporter<T> { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Invoker<T> invoker; private volatile boolean unexported = false; public AbstractExporter(Invoker<T> invoker) { if (invoker == null) { throw new IllegalStateException("service invoker == null"); } if (invoker.getInterface() == null) { throw new IllegalStateException("service type == null"); } if (invoker.getUrl() == null) { throw new IllegalStateException("service url == null"); } this.invoker = invoker; } @Override public Invoker<T> getInvoker() { return invoker; } @Override public final void unexport() { if (unexported) { return; } unexported = true; getInvoker().destroy(); afterUnExport(); } @Override public void register() {} @Override public void unregister() {} /** * subclasses need to override this method to destroy resources. */ public void afterUnExport() {} @Override public String toString() { return getInvoker().toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; import org.apache.dubbo.common.serialize.support.SerializationOptimizer; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import org.apache.dubbo.rpc.support.ProtocolUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.OPTIMIZER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; /** * abstract ProtocolSupport. */ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); protected final Map<String, Exporter<?>> exporterMap = new ConcurrentHashMap<>(); /** * <host:port, ProtocolServer> */ protected final Map<String, ProtocolServer> serverMap = new ConcurrentHashMap<>(); // TODO SoftReference protected final Set<Invoker<?>> invokers = new ConcurrentHashSet<>(); protected FrameworkModel frameworkModel; private final Set<String> optimizers = new ConcurrentHashSet<>(); @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } protected static String serviceKey(URL url) { int port = url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); return serviceKey(port, url.getPath(), url.getVersion(), url.getGroup()); } protected static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { return ProtocolUtils.serviceKey(port, serviceName, serviceVersion, serviceGroup); } @Override public List<ProtocolServer> getServers() { return Collections.unmodifiableList(new ArrayList<>(serverMap.values())); } protected void loadServerProperties(ProtocolServer server) { // read and hold config before destroy int serverShutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(server.getUrl().getScopeModel()); server.getAttributes().put(SHUTDOWN_WAIT_KEY, serverShutdownTimeout); } protected int getServerShutdownTimeout(ProtocolServer server) { return (int) server.getAttributes().getOrDefault(SHUTDOWN_WAIT_KEY, DEFAULT_SERVER_SHUTDOWN_TIMEOUT); } @Override public void destroy() { for (Invoker<?> invoker : invokers) { if (invoker != null) { try { if (logger.isInfoEnabled()) { logger.info("Destroy reference: " + invoker.getUrl()); } invoker.destroy(); } catch (Throwable t) { logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } } invokers.clear(); exporterMap.forEach((key, exporter) -> { if (exporter != null) { try { if (logger.isInfoEnabled()) { logger.info("Unexport service: " + exporter.getInvoker().getUrl()); } exporter.unexport(); } catch (Throwable t) { logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } }); exporterMap.clear(); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { return protocolBindingRefer(type, url); } @Deprecated protected abstract <T> Invoker<T> protocolBindingRefer(Class<T> type, URL url) throws RpcException; public Map<String, Exporter<?>> getExporterMap() { return exporterMap; } public Collection<Exporter<?>> getExporters() { return Collections.unmodifiableCollection(exporterMap.values()); } protected void optimizeSerialization(URL url) throws RpcException { String className = url.getParameter(OPTIMIZER_KEY, ""); if (StringUtils.isEmpty(className) || optimizers.contains(className)) { return; } logger.info("Optimizing the serialization process for Kryo, FST, etc..."); try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); if (!SerializationOptimizer.class.isAssignableFrom(clazz)) { throw new RpcException("The serialization optimizer " + className + " isn't an instance of " + SerializationOptimizer.class.getName()); } SerializationOptimizer optimizer = (SerializationOptimizer) clazz.newInstance(); if (optimizer.getSerializableClasses() == null) { return; } for (Class c : optimizer.getSerializableClasses()) { SerializableClassRegistry.registerClass(c); } optimizers.add(className); } catch (ClassNotFoundException e) { throw new RpcException("Cannot find the serialization optimizer class: " + className, e); } catch (InstantiationException | IllegalAccessException e) { throw new RpcException("Cannot instantiate the serialization optimizer class: " + className, e); } } protected String getAddr(URL url) { String bindIp = url.getParameter(org.apache.dubbo.remoting.Constants.BIND_IP_KEY, url.getHost()); if (url.getParameter(ANYHOST_KEY, false)) { bindIp = ANYHOST_VALUE; } return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(org.apache.dubbo.remoting.Constants.BIND_PORT_KEY, url.getPort()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.utils.UrlUtils; import java.io.IOException; import java.util.Collection; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.BaseServiceMetadata.interfaceFromServiceKey; import static org.apache.dubbo.common.BaseServiceMetadata.versionFromServiceKey; public class PermittedSerializationKeeper { private final ConcurrentMap<String, Set<Byte>> serviceToSerializationId = new ConcurrentHashMap<>(); private final Set<Byte> globalPermittedSerializationIds = new ConcurrentHashSet<>(); public void registerService(URL url) { Set<Byte> set = ConcurrentHashMapUtils.computeIfAbsent( serviceToSerializationId, keyWithoutGroup(url.getServiceKey()), k -> new ConcurrentHashSet<>()); Collection<String> serializations = UrlUtils.allSerializations(url); for (String serialization : serializations) { Byte id = CodecSupport.getIDByName(serialization); if (id != null) { set.add(id); globalPermittedSerializationIds.add(id); } } } public boolean checkSerializationPermitted(String serviceKeyWithoutGroup, Byte id) throws IOException { Set<Byte> set = serviceToSerializationId.get(serviceKeyWithoutGroup); if (set == null) { throw new IOException("Service " + serviceKeyWithoutGroup + " not found, invocation rejected."); } return set.contains(id); } private static String keyWithoutGroup(String serviceKey) { String interfaceName = interfaceFromServiceKey(serviceKey); String version = versionFromServiceKey(serviceKey); if (StringUtils.isEmpty(version)) { return interfaceName; } return interfaceName + CommonConstants.GROUP_CHAR_SEPARATOR + version; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.listener.InjvmExporterListener; import org.apache.dubbo.rpc.listener.ListenerExporterWrapper; import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.Collections; import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; /** * ListenerProtocol */ @Activate(order = 200) public class ProtocolListenerWrapper implements Protocol { private final Protocol protocol; public ProtocolListenerWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { if (UrlUtils.isRegistry(invoker.getUrl())) { return protocol.export(invoker); } List<ExporterListener> exporterListeners = ScopeModelUtil.getExtensionLoader( ExporterListener.class, invoker.getUrl().getScopeModel()) .getActivateExtension(invoker.getUrl(), EXPORTER_LISTENER_KEY); if (LOCAL_PROTOCOL.equals(invoker.getUrl().getProtocol())) { exporterListeners.add(invoker.getUrl() .getOrDefaultFrameworkModel() .getBeanFactory() .getBean(InjvmExporterListener.class)); } return new ListenerExporterWrapper<>(protocol.export(invoker), Collections.unmodifiableList(exporterListeners)); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (UrlUtils.isRegistry(url)) { return protocol.refer(type, url); } Invoker<T> invoker = protocol.refer(type, url); if (StringUtils.isEmpty(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY))) { invoker = new ListenerInvokerWrapper<>( invoker, Collections.unmodifiableList(ScopeModelUtil.getExtensionLoader( InvokerListener.class, invoker.getUrl().getScopeModel()) .getActivateExtension(url, INVOKER_LISTENER_KEY))); } return invoker; } @Override public void destroy() { protocol.destroy(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReferenceCountInvokerWrapper<T> implements Invoker<T> { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountInvokerWrapper.class); private final Invoker<T> invoker; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AtomicBoolean destroyed = new AtomicBoolean(false); public ReferenceCountInvokerWrapper(Invoker<T> invoker) { this.invoker = invoker; } @Override public URL getUrl() { return invoker.getUrl(); } @Override public boolean isAvailable() { return !destroyed.get() && invoker.isAvailable(); } @Override public void destroy() { try { int timeout = ConfigurationUtils.getServerShutdownTimeout(invoker.getUrl().getScopeModel()); boolean locked = lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS); if (!locked) { logger.warn( LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", "Failed to wait for invocation end in " + timeout + "ms."); } destroyed.set(true); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { try { lock.writeLock().unlock(); } catch (IllegalMonitorStateException ignore) { // ignore if lock failed, maybe in a long invoke } catch (Throwable t) { logger.warn( LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", "Unexpected error occurred when releasing write lock, cause: " + t.getMessage(), t); } } invoker.destroy(); } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public Result invoke(Invocation invocation) throws RpcException { try { lock.readLock().lock(); if (destroyed.get()) { logger.warn( LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", "Remote invoker has been destroyed, and unable to invoke anymore."); throw new RpcException("This invoker has been destroyed!"); } return invoker.invoke(invocation); } finally { lock.readLock().unlock(); } } public Invoker<T> getInvoker() { return invoker; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import java.util.List; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel; @Activate public class ProtocolSerializationWrapper implements Protocol { private final Protocol protocol; public ProtocolSerializationWrapper(Protocol protocol) { this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { getFrameworkModel(invoker.getUrl().getScopeModel()) .getBeanFactory() .getBean(PermittedSerializationKeeper.class) .registerService(invoker.getUrl()); return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { return protocol.refer(type, url); } @Override public void destroy() { protocol.destroy(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; public abstract class AbstractProxyProtocol extends AbstractProtocol { private final List<Class<?>> rpcExceptions = new CopyOnWriteArrayList<>(); protected ProxyFactory proxyFactory; public AbstractProxyProtocol() {} public AbstractProxyProtocol(Class<?>... exceptions) { for (Class<?> exception : exceptions) { addRpcException(exception); } } public void addRpcException(Class<?> exception) { this.rpcExceptions.add(exception); } public ProxyFactory getProxyFactory() { return proxyFactory; } public void setProxyFactory(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } @Override @SuppressWarnings("unchecked") public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException { final String uri = serviceKey(invoker.getUrl()); Exporter<T> exporter = (Exporter<T>) exporterMap.get(uri); if (exporter != null) { // When modifying the configuration through override, you need to re-expose the newly modified service. if (Objects.equals(exporter.getInvoker().getUrl(), invoker.getUrl())) { return exporter; } } final Runnable runnable = doExport(proxyFactory.getProxy(invoker, true), invoker.getInterface(), invoker.getUrl()); exporter = new AbstractExporter<T>(invoker) { @Override public void afterUnExport() { exporterMap.remove(uri); if (runnable != null) { try { runnable.run(); } catch (Throwable t) { logger.warn(PROTOCOL_UNSUPPORTED, "", "", t.getMessage(), t); } } } }; exporterMap.put(uri, exporter); return exporter; } @Override protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException { final Invoker<T> target = proxyFactory.getInvoker(doRefer(type, url), type, url); Invoker<T> invoker = new AbstractInvoker<T>(type, url) { @Override protected Result doInvoke(Invocation invocation) throws Throwable { try { Result result = target.invoke(invocation); // FIXME result is an AsyncRpcResult instance. Throwable e = result.getException(); if (e != null) { for (Class<?> rpcException : rpcExceptions) { if (rpcException.isAssignableFrom(e.getClass())) { throw getRpcException(type, url, invocation, e); } } } return result; } catch (RpcException e) { if (e.getCode() == RpcException.UNKNOWN_EXCEPTION) { e.setCode(getErrorCode(e.getCause())); } throw e; } catch (Throwable e) { throw getRpcException(type, url, invocation, e); } } @Override public void destroy() { super.destroy(); target.destroy(); invokers.remove(this); AbstractProxyProtocol.this.destroyInternal(url); } }; invokers.add(invoker); return invoker; } // used to destroy unused clients and other resource protected void destroyInternal(URL url) { // subclass override } protected RpcException getRpcException(Class<?> type, URL url, Invocation invocation, Throwable e) { RpcException re = new RpcException( "Failed to invoke remote service: " + type + ", method: " + invocation.getMethodName() + ", cause: " + e.getMessage(), e); re.setCode(getErrorCode(e)); return re; } protected String getAddr(URL url) { String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); if (url.getParameter(ANYHOST_KEY, false)) { bindIp = ANYHOST_VALUE; } return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); } protected int getErrorCode(Throwable e) { return RpcException.UNKNOWN_EXCEPTION; } protected abstract <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException; protected abstract <T> T doRefer(Class<T> type, URL url) throws RpcException; protected class ProxyProtocolServer implements ProtocolServer { private RemotingServer server; private String address; private Map<String, Object> attributes = new ConcurrentHashMap<>(); public ProxyProtocolServer(RemotingServer server) { this.server = server; } @Override public RemotingServer getRemotingServer() { return server; } @Override public String getAddress() { return StringUtils.isNotEmpty(address) ? address : server.getUrl().getAddress(); } @Override public void setAddress(String address) { this.address = address; } @Override public URL getUrl() { return server.getUrl(); } @Override public void close() { server.close(); } @Override public Map<String, Object> getAttributes() { return attributes; } } protected abstract class RemotingServerAdapter implements RemotingServer { public abstract Object getDelegateServer(); /** * @return */ @Override public boolean isBound() { return false; } @Override public Collection<Channel> getChannels() { return null; } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return null; } @Override public void reset(Parameters parameters) {} @Override public void reset(URL url) {} @Override public URL getUrl() { return null; } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException {} @Override public void close() {} @Override public void close(int timeout) {} @Override public void startClose() {} @Override public boolean isClosed() { return false; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerCountWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerCountWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.RpcException; @Activate(order = Integer.MIN_VALUE + 1000) public class InvokerCountWrapper implements Protocol { private final Protocol protocol; public InvokerCountWrapper(Protocol protocol) { this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (UrlUtils.isRegistry(url)) { return protocol.refer(type, url); } return new ReferenceCountInvokerWrapper<>(protocol.refer(type, url)); } @Override public void destroy() { protocol.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.SerializeSecurityConfigurator; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.List; import java.util.Optional; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; @Activate(order = 200) public class ProtocolSecurityWrapper implements Protocol { private final Protocol protocol; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ProtocolSecurityWrapper.class); public ProtocolSecurityWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { try { ServiceModel serviceModel = invoker.getUrl().getServiceModel(); ScopeModel scopeModel = invoker.getUrl().getScopeModel(); SerializeSecurityConfigurator serializeSecurityConfigurator = ScopeModelUtil.getModuleModel(scopeModel) .getBeanFactory() .getBean(SerializeSecurityConfigurator.class); serializeSecurityConfigurator.refreshStatus(); serializeSecurityConfigurator.refreshCheck(); Optional.ofNullable(invoker.getInterface()).ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceModel) .map(ServiceDescriptor::getServiceInterfaceClass) .ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceMetadata) .map(ServiceMetadata::getServiceType) .ifPresent(serializeSecurityConfigurator::registerInterface); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "", "", "Failed to register interface for security check", t); } return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { try { ServiceModel serviceModel = url.getServiceModel(); ScopeModel scopeModel = url.getScopeModel(); SerializeSecurityConfigurator serializeSecurityConfigurator = ScopeModelUtil.getModuleModel(scopeModel) .getBeanFactory() .getBean(SerializeSecurityConfigurator.class); serializeSecurityConfigurator.refreshStatus(); serializeSecurityConfigurator.refreshCheck(); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceModel) .map(ServiceDescriptor::getServiceInterfaceClass) .ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceMetadata) .map(ServiceMetadata::getServiceType) .ifPresent(serializeSecurityConfigurator::registerInterface); serializeSecurityConfigurator.registerInterface(type); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "", "", "Failed to register interface for security check", t); } return protocol.refer(type, url); } @Override public void destroy() { protocol.destroy(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; /** * InvokerWrapper */ public class InvokerWrapper<T> implements Invoker<T> { protected final Invoker<T> invoker; private final URL url; public InvokerWrapper(Invoker<T> invoker, URL url) { this.invoker = invoker; this.url = url; } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return invoker.isAvailable(); } @Override public Result invoke(Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void destroy() { invoker.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.Node; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.InvokeMode; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_VERSION; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; /** * This Invoker works on Consumer side. */ public abstract class AbstractInvoker<T> implements Invoker<T> { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractInvoker.class); /** * Service interface type */ private final Class<T> type; /** * {@link Node} url */ private final URL url; /** * {@link Invoker} default attachment */ private final Map<String, Object> attachment; protected final String version; /** * {@link Node} available */ private volatile boolean available = true; /** * {@link Node} destroy */ private volatile boolean destroyed = false; /** * Whether set future to Thread Local when invocation mode is sync */ private static final boolean setFutureWhenSync = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty( CommonConstants.ThirdPartyProperty.SET_FUTURE_IN_SYNC_MODE, "true")); // -- Constructor public AbstractInvoker(Class<T> type, URL url) { this(type, url, (Map<String, Object>) null); } public AbstractInvoker(Class<T> type, URL url, String[] keys) { this(type, url, convertAttachment(url, keys)); } public AbstractInvoker(Class<T> type, URL url, Map<String, Object> attachment) { if (type == null) { throw new IllegalArgumentException("service type == null"); } if (url == null) { throw new IllegalArgumentException("service url == null"); } this.type = type; this.url = url; this.attachment = attachment == null ? null : Collections.unmodifiableMap(attachment); this.version = url.getVersion(DEFAULT_VERSION); } private static Map<String, Object> convertAttachment(URL url, String[] keys) { if (ArrayUtils.isEmpty(keys)) { return null; } Map<String, Object> attachment = new HashMap<>(keys.length); for (String key : keys) { String value = url.getParameter(key); if (value != null && value.length() > 0) { attachment.put(key, value); } } return attachment; } // -- Public api @Override public Class<T> getInterface() { return type; } @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return available; } @Override public void destroy() { this.destroyed = true; setAvailable(false); } protected void setAvailable(boolean available) { this.available = available; } public boolean isDestroyed() { return destroyed; } @Override public String toString() { return getInterface() + " -> " + (getUrl() == null ? "" : getUrl().getAddress()); } @Override public Result invoke(Invocation inv) throws RpcException { // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed if (isDestroyed()) { logger.warn( PROTOCOL_FAILED_REQUEST, "", "", "Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); } RpcInvocation invocation = (RpcInvocation) inv; // prepare rpc invocation prepareInvocation(invocation); // do invoke rpc invocation and return async result AsyncRpcResult asyncResult = doInvokeAndReturn(invocation); // wait rpc result if sync waitForResultIfSync(asyncResult, invocation); return asyncResult; } private void prepareInvocation(RpcInvocation inv) { inv.setInvoker(this); addInvocationAttachments(inv); inv.setInvokeMode(RpcUtils.getInvokeMode(url, inv)); RpcUtils.attachInvocationIdIfAsync(getUrl(), inv); attachInvocationSerializationId(inv); } /** * Attach Invocation Serialization id * <p> * <ol> * <li>Obtain the value from <code>prefer_serialization</code></li> * <li>If the preceding information is not obtained, obtain the value from <code>serialization</code></li> * <li>If neither is obtained, use the default value</li> * </ol> * </p> * * @param inv inv */ private void attachInvocationSerializationId(RpcInvocation inv) { Byte serializationId = UrlUtils.serializationId(getUrl()); if (serializationId != null) { inv.put(SERIALIZATION_ID_KEY, serializationId); } } private void addInvocationAttachments(RpcInvocation invocation) { // invoker attachment if (CollectionUtils.isNotEmptyMap(attachment)) { invocation.addObjectAttachmentsIfAbsent(attachment); } // client context attachment Map<String, Object> clientContextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); if (CollectionUtils.isNotEmptyMap(clientContextAttachments)) { invocation.addObjectAttachmentsIfAbsent(clientContextAttachments); } } private AsyncRpcResult doInvokeAndReturn(RpcInvocation invocation) { AsyncRpcResult asyncResult; try { asyncResult = (AsyncRpcResult) doInvoke(invocation); } catch (InvocationTargetException e) { Throwable te = e.getTargetException(); if (te != null) { // if biz exception if (te instanceof RpcException) { ((RpcException) te).setCode(RpcException.BIZ_EXCEPTION); } asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, te, invocation); } else { asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } } catch (RpcException e) { // if biz exception if (e.isBiz()) { asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } else { throw e; } } catch (Throwable e) { asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } if (setFutureWhenSync || invocation.getInvokeMode() != InvokeMode.SYNC) { // set server context RpcContext.getServiceContext().setFuture(new FutureAdapter<>(asyncResult.getResponseFuture())); } return asyncResult; } private void waitForResultIfSync(AsyncRpcResult asyncResult, RpcInvocation invocation) { if (InvokeMode.SYNC != invocation.getInvokeMode()) { return; } try { /* * NOTICE! * must call {@link java.util.concurrent.CompletableFuture#get(long, TimeUnit)} because * {@link java.util.concurrent.CompletableFuture#get()} was proved to have serious performance drop. */ Object timeoutKey = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY); long timeout = RpcUtils.convertToNumber(timeoutKey, Integer.MAX_VALUE); asyncResult.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RpcException( "Interrupted unexpectedly while waiting for remote result to return! method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (ExecutionException e) { Throwable rootCause = e.getCause(); if (rootCause instanceof TimeoutException) { throw new RpcException( RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } else if (rootCause instanceof RemotingException) { throw new RpcException( RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } else if (rootCause instanceof SerializationException) { throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, "Invoke remote method failed cause by serialization error. remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } else { throw new RpcException( RpcException.UNKNOWN_EXCEPTION, "Fail to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } } catch (java.util.concurrent.TimeoutException e) { throw new RpcException( RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (Throwable e) { throw new RpcException(e.getMessage(), e); } } // -- Protected api protected ExecutorService getCallbackExecutor(URL url, Invocation inv) { if (InvokeMode.SYNC == RpcUtils.getInvokeMode(getUrl(), inv)) { return new ThreadlessExecutor(); } return ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .getExecutor(url); } /** * Specific implementation of the {@link #invoke(Invocation)} method */ protected abstract Result doInvoke(Invocation invocation) throws Throwable; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/package-info.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * {@link org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter} was in dubbo-rpc-dubbo module, * considering some users will use this class directly, keep the package not changed. */ package org.apache.dubbo.rpc.protocol.dubbo;
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * This is the type of the Future instance users get in an async call: * 1. unwrap AppResponse in appResponseFuture and convert to plain biz result represented by FutureAdapter. * 2. customized behaviors meaningful for RPC, for example, {@link #cancel(boolean)} */ public class FutureAdapter<V> extends CompletableFuture<V> { private final CompletableFuture<AppResponse> appResponseFuture; public FutureAdapter(CompletableFuture<AppResponse> future) { this.appResponseFuture = future; future.whenComplete((appResponse, t) -> { if (t != null) { if (t instanceof CompletionException) { t = t.getCause(); } this.completeExceptionally(t); } else { if (appResponse.hasException()) { this.completeExceptionally(appResponse.getException()); } else { this.complete((V) appResponse.getValue()); } } }); } // TODO figure out the meaning of cancel in DefaultFuture. @Override public boolean cancel(boolean mayInterruptIfRunning) { // Invocation invocation = invocationSoftReference.get(); // if (invocation != null) { // invocation.getInvoker().invoke(cancel); // } return appResponseFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return appResponseFuture.isCancelled(); } @Override public boolean isDone() { return super.isDone(); } @Override @SuppressWarnings("unchecked") public V get() throws InterruptedException, ExecutionException { try { return super.get(); } catch (ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } @Override @SuppressWarnings("unchecked") public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return super.get(timeout, unit); } catch (TimeoutException | ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.model.AsyncMethodInfo; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; /** * EventFilter */ @Activate(group = CommonConstants.CONSUMER) public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { public static final String ASYNC_METHOD_INFO = "async-method-info"; protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FutureFilter.class); @Override public Result invoke(final Invoker<?> invoker, final Invocation invocation) throws RpcException { fireInvokeCallback(invoker, invocation); // need to configure if there's return value before the invocation in order to help invoker to judge if it's // necessary to return future. return invoker.invoke(invocation); } @Override public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) { if (result.hasException()) { fireThrowCallback(invoker, invocation, result.getException()); } else { fireReturnCallback(invoker, invocation, result.getValue()); } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { fireThrowCallback(invoker, invocation, t); } private void fireInvokeCallback(final Invoker<?> invoker, final Invocation invocation) { final AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onInvokeMethod = asyncMethodInfo.getOninvokeMethod(); final Object onInvokeInst = asyncMethodInfo.getOninvokeInstance(); if (onInvokeMethod == null && onInvokeInst == null) { return; } if (onInvokeMethod == null || onInvokeInst == null) { throw new IllegalStateException( "service:" + invoker.getUrl().getServiceKey() + " has a oninvoke callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onInvokeMethod.isAccessible()) { onInvokeMethod.setAccessible(true); } Object[] params = invocation.getArguments(); try { onInvokeMethod.invoke(onInvokeInst, params); } catch (InvocationTargetException e) { fireThrowCallback(invoker, invocation, e.getTargetException()); } catch (Throwable e) { fireThrowCallback(invoker, invocation, e); } } private void fireReturnCallback(final Invoker<?> invoker, final Invocation invocation, final Object result) { final AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onReturnMethod = asyncMethodInfo.getOnreturnMethod(); final Object onReturnInst = asyncMethodInfo.getOnreturnInstance(); // not set onreturn callback if (onReturnMethod == null && onReturnInst == null) { return; } if (onReturnMethod == null || onReturnInst == null) { throw new IllegalStateException( "service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); } Object[] args = invocation.getArguments(); Object[] params; Class<?>[] rParaTypes = onReturnMethod.getParameterTypes(); if (rParaTypes.length > 1) { if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = result; params[1] = args; } else { params = new Object[args.length + 1]; params[0] = result; System.arraycopy(args, 0, params, 1, args.length); } } else { params = new Object[] {result}; } try { onReturnMethod.invoke(onReturnInst, params); } catch (InvocationTargetException e) { fireThrowCallback(invoker, invocation, e.getTargetException()); } catch (Throwable e) { fireThrowCallback(invoker, invocation, e); } } private void fireThrowCallback(final Invoker<?> invoker, final Invocation invocation, final Throwable exception) { final AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onthrowMethod = asyncMethodInfo.getOnthrowMethod(); final Object onthrowInst = asyncMethodInfo.getOnthrowInstance(); // onthrow callback not configured if (onthrowMethod == null && onthrowInst == null) { return; } if (onthrowMethod == null || onthrowInst == null) { throw new IllegalStateException( "service:" + invoker.getUrl().getServiceKey() + " has a onthrow callback config , but no such " + (onthrowMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onthrowMethod.isAccessible()) { onthrowMethod.setAccessible(true); } Class<?>[] rParaTypes = onthrowMethod.getParameterTypes(); if (rParaTypes[0].isAssignableFrom(exception.getClass())) { try { Object[] args = invocation.getArguments(); Object[] params; if (rParaTypes.length > 1) { if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = exception; params[1] = args; } else { params = new Object[args.length + 1]; params[0] = exception; System.arraycopy(args, 0, params, 1, args.length); } } else { params = new Object[] {exception}; } onthrowMethod.invoke(onthrowInst, params); } catch (Throwable e) { logger.error( PROTOCOL_FAILED_REQUEST, "", "", RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); } } else { logger.error( PROTOCOL_FAILED_REQUEST, "", "", RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); } } private AsyncMethodInfo getAsyncMethodInfo(Invoker<?> invoker, Invocation invocation) { AsyncMethodInfo asyncMethodInfo = (AsyncMethodInfo) invocation.get(ASYNC_METHOD_INFO); if (asyncMethodInfo != null) { return asyncMethodInfo; } ServiceModel serviceModel = invocation.getServiceModel(); if (!(serviceModel instanceof ConsumerModel)) { return null; } String methodName = RpcUtils.getMethodName(invocation); return ((ConsumerModel) serviceModel).getAsyncInfo(methodName); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/ProtocolTest.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/ProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; class ProtocolTest { IEcho echo = new IEcho() { public String echo(String e) { return e; } }; static { InjvmProtocol injvm = InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()); } ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); URL url = URL.valueOf( "injvm://localhost:0/org.apache.dubbo.rpc.support.IEcho?interface=org.apache.dubbo.rpc.support.IEcho") .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<IEcho> invoker = proxyFactory.getInvoker(echo, IEcho.class, url); @Test void test_destroyWontCloseAllProtocol() throws Exception { Protocol autowireProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); Protocol InjvmProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("injvm"); assertEquals(0, InjvmProtocol.getDefaultPort()); InjvmProtocol.export(invoker); Invoker<IEcho> refer = InjvmProtocol.refer(IEcho.class, url); IEcho echoProxy = proxyFactory.getProxy(refer); assertEquals("ok", echoProxy.echo("ok")); try { autowireProtocol.destroy(); } catch (UnsupportedOperationException expected) { assertThat( expected.getMessage(), containsString("of interface org.apache.dubbo.rpc.Protocol is not adaptive method!")); } assertEquals("ok2", echoProxy.echo("ok2")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoRequest.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import java.io.Serializable; /** * TestRequest. */ class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; private String mServiceName; private String mMethodName; private Class<?>[] mParameterTypes; private Object[] mArguments; public DemoRequest(String serviceName, String methodName, Class<?>[] parameterTypes, Object[] args) { mServiceName = serviceName; mMethodName = methodName; mParameterTypes = parameterTypes; mArguments = args; } public String getServiceName() { return mServiceName; } public String getMethodName() { return mMethodName; } public Class<?>[] getParameterTypes() { return mParameterTypes; } public Object[] getArguments() { return mArguments; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.FutureContext; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; 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; /** * <code>ProxiesTest</code> */ class InjvmProtocolTest { private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final List<Exporter<?>> exporters = new ArrayList<>(); @AfterEach public void after() throws Exception { for (Exporter<?> exporter : exporters) { exporter.unexport(); } exporters.clear(); } @Test void testLocalProtocol() throws Exception { DemoService service = new DemoServiceImpl(); Invoker<?> invoker = proxy.getInvoker( service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule())); assertTrue(invoker.isAvailable()); Exporter<?> exporter = protocol.export(invoker); exporters.add(exporter); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()))); assertEquals(service.getSize(new String[] {"", "", ""}), 3); service.invoke("injvm://127.0.0.1/TestService", "invoke"); InjvmInvoker<?> injvmInvoker = new InjvmInvoker<>( DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService"), null, new HashMap<>()); assertFalse(injvmInvoker.isAvailable()); } @Test void testLocalProtocolWithToken() { DemoService service = new DemoServiceImpl(); Invoker<?> invoker = proxy.getInvoker( service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService?token=abc") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule())); assertTrue(invoker.isAvailable()); Exporter<?> exporter = protocol.export(invoker); exporters.add(exporter); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()))); assertEquals(service.getSize(new String[] {"", "", ""}), 3); } @Test void testIsInjvmRefer() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); exporters.add(exporter); url = url.setProtocol("dubbo"); assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = url.addParameter(GROUP_KEY, "*").addParameter(VERSION_KEY, "*"); assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(SCOPE_KEY, SCOPE_LOCAL); assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(LOCAL_PROTOCOL, true); assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(SCOPE_KEY, SCOPE_REMOTE); assertFalse( InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(GENERIC_KEY, true); assertFalse( InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter("cluster", "broadcast"); assertFalse( InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); } @Test void testLocalProtocolAsync() throws ExecutionException, InterruptedException { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(ASYNC_KEY, true) .addParameter(INTERFACE_KEY, DemoService.class.getName()) .addParameter("application", "consumer") .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<?> invoker = proxy.getInvoker(service, DemoService.class, url); assertTrue(invoker.isAvailable()); Exporter<?> exporter = protocol.export(invoker); exporters.add(exporter); service = proxy.getProxy(protocol.refer(DemoService.class, url)); assertNull(service.getAsyncResult()); assertEquals("DONE", FutureContext.getContext().getCompletableFuture().get()); } @Test void testApplication() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .addParameter("application", "consumer") .addParameter(APPLICATION_KEY, "test-app") .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<?> invoker = proxy.getInvoker(service, DemoService.class, url); assertTrue(invoker.isAvailable()); Exporter<?> exporter = protocol.export(invoker); exporters.add(exporter); service = proxy.getProxy(protocol.refer(DemoService.class, url)); assertEquals("test-app", service.getApplication()); assertTrue(StringUtils.isEmpty(RpcContext.getServiceContext().getRemoteApplicationName())); } @Test void testRemoteAddress() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .addParameter("application", "consumer") .addParameter(APPLICATION_KEY, "test-app") .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<?> invoker = proxy.getInvoker(service, DemoService.class, url); assertTrue(invoker.isAvailable()); Exporter<?> exporter = protocol.export(invoker); exporters.add(exporter); service = proxy.getProxy(protocol.refer(DemoService.class, url)); assertEquals("127.0.0.1:0", service.getRemoteAddress()); assertNull(RpcContext.getServiceContext().getRemoteAddress()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/Type.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/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.rpc.protocol.injvm; 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-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/IEcho.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/IEcho.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; public interface IEcho { String echo(String e); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoServiceImpl.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/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.rpc.protocol.injvm; 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); public DemoServiceImpl() { super(); } public void sayHello(String name) { logger.debug("hello {}", name); } public String echo(String text) { return text; } 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 int stringLength(String str) { return str.length(); } @Override public String getAsyncResult() { try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error("getAsyncResult() Interrupted"); } return "DONE"; } @Override public String getApplication() { return RpcContext.getServiceContext().getRemoteApplicationName(); } @Override public String getRemoteAddress() { return RpcContext.getServiceContext().getRemoteAddressString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmClassLoaderTest.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmClassLoaderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.compiler.support.CtClassBuilder; import org.apache.dubbo.common.compiler.support.JavassistCompiler; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.config.ApplicationConfig; 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.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import demo.Empty; import demo.MultiClassLoaderService; import demo.MultiClassLoaderServiceImpl; import demo.MultiClassLoaderServiceRequest; import demo.MultiClassLoaderServiceResult; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class InjvmClassLoaderTest { @Test void testDifferentClassLoaderRequest() throws Exception { String basePath = DemoService.class .getProtectionDomain() .getCodeSource() .getLocation() .getFile(); basePath = java.net.URLDecoder.decode(basePath, "UTF-8"); TestClassLoader1 classLoader1 = new TestClassLoader1(basePath); TestClassLoader1 classLoader2 = new TestClassLoader1(basePath); TestClassLoader2 classLoader3 = new TestClassLoader2(classLoader2, basePath); ApplicationConfig applicationConfig = new ApplicationConfig("TestApp"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ModuleModel moduleModel = applicationModel.newModule(); Class clazz1 = classLoader1.loadClass(MultiClassLoaderService.class.getName(), false); Class<?> clazz1impl = classLoader1.loadClass(MultiClassLoaderServiceImpl.class.getName(), false); Class<?> requestClazzCustom1 = compileCustomRequest(classLoader1); Class<?> resultClazzCustom1 = compileCustomResult(classLoader1); classLoader1.loadedClass.put(requestClazzCustom1.getName(), requestClazzCustom1); classLoader1.loadedClass.put(resultClazzCustom1.getName(), resultClazzCustom1); // AtomicReference to cache request/response of provider AtomicReference innerRequestReference = new AtomicReference(); AtomicReference innerResultReference = new AtomicReference(); innerResultReference.set(resultClazzCustom1.getDeclaredConstructor().newInstance()); Constructor<?> declaredConstructor = clazz1impl.getDeclaredConstructor(AtomicReference.class, AtomicReference.class); // export provider ProxyFactory proxyFactory = moduleModel.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); Protocol protocol = moduleModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); Object providerInstance = declaredConstructor.newInstance(innerRequestReference, innerResultReference); URL url = URL.valueOf("injvm://localhost:0/" + MultiClassLoaderServiceImpl.class.getName() + "?interface=" + MultiClassLoaderServiceImpl.class.getName()); ServiceDescriptor providerServiceDescriptor = moduleModel.getServiceRepository().registerService(clazz1); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), providerInstance, providerServiceDescriptor, null, null); providerModel.setClassLoader(classLoader1); URL providerUrl = url.setScopeModel(moduleModel).setServiceModel(providerModel); Invoker invoker = proxyFactory.getInvoker(providerInstance, clazz1, providerUrl); Exporter<?> exporter = protocol.export(invoker); Class<?> clazz2 = classLoader2.loadClass(MultiClassLoaderService.class.getName(), false); Class<?> requestClazzOrigin = classLoader2.loadClass(MultiClassLoaderServiceRequest.class.getName(), false); Class<?> requestClazzCustom2 = compileCustomRequest(classLoader2); Class<?> resultClazzCustom3 = compileCustomResult(classLoader3); classLoader2.loadedClass.put(requestClazzCustom2.getName(), requestClazzCustom2); classLoader3.loadedClass.put(resultClazzCustom3.getName(), resultClazzCustom3); // refer consumer ServiceDescriptor consumerServiceDescriptor = moduleModel.getServiceRepository().registerService(clazz2); ConsumerModel consumerModel = new ConsumerModel( clazz2.getName(), null, consumerServiceDescriptor, ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(clazz2)); consumerModel.setClassLoader(classLoader3); URL consumerUrl = url.setScopeModel(moduleModel).setServiceModel(consumerModel); Object object1 = proxyFactory.getProxy(protocol.refer(clazz2, consumerUrl)); java.lang.reflect.Method callBean1 = object1.getClass().getDeclaredMethod("call", requestClazzOrigin); callBean1.setAccessible(true); Object result1 = callBean1.invoke( object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); // invoke result should load from classLoader3 ( sub classLoader of classLoader2 --> consumer side classLoader) Assertions.assertEquals(resultClazzCustom3, result1.getClass()); Assertions.assertNotEquals(classLoader2, result1.getClass().getClassLoader()); // invoke request param should load from classLoader1 ( provider side classLoader ) Assertions.assertEquals( classLoader1, innerRequestReference.get().getClass().getClassLoader()); exporter.unexport(); applicationModel.destroy(); } private Class<?> compileCustomRequest(ClassLoader classLoader) throws NotFoundException, CannotCompileException, ClassNotFoundException { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(MultiClassLoaderServiceRequest.class.getName() + "A"); builder.setSuperClassName(MultiClassLoaderServiceRequest.class.getName()); CtClass cls = builder.build(classLoader); ClassPool cp = cls.getClassPool(); if (classLoader == null) { classLoader = cp.getClassLoader(); } return cp.toClass( cls, classLoader.loadClass(Empty.class.getName()), classLoader, JavassistCompiler.class.getProtectionDomain()); } private Class<?> compileCustomResult(ClassLoader classLoader) throws NotFoundException, CannotCompileException, ClassNotFoundException { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(MultiClassLoaderServiceResult.class.getName() + "A"); builder.setSuperClassName(MultiClassLoaderServiceResult.class.getName()); CtClass cls = builder.build(classLoader); ClassPool cp = cls.getClassPool(); if (classLoader == null) { classLoader = cp.getClassLoader(); } return cp.toClass( cls, classLoader.loadClass(Empty.class.getName()), classLoader, JavassistCompiler.class.getProtectionDomain()); } private static class TestClassLoader1 extends ClassLoader { private String basePath; public TestClassLoader1(String basePath) { this.basePath = basePath; } Map<String, Class<?>> loadedClass = new ConcurrentHashMap<>(); @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = loadClassData(name); return defineClass(name, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException(); } } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (loadedClass.containsKey(name)) { return loadedClass.get(name); } if (name.startsWith("demo")) { if (name.equals(MultiClassLoaderServiceRequest.class.getName()) || name.equals(MultiClassLoaderServiceResult.class.getName())) { return super.loadClass(name, resolve); } Class<?> aClass = this.findClass(name); this.loadedClass.put(name, aClass); if (resolve) { this.resolveClass(aClass); } return aClass; } else { Class<?> loadedClass = this.findLoadedClass(name); if (loadedClass != null) { return loadedClass; } else { return super.loadClass(name, resolve); } } } public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); int length = fileInputStream.available(); classBytes = new byte[length]; fileInputStream.read(classBytes); fileInputStream.close(); return classBytes; } } private static class TestClassLoader2 extends ClassLoader { private String basePath; private TestClassLoader1 testClassLoader; Map<String, Class<?>> loadedClass = new ConcurrentHashMap<>(); public TestClassLoader2(TestClassLoader1 testClassLoader, String basePath) { this.testClassLoader = testClassLoader; this.basePath = basePath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = loadClassData(name); return defineClass(name, bytes, 0, bytes.length); } catch (Exception e) { return testClassLoader.loadClass(name, false); } } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (loadedClass.containsKey(name)) { return loadedClass.get(name); } if (name.startsWith("demo.MultiClassLoaderServiceRe") || name.startsWith("demo.Empty")) { Class<?> aClass = this.findClass(name); this.loadedClass.put(name, aClass); if (resolve) { this.resolveClass(aClass); } return aClass; } else { return testClassLoader.loadClass(name, resolve); } } public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); int length = fileInputStream.available(); classBytes = new byte[length]; fileInputStream.read(classBytes); fileInputStream.close(); return classBytes; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoService.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/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.rpc.protocol.injvm; /** * <code>TestService</code> */ public interface DemoService { void sayHello(String name); String echo(String text); 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); String getAsyncResult(); String getApplication(); String getRemoteAddress(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmDeepCopyTest.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmDeepCopyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.config.ApplicationConfig; 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.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.io.Serializable; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class InjvmDeepCopyTest { @Test void testDeepCopy() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("TestInjvm")); ModuleModel moduleModel = applicationModel.newModule(); AtomicReference<Data> requestReference = new AtomicReference<>(); AtomicReference<Data> responseReference = new AtomicReference<>(); Demo demo = new Demo(requestReference, responseReference); // export provider ProxyFactory proxyFactory = moduleModel.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); Protocol protocol = moduleModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf( "injvm://localhost:0/" + DemoInterface.class.getName() + "?interface=" + DemoInterface.class.getName()); ServiceDescriptor providerServiceDescriptor = moduleModel.getServiceRepository().registerService(DemoInterface.class); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), demo, providerServiceDescriptor, null, null); URL providerUrl = url.setScopeModel(moduleModel).setServiceModel(providerModel); Invoker invoker = proxyFactory.getInvoker(demo, DemoInterface.class, providerUrl); Exporter<?> exporter = protocol.export(invoker); // refer consumer ServiceDescriptor consumerServiceDescriptor = moduleModel.getServiceRepository().registerService(DemoInterface.class); ConsumerModel consumerModel = new ConsumerModel( DemoInterface.class.getName(), null, consumerServiceDescriptor, ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(DemoInterface.class)); URL consumerUrl = url.setScopeModel(moduleModel).setServiceModel(consumerModel); DemoInterface stub = proxyFactory.getProxy(protocol.refer(DemoInterface.class, consumerUrl)); Data request = new Data(); Data response = stub.call(request); Assertions.assertNotEquals(requestReference.get(), request); Assertions.assertNotEquals(responseReference.get(), response); Data response1 = stub.call(null); Assertions.assertNull(requestReference.get()); Assertions.assertNull(responseReference.get()); Assertions.assertNull(response1); exporter.unexport(); applicationModel.destroy(); } interface DemoInterface { Data call(Data obj); } private static class Demo implements DemoInterface { private AtomicReference<Data> requestReference; private AtomicReference<Data> responseReference; public Demo(AtomicReference<Data> requestReference, AtomicReference<Data> responseReference) { this.requestReference = requestReference; this.responseReference = responseReference; } @Override public Data call(Data obj) { requestReference.set(obj); Data result = null; if (obj != null) { result = new Data(); } responseReference.set(result); return result; } } private static class Data implements Serializable {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceResult.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; import java.io.Serializable; public class MultiClassLoaderServiceResult implements Serializable {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/Empty.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/Empty.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; public class Empty {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceRequest.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; import java.io.Serializable; public class MultiClassLoaderServiceRequest implements Serializable {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderService.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; public interface MultiClassLoaderService { Object call(MultiClassLoaderServiceRequest innerRequest); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceImpl.java
dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; import java.util.concurrent.atomic.AtomicReference; public class MultiClassLoaderServiceImpl implements MultiClassLoaderService { private AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference; private AtomicReference<MultiClassLoaderServiceResult> innerResultReference; public MultiClassLoaderServiceImpl( AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference, AtomicReference<MultiClassLoaderServiceResult> innerResultReference) { this.innerRequestReference = innerRequestReference; this.innerResultReference = innerResultReference; } @Override public MultiClassLoaderServiceResult call(MultiClassLoaderServiceRequest innerRequest) { innerRequestReference.set(innerRequest); return innerResultReference.get(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java
dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.protocol.AbstractProtocol; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.BROADCAST_CLUSTER; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; public class InjvmProtocol extends AbstractProtocol { public static final String NAME = LOCAL_PROTOCOL; public static final int DEFAULT_PORT = 0; public static InjvmProtocol getInjvmProtocol(ScopeModel scopeModel) { return (InjvmProtocol) scopeModel.getExtensionLoader(Protocol.class).getExtension(InjvmProtocol.NAME, false); } static Exporter<?> getExporter(Map<String, Exporter<?>> map, URL key) { Exporter<?> result = null; if (!key.getServiceKey().contains("*")) { result = map.get(key.getServiceKey()); } else { if (CollectionUtils.isNotEmptyMap(map)) { for (Exporter<?> exporter : map.values()) { if (UrlUtils.isServiceKeyMatch(key, exporter.getInvoker().getUrl())) { result = exporter; break; } } } } return result; } @Override public int getDefaultPort() { return DEFAULT_PORT; } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { return new InjvmExporter<>(invoker, invoker.getUrl().getServiceKey(), exporterMap); } @Override public <T> Invoker<T> protocolBindingRefer(Class<T> serviceType, URL url) throws RpcException { return new InjvmInvoker<>(serviceType, url, url.getServiceKey(), exporterMap); } public boolean isInjvmRefer(URL url) { String scope = url.getParameter(SCOPE_KEY); // Since injvm protocol is configured explicitly, we don't need to set any extra flag, use normal refer process. if (SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) { // if it's declared as local reference // 'scope=local' is equivalent to 'injvm=true', injvm will be deprecated in the future release return true; } else if (SCOPE_REMOTE.equals(scope)) { // it's declared as remote reference return false; } else if (url.getParameter(GENERIC_KEY, false)) { // generic invocation is not local reference return false; } else if (getExporter(exporterMap, url) != null) { // Broadcast cluster means that multiple machines will be called, // which is not converted to injvm protocol at this time. if (BROADCAST_CLUSTER.equalsIgnoreCase(url.getParameter(CLUSTER_KEY))) { return false; } // by default, go through local reference if there's the service exposed locally return true; } else { return false; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmExporter.java
dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmExporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.AbstractExporter; import java.util.Map; /** * InjvmExporter */ public class InjvmExporter<T> extends AbstractExporter<T> { private final String key; private final Map<String, Exporter<?>> exporterMap; InjvmExporter(Invoker<T> invoker, String key, Map<String, Exporter<?>> exporterMap) { super(invoker); this.key = key; this.exporterMap = exporterMap; exporterMap.put(key, this); } @Override public void afterUnExport() { exporterMap.remove(key); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/ParamDeepCopyUtil.java
dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/ParamDeepCopyUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.lang.reflect.Type; @SPI(scope = ExtensionScope.FRAMEWORK) public interface ParamDeepCopyUtil { default <T> T copy(URL url, Object src, Class<T> targetClass) { return copy(url, src, targetClass, null); } <T> T copy(URL url, Object src, Class<T> targetClass, Type type); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java
dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.threadlocal.InternalThreadLocalMap; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.url.component.DubboServiceAddressURL; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.FutureContext; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.InvokeMode; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; /** * InjvmInvoker */ public class InjvmInvoker<T> extends AbstractInvoker<T> { private final String key; private final Map<String, Exporter<?>> exporterMap; private volatile Exporter<?> exporter = null; private volatile URL consumerUrl = null; private final ExecutorRepository executorRepository; private final ParamDeepCopyUtil paramDeepCopyUtil; private final boolean shouldIgnoreSameModule; private static final boolean setFutureWhenSync = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty( CommonConstants.ThirdPartyProperty.SET_FUTURE_IN_SYNC_MODE, "true")); InjvmInvoker(Class<T> type, URL url, String key, Map<String, Exporter<?>> exporterMap) { super(type, url); this.key = key; this.exporterMap = exporterMap; this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); this.paramDeepCopyUtil = url.getOrDefaultFrameworkModel() .getExtensionLoader(ParamDeepCopyUtil.class) .getExtension(url.getParameter(CommonConstants.INJVM_COPY_UTIL_KEY, DefaultParamDeepCopyUtil.NAME)); this.shouldIgnoreSameModule = url.getParameter(CommonConstants.INJVM_IGNORE_SAME_MODULE_KEY, false); } @Override public boolean isAvailable() { InjvmExporter<?> exporter = (InjvmExporter<?>) exporterMap.get(key); if (exporter == null) { return false; } else { return super.isAvailable(); } } @Override public Result doInvoke(Invocation invocation) throws Throwable { if (exporter == null) { exporter = InjvmProtocol.getExporter(exporterMap, getUrl()); if (exporter == null) { throw new RpcException("Service [" + key + "] not found."); } } // Solve local exposure, the server opens the token, and the client call fails. Invoker<?> invoker = exporter.getInvoker(); URL serverURL = invoker.getUrl(); boolean serverHasToken = serverURL.hasParameter(Constants.TOKEN_KEY); if (serverHasToken) { invocation.setAttachment(Constants.TOKEN_KEY, serverURL.getParameter(Constants.TOKEN_KEY)); } if (consumerUrl == null) { // no need to sync, multi-objects is acceptable and will be gc-ed. consumerUrl = new DubboServiceAddressURL(serverURL.getUrlAddress(), serverURL.getUrlParam(), getUrl(), null); } int timeout = RpcUtils.calculateTimeout(consumerUrl, invocation, RpcUtils.getMethodName(invocation), DEFAULT_TIMEOUT); if (timeout <= 0) { return AsyncRpcResult.newDefaultAsyncResult( new RpcException( RpcException.TIMEOUT_TERMINATE, "No time left for making the following call: " + invocation.getServiceName() + "." + RpcUtils.getMethodName(invocation) + ", terminate directly."), invocation); } invocation.setAttachment(TIMEOUT_KEY, String.valueOf(timeout)); String desc = ReflectUtils.getDesc(invocation.getParameterTypes()); // recreate invocation ---> deep copy parameters Invocation copiedInvocation = recreateInvocation(invocation, invoker, desc); if (isAsync(invoker.getUrl(), getUrl())) { ((RpcInvocation) copiedInvocation).setInvokeMode(InvokeMode.ASYNC); // use consumer executor ExecutorService executor = executorRepository.createExecutorIfAbsent( ExecutorUtil.setThreadName(getUrl(), SERVER_THREAD_POOL_NAME)); CompletableFuture<AppResponse> appResponseFuture = CompletableFuture.supplyAsync( () -> { // clear thread local before child invocation, prevent context pollution InternalThreadLocalMap originTL = InternalThreadLocalMap.getAndRemove(); try { RpcContext.getServiceContext().setRemoteAddress(LOCALHOST_VALUE, 0); RpcContext.getServiceContext().setRemoteApplicationName(getUrl().getApplication()); Result result = invoker.invoke(copiedInvocation); if (result.hasException()) { AppResponse appResponse = new AppResponse(result.getException()); appResponse.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); return appResponse; } else { rebuildValue(invocation, invoker, result); AppResponse appResponse = new AppResponse(result.getValue()); appResponse.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); return appResponse; } } finally { InternalThreadLocalMap.set(originTL); } }, executor); // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) { FutureContext.getContext().setCompatibleFuture(appResponseFuture); } AsyncRpcResult result = new AsyncRpcResult(appResponseFuture, copiedInvocation); result.setExecutor(executor); return result; } else { Result result; // clear thread local before child invocation, prevent context pollution InternalThreadLocalMap originTL = InternalThreadLocalMap.getAndRemove(); try { RpcContext.getServiceContext().setRemoteAddress(LOCALHOST_VALUE, 0); RpcContext.getServiceContext().setRemoteApplicationName(getUrl().getApplication()); result = invoker.invoke(copiedInvocation); } finally { InternalThreadLocalMap.set(originTL); } CompletableFuture<AppResponse> future = new CompletableFuture<>(); AppResponse rpcResult = new AppResponse(copiedInvocation); if (result instanceof AsyncRpcResult) { result.whenCompleteWithContext((r, t) -> { if (t != null) { rpcResult.setException(t); } else { if (r.hasException()) { rpcResult.setException(r.getException()); } else { Object rebuildValue = rebuildValue(invocation, invoker, r.getValue()); rpcResult.setValue(rebuildValue); } } rpcResult.setObjectAttachments(new HashMap<>(r.getObjectAttachments())); future.complete(rpcResult); }); } else { if (result.hasException()) { rpcResult.setException(result.getException()); } else { Object rebuildValue = rebuildValue(invocation, invoker, result.getValue()); rpcResult.setValue(rebuildValue); } rpcResult.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); future.complete(rpcResult); } return new AsyncRpcResult(future, invocation); } } private Class<?> getReturnType(ServiceModel consumerServiceModel, String methodName, String desc) { MethodDescriptor consumerMethod = consumerServiceModel.getServiceModel().getMethod(methodName, desc); if (consumerMethod != null) { Type[] returnTypes = consumerMethod.getReturnTypes(); if (ArrayUtils.isNotEmpty(returnTypes)) { return (Class<?>) returnTypes[0]; } } return null; } private Invocation recreateInvocation(Invocation invocation, Invoker<?> invoker, String desc) { ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); ServiceModel providerServiceModel = invoker.getUrl().getServiceModel(); if (providerServiceModel == null) { return invocation; } String methodName = invocation.getMethodName(); if (isSkipCopy(invocation, invoker)) { // generic invoke, skip copy arguments RpcInvocation copiedInvocation = new RpcInvocation( invocation.getTargetServiceUniqueName(), providerServiceModel, methodName, invocation.getServiceName(), invocation.getProtocolServiceKey(), invocation.getParameterTypes(), invocation.getArguments(), invocation.copyObjectAttachments(), invocation.getInvoker(), new HashMap<>(), invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); copiedInvocation.setInvoker(invoker); return copiedInvocation; } MethodDescriptor providerMethod = providerServiceModel.getServiceModel().getMethod(methodName, desc); Object[] realArgument = null; if (providerMethod != null) { Class<?>[] pts = providerMethod.getParameterClasses(); Object[] args = invocation.getArguments(); // switch ClassLoader Thread.currentThread().setContextClassLoader(providerServiceModel.getClassLoader()); try { // copy parameters if (pts != null && args != null && pts.length == args.length) { realArgument = new Object[pts.length]; for (int i = 0; i < pts.length; i++) { realArgument[i] = paramDeepCopyUtil.copy(consumerUrl, args[i], pts[i]); } } if (realArgument == null) { realArgument = args; } RpcInvocation copiedInvocation = new RpcInvocation( invocation.getTargetServiceUniqueName(), providerServiceModel, methodName, invocation.getServiceName(), invocation.getProtocolServiceKey(), pts, realArgument, invocation.copyObjectAttachments(), invocation.getInvoker(), new HashMap<>(), invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); copiedInvocation.setInvoker(invoker); return copiedInvocation; } finally { Thread.currentThread().setContextClassLoader(originClassLoader); } } else { return invocation; } } private boolean isSkipCopy(Invocation invocation, Invoker<?> invoker) { ServiceModel providerServiceModel = invoker.getUrl().getServiceModel(); if (providerServiceModel == null) { return true; } String methodName = invocation.getMethodName(); ServiceModel consumerServiceModel = invocation.getServiceModel(); boolean shouldSkip = shouldIgnoreSameModule && consumerServiceModel != null && Objects.equals(providerServiceModel.getModuleModel(), consumerServiceModel.getModuleModel()); return CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName) || shouldSkip; } private Object rebuildValue(Invocation invocation, Invoker<?> invoker, Object originValue) { if (isSkipCopy(invocation, invoker)) { return originValue; } Object value = originValue; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { // 1. By default, the classloader of the current Thread is the consumer class loader. ClassLoader consumerClassLoader = contextClassLoader; ServiceModel serviceModel = getUrl().getServiceModel(); // 2. If there is a ConsumerModel in the url, the classloader of the ConsumerModel is consumerLoader if (Objects.nonNull(serviceModel) && serviceModel instanceof ConsumerModel) { consumerClassLoader = serviceModel.getClassLoader(); } // 3. request result copy if (Objects.nonNull(consumerClassLoader)) { Thread.currentThread().setContextClassLoader(consumerClassLoader); Type[] returnTypes = RpcUtils.getReturnTypes(invocation); if (returnTypes == null) { return originValue; } if (returnTypes.length == 1) { value = paramDeepCopyUtil.copy(consumerUrl, originValue, (Class<?>) returnTypes[0]); } else if (returnTypes.length == 2) { value = paramDeepCopyUtil.copy(consumerUrl, originValue, (Class<?>) returnTypes[0], returnTypes[1]); } } return value; } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } private boolean isAsync(URL remoteUrl, URL localUrl) { if (localUrl.hasParameter(ASYNC_KEY)) { return localUrl.getParameter(ASYNC_KEY, false); } return remoteUrl.getParameter(ASYNC_KEY, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java
dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.injvm; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; 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.common.utils.ProtobufUtils; import org.apache.dubbo.remoting.utils.UrlUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE; public class DefaultParamDeepCopyUtil implements ParamDeepCopyUtil { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultParamDeepCopyUtil.class); public static final String NAME = "default"; @Override @SuppressWarnings({"unchecked"}) public <T> T copy(URL url, Object src, Class<T> targetClass, Type type) { // TODO: maybe we have better way to do this if (src != null && ProtobufUtils.isProtobufClass(src.getClass())) { return (T) src; } Serialization serialization = url.getOrDefaultFrameworkModel() .getExtensionLoader(Serialization.class) .getExtension(UrlUtils.serializationOrDefault(url)); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(src); objectOutput.flushBuffer(); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray())) { ObjectInput objectInput = serialization.deserialize(url, inputStream); if (type != null) { return objectInput.readObject(targetClass, type); } else { return objectInput.readObject(targetClass); } } catch (ClassNotFoundException | IOException e) { logger.error(PROTOCOL_ERROR_DESERIALIZE, "", "", "Unable to deep copy parameter to target class.", e); } } catch (Throwable e) { logger.error(PROTOCOL_ERROR_DESERIALIZE, "", "", "Unable to deep copy parameter to target class.", e); } if (src.getClass().equals(targetClass)) { return (T) src; } else { return null; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.rpc.TriRpcStatus.Code; import java.io.Serializable; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.RpcException.FORBIDDEN_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.METHOD_NOT_FOUND; import static org.apache.dubbo.rpc.RpcException.TIMEOUT_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.UNKNOWN_EXCEPTION; import static org.junit.jupiter.api.Assertions.fail; class TriRpcStatusTest { @Test void fromCode() { Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.fromCode(2).code); try { TriRpcStatus.fromCode(1000); fail(); } catch (Throwable t) { // pass } } @Test void testFromCode() { Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.fromCode(Code.UNKNOWN).code); } @Test void getStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException).code); } @Test void testGetStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException, null).code); Assertions.assertEquals( TriRpcStatus.DEADLINE_EXCEEDED.code, TriRpcStatus.getStatus(new RpcException(RpcException.TIMEOUT_EXCEPTION), null).code); Assertions.assertEquals( TriRpcStatus.DEADLINE_EXCEEDED.code, TriRpcStatus.getStatus(new TimeoutException(true, null, null), null).code); } @Test void rpcExceptionCodeToGrpcCode() { Assertions.assertEquals(Code.DEADLINE_EXCEEDED, TriRpcStatus.dubboCodeToTriCode(2)); } @Test void limitSizeTo1KB() { String a = "a"; for (int i = 0; i < 11; i++) { a += a; } Assertions.assertEquals(1024, TriRpcStatus.limitSizeTo1KB(a).length()); Assertions.assertEquals(1, TriRpcStatus.limitSizeTo1KB("a").length()); } @Test void decodeMessage() { String message = "😯"; Assertions.assertEquals(message, TriRpcStatus.decodeMessage(TriRpcStatus.encodeMessage(message))); Assertions.assertTrue(TriRpcStatus.decodeMessage("").isEmpty()); Assertions.assertTrue(TriRpcStatus.decodeMessage(null).isEmpty()); } @Test void httpStatusToGrpcCode() { Assertions.assertEquals(Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(404)); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.BAD_GATEWAY.code())); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.TOO_MANY_REQUESTS.code())); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code())); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.GATEWAY_TIMEOUT.code())); Assertions.assertEquals(Code.INTERNAL, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.CONTINUE.code())); Assertions.assertEquals( Code.INTERNAL, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code())); Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.ACCEPTED.code())); Assertions.assertEquals( Code.PERMISSION_DENIED, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.FORBIDDEN.code())); Assertions.assertEquals( Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.NOT_FOUND.code())); } @Test void isOk() { Assertions.assertTrue(TriRpcStatus.OK.isOk()); Assertions.assertFalse(TriRpcStatus.NOT_FOUND.isOk()); } @Test void withCause() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withCause = origin.withCause(new IllegalStateException("test")); Assertions.assertNull(origin.cause); Assertions.assertTrue(withCause.cause.getMessage().contains("test")); } @Test void withDescription() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withDesc = origin.withDescription("desc"); Assertions.assertNull(origin.description); Assertions.assertTrue(withDesc.description.contains("desc")); } @Test void appendDescription() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withDesc = origin.appendDescription("desc0"); TriRpcStatus withDesc2 = withDesc.appendDescription("desc1"); Assertions.assertNull(origin.description); Assertions.assertTrue(withDesc2.description.contains("desc1")); Assertions.assertTrue(withDesc2.description.contains("desc0")); } @Test void asException() { StatusRpcException exception = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .asException(); Assertions.assertEquals(Code.NOT_FOUND, exception.getStatus().code); } @Test void toEncodedMessage() { String message = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .toEncodedMessage(); Assertions.assertTrue(message.contains("desc")); Assertions.assertTrue(message.contains("test")); } @Test void toMessageWithoutCause() { String message = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .toMessageWithoutCause(); Assertions.assertTrue(message.contains("desc")); Assertions.assertFalse(message.contains("test")); } @Test void toMessage() { String message = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .toMessage(); Assertions.assertTrue(message.contains("desc")); Assertions.assertTrue(message.contains("test")); } @Test void encodeMessage() { Assertions.assertTrue(TriRpcStatus.encodeMessage(null).isEmpty()); Assertions.assertTrue(TriRpcStatus.encodeMessage("").isEmpty()); } @Test void fromMessage() { String origin = "haha test 😊"; final String encoded = TriRpcStatus.encodeMessage(origin); Assertions.assertNotEquals(origin, encoded); final String decoded = TriRpcStatus.decodeMessage(encoded); Assertions.assertEquals(origin, decoded); } @Test void toMessage2() { String content = "\t\ntest with whitespace\r\nand Unicode BMP ☺ and non-BMP 😈\t\n"; final TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription(content); Assertions.assertEquals(content, status.toMessage()); } @Test void triCodeToDubboCode() { Assertions.assertEquals(TIMEOUT_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.DEADLINE_EXCEEDED)); Assertions.assertEquals(FORBIDDEN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.PERMISSION_DENIED)); Assertions.assertEquals(METHOD_NOT_FOUND, TriRpcStatus.triCodeToDubboCode(Code.UNIMPLEMENTED)); Assertions.assertEquals(UNKNOWN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.UNKNOWN)); } @Test void testSerializable() { TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription("test"); Assertions.assertInstanceOf(Serializable.class, status.asException()); Assertions.assertInstanceOf(Serializable.class, status.asException().getStatus()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class StatusRpcExceptionTest { @Test void getStatus() { Assertions.assertEquals( TriRpcStatus.INTERNAL, ((StatusRpcException) TriRpcStatus.INTERNAL.asException()).getStatus()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; class StubInvocationUtilTest { private Invoker<IGreeter> invoker; private MethodDescriptor method; private String request = "request"; private String response = "response"; private Result result; private Invoker<IGreeter> createMockInvoker(URL url) { Invoker<IGreeter> invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(IGreeter.class); return invoker; } private URL createMockURL(ConsumerModel consumerModel) { URL url = Mockito.mock(URL.class); when(url.getServiceModel()).thenReturn(consumerModel); when(url.getServiceInterface()).thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()).thenReturn(IGreeter.class.getName()); return url; } private ConsumerModel createMockConsumerModel(ServiceDescriptor serviceDescriptor) { ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); when(consumerModel.getServiceModel()).thenReturn(serviceDescriptor); return consumerModel; } private Result createMockResult(String response) throws Throwable { Result result = Mockito.mock(Result.class); when(result.recreate()).thenReturn(response); return result; } private MethodDescriptor createMockMethodDescriptor() { MethodDescriptor method = Mockito.mock(MethodDescriptor.class); when(method.getParameterClasses()).thenReturn(new Class[] {String.class}); when(method.getMethodName()).thenReturn("sayHello"); return method; } @BeforeEach void init() throws Throwable { ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); ConsumerModel consumerModel = createMockConsumerModel(serviceDescriptor); URL url = createMockURL(consumerModel); invoker = createMockInvoker(url); result = createMockResult("response"); method = createMockMethodDescriptor(); } @Test void unaryCall() { when(invoker.invoke(any(Invocation.class))).thenReturn(result); Object ret = StubInvocationUtil.unaryCall(invoker, method, request); Assertions.assertEquals(response, ret); } @Test void unaryCall2() { when(invoker.invoke(any(Invocation.class))) .thenThrow(new RuntimeException("a")) .thenThrow(new Error("b")); try { StubInvocationUtil.unaryCall(invoker, method, request); fail(); } catch (Throwable t) { // pass } try { StubInvocationUtil.unaryCall(invoker, method, request); fail(); } catch (Throwable t) { // pass } } @Test void testUnaryCall() throws Throwable { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> result); CountDownLatch latch = new CountDownLatch(1); AtomicReference<Object> atomicReference = new AtomicReference<>(); StreamObserver<Object> responseObserver = new StreamObserver<Object>() { @Override public void onNext(Object data) { atomicReference.set(data); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { latch.countDown(); } }; StubInvocationUtil.unaryCall(invoker, method, request, responseObserver); latch.await(1, TimeUnit.SECONDS); Assertions.assertEquals(response, atomicReference.get()); } @Test void biOrClientStreamCall() throws InterruptedException { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> { Invocation invocation = (Invocation) invocationOnMock.getArguments()[0]; StreamObserver<Object> observer = (StreamObserver<Object>) invocation.getArguments()[0]; observer.onNext(response); observer.onCompleted(); when(result.recreate()).then(invocationOnMock1 -> new StreamObserver<Object>() { @Override public void onNext(Object data) { observer.onNext(data); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { observer.onCompleted(); } }); return result; }); CountDownLatch latch = new CountDownLatch(11); StreamObserver<Object> responseObserver = new StreamObserver<Object>() { @Override public void onNext(Object data) { latch.countDown(); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { latch.countDown(); } }; StreamObserver<Object> observer = StubInvocationUtil.biOrClientStreamCall(invoker, method, responseObserver); for (int i = 0; i < 10; i++) { observer.onNext(request); } observer.onCompleted(); Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS)); } @Test void serverStreamCall() throws InterruptedException { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> { Invocation invocation = (Invocation) invocationOnMock.getArguments()[0]; StreamObserver<Object> observer = (StreamObserver<Object>) invocation.getArguments()[1]; for (int i = 0; i < 10; i++) { observer.onNext(response); } observer.onCompleted(); return result; }); CountDownLatch latch = new CountDownLatch(11); StreamObserver<Object> responseObserver = new StreamObserver<Object>() { @Override public void onNext(Object data) { latch.countDown(); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { latch.countDown(); } }; StubInvocationUtil.serverStreamCall(invoker, method, request, responseObserver); Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp3ProtocolTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp3ProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.rpc.Constants; 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.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterImpl; import org.apache.dubbo.rpc.protocol.tri.support.MockStreamObserver; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TripleHttp3ProtocolTest { @Test void testDemoProtocol() throws Exception { IGreeterImpl serviceImpl = new IGreeterImpl(); int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); Map<String, String> settings = new HashMap<>(); settings.put(Constants.H3_SETTINGS_HTTP3_ENABLED, "true"); settings.put(Constants.H3_SETTINGS_HTTP3_NEGOTIATION, "false"); applicationModel.modelEnvironment().updateAppConfigMap(settings); SslConfig sslConfig = new SslConfig(); sslConfig.setScopeModel(applicationModel); sslConfig.setServerKeyCertChainPath(getAbsolutePath("/certs/server.pem")); sslConfig.setServerPrivateKeyPath(getAbsolutePath("/certs/server.key")); sslConfig.setServerTrustCertCollectionPath(getAbsolutePath("/certs/ca.pem")); sslConfig.setClientKeyCertChainPath(getAbsolutePath("/certs/client.pem")); sslConfig.setClientPrivateKeyPath(getAbsolutePath("/certs/client.key")); sslConfig.setClientTrustCertCollectionPath(getAbsolutePath("/certs/ca.pem")); applicationModel.getApplicationConfigManager().setSsl(sslConfig); URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter.class); ProviderModel providerModel = new ProviderModel( providerUrl.getServiceKey(), serviceImpl, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel()); ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker<IGreeter> invoker = proxy.getInvoker(serviceImpl, IGreeter.class, providerUrl); Exporter<IGreeter> export = protocol.export(invoker); URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter greeterProxy = proxy.getProxy(protocol.refer(IGreeter.class, consumerUrl)); Thread.sleep(1000); Assertions.assertTrue(Http3Exchanger.isEnabled(providerUrl)); // 1. test unaryStream String REQUEST_MSG = "hello world"; Assertions.assertEquals(REQUEST_MSG, greeterProxy.echo(REQUEST_MSG)); Assertions.assertEquals(REQUEST_MSG, serviceImpl.echoAsync(REQUEST_MSG).get()); // 2. test serverStream MockStreamObserver outboundMessageSubscriber1 = new MockStreamObserver(); greeterProxy.serverStream(REQUEST_MSG, outboundMessageSubscriber1); outboundMessageSubscriber1.getLatch().await(3000, TimeUnit.MILLISECONDS); Assertions.assertEquals(REQUEST_MSG, outboundMessageSubscriber1.getOnNextData()); Assertions.assertTrue(outboundMessageSubscriber1.isOnCompleted()); // 3. test bidirectionalStream MockStreamObserver outboundMessageSubscriber2 = new MockStreamObserver(); StreamObserver<String> inboundMessageObserver = greeterProxy.bidirectionalStream(outboundMessageSubscriber2); inboundMessageObserver.onNext(REQUEST_MSG); inboundMessageObserver.onCompleted(); outboundMessageSubscriber2.getLatch().await(3000, TimeUnit.MILLISECONDS); // verify client Assertions.assertEquals(IGreeter.SERVER_MSG, outboundMessageSubscriber2.getOnNextData()); Assertions.assertTrue(outboundMessageSubscriber2.isOnCompleted()); // verify server MockStreamObserver serverOutboundMessageSubscriber = (MockStreamObserver) serviceImpl.getMockStreamObserver(); serverOutboundMessageSubscriber.getLatch().await(1000, TimeUnit.MILLISECONDS); Assertions.assertEquals(REQUEST_MSG, serverOutboundMessageSubscriber.getOnNextData()); Assertions.assertTrue(serverOutboundMessageSubscriber.isOnCompleted()); export.unexport(); protocol.destroy(); // resource recycle. serviceRepository.destroy(); } private static String getAbsolutePath(String resourcePath) throws Exception { java.net.URL resourceUrl = TripleHttp3ProtocolTest.class.getResource(resourcePath); Assertions.assertNotNull(resourceUrl, "Cert file '" + resourcePath + "' is required"); return Paths.get(resourceUrl.toURI()).toAbsolutePath().toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/HelloReply.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/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.rpc.protocol.tri; import com.google.protobuf.Message; public final class HelloReply extends com.google.protobuf.GeneratedMessageV3 { @Override protected FieldAccessorTable internalGetFieldAccessorTable() { return null; } @Override protected Message.Builder newBuilderForType(BuilderParent builderParent) { return null; } @Override public Message.Builder newBuilderForType() { return null; } @Override public Message.Builder toBuilder() { return null; } @Override public Message getDefaultInstanceForType() { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.junit.jupiter.api.Test; class ClassLoadUtilTest { @Test void switchContextLoader() { ClassLoadUtil.switchContextLoader(Thread.currentThread().getContextClassLoader()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.StatusRpcException; import org.apache.dubbo.rpc.TriRpcStatus; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class DeadlineFutureTest { @Test void test() throws InterruptedException, ExecutionException { String service = "service"; String method = "method"; String address = "localhost:12201"; DeadlineFuture timeout = DeadlineFuture.newFuture(service, method, address, 10, ImmediateEventExecutor.INSTANCE); TimeUnit.MILLISECONDS.sleep(20); AppResponse timeoutResponse = timeout.get(); Assertions.assertTrue(timeoutResponse.getException() instanceof StatusRpcException); DeadlineFuture success = DeadlineFuture.newFuture(service, method, address, 1000, ImmediateEventExecutor.INSTANCE); AppResponse response = new AppResponse(); success.received(TriRpcStatus.OK, response); AppResponse response1 = success.get(); Assertions.assertEquals(response, response1); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; 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.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter2; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter2Impl; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ExceptionUtilsTest { private IllegalStateException exception = new IllegalStateException("Exception0"); @Test void getStackTrace() { Assertions.assertTrue(ExceptionUtils.getStackTrace(exception).contains("Exception0")); } @Test void getStackFrameString() { String str = ExceptionUtils.getStackFrameString(Arrays.stream(exception.getStackTrace()) .map(StackTraceElement::toString) .collect(Collectors.toList())); Assertions.assertTrue(str.contains("ExceptionUtilsTest")); } @Test void getStackFrames() { StackTraceElement[] traces = exception.getStackTrace(); List<String> frames = Arrays.stream(traces).map(StackTraceElement::toString).collect(Collectors.toList()); String str = ExceptionUtils.getStackFrameString(frames); List<String> stackFrames = Arrays.stream(ExceptionUtils.getStackFrames(str)).collect(Collectors.toList()); Assertions.assertEquals(frames, stackFrames); } @Test void testGetStackFrames() { String[] stackFrames = ExceptionUtils.getStackFrames(exception); Assertions.assertNotEquals(0, stackFrames.length); } @Test void getStackFrameList() { List<String> stackFrameList = ExceptionUtils.getStackFrameList(exception, 10); Assertions.assertEquals(10, stackFrameList.size()); } @Test void testGetStackFrameList() { List<String> stackFrameList = ExceptionUtils.getStackFrameList(exception); Assertions.assertNotEquals(10, stackFrameList.size()); } @Test void testSelfDefineException() throws Exception { IGreeter2 serviceImpl = new IGreeter2Impl(); int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()) .addParameter(CommonConstants.TIMEOUT_KEY, 10000); ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter2.class); ProviderModel providerModel = new ProviderModel( providerUrl.getServiceKey(), serviceImpl, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter2.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel()); ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker<IGreeter2> invoker = proxy.getInvoker(serviceImpl, IGreeter2.class, providerUrl); Exporter<IGreeter2> export = protocol.export(invoker); URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()) .addParameter(CommonConstants.TIMEOUT_KEY, 10000); ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter2 greeterProxy = proxy.getProxy(protocol.refer(IGreeter2.class, consumerUrl)); Thread.sleep(1000); // 1. test unaryStream String REQUEST_MSG = "hello world"; String EXPECT_RESPONSE_MSG = "I am self define exception"; try { greeterProxy.echo(REQUEST_MSG); } catch (IGreeterException e) { Assertions.assertEquals(EXPECT_RESPONSE_MSG, e.getMessage()); } Exception e = greeterProxy.echoException(REQUEST_MSG); Assertions.assertEquals(EXPECT_RESPONSE_MSG, e.getMessage()); export.unexport(); protocol.destroy(); // resource recycle. serviceRepository.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DataWrapper.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DataWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; public class DataWrapper<T> { public T data; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; 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.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterImpl; import org.apache.dubbo.rpc.protocol.tri.support.MockStreamObserver; import org.apache.dubbo.rpc.service.EchoService; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.protocol.tri.support.IGreeter.SERVER_MSG; import static org.junit.jupiter.api.Assertions.assertEquals; class TripleProtocolTest { @Test void testDemoProtocol() throws Exception { IGreeterImpl serviceImpl = new IGreeterImpl(); int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter.class); ProviderModel providerModel = new ProviderModel( providerUrl.getServiceKey(), serviceImpl, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("tri"); ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker<IGreeter> invoker = proxy.getInvoker(serviceImpl, IGreeter.class, providerUrl); Exporter<IGreeter> export = protocol.export(invoker); URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter greeterProxy = proxy.getProxy(protocol.refer(IGreeter.class, consumerUrl)); Thread.sleep(1000); // 1. test unaryStream String REQUEST_MSG = "hello world"; Assertions.assertEquals(REQUEST_MSG, greeterProxy.echo(REQUEST_MSG)); Assertions.assertEquals(REQUEST_MSG, serviceImpl.echoAsync(REQUEST_MSG).get()); // 2. test serverStream MockStreamObserver outboundMessageSubscriber1 = new MockStreamObserver(); greeterProxy.serverStream(REQUEST_MSG, outboundMessageSubscriber1); outboundMessageSubscriber1.getLatch().await(3000, TimeUnit.MILLISECONDS); Assertions.assertEquals(outboundMessageSubscriber1.getOnNextData(), REQUEST_MSG); Assertions.assertTrue(outboundMessageSubscriber1.isOnCompleted()); // 3. test bidirectionalStream MockStreamObserver outboundMessageSubscriber2 = new MockStreamObserver(); StreamObserver<String> inboundMessageObserver = greeterProxy.bidirectionalStream(outboundMessageSubscriber2); inboundMessageObserver.onNext(REQUEST_MSG); inboundMessageObserver.onCompleted(); outboundMessageSubscriber2.getLatch().await(3000, TimeUnit.MILLISECONDS); // verify client Assertions.assertEquals(outboundMessageSubscriber2.getOnNextData(), SERVER_MSG); Assertions.assertTrue(outboundMessageSubscriber2.isOnCompleted()); // verify server MockStreamObserver serverOutboundMessageSubscriber = (MockStreamObserver) serviceImpl.getMockStreamObserver(); serverOutboundMessageSubscriber.getLatch().await(1000, TimeUnit.MILLISECONDS); Assertions.assertEquals(REQUEST_MSG, serverOutboundMessageSubscriber.getOnNextData()); Assertions.assertTrue(serverOutboundMessageSubscriber.isOnCompleted()); EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, consumerUrl)); assertEquals(echo.$echo("test"), "test"); assertEquals(echo.$echo("abcdefg"), "abcdefg"); assertEquals(echo.$echo(1234), 1234); export.unexport(); protocol.destroy(); // resource recycle. serviceRepository.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.Http2CodecUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * {@link Http2ProtocolDetector} */ class Http2ProtocolDetectorTest { @Test void testDetect() { ProtocolDetector detector = new Http2ProtocolDetector(); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); ByteBuf connectionPrefaceBuf = Http2CodecUtil.connectionPrefaceBuf(); ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); ChannelBuffer in = new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer()); ProtocolDetector.Result result = detector.detect(in); Assertions.assertEquals( result.flag(), ProtocolDetector.Result.unrecognized().flag()); byteBuf.writeBytes(connectionPrefaceBuf); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); Assertions.assertEquals( result.flag(), ProtocolDetector.Result.recognized().flag()); byteBuf.clear(); byteBuf.writeBytes(connectionPrefaceBuf, 0, 1); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); Assertions.assertEquals( result.flag(), ProtocolDetector.Result.needMoreData().flag()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.concurrent.CompletableFuture; import io.reactivex.Single; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class ReflectionPackableMethodTest { @Test void testUnaryFuture() throws Exception { Method method = DescriptorService.class.getMethod("unaryFuture"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals(CompletableFuture.class, descriptor.getReturnClass()); assertEquals(String.class, descriptor.getReturnTypes()[0]); } @Test void testMethodWithNoParameters() throws Exception { Method method = DescriptorService.class.getMethod("noParameterMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Assertions.assertEquals(0, descriptor.getParameterClasses().length); } @Test void testMethodWithNoParametersAndReturnProtobuf() throws Exception { Method method = DescriptorService.class.getMethod("noParameterAndReturnProtobufMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Assertions.assertEquals(0, descriptor.getParameterClasses().length); assertFalse(needWrap(descriptor)); } @Test void testMethodWithNoParametersAndReturnJava() throws Exception { Method method = DescriptorService.class.getMethod("noParameterAndReturnJavaClassMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Assertions.assertEquals(0, descriptor.getParameterClasses().length); assertTrue(needWrap(descriptor)); } @Test void testWrapperBiStream() throws Exception { Method method = DescriptorService.class.getMethod("wrapBidirectionalStream", StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(1, descriptor.getParameterClasses().length); assertEquals(MethodDescriptor.RpcType.BI_STREAM, descriptor.getRpcType()); assertTrue(needWrap(descriptor)); } @Test void testBiStream() throws Exception { Method method = DescriptorService.class.getMethod("bidirectionalStream", StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(1, descriptor.getParameterClasses().length); assertSame(descriptor.getRpcType(), MethodDescriptor.RpcType.BI_STREAM); assertFalse(needWrap(descriptor)); } @Test void testIsStream() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("noParameterMethod"); ReflectionMethodDescriptor md1 = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, md1.getRpcType()); method = DescriptorService.class.getMethod("sayHello", HelloReply.class); ReflectionMethodDescriptor md2 = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, md2.getRpcType()); } @Test void testIsUnary() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("noParameterMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, descriptor.getRpcType()); method = DescriptorService.class.getMethod("sayHello", HelloReply.class); ReflectionMethodDescriptor md2 = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, md2.getRpcType()); } @Test void testIsServerStream() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("sayHelloServerStream", HelloReply.class, StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); Method method2 = DescriptorService.class.getMethod("sayHelloServerStream2", Object.class, StreamObserver.class); ReflectionMethodDescriptor descriptor2 = new ReflectionMethodDescriptor(method2); Assertions.assertTrue(needWrap(descriptor2)); } @Test void testObtainActualType() throws NoSuchMethodException { Method method1 = DescriptorService.class.getMethod("serverStream1", Object.class, StreamObserver.class); Class<?> clazz1 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method1.getGenericParameterTypes()[1]).getActualTypeArguments()[0]); Assertions.assertEquals(clazz1.getName(), String.class.getName()); Method method2 = DescriptorService.class.getMethod("serverStream2", Object.class, StreamObserver.class); Class<?> clazz2 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method2.getGenericParameterTypes()[1]).getActualTypeArguments()[0]); Assertions.assertEquals(clazz2.getName(), DataWrapper.class.getName()); Method method3 = DescriptorService.class.getMethod("biStream1", StreamObserver.class); Class<?> clazz31 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method3.getGenericReturnType()).getActualTypeArguments()[0]); Assertions.assertEquals(clazz31.getName(), String.class.getName()); Class<?> clazz32 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method3.getGenericParameterTypes()[0]).getActualTypeArguments()[0]); Assertions.assertEquals(clazz32.getName(), String.class.getName()); Method method4 = DescriptorService.class.getMethod("biStream2", StreamObserver.class); Class<?> clazz41 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method4.getGenericReturnType()).getActualTypeArguments()[0]); Assertions.assertEquals(clazz41.getName(), DataWrapper.class.getName()); Class<?> clazz42 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method4.getGenericParameterTypes()[0]).getActualTypeArguments()[0]); Assertions.assertEquals(clazz42.getName(), DataWrapper.class.getName()); } @Test void testIsNeedWrap() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("noParameterMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertTrue(needWrap(descriptor)); method = DescriptorService.class.getMethod("sayHello", HelloReply.class); descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); } @Test void testIgnoreMethod() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("iteratorServerStream", HelloReply.class); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); Method method2 = DescriptorService.class.getMethod("reactorMethod", HelloReply.class); MethodDescriptor descriptor2 = new ReflectionMethodDescriptor(method2); Assertions.assertFalse(needWrap(descriptor2)); Method method3 = DescriptorService.class.getMethod("reactorMethod2", Mono.class); MethodDescriptor descriptor3 = new ReflectionMethodDescriptor(method3); Assertions.assertFalse(needWrap(descriptor3)); Method method4 = DescriptorService.class.getMethod("rxJavaMethod", Single.class); MethodDescriptor descriptor4 = new ReflectionMethodDescriptor(method4); Assertions.assertFalse(needWrap(descriptor4)); } @Test void testMultiProtoParameter() throws Exception { Method method = DescriptorService.class.getMethod("testMultiProtobufParameters", HelloReply.class, HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); } @Test void testDiffParametersAndReturn() throws Exception { Method method = DescriptorService.class.getMethod("testDiffParametersAndReturn", HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); Method method2 = DescriptorService.class.getMethod("testDiffParametersAndReturn2", String.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); } @Test void testErrorServerStream() throws Exception { Method method = DescriptorService.class.getMethod("testErrorServerStream", StreamObserver.class, HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); Method method2 = DescriptorService.class.getMethod( "testErrorServerStream2", HelloReply.class, HelloReply.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); Method method3 = DescriptorService.class.getMethod("testErrorServerStream3", String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method3); needWrap(descriptor); }); Method method4 = DescriptorService.class.getMethod( "testErrorServerStream4", String.class, String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method4); needWrap(descriptor); }); } @Test void testErrorBiStream() throws Exception { Method method = DescriptorService.class.getMethod("testErrorBiStream", HelloReply.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); Method method2 = DescriptorService.class.getMethod("testErrorBiStream2", String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); Method method3 = DescriptorService.class.getMethod("testErrorBiStream3", StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method3); needWrap(descriptor); }); Method method4 = DescriptorService.class.getMethod("testErrorBiStream4", StreamObserver.class, String.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method4); needWrap(descriptor); }); } public boolean needWrap(MethodDescriptor method) { Class<?>[] actualRequestTypes; Class<?> actualResponseType; switch (method.getRpcType()) { case CLIENT_STREAM: case BI_STREAM: actualRequestTypes = new Class<?>[] { (Class<?>) ((ParameterizedType) method.getMethod().getGenericReturnType()).getActualTypeArguments()[0] }; actualResponseType = (Class<?>) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[0]) .getActualTypeArguments()[0]; break; case SERVER_STREAM: actualRequestTypes = method.getMethod().getParameterTypes(); actualResponseType = (Class<?>) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[1]) .getActualTypeArguments()[0]; break; case UNARY: actualRequestTypes = method.getParameterClasses(); actualResponseType = method.getReturnClass(); break; default: throw new IllegalStateException("Can not reach here"); } return ReflectionPackableMethod.needWrap(method, actualRequestTypes, actualResponseType); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWrapperTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWrapperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.triple.TripleWrapper; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import com.google.protobuf.ByteString; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TripleCustomerProtocolWrapperTest { @Test void testVarInt() { int seed = 3; while (seed < Integer.MAX_VALUE && seed > 0) { byte[] varIntBytes = TripleCustomerProtocolWrapper.varIntEncode(seed); ByteBuffer buffer = ByteBuffer.wrap(varIntBytes); int numDecodeFromVarIntByte = TripleCustomerProtocolWrapper.readRawVarint32(buffer); Assertions.assertEquals(seed, numDecodeFromVarIntByte); seed = seed * 7; } } @Test void testRangeViaInt() { for (int index = 0; index < 100000; index++) { byte[] varIntBytes = TripleCustomerProtocolWrapper.varIntEncode(index); ByteBuffer buffer = ByteBuffer.wrap(varIntBytes); int numDecodeFromVarIntByte = TripleCustomerProtocolWrapper.readRawVarint32(buffer); Assertions.assertEquals(index, numDecodeFromVarIntByte); } } @Test void testTripleRequestWrapperWithOnlySerializeType() { String serialize = "hession"; TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder.newBuilder(); TripleCustomerProtocolWrapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize).build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder().setSerializeType(serialize); Assertions.assertArrayEquals( tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); } @Test void testTripleRequestWrapperBuild() { byte[] firstArg = "i am first arg".getBytes(StandardCharsets.UTF_8); byte[] secondArg = "i am second arg".getBytes(StandardCharsets.UTF_8); String serialize = "hession"; TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder.newBuilder(); TripleCustomerProtocolWrapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(firstArg) .addArgs(secondArg) .build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() .setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(ByteString.copyFrom(firstArg)) .addArgs(ByteString.copyFrom(secondArg)); Assertions.assertArrayEquals( tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); } @Test void testTripleRequestWrapperParseFrom() { byte[] firstArg = "i am first arg".getBytes(StandardCharsets.UTF_8); byte[] secondArg = "i am second arg".getBytes(StandardCharsets.UTF_8); String serialize = "hession4"; TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder.newBuilder(); TripleCustomerProtocolWrapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(firstArg) .addArgs(secondArg) .build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() .setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(ByteString.copyFrom(firstArg)) .addArgs(ByteString.copyFrom(secondArg)); TripleCustomerProtocolWrapper.TripleRequestWrapper parseFrom = TripleCustomerProtocolWrapper.TripleRequestWrapper.parseFrom( pbbuilder.build().toByteArray()); Assertions.assertEquals(parseFrom.getSerializeType(), tripleRequestWrapper.getSerializeType()); Assertions.assertArrayEquals( parseFrom.getArgs().toArray(), tripleRequestWrapper.getArgs().toArray()); Assertions.assertArrayEquals( parseFrom.getArgTypes().toArray(), tripleRequestWrapper.getArgTypes().toArray()); } @Test void testTripleResponseWrapperWithNullData() { String serializeType = "hession4"; String type = "String"; TripleCustomerProtocolWrapper.TripleResponseWrapper.Builder builder = TripleCustomerProtocolWrapper.TripleResponseWrapper.Builder.newBuilder(); TripleCustomerProtocolWrapper.TripleResponseWrapper tripleResponseWrapper = builder.setSerializeType(serializeType).setType(type).build(); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder().setType(type).setSerializeType(serializeType); Assertions.assertArrayEquals(pbBuilder.build().toByteArray(), tripleResponseWrapper.toByteArray()); } @Test void testTripleResponseWrapper() { String serializeType = "hession4"; String type = "String"; String data = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + " * contributor license agreements. See the NOTICE file distributed with\n" + " * this work for additional information regarding copyright ownership.\n" + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + " * (the \"License\"); you may not use this file except in compliance with\n" + " * the License. You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); TripleCustomerProtocolWrapper.TripleResponseWrapper.Builder builder = TripleCustomerProtocolWrapper.TripleResponseWrapper.Builder.newBuilder(); TripleCustomerProtocolWrapper.TripleResponseWrapper tripleResponseWrapper = builder.setSerializeType( serializeType) .setType(type) .setData(dataBytes) .build(); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() .setType(type) .setData(ByteString.copyFrom(dataBytes)) .setSerializeType(serializeType); Assertions.assertArrayEquals(pbBuilder.build().toByteArray(), tripleResponseWrapper.toByteArray()); } @Test void testTripleResponseParseFrom() { String serializeType = "hession4"; String type = "String"; String data = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + " * contributor license agreements. See the NOTICE file distributed with\n" + " * this work for additional information regarding copyright ownership.\n" + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + " * (the \"License\"); you may not use this file except in compliance with\n" + " * the License. You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() .setType(type) .setData(ByteString.copyFrom(dataBytes)) .setSerializeType(serializeType); byte[] pbRawBytes = pbBuilder.build().toByteArray(); TripleCustomerProtocolWrapper.TripleResponseWrapper tripleResponseWrapper = TripleCustomerProtocolWrapper.TripleResponseWrapper.parseFrom(pbRawBytes); Assertions.assertArrayEquals(pbRawBytes, tripleResponseWrapper.toByteArray()); Assertions.assertArrayEquals(dataBytes, tripleResponseWrapper.getData()); Assertions.assertEquals(serializeType, tripleResponseWrapper.getSerializeType()); Assertions.assertEquals(type, tripleResponseWrapper.getType()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.PathResolver; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class TriplePathResolverTest { private static final PathResolver PATH_RESOLVER = FrameworkModel.defaultModel().getDefaultExtension(PathResolver.class); private static final String SERVICE_NAME = "DemoService"; private static final Invoker<Object> INVOKER = new Invoker<Object>() { @Override public URL getUrl() { ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); Mockito.when(serviceDescriptor.getInterfaceName()).thenReturn(SERVICE_NAME); ServiceModel serviceModel = Mockito.mock(ServiceModel.class); Mockito.when(serviceModel.getServiceModel()).thenReturn(serviceDescriptor); return URL.valueOf("tri://localhost/demo/" + SERVICE_NAME) .setServiceInterface(SERVICE_NAME) .addParameter(CommonConstants.GROUP_KEY, "g1") .addParameter(CommonConstants.VERSION_KEY, "1.0.1") .setServiceModel(serviceModel); } @Override public boolean isAvailable() { return false; } @Override public void destroy() {} @Override public Class<Object> getInterface() { return null; } @Override public Result invoke(Invocation invocation) throws RpcException { return null; } }; @BeforeEach public void init() { PATH_RESOLVER.add("/abc", INVOKER); PATH_RESOLVER.register(INVOKER); } @AfterEach public void destroy() { PATH_RESOLVER.destroy(); } @Test void testResolve() { Assertions.assertEquals(INVOKER, getInvokerByPath("/abc")); } @Test void testResolveWithContextPath() { String path = "demo/" + SERVICE_NAME; Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(SERVICE_NAME, null, null)); Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(path, null, null)); Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(SERVICE_NAME, "g1", "1.0.1")); Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(path, "g1", "1.0.1")); Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(SERVICE_NAME, "g2", "1.0.2")); Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(path, "g2", "1.0.2")); TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT = false; Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(SERVICE_NAME, "g1", "1.0.1")); Assertions.assertEquals(INVOKER, PATH_RESOLVER.resolve(path, "g1", "1.0.1")); Assertions.assertNull(PATH_RESOLVER.resolve(SERVICE_NAME, "g2", "1.0.2")); Assertions.assertNull(PATH_RESOLVER.resolve(path, "g2", "1.0.2")); } @Test void testRemove() { Assertions.assertEquals(INVOKER, getInvokerByPath("/abc")); PATH_RESOLVER.remove("/abc"); Assertions.assertNull(getInvokerByPath("/abc")); } @Test void testNative() { String path = "path"; Assertions.assertFalse(PATH_RESOLVER.hasNativeStub(path)); PATH_RESOLVER.addNativeStub(path); Assertions.assertTrue(PATH_RESOLVER.hasNativeStub(path)); } @Test void testDestroy() { Assertions.assertEquals(INVOKER, getInvokerByPath("/abc")); { PATH_RESOLVER.add("/bcd", INVOKER); Assertions.assertEquals(INVOKER, getInvokerByPath("/bcd")); } PATH_RESOLVER.destroy(); Assertions.assertNull(getInvokerByPath("/abc")); Assertions.assertNull(getInvokerByPath("/bcd")); } private Invoker<?> getInvokerByPath(String path) { return PATH_RESOLVER.resolve(path, null, null); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.triple.TripleWrapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import com.google.protobuf.BoolValue; import com.google.protobuf.BytesValue; import com.google.protobuf.DoubleValue; import com.google.protobuf.Empty; import com.google.protobuf.EnumValue; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.google.protobuf.ListValue; import com.google.protobuf.Message; import com.google.protobuf.Parser; import com.google.protobuf.StringValue; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link SingleProtobufUtils} */ class SingleProtobufUtilsTest { @Test void test() throws IOException { Assertions.assertFalse(SingleProtobufUtils.isSupported(SingleProtobufUtilsTest.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(Empty.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(BoolValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(Int32Value.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(Int64Value.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(FloatValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(DoubleValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(BytesValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(StringValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(EnumValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(ListValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(HealthCheckResponse.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(HealthCheckRequest.class)); Message message = SingleProtobufUtils.defaultInst(HealthCheckRequest.class); Assertions.assertNotNull(message); Parser<HealthCheckRequest> parser = SingleProtobufUtils.getParser(HealthCheckRequest.class); Assertions.assertNotNull(parser); TripleWrapper.TripleRequestWrapper requestWrapper = TripleWrapper.TripleRequestWrapper.newBuilder() .setSerializeType("hessian4") .build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SingleProtobufUtils.serialize(requestWrapper, bos); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); TripleWrapper.TripleRequestWrapper tripleRequestWrapper = SingleProtobufUtils.deserialize(bis, TripleWrapper.TripleRequestWrapper.class); Assertions.assertEquals(tripleRequestWrapper.getSerializeType(), "hessian4"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import java.io.IOException; import io.grpc.health.v1.HealthCheckRequest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PbUnpackTest { @Test void unpack() throws IOException { HealthCheckRequest req = HealthCheckRequest.newBuilder().setService("service").build(); PbUnpack<HealthCheckRequest> unpack = new PbUnpack<>(HealthCheckRequest.class); HealthCheckRequest obj = (HealthCheckRequest) unpack.unpack(req.toByteArray()); Assertions.assertEquals("service", obj.getService()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; public interface DescriptorService { CompletableFuture<String> unaryFuture(); void noParameterMethod(); /** * unray return protobuf class * * @return protobuf class */ HelloReply noParameterAndReturnProtobufMethod(); /** * unray return java class * * @return */ String noParameterAndReturnJavaClassMethod(); /** * bi stream need wrapper * * @param streamObserver * @return */ StreamObserver<String> wrapBidirectionalStream(StreamObserver<String> streamObserver); /** * no need wrapper bi stream * * @param streamObserver * @return */ StreamObserver<HelloReply> bidirectionalStream(StreamObserver<HelloReply> streamObserver); /** * only for test. * * @param reply * @return */ HelloReply sayHello(HelloReply reply); void sayHelloServerStream(HelloReply request, StreamObserver<HelloReply> reply); void sayHelloServerStream2(Object request, StreamObserver<Object> reply); /** * obtain actual type in streamObserver */ void serverStream1(Object request, StreamObserver<String> streamObserver); void serverStream2(Object request, StreamObserver<DataWrapper<String>> streamObserver); StreamObserver<String> biStream1(StreamObserver<String> streamObserver); StreamObserver<DataWrapper<String>> biStream2(StreamObserver<DataWrapper<String>> streamObserver); /***********************grpc******************************/ java.util.Iterator<HelloReply> iteratorServerStream(HelloReply request); reactor.core.publisher.Mono<HelloReply> reactorMethod(HelloReply reactorRequest); reactor.core.publisher.Mono<HelloReply> reactorMethod2(reactor.core.publisher.Mono<HelloReply> reactorRequest); io.reactivex.Single<HelloReply> rxJavaMethod(io.reactivex.Single<HelloReply> replySingle); /**********************test error*****************/ void testMultiProtobufParameters(HelloReply reply1, HelloReply reply2); String testDiffParametersAndReturn(HelloReply reply1); HelloReply testDiffParametersAndReturn2(String reply1); void testErrorServerStream(StreamObserver<HelloReply> reply, HelloReply request); void testErrorServerStream2(HelloReply request, HelloReply request2, StreamObserver<HelloReply> reply); void testErrorServerStream3(String aa, StreamObserver<HelloReply> reply); void testErrorServerStream4(String aa, String bb, StreamObserver<String> reply); StreamObserver<HelloReply> testErrorBiStream(HelloReply reply, StreamObserver<HelloReply> observer); StreamObserver<HelloReply> testErrorBiStream2(String reply, StreamObserver<HelloReply> observer); StreamObserver<String> testErrorBiStream3(StreamObserver<HelloReply> observer); StreamObserver<String> testErrorBiStream4(StreamObserver<HelloReply> observer, String str); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.call.ClientCall; import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall; import org.apache.dubbo.rpc.protocol.tri.compressor.Identity; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import java.util.HashSet; import java.util.concurrent.ExecutorService; import io.netty.channel.Channel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; class TripleInvokerTest { @Test void testNewCall() throws NoSuchMethodException { URL url = URL.valueOf("tri://127.0.0.1:9103/" + IGreeter.class.getName()); Channel channel = Mockito.mock(Channel.class); AbstractConnectionClient connectionClient = Mockito.mock(AbstractConnectionClient.class); ConnectionManager connectionManager = Mockito.mock(ConnectionManager.class); when(connectionManager.connect(any(URL.class), any(ChannelHandler.class))) .thenReturn(connectionClient); when(connectionClient.getChannel(true)).thenReturn(channel); when(connectionClient.isConnected()).thenReturn(true); ExecutorService executorService = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .createExecutorIfAbsent(url); TripleClientCall call = Mockito.mock(TripleClientCall.class); StreamObserver streamObserver = Mockito.mock(StreamObserver.class); when(call.start(any(RequestMetadata.class), any(ClientCall.Listener.class))) .thenReturn(streamObserver); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("test"); invocation.setArguments(new Object[] {streamObserver, streamObserver}); TripleInvoker<IGreeter> invoker = new TripleInvoker<>( IGreeter.class, url, Identity.MESSAGE_ENCODING, connectionClient, new HashSet<>(), executorService); MethodDescriptor echoMethod = new ReflectionMethodDescriptor(IGreeter.class.getDeclaredMethod("echo", String.class)); Assertions.assertTrue(invoker.isAvailable()); invoker.invokeUnary(echoMethod, invocation, call, new ThreadlessExecutor()); invoker.destroy(); Assertions.assertFalse(invoker.isAvailable()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.CancellationContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class CancelableStreamObserverTest { @Test void setCancellationContext() { CancelableStreamObserver<Object> observer = new CancelableStreamObserver<Object>() { @Override public void onNext(Object data) {} @Override public void onError(Throwable throwable) {} @Override public void onCompleted() {} }; CancellationContext cancellationContext = new CancellationContext(); observer.setCancellationContext(cancellationContext); observer.cancel(new IllegalStateException()); Assertions.assertTrue(cancellationContext.isCancelled()); } @Test void cancel() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.support; public interface IGreeter2 { String SERVER_MSG = "HELLO WORLD"; /** * Use request to respond */ String echo(String request) throws IGreeterException; Exception echoException(String request); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CountDownLatch; /** * Usually use it to simulate a outboundMessageSubscriber */ public class MockStreamObserver implements StreamObserver<String> { private String onNextData; private Throwable onErrorThrowable; private boolean onCompleted; private CountDownLatch latch = new CountDownLatch(1); @Override public void onNext(String data) { onNextData = data; } @Override public void onError(Throwable throwable) { onErrorThrowable = throwable; } @Override public void onCompleted() { onCompleted = true; latch.countDown(); } public String getOnNextData() { return onNextData; } public Throwable getOnErrorThrowable() { return onErrorThrowable; } public boolean isOnCompleted() { return onCompleted; } public CountDownLatch getLatch() { return latch; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; public class IGreeterImpl implements IGreeter { private StreamObserver<String> mockStreamObserver; @Override public String echo(String request) { return request; } @Override public void serverStream(String str, StreamObserver<String> observer) { observer.onNext(str); observer.onCompleted(); } @Override public StreamObserver<String> bidirectionalStream(StreamObserver<String> observer) { mockStreamObserver = new MockStreamObserver() { @Override public void onNext(String data) { super.onNext(data); observer.onNext(SERVER_MSG); } @Override public void onCompleted() { super.onCompleted(); observer.onCompleted(); } }; return mockStreamObserver; // This will serve as the server's outboundMessageSubscriber } public StreamObserver<String> getMockStreamObserver() { return mockStreamObserver; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.support; public class IGreeter2Impl implements IGreeter2 { @Override public String echo(String request) throws IGreeterException { throw new IGreeterException("I am self define exception"); } @Override public Exception echoException(String request) { return new IGreeterException("I am self define exception"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.support; public class IGreeterException extends Exception { private String message; public IGreeterException(String message) { super(message); this.message = message; } public IGreeterException(String message, Throwable cause) { super(message, cause); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; public interface IGreeter { String SERVER_MSG = "HELLO WORLD"; /** * Use request to respond */ String echo(String request); default CompletableFuture<String> echoAsync(String request) { return CompletableFuture.supplyAsync(() -> echo(request)); } void serverStream(String str, StreamObserver<String> observer); StreamObserver<String> bidirectionalStream(StreamObserver<String> observer); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.service; import org.apache.dubbo.rpc.StatusRpcException; import org.apache.dubbo.rpc.TriRpcStatus.Code; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse.ServingStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; class HealthStatusManagerTest { private final TriHealthImpl health = new TriHealthImpl(); private final HealthStatusManager manager = new HealthStatusManager(health); @Test void getHealthService() { Assertions.assertNotNull(manager.getHealthService()); } @Test void setStatus() { String service = "serv0"; manager.setStatus(service, ServingStatus.SERVING); ServingStatus stored = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); } @Test void clearStatus() { String service = "serv1"; manager.setStatus(service, ServingStatus.SERVING); ServingStatus stored = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); manager.clearStatus(service); try { manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()); fail(); } catch (StatusRpcException e) { Assertions.assertEquals(Code.NOT_FOUND, e.getStatus().code); } } @Test void enterTerminalState() { String service = "serv2"; manager.setStatus(service, ServingStatus.SERVING); ServingStatus stored = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); manager.enterTerminalState(); ServingStatus stored2 = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.NOT_SERVING, stored2); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.service; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.IdentityHashMap; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import io.grpc.health.v1.HealthCheckResponse.ServingStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link TriHealthImpl} */ class TriHealthImplTest { @Test void testCheck() { TriHealthImpl triHealth = new TriHealthImpl(); HealthCheckRequest request = HealthCheckRequest.newBuilder().build(); HealthCheckResponse response = triHealth.check(request); Assertions.assertEquals(response.getStatus(), HealthCheckResponse.ServingStatus.SERVING); HealthCheckRequest badRequest = HealthCheckRequest.newBuilder().setService("test").build(); Assertions.assertThrows(RpcException.class, () -> triHealth.check(badRequest)); } @Test void testWatch() throws Exception { TriHealthImpl triHealth = new TriHealthImpl(); HealthCheckRequest request = HealthCheckRequest.newBuilder().setService("testWatch").build(); triHealth.setStatus(request.getService(), ServingStatus.SERVING); StreamObserver<HealthCheckResponse> streamObserver = new MockStreamObserver(); RpcContext.removeCancellationContext(); // test watch triHealth.watch(request, streamObserver); Assertions.assertNotNull(RpcContext.getCancellationContext().getListeners()); HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> watches = getWatches(triHealth); Assertions.assertTrue(watches.containsKey(request.getService())); Assertions.assertTrue(watches.get(request.getService()).containsKey(streamObserver)); Assertions.assertTrue(watches.get(request.getService()).get(streamObserver)); MockStreamObserver mockStreamObserver = (MockStreamObserver) streamObserver; Assertions.assertEquals(mockStreamObserver.getCount(), 1); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVING); // test setStatus triHealth.setStatus(request.getService(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); Assertions.assertEquals(mockStreamObserver.getCount(), 2); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); triHealth.enterTerminalState(); Assertions.assertEquals(mockStreamObserver.getCount(), 3); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.NOT_SERVING); // test clearStatus turnOffTerminal(triHealth); triHealth.clearStatus(request.getService()); Assertions.assertEquals(mockStreamObserver.getCount(), 4); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); // test listener RpcContext.getCancellationContext().close(); Assertions.assertTrue(watches.isEmpty()); } private void turnOffTerminal(TriHealthImpl triHealth) throws NoSuchFieldException, IllegalAccessException { Field terminalField = triHealth.getClass().getDeclaredField("terminal"); terminalField.setAccessible(true); terminalField.set(triHealth, false); } private HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> getWatches( TriHealthImpl triHealth) throws Exception { Field watchersField = triHealth.getClass().getDeclaredField("watchers"); watchersField.setAccessible(true); HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> watches = (HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>>) watchersField.get(triHealth); return watches; } class MockStreamObserver implements StreamObserver<HealthCheckResponse> { private int count = 0; private HealthCheckResponse response; @Override public void onNext(HealthCheckResponse data) { count++; response = data; } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() {} public int getCount() { return count; } public HealthCheckResponse getResponse() { return response; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.service; import org.apache.dubbo.rpc.PathResolver; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.stub.StubSuppliers; import io.grpc.health.v1.DubboHealthTriple; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link TriBuiltinService} */ class TriBuiltinServiceTest { @Test void testDefaultNotEnable() { FrameworkModel frameworkModel = new FrameworkModel(); TriBuiltinService triBuiltinService = new TriBuiltinService(frameworkModel); Assertions.assertFalse(triBuiltinService.enable()); Assertions.assertNull(triBuiltinService.getHealthStatusManager()); } @Test void testForceEnable() { FrameworkModel frameworkModel = new FrameworkModel(); TriBuiltinService triBuiltinService = new TriBuiltinService(frameworkModel); triBuiltinService.init(); String serviceName = DubboHealthTriple.SERVICE_NAME; Assertions.assertNotNull(triBuiltinService.getHealthStatusManager()); PathResolver pathResolver = frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension(); Assertions.assertNotNull(pathResolver.resolve(serviceName, null, null)); ModuleServiceRepository repository = frameworkModel.getInternalApplicationModel().getInternalModule().getServiceRepository(); Assertions.assertFalse(repository.getAllServices().isEmpty()); Assertions.assertNotNull(StubSuppliers.getServiceDescriptor(serviceName)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.rpc.TriRpcStatus; import java.util.Map; public class MockClientStreamListener implements ClientStream.Listener { public TriRpcStatus status; public byte[] message; public boolean started; @Override public void onStart() { started = true; } @Override public void onComplete(TriRpcStatus status, Map<String, Object> attachments) { this.status = status; } @Override public void onClose() {} @Override public void onMessage(byte[] message, boolean isNeedReturnException) { this.message = message; } @Override public void onCancelByRemote(TriRpcStatus status) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import io.netty.handler.codec.http2.DefaultHttp2Headers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class StreamUtilsTest { @Test void encodeBase64ASCII() { String content = "😯"; Assertions.assertArrayEquals( content.getBytes(StandardCharsets.UTF_8), StreamUtils.decodeASCIIByte(StreamUtils.encodeBase64ASCII(content.getBytes(StandardCharsets.UTF_8)))); } @Test void testConvertAttachment() throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(10); DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.add("key", "value"); Map<String, Object> attachments = new HashMap<>(); attachments.put(HttpHeaderNames.PATH.getName(), "value"); attachments.put("key1111", "value"); attachments.put("Upper", "Upper"); attachments.put("obj", new Object()); StreamUtils.putHeaders(headers, attachments, false); Assertions.assertNull(headers.get(HttpHeaderNames.PATH.getName())); Assertions.assertNull(headers.get("Upper")); Assertions.assertNull(headers.get("obj")); headers = new DefaultHttp2Headers(); headers.add("key", "value"); StreamUtils.putHeaders(headers, attachments, true); Assertions.assertNull(headers.get(HttpHeaderNames.PATH.getName())); Assertions.assertNull(headers.get("Upper")); Assertions.assertNull(headers.get("obj")); String jsonRaw = headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getName()).toString(); String json = TriRpcStatus.decodeMessage(jsonRaw); Map<String, String> upperMap = JsonUtils.toJavaObject(json, Map.class); Assertions.assertArrayEquals( "Upper".getBytes(StandardCharsets.UTF_8), upperMap.get("upper").getBytes(StandardCharsets.UTF_8)); int count = 10000; CountDownLatch latch = new CountDownLatch(count); for (int i = 0; i < count; i++) { String randomKey = "key" + i; String randomValue = "value" + i; Map<String, Object> attachments2 = new HashMap<>(); attachments2.put(HttpHeaderNames.PATH.getName(), "value"); attachments2.put("key1111", "value"); attachments2.put("Upper", "Upper"); attachments2.put("obj", new Object()); attachments2.put(randomKey, randomValue); executorService.execute(() -> { DefaultHttp2Headers headers2 = new DefaultHttp2Headers(); headers2.add("key", "value"); StreamUtils.putHeaders(headers2, attachments2, true); if (headers2.get(HttpHeaderNames.PATH.getName()) != null) { return; } if (headers2.get("Upper") != null) { return; } if (headers2.get("obj") != null) { return; } if (!headers2.get(randomKey).toString().equals(randomValue)) { return; } latch.countDown(); }); } latch.await(10, TimeUnit.SECONDS); Assertions.assertEquals(0, latch.getCount()); executorService.shutdown(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.message.MediaType; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.RequestMetadata; import org.apache.dubbo.rpc.protocol.tri.TripleConstants; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import org.apache.dubbo.rpc.protocol.tri.command.CancelQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.CreateStreamQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.EndStreamQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor; import org.apache.dubbo.rpc.protocol.tri.h12.http2.Http2TripleClientStream; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; import java.util.concurrent.Executor; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpScheme; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class TripleClientStreamTest { @Test void progress() { final URL url = URL.valueOf("tri://127.0.0.1:8080/foo.bar.service"); final ModuleServiceRepository repo = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); repo.registerService(IGreeter.class); final ServiceDescriptor serviceDescriptor = repo.getService(IGreeter.class.getName()); final MethodDescriptor methodDescriptor = serviceDescriptor.getMethod("echo", new Class<?>[] {String.class}); MockClientStreamListener listener = new MockClientStreamListener(); TripleWriteQueue writeQueue = mock(TripleWriteQueue.class); final EmbeddedChannel channel = new EmbeddedChannel(); when(writeQueue.enqueueFuture(any(QueuedCommand.class), any(Executor.class))) .thenReturn(channel.newPromise()); Http2StreamChannel http2StreamChannel = mock(Http2StreamChannel.class); when(http2StreamChannel.isActive()).thenReturn(true); when(http2StreamChannel.newSucceededFuture()).thenReturn(channel.newSucceededFuture()); when(http2StreamChannel.eventLoop()).thenReturn(new NioEventLoopGroup().next()); when(http2StreamChannel.newPromise()).thenReturn(channel.newPromise()); when(http2StreamChannel.parent()).thenReturn(channel); AbstractTripleClientStream stream = new Http2TripleClientStream( url.getOrDefaultFrameworkModel(), ImmediateEventExecutor.INSTANCE, writeQueue, listener, http2StreamChannel); verify(writeQueue).enqueue(any(CreateStreamQueueCommand.class)); final RequestMetadata requestMetadata = new RequestMetadata(); requestMetadata.method = methodDescriptor; requestMetadata.scheme = TripleConstants.HTTP_SCHEME; requestMetadata.compressor = Compressor.NONE; requestMetadata.acceptEncoding = Compressor.NONE.getMessageEncoding(); requestMetadata.address = url.getAddress(); requestMetadata.service = url.getPath(); requestMetadata.group = url.getGroup(); requestMetadata.version = url.getVersion(); stream.sendHeader(requestMetadata.toHeaders()); verify(writeQueue).enqueueFuture(any(HeaderQueueCommand.class), any(Executor.class)); // no other commands verify(writeQueue).enqueue(any(QueuedCommand.class)); stream.sendMessage(new byte[0], 0); verify(writeQueue).enqueueFuture(any(DataQueueCommand.class), any(Executor.class)); verify(writeQueue, times(2)).enqueueFuture(any(QueuedCommand.class), any(Executor.class)); stream.halfClose(); verify(writeQueue).enqueueFuture(any(EndStreamQueueCommand.class), any(Executor.class)); verify(writeQueue, times(3)).enqueueFuture(any(QueuedCommand.class), any(Executor.class)); stream.cancelByLocal(TriRpcStatus.CANCELLED); verify(writeQueue, times(1)).enqueue(any(CancelQueueCommand.class)); verify(writeQueue, times(3)).enqueueFuture(any(QueuedCommand.class), any(Executor.class)); H2TransportListener transportListener = stream.createTransportListener(); DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.scheme(HttpScheme.HTTP.name()).status(HttpResponseStatus.OK.codeAsText()); headers.set(TripleHeaderEnum.STATUS_KEY.getKey(), TriRpcStatus.OK.code.code + ""); headers.set(HttpHeaderNames.CONTENT_TYPE.getKey(), MediaType.APPLICATION_GRPC_PROTO.getName()); transportListener.onHeader(headers, false); Assertions.assertTrue(listener.started); stream.request(2); byte[] data = new byte[] {0, 0, 0, 0, 1, 1}; final ByteBuf buf = Unpooled.wrappedBuffer(data); transportListener.onData(buf, false); Assertions.assertEquals(1, listener.message.length); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.call; class ClientCallTest {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestServerTransportListener.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestServerTransportListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; import org.apache.dubbo.remoting.http12.h2.Http2Header; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListener; import java.util.concurrent.Executor; public class TestServerTransportListener extends GenericHttp2ServerTransportListener { public TestServerTransportListener(H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) { super(h2StreamChannel, url, frameworkModel); } @Override protected Executor initializeExecutor(URL url, Http2Header metadata) { return Runnable::run; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRunnerImpl.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRunnerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.Constants; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder; import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder; import org.apache.dubbo.remoting.http12.message.MediaType; import org.apache.dubbo.remoting.http12.message.codec.JsonCodec; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext; import org.apache.dubbo.rpc.protocol.tri.TripleConstants; import org.apache.dubbo.rpc.protocol.tri.rest.RestHttpMessageCodec; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import org.apache.dubbo.rpc.protocol.tri.test.TestRunnerBuilder.TProvider; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; final class TestRunnerImpl implements TestRunner { static final Http2InputMessage END = new Http2InputMessageFrame(new ByteArrayInputStream(new byte[0]), true); private final FrameworkModel frameworkModel; private final ApplicationModel applicationModel; TestRunnerImpl(List<TProvider<?>> providers) { frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); Protocol protocol = applicationModel.getExtensionLoader(Protocol.class).getExtension(TestProtocol.NAME); ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); for (TProvider<?> provider : providers) { registerProvider(provider, protocol, proxy); } } private <T> void registerProvider(TProvider<T> provider, Protocol protocol, ProxyFactory proxy) { Class<T> type = provider.type; String typeName = type.getName(); Map<String, String> parameters = new LinkedHashMap<>(provider.parameters); parameters.put(CommonConstants.INTERFACE_KEY, typeName); String contextPath = parameters.get(Constants.CONTEXTPATH_KEY); String path = contextPath == null ? typeName : contextPath + '/' + typeName; URL providerUrl = new URL(TestProtocol.NAME, TestProtocol.HOST, TestProtocol.PORT, path, parameters); ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(type); ProviderModel providerModel = new ProviderModel( providerUrl.getServiceKey(), provider.service, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(type)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); protocol.export(proxy.getInvoker(provider.service, type, providerUrl)); } @Override @SuppressWarnings("unchecked") public TestResponse run(TestRequest request) { MockH2StreamChannel channel = new MockH2StreamChannel(); URL url = new URL(TestProtocol.NAME, TestProtocol.HOST, TestProtocol.PORT, request.getProviderParams()); TestServerTransportListener listener = new TestServerTransportListener(channel, url, frameworkModel); if (request.getMethod() == null) { request.setMethod(HttpMethods.GET.name()); } String path = request.getPath(); Assert.notNull(path, "path is required"); if (!request.getParams().isEmpty()) { StringBuilder sb = new StringBuilder(path); boolean hasQuery = path.indexOf('?') != -1; for (Map.Entry<String, Object> entry : request.getParams().entrySet()) { String key = RequestUtils.encodeURL(entry.getKey()); Object value = entry.getValue(); if (value instanceof List) { for (Object obj : (List<Object>) value) { if (obj != null) { if (hasQuery) { sb.append('&'); } else { hasQuery = true; sb.append('?'); } sb.append(key).append('=').append(RequestUtils.encodeURL(obj.toString())); } } } else if (value instanceof Object[]) { for (Object obj : (Object[]) value) { if (obj != null) { if (hasQuery) { sb.append('&'); } else { hasQuery = true; sb.append('?'); } sb.append(key).append('=').append(RequestUtils.encodeURL(obj.toString())); } } } else { if (hasQuery) { sb.append('&'); } else { hasQuery = true; sb.append('?'); } sb.append(key); if (value != null) { sb.append('=').append(RequestUtils.encodeURL(value.toString())); } } } request.setPath(sb.toString()); } if (!request.getCookies().isEmpty()) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : request.getCookies().entrySet()) { sb.append(entry.getKey()) .append('=') .append(RequestUtils.encodeURL(entry.getValue())) .append(';'); } request.setHeader("cookie", sb.toString()); } listener.onMetadata(request.toMetadata()); RpcInvocationBuildContext context = listener.getContext(); HttpMessageDecoder decoder = JsonCodec.INSTANCE; if (context != null) { String ct = request.getContentType(); boolean isForm = ct != null && ct.startsWith(MediaType.APPLICATION_FROM_URLENCODED.getName()); HttpMessageEncoder encoder; Object coder; if (isForm) { encoder = UrlEncodeFormEncoder.INSTANCE; coder = context.getHttpMessageDecoder(); } else { encoder = context.getHttpMessageEncoder(); coder = encoder; } if (coder instanceof RestHttpMessageCodec) { coder = ((RestHttpMessageCodec) coder).getMessageEncoder(); if (coder instanceof HttpMessageDecoder) { decoder = (HttpMessageDecoder) coder; } } HttpRequest hRequest = (HttpRequest) context.getAttributes().get(TripleConstants.HTTP_REQUEST_KEY); if (CollectionUtils.isEmpty(request.getBodies())) { if (HttpMethods.supportBody(hRequest.method())) { listener.onData(END); } } else { for (Object body : request.getBodies()) { byte[] bytes; if (body instanceof String) { bytes = ((String) body).getBytes(StandardCharsets.UTF_8); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(256); encoder.encode(bos, body); bytes = bos.toByteArray(); } listener.onData(new Http2InputMessageFrame(new ByteArrayInputStream(bytes), false)); } listener.onData(END); } } return new TestResponse(channel.getHttpMetadata().headers(), channel.getBodies(), decoder); } @Override public <T> T run(TestRequest request, Class<T> type) { return run(request).getBody(type); } @Override public <T> T get(TestRequest request, Class<T> type) { return run(request.setMethod(HttpMethods.GET.name()), type); } @Override public String get(TestRequest request) { return get(request, String.class); } @Override public <T> T get(String path, Class<T> type) { return get(new TestRequest(path), type); } @Override public <T> List<T> gets(String path, Class<T> type) { return run(new TestRequest(path).setMethod(HttpMethods.GET.name())).getBodies(type); } @Override public String get(String path) { return get(new TestRequest(path)); } @Override public List<String> gets(String path) { return gets(path, String.class); } @Override public <T> T post(TestRequest request, Class<T> type) { return run(request.setMethod(HttpMethods.POST.name()), type); } @Override public String post(TestRequest request) { return post(request, String.class); } @Override public <T> T post(String path, Object body, Class<T> type) { return post(new TestRequest(path).setBody(body), type); } @Override public <T> List<T> posts(String path, Object body, Class<T> type) { return run(new TestRequest(path).setMethod(HttpMethods.POST.name()).setBody(body)) .getBodies(type); } @Override public String post(String path, Object body) { return post(new TestRequest(path).setBody(body)); } @Override public List<String> posts(String path, Object body) { return posts(path, body, String.class); } @Override public <T> T put(TestRequest request, Class<T> type) { return run(request.setMethod(HttpMethods.PUT.name()), type); } @Override public String put(TestRequest request) { return put(request, String.class); } @Override public <T> T put(String path, Object body, Class<T> type) { return put(new TestRequest(path).setBody(body), type); } @Override public String put(String path, Object body) { return post(new TestRequest(path).setBody(body)); } @Override public <T> T patch(TestRequest request, Class<T> type) { return run(request.setMethod(HttpMethods.PATCH.name()), type); } @Override public String patch(TestRequest request) { return patch(request, String.class); } @Override public <T> T patch(String path, Object body, Class<T> type) { return patch(new TestRequest(path).setBody(body), type); } @Override public String patch(String path, Object body) { return patch(new TestRequest(path).setBody(body)); } @Override public <T> T delete(TestRequest request, Class<T> type) { return run(request.setMethod(HttpMethods.DELETE.name()), type); } @Override public String delete(TestRequest request) { return delete(request, String.class); } @Override public <T> T delete(String path, Class<T> type) { return patch(new TestRequest(path), type); } @Override public String delete(String path) { return delete(new TestRequest(path)); } @Override public void destroy() { applicationModel.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestProtocol.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.AbstractExporter; import org.apache.dubbo.rpc.protocol.AbstractProtocol; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.DefaultRequestMappingRegistry; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingRegistry; public class TestProtocol extends AbstractProtocol { public static final String NAME = "test"; public static final String HOST = "127.0.0.1"; public static final int PORT = 8081; private final RequestMappingRegistry mappingRegistry; public TestProtocol(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; mappingRegistry = frameworkModel.getBeanFactory().getOrRegisterBean(DefaultRequestMappingRegistry.class); } @Override public int getDefaultPort() { return PORT; } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { AbstractExporter<T> exporter = new AbstractExporter<T>(invoker) { @Override public void afterUnExport() { mappingRegistry.unregister(invoker); } }; invokers.add(invoker); mappingRegistry.register(invoker); return exporter; } @Override protected <T> Invoker<T> protocolBindingRefer(Class<T> type, URL url) throws RpcException { throw new UnsupportedOperationException(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestResponse.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.exception.HttpStatusException; import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder; import org.apache.dubbo.remoting.http12.message.MediaType; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName; import static java.nio.charset.StandardCharsets.UTF_8; @SuppressWarnings("unchecked") public class TestResponse { private final HttpHeaders headers; private final List<OutputStream> oss; private final HttpMessageDecoder decoder; private List<Object> bodies; public TestResponse(HttpHeaders headers, List<OutputStream> oss, HttpMessageDecoder decoder) { this.headers = headers; this.oss = oss; this.decoder = decoder; } public HttpHeaders getHeaders() { return headers; } public String getHeader(String name) { return headers.getFirst(name); } public int getStatus() { return Integer.parseInt(headers.getFirst(PseudoHeaderName.STATUS.value())); } public boolean isOk() { return getStatus() == 200; } public String getContentType() { return headers.getFirst(HttpHeaderNames.CONTENT_TYPE.getKey()); } public <T> T getBody(Class<T> type) { if (type != String.class) { int status = getStatus(); if (status >= 400) { List<String> bodies = getBodies(String.class); String message = bodies.isEmpty() ? null : bodies.get(0); throw new HttpStatusException(status, "body=" + message); } } List<T> bodies = getBodies(type); return bodies.isEmpty() ? null : bodies.get(0); } public <T> List<T> getBodies(Class<T> type) { List<T> bodies = (List<T>) this.bodies; if (bodies == null) { bodies = new ArrayList<>(oss.size()); boolean isTextEvent = MediaType.TEXT_EVENT_STREAM.getName().equals(getContentType()); for (int i = 0, size = oss.size(); i < size; i++) { ByteArrayOutputStream bos = (ByteArrayOutputStream) oss.get(i); if (isTextEvent) { String data = new String(bos.toByteArray(), UTF_8); if (data.startsWith("data:")) { String body = data.substring(5, data.length() - 2); bodies.add((T) decoder.decode(new ByteArrayInputStream(body.getBytes(UTF_8)), type)); } continue; } if (bos.size() == 0) { bodies.add(null); } else { bodies.add((T) decoder.decode(new ByteArrayInputStream(bos.toByteArray()), type)); } } this.bodies = (List<Object>) bodies; } return bodies; } public String getValue() { return getBody(String.class); } public List<String> getValues() { return getBodies(String.class); } public Integer getIntValue() { return getBody(Integer.class); } public List<Integer> getIntValues() { return getBodies(Integer.class); } public Long getLongValue() { return getBody(Long.class); } public List<Long> getLongValues() { return getBodies(Long.class); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/MockH2StreamChannel.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/MockH2StreamChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; public class MockH2StreamChannel implements H2StreamChannel { private HttpMetadata httpMetadata; private final List<OutputStream> bodies = new ArrayList<>(); @Override public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) { if (this.httpMetadata == null) { this.httpMetadata = httpMetadata; } else { this.httpMetadata.headers().add(httpMetadata.headers()); } return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) { bodies.add(httpOutputMessage.getBody()); return CompletableFuture.completedFuture(null); } @Override public SocketAddress remoteAddress() { return InetSocketAddress.createUnresolved(TestProtocol.HOST, TestProtocol.PORT + 1); } @Override public SocketAddress localAddress() { return InetSocketAddress.createUnresolved(TestProtocol.HOST, TestProtocol.PORT); } @Override public void flush() {} @Override public CompletableFuture<Void> writeResetFrame(long errorCode) { return CompletableFuture.completedFuture(null); } @Override public Http2OutputMessage newOutputMessage(boolean endStream) { return new MockHttp2OutputMessage(endStream); } public HttpMetadata getHttpMetadata() { return httpMetadata; } public List<OutputStream> getBodies() { return bodies; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/UrlEncodeFormEncoder.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/UrlEncodeFormEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.remoting.http12.exception.DecodeException; import org.apache.dubbo.remoting.http12.exception.EncodeException; import org.apache.dubbo.remoting.http12.exception.HttpStatusException; import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder; import org.apache.dubbo.remoting.http12.message.MediaType; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; public final class UrlEncodeFormEncoder implements HttpMessageEncoder { public static final UrlEncodeFormEncoder INSTANCE = new UrlEncodeFormEncoder(); @Override public void encode(OutputStream os, Object data, Charset charset) throws EncodeException { try { if (data instanceof String) { os.write(((String) data).getBytes()); return; } if (data instanceof Map) { StringBuilder sb = new StringBuilder(64); for (Map.Entry<?, ?> entry : ((Map<?, ?>) data).entrySet()) { sb.append(encode(entry.getKey())) .append('=') .append(encode(entry.getValue())) .append('&'); } int len = sb.length(); if (len > 1) { os.write(sb.substring(0, len - 1).getBytes(charset)); } return; } } catch (HttpStatusException e) { throw e; } catch (Throwable t) { throw new EncodeException("Error encoding form-urlencoded", t); } throw new DecodeException("Only supports String or Map as return type."); } private static String encode(Object value) throws UnsupportedEncodingException { return URLEncoder.encode(String.valueOf(value), StandardCharsets.UTF_8.name()); } @Override public MediaType mediaType() { return MediaType.APPLICATION_FROM_URLENCODED; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/MockHttp2OutputMessage.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/MockHttp2OutputMessage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage; import java.io.ByteArrayOutputStream; import java.io.OutputStream; public class MockHttp2OutputMessage implements Http2OutputMessage { private final OutputStream outputStream; private final boolean endStream; public MockHttp2OutputMessage(boolean endStream) { outputStream = new ByteArrayOutputStream(); this.endStream = endStream; } @Override public OutputStream getBody() { return outputStream; } @Override public boolean isEndStream() { return endStream; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRunnerBuilder.java
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRunnerBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static java.util.Objects.requireNonNull; public final class TestRunnerBuilder { private final List<TProvider<?>> providers = new ArrayList<>(); public static TestRunnerBuilder builder() { return new TestRunnerBuilder(); } public static TestRunnerBuilder of(Object service) { return builder().provider(service); } public static <T> TestRunnerBuilder of(Class<T> type, T service) { return builder().provider(type, service); } public <T> TestRunnerBuilder provider(Class<T> type, T service, Map<String, String> parameters) { providers.add(new TProvider<>(requireNonNull(type), requireNonNull(service), parameters)); return this; } public <T> TestRunnerBuilder provider(Class<T> type, T service) { return provider(type, service, Collections.emptyMap()); } @SuppressWarnings({"rawtypes", "unchecked"}) public TestRunnerBuilder provider(Object service, Map<String, String> parameters) { requireNonNull(service); Class<?>[] interfaces = service.getClass().getInterfaces(); providers.add(new TProvider(interfaces[0], service, parameters)); return this; } public TestRunnerBuilder provider(Object service) { return provider(service, Collections.emptyMap()); } public TestRunner build() { return new TestRunnerImpl(providers); } static final class TProvider<T> { final Class<T> type; final T service; final Map<String, String> parameters; TProvider(Class<T> type, T service, Map<String, String> parameters) { this.type = type; this.service = service; this.parameters = parameters; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false