repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java
dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.context; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.context.ApplicationExt; import org.apache.dubbo.common.extension.DisableInject; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConfigKeys; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static java.util.Optional.ofNullable; import static org.apache.dubbo.config.AbstractConfig.getTagName; /** * A lock-free config manager (through ConcurrentHashMap), for fast read operation. * The Write operation lock with sub configs map of config type, for safely check and add new config. */ public class ConfigManager extends AbstractConfigManager implements ApplicationExt { private static final Logger logger = LoggerFactory.getLogger(ConfigManager.class); public static final String NAME = "config"; public static final String BEAN_NAME = "dubboConfigManager"; public static final String DUBBO_CONFIG_MODE = ConfigKeys.DUBBO_CONFIG_MODE; public ConfigManager(ApplicationModel applicationModel) { super( applicationModel, Arrays.asList( ApplicationConfig.class, MonitorConfig.class, MetricsConfig.class, SslConfig.class, ProtocolConfig.class, RegistryConfig.class, ConfigCenterConfig.class, MetadataReportConfig.class, TracingConfig.class)); } public static ProtocolConfig getProtocolOrDefault(URL url) { return getProtocolOrDefault(url.getOrDefaultApplicationModel(), url.getProtocol()); } public static ProtocolConfig getProtocolOrDefault(String idOrName) { return getProtocolOrDefault(ApplicationModel.defaultModel(), idOrName); } private static ProtocolConfig getProtocolOrDefault(ApplicationModel applicationModel, String idOrName) { return applicationModel.getApplicationConfigManager().getOrAddProtocol(idOrName); } // ApplicationConfig correlative methods /** * Set application config */ @DisableInject public void setApplication(ApplicationConfig application) { addConfig(application); } public Optional<ApplicationConfig> getApplication() { return ofNullable(getSingleConfig(getTagName(ApplicationConfig.class))); } public ApplicationConfig getApplicationOrElseThrow() { return getApplication().orElseThrow(() -> new IllegalStateException("There's no ApplicationConfig specified.")); } // MonitorConfig correlative methods @DisableInject public void setMonitor(MonitorConfig monitor) { addConfig(monitor); } public Optional<MonitorConfig> getMonitor() { return ofNullable(getSingleConfig(getTagName(MonitorConfig.class))); } @DisableInject public void setMetrics(MetricsConfig metrics) { addConfig(metrics); } public Optional<MetricsConfig> getMetrics() { return ofNullable(getSingleConfig(getTagName(MetricsConfig.class))); } @DisableInject public void setTracing(TracingConfig tracing) { addConfig(tracing); } public Optional<TracingConfig> getTracing() { return ofNullable(getSingleConfig(getTagName(TracingConfig.class))); } @DisableInject public void setSsl(SslConfig sslConfig) { addConfig(sslConfig); } public Optional<SslConfig> getSsl() { return ofNullable(getSingleConfig(getTagName(SslConfig.class))); } // ConfigCenterConfig correlative methods public void addConfigCenter(ConfigCenterConfig configCenter) { addConfig(configCenter); } public void addConfigCenters(Iterable<ConfigCenterConfig> configCenters) { configCenters.forEach(this::addConfigCenter); } public Optional<Collection<ConfigCenterConfig>> getDefaultConfigCenter() { Collection<ConfigCenterConfig> defaults = getDefaultConfigs(getConfigsMap(getTagName(ConfigCenterConfig.class))); if (CollectionUtils.isEmpty(defaults)) { defaults = getConfigCenters(); } return ofNullable(defaults); } public Optional<ConfigCenterConfig> getConfigCenter(String id) { return getConfig(ConfigCenterConfig.class, id); } public Collection<ConfigCenterConfig> getConfigCenters() { return getConfigs(getTagName(ConfigCenterConfig.class)); } // MetadataReportConfig correlative methods public void addMetadataReport(MetadataReportConfig metadataReportConfig) { addConfig(metadataReportConfig); } public void addMetadataReports(Iterable<MetadataReportConfig> metadataReportConfigs) { metadataReportConfigs.forEach(this::addMetadataReport); } public Collection<MetadataReportConfig> getMetadataConfigs() { return getConfigs(getTagName(MetadataReportConfig.class)); } public Collection<MetadataReportConfig> getDefaultMetadataConfigs() { Collection<MetadataReportConfig> defaults = getDefaultConfigs(getConfigsMap(getTagName(MetadataReportConfig.class))); if (CollectionUtils.isEmpty(defaults)) { return getMetadataConfigs(); } return defaults; } // ProtocolConfig correlative methods public void addProtocol(ProtocolConfig protocolConfig) { addConfig(protocolConfig); } public void addProtocols(Iterable<ProtocolConfig> protocolConfigs) { if (protocolConfigs != null) { protocolConfigs.forEach(this::addProtocol); } } public Optional<ProtocolConfig> getProtocol(String idOrName) { return getConfig(ProtocolConfig.class, idOrName); } public ProtocolConfig getOrAddProtocol(String idOrName) { Optional<ProtocolConfig> protocol = getProtocol(idOrName); if (protocol.isPresent()) { return protocol.get(); } // Avoiding default protocol configuration overriding custom protocol configuration // due to `getOrAddProtocol` being called when they are not loaded idOrName = idOrName + ".default"; protocol = getProtocol(idOrName); if (protocol.isPresent()) { return protocol.get(); } ProtocolConfig protocolConfig = addConfig(new ProtocolConfig(idOrName)); // addProtocol triggers refresh when other protocols exist in the ConfigManager. // so refresh is only done when ProtocolConfig is not refreshed. if (!protocolConfig.isRefreshed()) { protocolConfig.refresh(); } return protocolConfig; } public List<ProtocolConfig> getDefaultProtocols() { return getDefaultConfigs(ProtocolConfig.class); } @Override @SuppressWarnings("RedundantMethodOverride") public <C extends AbstractConfig> List<C> getDefaultConfigs(Class<C> cls) { return getDefaultConfigs(getConfigsMap(getTagName(cls))); } public Collection<ProtocolConfig> getProtocols() { return getConfigs(getTagName(ProtocolConfig.class)); } // RegistryConfig correlative methods public void addRegistry(RegistryConfig registryConfig) { addConfig(registryConfig); } public void addRegistries(Iterable<RegistryConfig> registryConfigs) { if (registryConfigs != null) { registryConfigs.forEach(this::addRegistry); } } public Optional<RegistryConfig> getRegistry(String id) { return getConfig(RegistryConfig.class, id); } public List<RegistryConfig> getDefaultRegistries() { return getDefaultConfigs(getConfigsMap(getTagName(RegistryConfig.class))); } public Collection<RegistryConfig> getRegistries() { return getConfigs(getTagName(RegistryConfig.class)); } @Override public void refreshAll() { // refresh all configs here getApplication().ifPresent(ApplicationConfig::refresh); getMonitor().ifPresent(MonitorConfig::refresh); getMetrics().ifPresent(MetricsConfig::refresh); getTracing().ifPresent(TracingConfig::refresh); getSsl().ifPresent(SslConfig::refresh); getProtocols().forEach(ProtocolConfig::refresh); getRegistries().forEach(RegistryConfig::refresh); getConfigCenters().forEach(ConfigCenterConfig::refresh); getMetadataConfigs().forEach(MetadataReportConfig::refresh); } @Override public void loadConfigs() { // application config has load before starting config center // load dubbo.applications.xxx loadConfigsOfTypeFromProps(ApplicationConfig.class); // load dubbo.monitors.xxx loadConfigsOfTypeFromProps(MonitorConfig.class); // load dubbo.metrics.xxx loadConfigsOfTypeFromProps(MetricsConfig.class); // load dubbo.tracing.xxx loadConfigsOfTypeFromProps(TracingConfig.class); // load multiple config types: // load dubbo.protocols.xxx loadConfigsOfTypeFromProps(ProtocolConfig.class); // load dubbo.registries.xxx loadConfigsOfTypeFromProps(RegistryConfig.class); // load dubbo.metadata-report.xxx loadConfigsOfTypeFromProps(MetadataReportConfig.class); // config centers has been loaded before starting config center // loadConfigsOfTypeFromProps(ConfigCenterConfig.class); refreshAll(); checkConfigs(); // set model name if (StringUtils.isBlank(applicationModel.getModelName())) { applicationModel.setModelName(applicationModel.getApplicationName()); } } private void checkConfigs() { // check config types (ignore metadata-center) List<Class<? extends AbstractConfig>> multipleConfigTypes = Arrays.asList( ApplicationConfig.class, ProtocolConfig.class, RegistryConfig.class, MonitorConfig.class, MetricsConfig.class, TracingConfig.class, SslConfig.class); for (Class<? extends AbstractConfig> configType : multipleConfigTypes) { checkDefaultAndValidateConfigs(configType); } // check port conflicts Map<Integer, ProtocolConfig> protocolPortMap = new LinkedHashMap<>(); for (ProtocolConfig protocol : getProtocols()) { Integer port = protocol.getPort(); if (port == null || port == -1) { continue; } ProtocolConfig prevProtocol = protocolPortMap.get(port); if (prevProtocol != null) { throw new IllegalStateException("Duplicated port used by protocol configs, port: " + port + ", configs: " + Arrays.asList(prevProtocol, protocol)); } protocolPortMap.put(port, protocol); } // Log the current configurations. logger.info("The current configurations or effective configurations are as follows:"); for (Class<? extends AbstractConfig> configType : multipleConfigTypes) { getConfigs(configType).forEach((config) -> logger.info(config.toString())); } } public ConfigMode getConfigMode() { return configMode; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java
dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.context; import org.apache.dubbo.common.context.ModuleExt; import org.apache.dubbo.common.extension.DisableInject; 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.config.AbstractConfig; import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ReferenceConfigBase; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfigBase; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static java.util.Optional.ofNullable; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.config.AbstractConfig.getTagName; /** * Manage configs of module */ public class ModuleConfigManager extends AbstractConfigManager implements ModuleExt { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ModuleConfigManager.class); public static final String NAME = "moduleConfig"; private final Map<String, AbstractInterfaceConfig> serviceConfigCache = new ConcurrentHashMap<>(); private final ConfigManager applicationConfigManager; public ModuleConfigManager(ModuleModel moduleModel) { super( moduleModel, Arrays.asList( ModuleConfig.class, ServiceConfigBase.class, ReferenceConfigBase.class, ProviderConfig.class, ConsumerConfig.class)); applicationConfigManager = moduleModel.getApplicationModel().getApplicationConfigManager(); } // ModuleConfig correlative methods @DisableInject public void setModule(ModuleConfig module) { addConfig(module); } public Optional<ModuleConfig> getModule() { return ofNullable(getSingleConfig(getTagName(ModuleConfig.class))); } // ServiceConfig correlative methods public void addService(ServiceConfigBase<?> serviceConfig) { addConfig(serviceConfig); } public void addServices(Iterable<ServiceConfigBase<?>> serviceConfigs) { serviceConfigs.forEach(this::addService); } public Collection<ServiceConfigBase> getServices() { return getConfigs(getTagName(ServiceConfigBase.class)); } public <T> ServiceConfigBase<T> getService(String id) { return getConfig(ServiceConfigBase.class, id).orElse(null); } // ReferenceConfig correlative methods public void addReference(ReferenceConfigBase<?> referenceConfig) { addConfig(referenceConfig); } public void addReferences(Iterable<ReferenceConfigBase<?>> referenceConfigs) { referenceConfigs.forEach(this::addReference); } public Collection<ReferenceConfigBase<?>> getReferences() { return getConfigs(getTagName(ReferenceConfigBase.class)); } public <T> ReferenceConfigBase<T> getReference(String id) { return getConfig(ReferenceConfigBase.class, id).orElse(null); } public void addProvider(ProviderConfig providerConfig) { addConfig(providerConfig); } public void addProviders(Iterable<ProviderConfig> providerConfigs) { providerConfigs.forEach(this::addProvider); } public Optional<ProviderConfig> getProvider(String id) { return getConfig(ProviderConfig.class, id); } /** * Only allows one default ProviderConfig */ public Optional<ProviderConfig> getDefaultProvider() { List<ProviderConfig> providerConfigs = getDefaultConfigs(getConfigsMap(getTagName(ProviderConfig.class))); if (CollectionUtils.isNotEmpty(providerConfigs)) { return Optional.of(providerConfigs.get(0)); } return Optional.empty(); } public Collection<ProviderConfig> getProviders() { return getConfigs(getTagName(ProviderConfig.class)); } // ConsumerConfig correlative methods public void addConsumer(ConsumerConfig consumerConfig) { addConfig(consumerConfig); } public void addConsumers(Iterable<ConsumerConfig> consumerConfigs) { consumerConfigs.forEach(this::addConsumer); } public Optional<ConsumerConfig> getConsumer(String id) { return getConfig(ConsumerConfig.class, id); } /** * Only allows one default ConsumerConfig */ public Optional<ConsumerConfig> getDefaultConsumer() { List<ConsumerConfig> consumerConfigs = getDefaultConfigs(getConfigsMap(getTagName(ConsumerConfig.class))); if (CollectionUtils.isNotEmpty(consumerConfigs)) { return Optional.of(consumerConfigs.get(0)); } return Optional.empty(); } public Collection<ConsumerConfig> getConsumers() { return getConfigs(getTagName(ConsumerConfig.class)); } @Override public void refreshAll() { // refresh all configs here getModule().ifPresent(ModuleConfig::refresh); getProviders().forEach(ProviderConfig::refresh); getConsumers().forEach(ConsumerConfig::refresh); getReferences().forEach(ReferenceConfigBase::refresh); getServices().forEach(ServiceConfigBase::refresh); } @Override public void clear() { super.clear(); this.serviceConfigCache.clear(); } @Override protected <C extends AbstractConfig> Optional<C> findDuplicatedConfig(Map<String, C> configsMap, C config) { // check duplicated configs // special check service and reference config by unique service name, speed up the processing of large number of // instances if (config instanceof ReferenceConfigBase || config instanceof ServiceConfigBase) { C existedConfig = (C) findDuplicatedInterfaceConfig((AbstractInterfaceConfig) config); if (existedConfig != null) { return Optional.of(existedConfig); } } else { return super.findDuplicatedConfig(configsMap, config); } return Optional.empty(); } @Override protected <C extends AbstractConfig> boolean removeIfAbsent(C config, Map<String, C> configsMap) { if (super.removeIfAbsent(config, configsMap)) { if (config instanceof ReferenceConfigBase || config instanceof ServiceConfigBase) { removeInterfaceConfig((AbstractInterfaceConfig) config); } return true; } return false; } /** * check duplicated ReferenceConfig/ServiceConfig * * @param config */ private AbstractInterfaceConfig findDuplicatedInterfaceConfig(AbstractInterfaceConfig config) { String uniqueServiceName; Map<String, AbstractInterfaceConfig> configCache; if (config instanceof ReferenceConfigBase) { return null; } else if (config instanceof ServiceConfigBase) { ServiceConfigBase serviceConfig = (ServiceConfigBase) config; uniqueServiceName = serviceConfig.getUniqueServiceName(); configCache = serviceConfigCache; } else { throw new IllegalArgumentException( "Illegal type of parameter 'config' : " + config.getClass().getName()); } AbstractInterfaceConfig prevConfig = configCache.putIfAbsent(uniqueServiceName, config); if (prevConfig != null) { if (prevConfig == config) { return prevConfig; } if (prevConfig.equals(config)) { // Is there any problem with ignoring duplicate and equivalent but different ReferenceConfig instances? if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Ignore duplicated and equal config: " + config); } return prevConfig; } String configType = config.getClass().getSimpleName(); String msg = "Found multiple " + configType + "s with unique service name [" + uniqueServiceName + "], previous: " + prevConfig + ", later: " + config + ". " + "There can only be one instance of " + configType + " with the same triple (group, interface, version). " + "If multiple instances are required for the same interface, please use a different group or version."; if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg); } if (!this.ignoreDuplicatedInterface) { throw new IllegalStateException(msg); } } return prevConfig; } private void removeInterfaceConfig(AbstractInterfaceConfig config) { String uniqueServiceName; Map<String, AbstractInterfaceConfig> configCache; if (config instanceof ReferenceConfigBase) { return; } else if (config instanceof ServiceConfigBase) { ServiceConfigBase serviceConfig = (ServiceConfigBase) config; uniqueServiceName = serviceConfig.getUniqueServiceName(); configCache = serviceConfigCache; } else { throw new IllegalArgumentException( "Illegal type of parameter 'config' : " + config.getClass().getName()); } configCache.remove(uniqueServiceName, config); } @Override public void loadConfigs() { // load dubbo.providers.xxx loadConfigsOfTypeFromProps(ProviderConfig.class); // load dubbo.consumers.xxx loadConfigsOfTypeFromProps(ConsumerConfig.class); // load dubbo.modules.xxx loadConfigsOfTypeFromProps(ModuleConfig.class); // check configs checkDefaultAndValidateConfigs(ProviderConfig.class); checkDefaultAndValidateConfigs(ConsumerConfig.class); checkDefaultAndValidateConfigs(ModuleConfig.class); } // // Delegate read application configs // public ConfigManager getApplicationConfigManager() { return applicationConfigManager; } @Override public <C extends AbstractConfig> Map<String, C> getConfigsMap(Class<C> cls) { if (isSupportConfigType(cls)) { return super.getConfigsMap(cls); } else { // redirect to application ConfigManager return applicationConfigManager.getConfigsMap(cls); } } @Override public <C extends AbstractConfig> Collection<C> getConfigs(Class<C> configType) { if (isSupportConfigType(configType)) { return super.getConfigs(configType); } else { return applicationConfigManager.getConfigs(configType); } } @Override public <T extends AbstractConfig> Optional<T> getConfig(Class<T> cls, String idOrName) { if (isSupportConfigType(cls)) { return super.getConfig(cls, idOrName); } else { return applicationConfigManager.getConfig(cls, idOrName); } } @Override public <C extends AbstractConfig> List<C> getDefaultConfigs(Class<C> cls) { if (isSupportConfigType(cls)) { return super.getDefaultConfigs(cls); } else { return applicationConfigManager.getDefaultConfigs(cls); } } public Optional<ApplicationConfig> getApplication() { return applicationConfigManager.getApplication(); } public Optional<MonitorConfig> getMonitor() { return applicationConfigManager.getMonitor(); } public Optional<MetricsConfig> getMetrics() { return applicationConfigManager.getMetrics(); } public Optional<TracingConfig> getTracing() { return applicationConfigManager.getTracing(); } public Optional<SslConfig> getSsl() { return applicationConfigManager.getSsl(); } public Optional<Collection<ConfigCenterConfig>> getDefaultConfigCenter() { return applicationConfigManager.getDefaultConfigCenter(); } public Optional<ConfigCenterConfig> getConfigCenter(String id) { return applicationConfigManager.getConfigCenter(id); } public Collection<ConfigCenterConfig> getConfigCenters() { return applicationConfigManager.getConfigCenters(); } public Collection<MetadataReportConfig> getMetadataConfigs() { return applicationConfigManager.getMetadataConfigs(); } public Collection<MetadataReportConfig> getDefaultMetadataConfigs() { return applicationConfigManager.getDefaultMetadataConfigs(); } public Optional<ProtocolConfig> getProtocol(String idOrName) { return applicationConfigManager.getProtocol(idOrName); } public List<ProtocolConfig> getDefaultProtocols() { return applicationConfigManager.getDefaultProtocols(); } public Collection<ProtocolConfig> getProtocols() { return applicationConfigManager.getProtocols(); } public Optional<RegistryConfig> getRegistry(String id) { return applicationConfigManager.getRegistry(id); } public List<RegistryConfig> getDefaultRegistries() { return applicationConfigManager.getDefaultRegistries(); } public Collection<RegistryConfig> getRegistries() { return applicationConfigManager.getRegistries(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java
dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.context; import org.apache.dubbo.config.AbstractConfig; public interface ConfigValidator { void validate(AbstractConfig config); }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.Constants.INPUT_KEY; import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; class DubboCountCodecTest { @Test void test() throws Exception { DubboCountCodec dubboCountCodec = new DubboCountCodec(FrameworkModel.defaultModel()); ChannelBuffer buffer = ChannelBuffers.buffer(2048); Channel channel = new MockChannel(); Assertions.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT, dubboCountCodec.decode(channel, buffer)); List<DefaultFuture> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { Request request = new Request(i); futures.add(DefaultFuture.newFuture(channel, request, 1000, null)); RpcInvocation rpcInvocation = new RpcInvocation( null, "echo", DemoService.class.getName(), "", new Class<?>[] {String.class}, new String[] {"yug"}); request.setData(rpcInvocation); dubboCountCodec.encode(channel, buffer, request); } for (int i = 0; i < 10; i++) { Response response = new Response(i); AppResponse appResponse = new AppResponse(i); response.setResult(appResponse); dubboCountCodec.encode(channel, buffer, response); } MultiMessage multiMessage = (MultiMessage) dubboCountCodec.decode(channel, buffer); Assertions.assertEquals(20, multiMessage.size()); int requestCount = 0; int responseCount = 0; Iterator iterator = multiMessage.iterator(); while (iterator.hasNext()) { Object result = iterator.next(); if (result instanceof Request) { requestCount++; Object bytes = ((RpcInvocation) ((Request) result).getData()).getObjectAttachment(INPUT_KEY); Assertions.assertNotNull(bytes); } else if (result instanceof Response) { responseCount++; Object bytes = ((AppResponse) ((Response) result).getResult()).getObjectAttachment(OUTPUT_KEY); Assertions.assertNotNull(bytes); } } Assertions.assertEquals(requestCount, 10); Assertions.assertEquals(responseCount, 10); futures.forEach(DefaultFuture::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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; /** * dubbo protocol lazy connect test */ class DubboLazyConnectTest { @BeforeAll public static void setUpBeforeClass() {} @BeforeEach public void setUp() {} @AfterAll public static void tearDownAfterClass() { ProtocolUtils.closeAll(); } @Test void testSticky1() { Assertions.assertThrows(RpcException.class, () -> { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.refer(IDemoService.class, url); }); } @Test void testSticky2() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); ProtocolUtils.refer(IDemoService.class, url); } @Test void testSticky3() { Assertions.assertThrows(IllegalStateException.class, () -> { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); IDemoService service = ProtocolUtils.refer(IDemoService.class, url); service.get(); }); } @Test void testSticky4() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true&timeout=20000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); IDemoService service = ProtocolUtils.refer(IDemoService.class, url); Assertions.assertEquals("ok", service.get()); } public class DemoServiceImpl implements IDemoService { public String get() { return "ok"; } } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/IDemoService.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/IDemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public interface IDemoService { String 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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; 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.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import java.io.IOException; import java.io.InputStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; import static org.apache.dubbo.rpc.RpcException.BIZ_EXCEPTION; import static org.apache.dubbo.rpc.protocol.dubbo.DubboCodec.RESPONSE_VALUE_WITH_ATTACHMENTS; import static org.apache.dubbo.rpc.protocol.dubbo.DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS; /** * {@link DecodeableRpcResult} */ class DecodeableRpcResultTest { private ModuleServiceRepository repository; @BeforeEach public void setUp() { repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); } @AfterEach public void tearDown() { FrameworkModel.destroyAll(); } @Test void test() throws Exception { // Mock a rpcInvocation, this rpcInvocation is usually generated by the client request, and stored in // Request#data Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, null, null); RpcInvocation rpcInvocation = new RpcInvocation( providerModel, "echo", DemoService.class.getName(), "", new Class<?>[] {String.class}, new String[] { "yug" }); rpcInvocation.put(SERIALIZATION_ID_KEY, proto); // Mock a response result returned from the server and write to the buffer Channel channel = new MockChannel(); Response response = new Response(1); Result result = new AppResponse(); result.setValue("yug"); response.setResult(result); ChannelBuffer buffer = writeBuffer(url, response, proto, false); // The client reads and decode the buffer InputStream is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); DecodeableRpcResult decodeableRpcResult = new DecodeableRpcResult(channel, response, is, rpcInvocation, proto); decodeableRpcResult.decode(); // Verify RESPONSE_VALUE_WITH_ATTACHMENTS // Verify that the decodeableRpcResult decoded by the client is consistent with the response returned by the // server Assertions.assertEquals(decodeableRpcResult.getValue(), result.getValue()); Assertions.assertTrue( CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), result.getObjectAttachments())); // Verify RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS Response exResponse = new Response(2); Result exResult = new AppResponse(); exResult.setException(new RpcException(BIZ_EXCEPTION)); exResponse.setResult(exResult); buffer = writeBuffer(url, exResponse, proto, true); is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); decodeableRpcResult = new DecodeableRpcResult(channel, response, is, rpcInvocation, proto); decodeableRpcResult.decode(); Assertions.assertEquals( ((RpcException) decodeableRpcResult.getException()).getCode(), ((RpcException) exResult.getException()).getCode()); Assertions.assertTrue( CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), exResult.getObjectAttachments())); } private ChannelBuffer writeBuffer(URL url, Response response, Byte proto, boolean writeEx) throws IOException { Serialization serialization = CodecSupport.getSerializationById(proto); ChannelBuffer buffer = ChannelBuffers.buffer(1024 * 10); ChannelBufferOutputStream outputStream = new ChannelBufferOutputStream(buffer); ObjectOutput out = serialization.serialize(url, outputStream); Result result = (Result) response.getResult(); if (!writeEx) { out.writeByte(RESPONSE_VALUE_WITH_ATTACHMENTS); out.writeObject(result.getValue()); } else { out.writeByte(RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS); out.writeThrowable(result.getException()); } result.getObjectAttachments().put(DUBBO_VERSION_KEY, Version.getProtocolVersion()); result.getObjectAttachments().put("k1", "v1"); out.writeAttachments(result.getObjectAttachments()); out.flushBuffer(); outputStream.close(); return buffer; } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class MultiThreadTest { private static final Logger logger = LoggerFactory.getLogger(MultiThreadTest.class); private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterEach public void after() { ProtocolUtils.closeAll(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .destroy(); } @Test void testDubboMultiThreadInvoke() throws Exception { String testService = DemoService.class.getName(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(testService, DemoService.class); int port = NetUtils.getAvailablePort(); Exporter<?> rpcExporter = protocol.export(proxy.getInvoker( new DemoServiceImpl(), DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + testService))); final AtomicInteger counter = new AtomicInteger(); final DemoService service = proxy.getProxy( protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + testService))); Assertions.assertEquals(service.getSize(new String[] {"123", "456", "789"}), 3); final StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1024 * 64 + 32; i++) sb.append('A'); Assertions.assertEquals(sb.toString(), service.echo(sb.toString())); ExecutorService exec = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { final int fi = i; exec.execute(new Runnable() { public void run() { for (int i = 0; i < 30; i++) { logger.info("{}:{}", fi, counter.getAndIncrement()); Assertions.assertEquals(service.echo(sb.toString()), sb.toString()); } } }); } exec.shutdown(); exec.awaitTermination(10, TimeUnit.SECONDS); rpcExporter.unexport(); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import java.lang.reflect.Field; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; /** * Check available status for dubboInvoker */ class DubboInvokerAvailableTest { private static DubboProtocol protocol; private static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @BeforeAll public static void setUpBeforeClass() {} @BeforeEach public void setUp() throws Exception { protocol = new DubboProtocol(FrameworkModel.defaultModel()); } @AfterAll public static void tearDownAfterClass() { ProtocolUtils.closeAll(); } @Test void test_Normal_available() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); invoker.destroy(); Assertions.assertFalse(invoker.isAvailable()); } @Test void test_Normal_ChannelReadOnly() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertFalse(invoker.isAvailable()); // reset status since connection is shared among invokers getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); } @Disabled @Test void test_normal_channel_close_wait_gracefully() { int testPort = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false"); Exporter<IDemoService> exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Exporter<IDemoService> exporter0 = ProtocolUtils.export(new DemoServiceImpl0(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); long start = System.currentTimeMillis(); try { System.setProperty(SHUTDOWN_WAIT_KEY, "2000"); protocol.destroy(); } finally { System.getProperties().remove(SHUTDOWN_WAIT_KEY); } long waitTime = System.currentTimeMillis() - start; Assertions.assertTrue(waitTime >= 2000); Assertions.assertFalse(invoker.isAvailable()); } @Test void test_NoInvokers() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); ExchangeClient[] clients = getClients(invoker); clients[0].close(); Assertions.assertFalse(invoker.isAvailable()); } @Test void test_Lazy_ChannelReadOnly() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Invoker<?> invoker = protocol.refer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); ExchangeClient exchangeClient = getClients((DubboInvoker<?>) invoker)[0]; Assertions.assertFalse(exchangeClient.isClosed()); exchangeClient.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); // invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); Assertions.assertFalse(invoker.isAvailable()); exchangeClient.removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); Assertions.assertTrue(invoker.isAvailable()); exchangeClient.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertFalse(invoker.isAvailable()); } /** * The test prefer serialization * * @throws Exception Exception */ @Test public void testPreferSerialization() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000&serialization=fastjson&prefer_serialization=fastjson2,hessian2"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Invoker<?> invoker = protocol.refer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); ExchangeClient exchangeClient = getClients((DubboInvoker<?>) invoker)[0]; Assertions.assertFalse(exchangeClient.isClosed()); // invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); } private ExchangeClient[] getClients(DubboInvoker<?> invoker) throws Exception { Field field = DubboInvoker.class.getDeclaredField("clientsProvider"); field.setAccessible(true); ClientsProvider clientsProvider = (ClientsProvider) field.get(invoker); List<? extends ExchangeClient> clients = clientsProvider.getClients(); Assertions.assertEquals(1, clients.size()); return clients.toArray(new ExchangeClient[0]); } public class DemoServiceImpl implements IDemoService { public String get() { return "ok"; } } public class DemoServiceImpl0 implements IDemoService { public String get() { return "ok"; } } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.DubboCodec.DUBBO_VERSION; /** * {@link DecodeableRpcInvocation} */ class DecodeableRpcInvocationTest { @Test void test() throws Exception { // Simulate the data called by the client(The called data is stored in invocation and written to the buffer) URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); RpcInvocation inv = new RpcInvocation( null, "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new String[] {"yug"}); inv.setObjectAttachment(PATH_KEY, url.getPath()); inv.setObjectAttachment(VERSION_KEY, url.getVersion()); inv.setObjectAttachment(DUBBO_VERSION_KEY, DUBBO_VERSION); inv.setObjectAttachment("k1", "v1"); inv.setObjectAttachment("k2", "v2"); inv.setTargetServiceUniqueName(url.getServiceKey()); // Write the data of inv to the buffer Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); ChannelBuffer buffer = writeBuffer(url, inv, proto); FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel .getDefaultModule() .getServiceRepository() .registerService(DemoService.class.getName(), DemoService.class); frameworkModel .getBeanFactory() .getBean(PermittedSerializationKeeper.class) .registerService(url); // Simulate the server to decode Channel channel = new MockChannel(); Request request = new Request(1); ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); DecodeableRpcInvocation decodeableRpcInvocation = new DecodeableRpcInvocation(frameworkModel, channel, request, is, proto); decodeableRpcInvocation.decode(); // Verify that the decodeableRpcInvocation data decoded by the server is consistent with the invocation data of // the client Assertions.assertEquals(request.getVersion(), DUBBO_VERSION); Assertions.assertEquals(decodeableRpcInvocation.getObjectAttachment(DUBBO_VERSION_KEY), DUBBO_VERSION); Assertions.assertEquals( decodeableRpcInvocation.getObjectAttachment(VERSION_KEY), inv.getObjectAttachment(VERSION_KEY)); Assertions.assertEquals( decodeableRpcInvocation.getObjectAttachment(PATH_KEY), inv.getObjectAttachment(PATH_KEY)); Assertions.assertEquals(decodeableRpcInvocation.getMethodName(), inv.getMethodName()); Assertions.assertEquals(decodeableRpcInvocation.getParameterTypesDesc(), inv.getParameterTypesDesc()); Assertions.assertArrayEquals(decodeableRpcInvocation.getParameterTypes(), inv.getParameterTypes()); Assertions.assertArrayEquals(decodeableRpcInvocation.getArguments(), inv.getArguments()); Assertions.assertTrue( CollectionUtils.mapEquals(decodeableRpcInvocation.getObjectAttachments(), inv.getObjectAttachments())); Assertions.assertEquals(decodeableRpcInvocation.getTargetServiceUniqueName(), inv.getTargetServiceUniqueName()); frameworkModel.destroy(); } private ChannelBuffer writeBuffer(URL url, RpcInvocation inv, Byte proto) throws IOException { Serialization serialization = CodecSupport.getSerializationById(proto); ChannelBuffer buffer = ChannelBuffers.buffer(1024); ChannelBufferOutputStream outputStream = new ChannelBufferOutputStream(buffer); ObjectOutput out = serialization.serialize(url, outputStream); out.writeUTF(inv.getAttachment(DUBBO_VERSION_KEY)); // dubbo version out.writeUTF(inv.getAttachment(PATH_KEY)); // path out.writeUTF(inv.getAttachment(VERSION_KEY)); // version out.writeUTF(inv.getMethodName()); // methodName out.writeUTF(inv.getParameterTypesDesc()); // parameterTypesDesc Object[] args = inv.getArguments(); if (args != null) { for (int i = 0; i < args.length; i++) { out.writeObject(args[i]); // args } } out.writeAttachments(inv.getObjectAttachments()); // attachments out.flushBuffer(); outputStream.close(); return buffer; } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.support.FailfastCluster; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteService; import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.Type; import org.apache.dubbo.rpc.service.EchoService; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; /** * <code>ProxiesTest</code> */ class DubboProtocolTest { private static final Logger logger = LoggerFactory.getLogger(DubboProtocolTest.class); private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterAll public static void after() { ProtocolUtils.closeAll(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .destroy(); } @BeforeAll public static void setup() { ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(DemoService.class); } @Test void testDemoProtocol() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); assertEquals(service.getSize(new String[] {"", "", ""}), 3); } @Test void testDubboProtocol() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) .addParameter("timeout", 3000L))); assertEquals(service.enumlength(new Type[] {}), Type.Lower); assertEquals(service.getSize(null), -1); assertEquals(service.getSize(new String[] {"", "", ""}), 3); Map<String, String> map = new HashMap<String, String>(); map.put("aa", "bb"); Set<String> set = service.keys(map); assertEquals(set.size(), 1); assertEquals(set.iterator().next(), "aa"); service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty") .addParameter("timeout", 3000L))); // test netty client StringBuffer buf = new StringBuffer(); for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A'); // cast to EchoService EchoService echo = proxy.getProxy(protocol.refer( EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty") .addParameter("timeout", 3000L))); assertEquals(echo.$echo(buf.toString()), buf.toString()); assertEquals(echo.$echo("test"), "test"); assertEquals(echo.$echo("abcdefg"), "abcdefg"); assertEquals(echo.$echo(1234), 1234); } // @Test // public void testDubboProtocolWithMina() throws Exception { // DemoService service = new DemoServiceImpl(); // int port = NetUtils.getAvailablePort(); // protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" // + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + // DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", // 3000L))); // for (int i = 0; i < 10; i++) { // assertEquals(service.enumlength(new Type[]{}), Type.Lower); // assertEquals(service.getSize(null), -1); // assertEquals(service.getSize(new String[]{"", "", ""}), 3); // } // Map<String, String> map = new HashMap<String, String>(); // map.put("aa", "bb"); // for (int i = 0; i < 10; i++) { // Set<String> set = service.keys(map); // assertEquals(set.size(), 1); // assertEquals(set.iterator().next(), "aa"); // service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); // } // // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + // DemoService.class.getName() + "?client=mina").addParameter("timeout", // 3000L))); // // test netty client // StringBuffer buf = new StringBuffer(); // for (int i = 0; i < 1024 * 32 + 32; i++) // buf.append('A'); // System.out.println(service.stringLength(buf.toString())); // // // cast to EchoService // EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + // port + "/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", // 3000L))); // for (int i = 0; i < 10; i++) { // assertEquals(echo.$echo(buf.toString()), buf.toString()); // assertEquals(echo.$echo("test"), "test"); // assertEquals(echo.$echo("abcdefg"), "abcdefg"); // assertEquals(echo.$echo(1234), 1234); // } // } @Test void testDubboProtocolMultiService() throws Exception { // DemoService service = new DemoServiceImpl(); // protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + // DemoService.class.getName()))); // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + // DemoService.class.getName()).addParameter("timeout", // 3000L))); RemoteService remote = new RemoteServiceImpl(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(RemoteService.class); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + RemoteService.class.getName()) .addParameter("timeout", 3000L); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(remote, RemoteService.class, url)); remote = proxy.getProxy(protocol.refer(RemoteService.class, url)); // service.sayHello("world"); // test netty client // assertEquals("world", service.echo("world")); assertEquals("hello world@" + RemoteServiceImpl.class.getName(), remote.sayHello("world")); // can't find target service addresses EchoService remoteEcho = (EchoService) remote; assertEquals(remoteEcho.$echo("ok"), "ok"); } @Test void testPerm() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) service.getSize(new String[] {"", "", ""}); logger.info("take:{}", System.currentTimeMillis() - start); } @Test @Disabled public void testNonSerializedParameter() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); try { service.nonSerializedParameter(new NonSerialized()); Assertions.fail(); } catch (RpcException e) { Assertions.assertTrue( e.getMessage() .contains( "org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } @Test @Disabled public void testReturnNonSerialized() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); try { service.returnNonSerialized(); Assertions.fail(); } catch (RpcException e) { Assertions.assertTrue( e.getMessage() .contains( "org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } @Disabled @Test void testRemoteApplicationName() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L) .addParameter("application", "consumer"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(service, DemoService.class, url)); Invoker<DemoService> invoker = protocol.refer(DemoService.class, url); Invocation invocation = new RpcInvocation( "getRemoteApplicationName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]); List<Invoker<DemoService>> invokers = Arrays.asList(invoker); Directory<DemoService> dic = Mockito.mock(Directory.class); Mockito.when(dic.list(invocation)).thenReturn(invokers); Mockito.when(dic.getUrl()).thenReturn(url); Mockito.when(dic.getConsumerUrl()).thenReturn(url); FailfastCluster cluster = new FailfastCluster(); Invoker<DemoService> clusterInvoker = cluster.join(dic, true); Result result = clusterInvoker.invoke(invocation); Thread.sleep(10); assertEquals(result.getValue(), "consumer"); } @Test void testPayloadOverException() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) .addParameter("payload", 10 * 1024))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) .addParameter("timeout", 6000L) .addParameter("payload", 160))); try { service.download(300); Assertions.fail(); } catch (Exception expected) { Assertions.assertTrue(expected.getMessage().contains("Data length too large")); } } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; 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.protocol.dubbo.support.ProtocolUtils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; class ArgumentCallbackTest { private static final Logger logger = LoggerFactory.getLogger(ArgumentCallbackTest.class); protected Exporter<IDemoService> exporter = null; protected Exporter<IHelloService> hello_exporter = null; protected Invoker<IDemoService> reference = null; protected URL serviceURL = null; protected URL consumerUrl = null; // ============================A gorgeous line of segmentation================================================ IDemoService demoProxy = null; @AfterEach public void tearDown() { destroyService(); ProtocolUtils.closeAll(); } public void exportService() { // export one service first, to test connection sharing serviceURL = serviceURL.addParameter("connections", 1); URL hellourl = serviceURL.setPath(IHelloService.class.getName()); ModuleServiceRepository serviceRepository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); serviceRepository.registerService(IDemoService.class); serviceRepository.registerService(IHelloService.class); hello_exporter = ProtocolUtils.export(new HelloServiceImpl(), IHelloService.class, hellourl); exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, serviceURL); } void referService() { ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(IDemoService.class); demoProxy = (IDemoService) ProtocolUtils.refer(IDemoService.class, consumerUrl); } @BeforeEach public void setUp() {} public void initOrResetUrl(int callbacks, int timeout) { int port = NetUtils.getAvailablePort(); consumerUrl = serviceURL = URL.valueOf( "dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=test" + "&xxx.0.callback=true" + "&xxx2.0.callback=true" + "&unxxx2.0.callback=false" + "&timeout=" + timeout + "&retries=0" + "&" + CALLBACK_INSTANCES_LIMIT_KEY + "=" + callbacks) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()) .setServiceModel(new ConsumerModel( IDemoService.class.getName(), null, null, ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(IDemoService.class))); // uncomment is unblock invoking // serviceURL = serviceURL.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); // consumerUrl = consumerUrl.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); } public void initOrResetService() { destroyService(); exportService(); referService(); } public void destroyService() { ApplicationModel.defaultModel().getApplicationServiceRepository().destroy(); demoProxy = null; try { if (exporter != null) exporter.unexport(); if (hello_exporter != null) hello_exporter.unexport(); if (reference != null) reference.destroy(); } catch (Exception e) { } } @Test void TestCallbackNormalWithBindPort() throws Exception { initOrResetUrl(1, 10000000); consumerUrl = serviceURL.addParameter(Constants.BIND_PORT_KEY, "7653"); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { logger.info("Received callback: {}", msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); assertCallbackCount(10, 100, count); destroyService(); } @Test void TestCallbackNormal() throws Exception { initOrResetUrl(1, 10000000); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { logger.info("Received callback: {}", msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); // Thread.sleep(10000000); assertCallbackCount(10, 100, count); destroyService(); } @Test void TestCallbackMultiInstans() throws Exception { initOrResetUrl(2, 3000); initOrResetService(); IDemoCallback callback = new IDemoCallback() { public String yyy(String msg) { logger.info("callback1: {}", msg); return "callback1 onChanged ," + msg; } }; IDemoCallback callback2 = new IDemoCallback() { public String yyy(String msg) { logger.info("callback2: {}", msg); return "callback2 onChanged ," + msg; } }; { demoProxy.xxx2(callback); Assertions.assertEquals(1, demoProxy.getCallbackCount()); Thread.sleep(500); demoProxy.unxxx2(callback); Assertions.assertEquals(0, demoProxy.getCallbackCount()); demoProxy.xxx2(callback2); Assertions.assertEquals(1, demoProxy.getCallbackCount()); Thread.sleep(500); demoProxy.unxxx2(callback2); Assertions.assertEquals(0, demoProxy.getCallbackCount()); demoProxy.xxx2(callback); Thread.sleep(500); Assertions.assertEquals(1, demoProxy.getCallbackCount()); demoProxy.unxxx2(callback); Assertions.assertEquals(0, demoProxy.getCallbackCount()); } { demoProxy.xxx2(callback); Assertions.assertEquals(1, demoProxy.getCallbackCount()); demoProxy.xxx2(callback); Assertions.assertEquals(1, demoProxy.getCallbackCount()); demoProxy.xxx2(callback2); Assertions.assertEquals(2, demoProxy.getCallbackCount()); } destroyService(); } @Test void TestCallbackConsumerLimit() { Assertions.assertThrows(RpcException.class, () -> { initOrResetUrl(1, 1000); // URL cannot be transferred automatically from the server side to the client side by using API, instead, // it needs manually specified. initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { logger.info("Received callback: {}", msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { logger.info("Received callback: {}", msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); destroyService(); }); } @Test void TestCallbackProviderLimit() { Assertions.assertThrows(RpcException.class, () -> { initOrResetUrl(1, 1000); // URL cannot be transferred automatically from the server side to the client side by using API, instead, // it needs manually specified. serviceURL = serviceURL.addParameter(CALLBACK_INSTANCES_LIMIT_KEY, 1 + ""); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { logger.info("Received callback: {}", msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { logger.info("Received callback: {}", msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); destroyService(); }); } private void assertCallbackCount(int runs, int sleep, AtomicInteger count) throws InterruptedException { int last = count.get(); for (int i = 0; i < runs; i++) { if (last > runs) break; Thread.sleep(sleep * 2); logger.info("{} {}", count.get(), last); Assertions.assertTrue(count.get() > last); last = count.get(); } // has one sync callback Assertions.assertEquals(runs + 1, count.get()); } @Disabled("need start with separate process") @Test void startProvider() throws Exception { exportService(); synchronized (ArgumentCallbackTest.class) { ArgumentCallbackTest.class.wait(); } } interface IDemoCallback { String yyy(String msg); } interface IHelloService { String sayHello(); } interface IDemoService { String get(); int getCallbackCount(); void xxx(IDemoCallback callback, String arg1, int runs, int sleep); void xxx2(IDemoCallback callback); void unxxx2(IDemoCallback callback); } class HelloServiceImpl implements IHelloService { public String sayHello() { return "hello"; } } class DemoServiceImpl implements IDemoService { private List<IDemoCallback> callbacks = new ArrayList<IDemoCallback>(); private volatile Thread t = null; private volatile Lock lock = new ReentrantLock(); public String get() { return "ok"; } public void xxx(final IDemoCallback callback, String arg1, final int runs, final int sleep) { callback.yyy("Sync callback msg .This is callback data. arg1:" + arg1); Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < runs; i++) { String ret = callback.yyy("server invoke callback : arg:" + System.currentTimeMillis()); logger.info("callback result is :{}", ret); try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.setDaemon(true); t.start(); logger.info("xxx invoke complete"); } public int getCallbackCount() { return callbacks.size(); } public void xxx2(IDemoCallback callback) { if (!callbacks.contains(callback)) { callbacks.add(callback); } startThread(); } private void startThread() { if (t == null || callbacks.size() == 0) { try { lock.lock(); t = new Thread(new Runnable() { public void run() { while (callbacks.size() > 0) { try { List<IDemoCallback> callbacksCopy = new ArrayList<IDemoCallback>(callbacks); for (IDemoCallback callback : callbacksCopy) { try { callback.yyy("this is callback msg,current time is :" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); callbacks.remove(callback); } } Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.setDaemon(true); t.start(); } finally { lock.unlock(); } } } public void unxxx2(IDemoCallback callback) { if (!callbacks.contains(callback)) { throw new IllegalStateException("callback instance not found"); } callbacks.remove(callback); } } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.exchange.ExchangeClient; 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.protocol.dubbo.support.ProtocolUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WARNING_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; class ReferenceCountExchangeClientTest { public static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Exporter<?> demoExporter; Exporter<?> helloExporter; Invoker<IDemoService> demoServiceInvoker; Invoker<IHelloService> helloServiceInvoker; IDemoService demoService; IHelloService helloService; ExchangeClient demoClient; ExchangeClient helloClient; String errorMsg = "safe guard client , should not be called ,must have a bug"; @BeforeAll public static void setUpBeforeClass() throws Exception {} @AfterAll public static void tearDownAfterClass() { ProtocolUtils.closeAll(); } public static Invoker<?> referInvoker(Class<?> type, URL url) { return DubboProtocol.getDubboProtocol().refer(type, url); } public static <T> Exporter<T> export(T instance, Class<T> type, String url) { return export(instance, type, URL.valueOf(url)); } public static <T> Exporter<T> export(T instance, Class<T> type, URL url) { return ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(proxy.getInvoker(instance, type, url)); } @BeforeEach public void setUp() throws Exception {} /** * test connection sharing */ @Test void test_share_connect() { init(0, 1); Assertions.assertEquals(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertEquals(demoClient, helloClient); destroy(); } /** * test connection not sharing */ @Test void test_not_share_connect() { init(1, 1); Assertions.assertNotSame(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertNotSame(demoClient, helloClient); destroy(); } /** * test using multiple shared connections */ @Test void test_multi_share_connect() { // here a three shared connection is established between a consumer process and a provider process. final int shareConnectionNum = 3; init(0, shareConnectionNum); List<ReferenceCountExchangeClient> helloReferenceClientList = getReferenceClientList(helloServiceInvoker); Assertions.assertEquals(shareConnectionNum, helloReferenceClientList.size()); List<ReferenceCountExchangeClient> demoReferenceClientList = getReferenceClientList(demoServiceInvoker); Assertions.assertEquals(shareConnectionNum, demoReferenceClientList.size()); // because helloServiceInvoker and demoServiceInvoker use share connect, so client list must be equal Assertions.assertEquals(helloReferenceClientList, demoReferenceClientList); Assertions.assertEquals(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertEquals(demoClient, helloClient); destroy(); } /** * test counter won't count down incorrectly when invoker is destroyed for multiple times */ @Test void test_multi_destroy() { init(0, 1); DubboAppender.doStart(); DubboAppender.clear(); demoServiceInvoker.destroy(); demoServiceInvoker.destroy(); Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(0, LogUtil.findMessage(errorMsg), "should not warning message"); LogUtil.checkNoError(); DubboAppender.doStop(); destroy(); } /** * Test against invocation still succeed even if counter has error */ @Test void test_counter_error() { init(0, 1); DubboAppender.doStart(); DubboAppender.clear(); // because the two interfaces are initialized, the ReferenceCountExchangeClient reference counter is 2 ReferenceCountExchangeClient client = getReferenceClient(helloServiceInvoker); // close once, counter counts down from 2 to 1, no warning occurs client.close(); Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(0, LogUtil.findMessage(errorMsg), "should not warning message"); // close twice, counter counts down from 1 to 0, no warning occurs client.close(); // wait close done. try { Thread.sleep(1000); } catch (InterruptedException e) { Assertions.fail(); } // client has been replaced with lazy client, close status is false because a new lazy client's exchange client // is null. Assertions.assertFalse(client.isClosed(), "client status close"); // invoker status is available because the default value of associated lazy client's initial state is true. Assertions.assertTrue(helloServiceInvoker.isAvailable(), "invoker status unavailable"); // due to the effect of LazyConnectExchangeClient, the client will be "revived" whenever there is a call. Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(1, LogUtil.findMessage(errorMsg), "should warning message"); // output one error every 5000 invocations. Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(1, LogUtil.findMessage(errorMsg), "should warning message"); DubboAppender.doStop(); /** * This is the third time to close the same client. Under normal circumstances, * a client value should be closed once (that is, the shutdown operation is irreversible). * After closing, the value of the reference counter of the client has become -1. * * But this is a bit special, because after the client is closed twice, there are several calls to helloService, * that is, the client inside the ReferenceCountExchangeClient is actually active, so the third shutdown here is still effective, * let the resurrection After the client is really closed. */ client.close(); // close status is false because the lazy client's exchange client is null again after close(). Assertions.assertFalse(client.isClosed(), "client status close"); // invoker status is available because the default value of associated lazy client's initial state is true. Assertions.assertTrue(helloServiceInvoker.isAvailable(), "invoker status unavailable"); // revive: initial the lazy client's exchange client again. Assertions.assertEquals("hello", helloService.hello()); destroy(); } @SuppressWarnings("unchecked") private void init(int connections, int shareConnections) { Assertions.assertTrue(connections >= 0); Assertions.assertTrue(shareConnections >= 1); int port = NetUtils.getAvailablePort(); String params = CONNECTIONS_KEY + "=" + connections + "&" + SHARE_CONNECTIONS_KEY + "=" + shareConnections + "&" + LAZY_REQUEST_WITH_WARNING_KEY + "=" + "true"; URL demoUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/demo?" + params); URL helloUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/hello?" + params); demoExporter = export(new DemoServiceImpl(), IDemoService.class, demoUrl); helloExporter = export(new HelloServiceImpl(), IHelloService.class, helloUrl); demoServiceInvoker = (Invoker<IDemoService>) referInvoker(IDemoService.class, demoUrl); demoService = proxy.getProxy(demoServiceInvoker); Assertions.assertEquals("demo", demoService.demo()); helloServiceInvoker = (Invoker<IHelloService>) referInvoker(IHelloService.class, helloUrl); helloService = proxy.getProxy(helloServiceInvoker); Assertions.assertEquals("hello", helloService.hello()); demoClient = getClient(demoServiceInvoker); helloClient = getClient(helloServiceInvoker); } private void destroy() { demoServiceInvoker.destroy(); helloServiceInvoker.destroy(); demoExporter.getInvoker().destroy(); helloExporter.getInvoker().destroy(); } private ExchangeClient getClient(Invoker<?> invoker) { if (invoker.getUrl().getParameter(CONNECTIONS_KEY, 1) == 1) { return getInvokerClient(invoker); } else { ReferenceCountExchangeClient client = getReferenceClient(invoker); try { Field clientField = ReferenceCountExchangeClient.class.getDeclaredField("client"); clientField.setAccessible(true); return (ExchangeClient) clientField.get(client); } catch (Exception e) { e.printStackTrace(); Assertions.fail(e.getMessage()); throw new RuntimeException(e); } } } private ReferenceCountExchangeClient getReferenceClient(Invoker<?> invoker) { return getReferenceClientList(invoker).get(0); } private List<ReferenceCountExchangeClient> getReferenceClientList(Invoker<?> invoker) { List<ExchangeClient> invokerClientList = getInvokerClientList(invoker); List<ReferenceCountExchangeClient> referenceCountExchangeClientList = new ArrayList<>(invokerClientList.size()); for (ExchangeClient exchangeClient : invokerClientList) { Assertions.assertTrue(exchangeClient instanceof ReferenceCountExchangeClient); referenceCountExchangeClientList.add((ReferenceCountExchangeClient) exchangeClient); } return referenceCountExchangeClientList; } private ExchangeClient getInvokerClient(Invoker<?> invoker) { return getInvokerClientList(invoker).get(0); } private List<ExchangeClient> getInvokerClientList(Invoker<?> invoker) { @SuppressWarnings("rawtypes") DubboInvoker dInvoker = (DubboInvoker) invoker; try { Field clientField = DubboInvoker.class.getDeclaredField("clientsProvider"); clientField.setAccessible(true); ClientsProvider clientsProvider = (ClientsProvider) clientField.get(dInvoker); List<? extends ExchangeClient> clients = clientsProvider.getClients(); List<ExchangeClient> clientList = new ArrayList<ExchangeClient>(clients.size()); for (ExchangeClient client : clients) { clientList.add(client); } // sorting makes it easy to compare between lists Collections.sort(clientList, Comparator.comparing(c -> Integer.valueOf(Objects.hashCode(c)))); return clientList; } catch (Exception e) { e.printStackTrace(); Assertions.fail(e.getMessage()); throw new RuntimeException(e); } } public interface IDemoService { String demo(); } public interface IHelloService { String hello(); } public class DemoServiceImpl implements IDemoService { public String demo() { return "demo"; } } public class HelloServiceImpl implements IHelloService { public String hello() { return "hello"; } } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.apache.dubbo.rpc.service.EchoService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RpcFilterTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterEach public void after() { ProtocolUtils.closeAll(); } @Test void testRpcFilter() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.support.DemoService?service.filter=echo"); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(DemoService.class); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(service, DemoService.class, url)); service = proxy.getProxy(protocol.refer(DemoService.class, url)); Assertions.assertEquals("123", service.echo("123")); // cast to EchoService EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, url)); Assertions.assertEquals(echo.$echo("test"), "test"); Assertions.assertEquals(echo.$echo("abcdefg"), "abcdefg"); Assertions.assertEquals(echo.$echo(1234), 1234); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteService.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.rmi.Remote; import java.rmi.RemoteException; public interface RemoteService extends Remote { String sayHello(String name) throws RemoteException; String getThreadName() throws RemoteException; }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; 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.service.GenericService; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EnumBak { private static final Logger logger = LoggerFactory.getLogger(EnumBak.class); private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @Test public void testNormal() { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk" + "&interface=" + DemoService.class.getName() + "&timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService("test", DemoService.class); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); URL consumerurl = serviceurl; Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); Assertions.assertEquals(Integer.MIN_VALUE, demoProxy.getInt(Integer.MIN_VALUE)); reference.destroy(); } @Disabled @Test public void testExportService() throws InterruptedException { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk&timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); synchronized (EnumBak.class) { EnumBak.class.wait(); } // URL consumerurl = serviceurl; // Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); // DemoService demoProxy = (DemoService)proxyFactory.createProxy(reference); //// System.out.println(demoProxy.getThreadName()); // System.out.println("byte:"+demoProxy.getbyte((byte)-128)); // // invoker.destroy(); // reference.destroy(); } @Test public void testNormalEnum() { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService("test", DemoService.class); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); URL consumerurl = serviceurl; Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); Type type = demoProxy.enumlength(Type.High); Assertions.assertEquals(Type.High, type); invoker.destroy(); reference.destroy(); } // verify compatibility when 2.0.5 invokes 2.0.3 @Disabled @Test public void testEnumCompat() { int port = NetUtils.getAvailablePort(); URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(DemoService.class); Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); Type type = demoProxy.enumlength(Type.High); Assertions.assertEquals(Type.High, type); reference.destroy(); } // verify compatibility when 2.0.5 invokes 2.0.3 @Disabled @Test public void testGenricEnumCompat() { int port = NetUtils.getAvailablePort(); URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); Invoker<GenericService> reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); Object obj = demoProxy.$invoke( "enumlength", new String[] {Type[].class.getName()}, new Object[] {new Type[] {Type.High, Type.High}}); logger.info("obj----------> {}", obj); reference.destroy(); } // verify compatibility when 2.0.5 invokes 2.0.3, enum in custom parameter @Disabled @Test public void testGenricCustomArg() { int port = NetUtils.getAvailablePort(); URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=2000000"); Invoker<GenericService> reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); Map<String, Object> arg = new HashMap<String, Object>(); arg.put("type", "High"); arg.put("name", "hi"); Object obj = demoProxy.$invoke("get", new String[] {"org.apache.dubbo.rpc.CustomArgument"}, new Object[] {arg}); logger.info("obj----------> {}", obj); reference.destroy(); } @Disabled @Test public void testGenericExport() throws InterruptedException { int port = NetUtils.getAvailablePort(); // port = 20880; URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); // SERVER Thread.sleep(Integer.MAX_VALUE); } @Disabled @Test public void testGenericEnum() throws InterruptedException { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); URL consumerurl = serviceurl; Invoker<GenericService> reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); Object obj = demoProxy.$invoke( "enumlength", new String[] {Type[].class.getName()}, new Object[] {new Type[] {Type.High, Type.High}}); logger.info("obj----------> {}", obj); invoker.destroy(); reference.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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoRequest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/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.dubbo.support; 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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Type.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/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.dubbo.support; 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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Person.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Person.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo.support; import java.io.Serializable; /** * Person.java */ public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoServiceImpl.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/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.dubbo.support; import org.apache.dubbo.rpc.RpcContext; import java.util.Arrays; import java.util.Map; import java.util.Set; 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 Map echo(Map map) { return map; } public long timestamp() { return System.currentTimeMillis(); } public String getThreadName() { return Thread.currentThread().getName(); } public int getSize(String[] strs) { if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { logger.info( "RpcContext.getServerAttachment().getRemoteHost()={}", RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { if (types.length == 0) return Type.Lower; return types[0]; } public Type getType(Type type) { return type; } public int stringLength(String str) { return str.length(); } public String get(CustomArgument arg1) { return arg1.toString(); } public int getInt(int arg) { return arg; } public Person gerPerson(Person person) { return person; } public Set<String> keys(Map<String, String> map) { return map == null ? null : map.keySet(); } public void nonSerializedParameter(NonSerialized ns) {} public NonSerialized returnNonSerialized() { return new NonSerialized(); } public long add(int a, long b) { return a + b; } @Override public int getPerson(Person person) { return person.getAge(); } @Override public int getPerson(Person person1, Person perso2) { return person1.getAge() + perso2.getAge(); } @Override public String getPerson(Man man) { return man.getName(); } @Override public String getRemoteApplicationName() { return RpcContext.getServiceContext().getRemoteApplicationName(); } @Override public byte[] download(int size) { byte[] bytes = new byte[size]; Arrays.fill(bytes, (byte) 0); return bytes; } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoService.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/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.dubbo.support; import java.util.Map; import java.util.Set; /** * <code>TestService</code> */ public interface DemoService { void sayHello(String name); Set<String> keys(Map<String, String> map); String echo(String text); Map echo(Map map); long timestamp(); String getThreadName(); int getSize(String[] strs); int getSize(Object[] os); Object invoke(String service, String method) throws Exception; int stringLength(String str); Type enumlength(Type... types); Type getType(Type type); String get(CustomArgument arg1); int getInt(int arg); void nonSerializedParameter(NonSerialized ns); NonSerialized returnNonSerialized(); long add(int a, long b); int getPerson(Person person); int getPerson(Person person1, Person perso2); String getPerson(Man man); String getRemoteApplicationName(); byte[] download(int size); }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo.support; import org.apache.dubbo.common.URL; 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.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; /** * TODO Comment of ProtocolUtils */ public class ProtocolUtils { public static <T> T refer(Class<T> type, String url) { return refer(type, URL.valueOf(url)); } public static <T> T refer(Class<T> type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return proxy.getProxy(protocol.refer(type, url)); } public static Invoker<?> referInvoker(Class<?> type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return (Invoker<?>) protocol.refer(type, url); } public static <T> Exporter<T> export(T instance, Class<T> type, String url) { return export(instance, type, URL.valueOf(url)); } public static <T> Exporter<T> export(T instance, Class<T> type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return protocol.export(proxy.getInvoker(instance, type, url)); } public static void closeAll() { DubboProtocol.getDubboProtocol().destroy(); FrameworkModel.destroyAll(); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; public class NonSerialized {}
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.rpc.RpcContext; import java.rmi.RemoteException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemoteServiceImpl implements RemoteService { private static final Logger logger = LoggerFactory.getLogger(RemoteServiceImpl.class); public String getThreadName() throws RemoteException { logger.debug( "RpcContext.getServerAttachment().getRemoteHost()={}", RpcContext.getServiceContext().getRemoteHost()); return Thread.currentThread().getName(); } public String sayHello(String name) throws RemoteException { return "hello " + name + "@" + RemoteServiceImpl.class.getName(); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.io.Serializable; /** * Man.java */ public class Man implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo.support; import java.io.Serializable; @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; public CustomArgument() {} public CustomArgument(Type type, String name) { super(); this.type = type; this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.lang.reflect.Field; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class TraceFilterTest { private static final Logger logger = LoggerFactory.getLogger(TraceFilterTest.class); private MockChannel mockChannel; private static final String TRACE_MAX = "trace.max"; private static final String TRACE_COUNT = "trace.count"; private static final String TRACERS_FIELD_NAME = "TRACERS"; @BeforeEach public void setUp() { URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo"); mockChannel = new MockChannel(url); } @AfterEach public void tearDown() { mockChannel.close(); } @Test void testAddAndRemoveTracer() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 100); Assertions.assertEquals(100, mockChannel.getAttribute(TRACE_MAX)); Assertions.assertTrue(mockChannel.getAttribute(TRACE_COUNT) instanceof AtomicInteger); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> o = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Assertions.assertTrue(o.containsKey(key)); Set<Channel> channels = o.get(key); Assertions.assertNotNull(channels); Assertions.assertTrue(channels.contains(mockChannel)); // remove tracer TraceFilter.removeTracer(type, method, mockChannel); Assertions.assertNull(mockChannel.getAttribute(TRACE_MAX)); Assertions.assertNull(mockChannel.getAttribute(TRACE_COUNT)); Assertions.assertFalse(channels.contains(mockChannel)); } @Test void testInvoke() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 2); Invoker<DemoService> mockInvoker = mock(Invoker.class); Invocation mockInvocation = mock(Invocation.class); Result mockResult = mock(Result.class); TraceFilter filter = new TraceFilter(); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvocation.getMethodName()).willReturn(method); given(mockInvocation.getArguments()).willReturn(new Object[0]); given(mockInvoker.invoke(mockInvocation)).willReturn(mockResult); given(mockResult.getValue()).willReturn("result"); // test invoke filter.invoke(mockInvoker, mockInvocation); String message = listToString(mockChannel.getReceivedObjects()); String expectMessage = "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.sayHello([]) -> \"result\""; logger.info("actual message: {}", message); Assertions.assertTrue(message.contains(expectMessage)); Assertions.assertTrue(message.contains("elapsed:")); AtomicInteger traceCount = (AtomicInteger) mockChannel.getAttribute(TRACE_COUNT); Assertions.assertEquals(1, traceCount.get()); // test remove channel when count >= max - 1 filter.invoke(mockInvoker, mockInvocation); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> o = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Assertions.assertTrue(o.containsKey(key)); Set<Channel> channels = o.get(key); Assertions.assertNotNull(channels); Assertions.assertFalse(channels.contains(mockChannel)); } private static String listToString(List<Object> objectList) { StringBuilder sb = new StringBuilder(); if (CollectionUtils.isEmpty(objectList)) { return ""; } objectList.forEach(o -> { sb.append(o.toString()); }); return sb.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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class MockChannel implements Channel { private Map<String, Object> attributes = new HashMap<>(); private List<Object> receivedObjects = new LinkedList<>(); private URL url; public MockChannel() {} public MockChannel(URL url) { this.url = url; } @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public boolean isConnected() { return true; } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Object getAttribute(String key) { return attributes.getOrDefault(key, null); } @Override public void setAttribute(String key, Object value) { attributes.put(key, value); } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public URL getUrl() { return url; } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException { receivedObjects.add(message); } @Override public void send(Object message, boolean sent) throws RemotingException { receivedObjects.add(message); } @Override public void close() {} @Override public void close(int timeout) {} @Override public void startClose() {} @Override public boolean isClosed() { return false; } public List<Object> getReceivedObjects() { return receivedObjects; } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetectorTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.pu; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class DubboDetectorTest { @Test void testDetect_Recognized() { DubboDetector detector = new DubboDetector(); ChannelBuffer in = ChannelBuffers.wrappedBuffer(new byte[] {(byte) 0xda, (byte) 0xbb}); assertEquals(DubboDetector.Result.recognized(), detector.detect(in)); } @Test void testDetect_Unrecognized() { DubboDetector detector = new DubboDetector(); ChannelBuffer in = ChannelBuffers.wrappedBuffer(new byte[] {(byte) 0x00, (byte) 0x00}); assertEquals(DubboDetector.Result.unrecognized(), detector.detect(in)); } @Test void testDetect_NeedMoreData() { DubboDetector detector = new DubboDetector(); ChannelBuffer in = ChannelBuffers.wrappedBuffer(new byte[] {(byte) 0xda}); assertEquals(DubboDetector.Result.needMoreData(), detector.detect(in)); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocolTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.pu; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.api.pu.ChannelOperator; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.verify; class DubboWireProtocolTest { @InjectMocks private DubboWireProtocol dubboWireProtocol; @Mock private ChannelOperator channelOperator; @BeforeEach void setUp() throws Exception { MockitoAnnotations.openMocks(this).close(); } @Test void testConfigServerProtocolHandler() { URL url = URL.valueOf("dubbo://localhost:20880"); List<ChannelHandler> handlers = new ArrayList<>(); dubboWireProtocol.configServerProtocolHandler(url, channelOperator); verify(channelOperator).configChannelHandler(handlers); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.remoting.ChannelHandler; import java.util.function.Consumer; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; public class MockHandler extends ChannelDuplexHandler { private final Consumer consumer; private final ChannelHandler handler; public MockHandler(Consumer consumer, ChannelHandler handler) { this.consumer = consumer; this.handler = handler; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { this.handler.received(new MockChannel(consumer), msg); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.utils.NetUtils; import java.net.InetSocketAddress; import java.net.SocketAddress; import io.netty.channel.embedded.EmbeddedChannel; public class LocalEmbeddedChannel extends EmbeddedChannel { public SocketAddress localAddress() { return new InetSocketAddress(20883); } @Override protected SocketAddress remoteAddress0() { return new InetSocketAddress(NetUtils.getAvailablePort()); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; import org.apache.dubbo.remoting.transport.DecodeHandler; import org.apache.dubbo.remoting.transport.MultiMessageHandler; import org.apache.dubbo.remoting.transport.netty4.NettyBackedChannelBuffer; import org.apache.dubbo.remoting.transport.netty4.NettyCodecAdapter; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; 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.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.protocol.dubbo.DecodeableRpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboCodec; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * These junit tests aim to test unpack and stick pack of dubbo and telnet */ class DubboTelnetDecodeTest { private static AtomicInteger dubbo = new AtomicInteger(0); private static AtomicInteger telnet = new AtomicInteger(0); private static AtomicInteger telnetDubbo = new AtomicInteger(0); private static AtomicInteger dubboDubbo = new AtomicInteger(0); private static AtomicInteger dubboTelnet = new AtomicInteger(0); private static AtomicInteger telnetTelnet = new AtomicInteger(0); @BeforeAll public static void setup() { ModuleServiceRepository serviceRepository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); serviceRepository.registerService(DemoService.class); } @AfterAll public static void teardown() { FrameworkModel.defaultModel().destroy(); } /** * just dubbo request * * @throws InterruptedException */ @Test void testDubboDecode() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( null, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { dubbo.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(dubboByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(1, dubbo.get()); } /** * just telnet request * * @throws InterruptedException */ @Test void testTelnetDecode() throws InterruptedException { ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("test\r\n".getBytes()); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { telnet.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(telnetByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(1, telnet.get()); } /** * telnet and dubbo request * * <p> * First ByteBuf: * +--------------------------------------------------+ * | telnet(incomplete) | * +--------------------------------------------------+ * <p> * * Second ByteBuf: * +--------------------------++----------------------+ * | telnet(the remaining) || dubbo(complete) | * +--------------------------++----------------------+ * || * Magic Code * * @throws InterruptedException */ @Test void testTelnetDubboDecoded() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("test\r".getBytes()); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { telnetDubbo.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { telnetDubbo.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(telnetByteBuf); ch.writeInbound(Unpooled.wrappedBuffer(Unpooled.wrappedBuffer("\n".getBytes()), dubboByteBuf)); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, telnetDubbo.get()); } /** * NOTE: This test case actually will fail, but the probability of this case is very small, * and users should use telnet in new QOS port(default port is 22222) since dubbo 2.5.8, * so we could ignore this problem. * * <p> * telnet and telnet request * * <p> * First ByteBuf (firstByteBuf): * +--------------------------------------------------+ * | telnet(incomplete) | * +--------------------------------------------------+ * <p> * * Second ByteBuf (secondByteBuf): * +--------------------------------------------------+ * | telnet(the remaining) | telnet(complete) | * +--------------------------------------------------+ * * @throws InterruptedException */ @Disabled @Test void testTelnetTelnetDecoded() throws InterruptedException { ByteBuf firstByteBuf = Unpooled.wrappedBuffer("ls\r".getBytes()); ByteBuf secondByteBuf = Unpooled.wrappedBuffer("\nls\r\n".getBytes()); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { telnetTelnet.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstByteBuf); ch.writeInbound(secondByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, telnetTelnet.get()); } /** * dubbo and dubbo request * * <p> * First ByteBuf (firstDubboByteBuf): * ++-------------------------------------------------+ * || dubbo(incomplete) | * ++-------------------------------------------------+ * || * Magic Code * <p> * * <p> * Second ByteBuf (secondDubboByteBuf): * +-------------------------++-----------------------+ * | dubbo(the remaining) || dubbo(complete) | * +-------------------------++-----------------------+ * || * Magic Code * * @throws InterruptedException */ @Test void testDubboDubboDecoded() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50); ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes() - 50); ByteBuf secondDubboByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, dubboByteBuf); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( null, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { dubboDubbo.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstDubboByteBuf); ch.writeInbound(secondDubboByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, dubboDubbo.get()); } /** * dubbo and telnet request * * <p> * First ByteBuf: * ++-------------------------------------------------+ * || dubbo(incomplete) | * ++-------------------------------------------------+ * || * Magic Code * * <p> * Second ByteBuf: * +--------------------------------------------------+ * | dubbo(the remaining) | telnet(complete) | * +--------------------------------------------------+ * * @throws InterruptedException */ @Test void testDubboTelnetDecoded() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50); ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes()); ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("\r\n".getBytes()); ByteBuf secondByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, telnetByteBuf); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { dubboTelnet.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { dubboTelnet.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstDubboByteBuf); ch.writeInbound(secondByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, dubboTelnet.get()); } private ByteBuf createDubboByteBuf() throws IOException { Request request = new Request(); RpcInvocation rpcInvocation = new RpcInvocation(); rpcInvocation.setMethodName("sayHello"); rpcInvocation.setParameterTypes(new Class[] {String.class}); rpcInvocation.setParameterTypesDesc(ReflectUtils.getDesc(new Class[] {String.class})); rpcInvocation.setArguments(new String[] {"dubbo"}); rpcInvocation.setAttachment("path", DemoService.class.getName()); rpcInvocation.setAttachment("interface", DemoService.class.getName()); rpcInvocation.setAttachment("version", "0.0.0"); request.setData(rpcInvocation); request.setVersion("2.0.2"); ByteBuf dubboByteBuf = Unpooled.buffer(); ChannelBuffer buffer = new NettyBackedChannelBuffer(dubboByteBuf); DubboCodec dubboCodec = new DubboCodec(FrameworkModel.defaultModel()); dubboCodec.encode(new MockChannel(), buffer, request); // register // frameworkModel.getServiceRepository().registerProviderUrl(); FrameworkModel.defaultModel() .getBeanFactory() .getBean(PermittedSerializationKeeper.class) .registerService( URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName() + "?version=0.0.0")); return dubboByteBuf; } private static boolean checkTelnetDecoded(Object msg) { if (msg instanceof String && !msg.toString().contains("Unsupported command:")) { return true; } return false; } private static boolean checkDubboDecoded(Object msg) { if (msg instanceof DecodeableRpcInvocation) { DecodeableRpcInvocation invocation = (DecodeableRpcInvocation) msg; if ("sayHello".equals(invocation.getMethodName()) && invocation.getParameterTypes().length == 1 && String.class.equals(invocation.getParameterTypes()[0]) && invocation.getArguments().length == 1 && "dubbo".equals(invocation.getArguments()[0]) && DemoService.class.getName().equals(invocation.getAttachment("path")) && DemoService.class.getName().equals(invocation.getAttachment("interface")) && "0.0.0".equals(invocation.getAttachment("version"))) { return true; } } return false; } private static CompletableFuture<Object> getDefaultFuture() { CompletableFuture<Object> future = new CompletableFuture<>(); AppResponse result = new AppResponse(); result.setValue("default result"); future.complete(result); 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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.function.Consumer; public class MockChannel implements Channel { private Consumer consumer; public MockChannel() {} public MockChannel(Consumer consumer) { this.consumer = consumer; } @Override public InetSocketAddress getRemoteAddress() { return new InetSocketAddress(NetUtils.getAvailablePort()); } @Override public boolean isConnected() { return false; } @Override public boolean hasAttribute(String key) { return false; } @Override public Object getAttribute(String key) { return null; } @Override public void setAttribute(String key, Object value) {} @Override public void removeAttribute(String key) {} @Override public URL getUrl() { return new ServiceConfigURL("dubbo", "localhost", 20880); } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return new InetSocketAddress(20883); } @Override public void send(Object message) throws RemotingException { if (consumer != null) { consumer.accept(message); } } @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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.util.Collections; import java.util.Set; public class MockChannelHandler implements ChannelHandler { // ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>(); @Override public void connected(Channel channel) throws RemotingException { channels.add(channel); } @Override public void disconnected(Channel channel) throws RemotingException { channels.remove(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { channel.send(message); } @Override public void received(Channel channel, Object message) throws RemotingException { // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); } public Set<Channel> getChannels() { return Collections.unmodifiableSet(channels); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/telnet/TestTelnetHandler.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/telnet/TestTelnetHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode.telnet; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; /** * ListTelnetHandler handler list services and its methods details. */ @Activate @Help(summary = "test telnet command.", detail = "test telnet command.") public class TestTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { return "TestTelnetHandler"; } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link ThreadPoolStatusChecker} */ class ThreadPoolStatusCheckerTest { @Test void test() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); ExecutorService executorService1 = Executors.newFixedThreadPool(1); ExecutorService executorService2 = Executors.newFixedThreadPool(10); dataStore.put(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8888", executorService1); dataStore.put(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8889", executorService2); ThreadPoolStatusChecker threadPoolStatusChecker = new ThreadPoolStatusChecker(ApplicationModel.defaultModel()); Status status = threadPoolStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.WARN); Assertions.assertEquals( status.getMessage(), "Pool status:WARN, max:1, core:1, largest:0, active:0, task:0, service port: 8888;" + "Pool status:OK, max:10, core:10, largest:0, active:0, task:0, service port: 8889"); // reset executorService1.shutdown(); executorService2.shutdown(); dataStore.remove(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8888"); dataStore.remove(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8889"); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; /** * {@link ServerStatusChecker} */ class ServerStatusCheckerTest { @Test void test() { ServerStatusChecker serverStatusChecker = new ServerStatusChecker(); Status status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.UNKNOWN); DubboProtocol dubboProtocol = Mockito.mock(DubboProtocol.class); ProtocolServer protocolServer = Mockito.mock(ProtocolServer.class); RemotingServer remotingServer = Mockito.mock(RemotingServer.class); List<ProtocolServer> servers = Arrays.asList(protocolServer); Mockito.when(dubboProtocol.getServers()).thenReturn(servers); Mockito.when(protocolServer.getRemotingServer()).thenReturn(remotingServer); Mockito.when(remotingServer.isBound()).thenReturn(true); Mockito.when(remotingServer.getLocalAddress()) .thenReturn(InetSocketAddress.createUnresolved("127.0.0.1", 9999)); Mockito.when(remotingServer.getChannels()).thenReturn(Arrays.asList(new MockChannel())); try (MockedStatic<DubboProtocol> mockDubboProtocol = Mockito.mockStatic(DubboProtocol.class)) { mockDubboProtocol.when(() -> DubboProtocol.getDubboProtocol()).thenReturn(dubboProtocol); status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.OK); // In JDK 17 : 127.0.0.1/<unresolved>:9999(clients:1) Assertions.assertTrue(status.getMessage().contains("127.0.0.1")); Assertions.assertTrue(status.getMessage().contains("9999(clients:1)")); Mockito.when(remotingServer.isBound()).thenReturn(false); status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.ERROR); // In JDK 17 : 127.0.0.1/<unresolved>:9999 Assertions.assertTrue(status.getMessage().contains("127.0.0.1")); Assertions.assertTrue(status.getMessage().contains("9999")); } } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.util.Collections; import java.util.Set; public class MockedChannelHandler implements ChannelHandler { // ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>(); @Override public void connected(Channel channel) throws RemotingException { channels.add(channel); } @Override public void disconnected(Channel channel) throws RemotingException { channels.remove(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { channel.send(message); } @Override public void received(Channel channel, Object message) throws RemotingException { // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); } public Set<Channel> getChannels() { return Collections.unmodifiableSet(channels); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.transport.MultiMessageHandler; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ChannelHandlersTest { @Test void test() { ChannelHandlers instance1 = ChannelHandlers.getInstance(); ChannelHandlers instance2 = ChannelHandlers.getInstance(); Assertions.assertEquals(instance1, instance2); ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9999); ChannelHandler wrappedHandler = ChannelHandlers.wrap(channelHandler, url); Assertions.assertTrue(wrappedHandler instanceof MultiMessageHandler); MultiMessageHandler multiMessageHandler = (MultiMessageHandler) wrappedHandler; ChannelHandler handler = multiMessageHandler.getHandler(); Assertions.assertEquals(channelHandler, handler); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; public class MockedChannel implements Channel { private boolean isClosed; private volatile boolean closing = false; private URL url; private ChannelHandler handler; private Map<String, Object> map = new HashMap<String, Object>(); public MockedChannel() { super(); } @Override public URL getUrl() { return url; } @Override public ChannelHandler getChannelHandler() { return this.handler; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException { this.send(message); } @Override public void close() { isClosed = true; } @Override public void close(int timeout) { this.close(); } @Override public void startClose() { closing = true; } @Override public boolean isClosed() { return isClosed; } @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public boolean isConnected() { return false; } @Override public boolean hasAttribute(String key) { return map.containsKey(key); } @Override public Object getAttribute(String key) { return map.get(key); } @Override public void setAttribute(String key, Object value) { map.put(key, value); } @Override public void removeAttribute(String key) { map.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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { @BeforeEach public void setUp() throws Exception { url = url.setScopeModel(ApplicationModel.defaultModel()); handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); } @Test void testConnectBlocked() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); Assertions.assertEquals(1, executor.getMaximumPoolSize()); int runs = 20; int taskCount = runs * 2; for (int i = 0; i < runs; i++) { handler.connected(new MockedChannel()); handler.disconnected(new MockedChannel()); Assertions.assertTrue(executor.getActiveCount() <= 1, executor.getActiveCount() + " must <=1"); } // queue.size Assertions.assertEquals(taskCount - 1, executor.getQueue().size()); for (int i = 0; i < taskCount; i++) { if (executor.getCompletedTaskCount() < taskCount) { sleep(100); } } Assertions.assertEquals(taskCount, executor.getCompletedTaskCount()); } @Test // biz error should not throw and affect biz thread. public void testConnectBizError() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); handler.connected(new MockedChannel()); } @Test // biz error should not throw and affect biz thread. public void testDisconnectBizError() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); handler.disconnected(new MockedChannel()); } @Test void testConnectExecuteError() throws RemotingException { Assertions.assertThrows(ExecutionException.class, () -> { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); executor.shutdown(); handler.connected(new MockedChannel()); }); } @Test void testDisconnectExecuteError() throws RemotingException { Assertions.assertThrows(ExecutionException.class, () -> { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); executor.shutdown(); handler.disconnected(new MockedChannel()); }); } // throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception @Test // (expected = RemotingException.class) public void testMessageReceivedBizError() throws RemotingException { handler.received(new MockedChannel(), ""); } // throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception @Test void testCaughtBizError() throws RemotingException { handler.caught(new MockedChannel(), new BizException()); } @Test @Disabled("FIXME") public void testReceivedInvokeInExecutor() throws RemotingException { Assertions.assertThrows(ExecutionException.class, () -> { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "SHARED_EXECUTOR", 1); executor.shutdown(); executor = (ThreadPoolExecutor) getField(handler, "executor", 1); executor.shutdown(); handler.received(new MockedChannel(), ""); }); } /** * Events do not pass through the thread pool and execute directly on the IO */ @SuppressWarnings("deprecation") @Disabled("Heartbeat is processed in HeartbeatHandler not WrappedChannelHandler.") @Test void testReceivedEventInvokeDirect() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "SHARED_EXECUTOR", 1); executor.shutdown(); executor = (ThreadPoolExecutor) getField(handler, "executor", 1); executor.shutdown(); Request req = new Request(); req.setHeartbeat(true); final AtomicInteger count = new AtomicInteger(0); handler.received( new MockedChannel() { @Override public void send(Object message) throws RemotingException { Assertions.assertTrue(((Response) message).isHeartbeat(), "response.heartbeat"); count.incrementAndGet(); } }, req); Assertions.assertEquals(1, count.get(), "channel.send must be invoke"); } }
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-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.lang.reflect.Field; import java.util.concurrent.ExecutorService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; class WrappedChannelHandlerTest { WrappedChannelHandler handler; URL url = URL.valueOf("dubbo://10.20.30.40:1234"); @BeforeEach public void setUp() throws Exception { url = url.setScopeModel(ApplicationModel.defaultModel()); handler = new WrappedChannelHandler(new BizChannelHandler(true), url); } @Test void test_Execute_Error() throws RemotingException {} protected Object getField(Object obj, String fieldName, int parentdepth) { try { Class<?> clazz = obj.getClass(); Field field = null; for (int i = 0; i <= parentdepth && field == null; i++) { Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (f.getName().equals(fieldName)) { field = f; break; } } clazz = clazz.getSuperclass(); } if (field != null) { field.setAccessible(true); return field.get(obj); } else { throw new NoSuchFieldException(); } } catch (Exception e) { throw new IllegalStateException(e); } } protected void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Test void testConnectBizError() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> handler.connected(new MockedChannel())); } @Test void testDisconnectBizError() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> handler.disconnected(new MockedChannel())); } @Test void testMessageReceivedBizError() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> handler.received(new MockedChannel(), "")); } @Test void testCaughtBizError() throws RemotingException { try { handler.caught(new MockedChannel(), new BizException()); fail(); } catch (Exception e) { Assertions.assertEquals(BizException.class, e.getCause().getClass()); } } @Test void testGetExecutor() { ExecutorService sharedExecutorService = handler.getSharedExecutorService(); Assertions.assertNotNull(sharedExecutorService); ExecutorService preferredExecutorService = handler.getPreferredExecutorService(new Object()); Assertions.assertEquals(preferredExecutorService, sharedExecutorService); Response response = new Response(10); preferredExecutorService = handler.getPreferredExecutorService(response); Assertions.assertEquals(preferredExecutorService, sharedExecutorService); Channel channel = new MockedChannel(); Request request = new Request(10); ExecutorService sharedExecutor = ExtensionLoader.getExtensionLoader(ExecutorRepository.class) .getDefaultExtension() .createExecutorIfAbsent(url); DefaultFuture future = DefaultFuture.newFuture(channel, request, 1000, null); preferredExecutorService = handler.getPreferredExecutorService(response); Assertions.assertEquals(preferredExecutorService, sharedExecutor); future.cancel(); ThreadlessExecutor executor = new ThreadlessExecutor(); future = DefaultFuture.newFuture(channel, request, 1000, executor); preferredExecutorService = handler.getPreferredExecutorService(response); Assertions.assertEquals(preferredExecutorService, executor); future.cancel(); FrameworkModel.destroyAll(); } class BizChannelHandler extends MockedChannelHandler { private boolean invokeWithBizError; public BizChannelHandler(boolean invokeWithBizError) { super(); this.invokeWithBizError = invokeWithBizError; } public BizChannelHandler() { super(); } @Override public void connected(Channel channel) throws RemotingException { if (invokeWithBizError) { throw new RemotingException(channel, "test connect biz error"); } sleep(20); } @Override public void disconnected(Channel channel) throws RemotingException { if (invokeWithBizError) { throw new RemotingException(channel, "test disconnect biz error"); } sleep(20); } @Override public void received(Channel channel, Object message) throws RemotingException { if (invokeWithBizError) { throw new RemotingException(channel, "test received biz error"); } sleep(20); } } class BizException extends RuntimeException { private static final long serialVersionUID = -7541893754900723624L; } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import static org.apache.dubbo.rpc.Constants.INVOCATION_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; public class DubboCodecSupport { public static Serialization getRequestSerialization(URL url, Invocation invocation) { Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { return CodecSupport.getSerializationById((byte) serializationTypeObj); } return url.getOrDefaultFrameworkModel() .getExtensionLoader(Serialization.class) .getExtension(UrlUtils.serializationOrDefault(url)); } public static Serialization getResponseSerialization(URL url, AppResponse appResponse) { Object invocationObj = appResponse.getAttribute(INVOCATION_KEY); if (invocationObj != null) { Invocation invocation = (Invocation) invocationObj; Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { return CodecSupport.getSerializationById((byte) serializationTypeObj); } } return url.getOrDefaultFrameworkModel() .getExtensionLoader(Serialization.class) .getExtension(UrlUtils.serializationOrDefault(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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; /** * dubbo protocol support class. */ @SuppressWarnings("deprecation") final class ReferenceCountExchangeClient implements ExchangeClient { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountExchangeClient.class); private final URL url; private final AtomicInteger referenceCount = new AtomicInteger(0); private final AtomicInteger disconnectCount = new AtomicInteger(0); private static final Integer warningPeriod = 50; private ExchangeClient client; private int shutdownWaitTime = DEFAULT_SERVER_SHUTDOWN_TIMEOUT; public ReferenceCountExchangeClient(ExchangeClient client, String codec) { this.client = client; this.referenceCount.incrementAndGet(); this.url = client.getUrl(); } @Override public void reset(URL url) { client.reset(url); } @Override public CompletableFuture<Object> request(Object request) throws RemotingException { return client.request(request); } @Override public URL getUrl() { return client.getUrl(); } @Override public InetSocketAddress getRemoteAddress() { return client.getRemoteAddress(); } @Override public ChannelHandler getChannelHandler() { return client.getChannelHandler(); } @Override public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException { return client.request(request, timeout); } @Override public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException { return client.request(request, executor); } @Override public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException { return client.request(request, timeout, executor); } @Override public boolean isConnected() { return client.isConnected(); } @Override public void reconnect() throws RemotingException { client.reconnect(); } @Override public InetSocketAddress getLocalAddress() { return client.getLocalAddress(); } @Override public boolean hasAttribute(String key) { return client.hasAttribute(key); } @Override public void reset(Parameters parameters) { client.reset(parameters); } @Override public void send(Object message) throws RemotingException { client.send(message); } @Override public ExchangeHandler getExchangeHandler() { return client.getExchangeHandler(); } @Override public Object getAttribute(String key) { return client.getAttribute(key); } @Override public void send(Object message, boolean sent) throws RemotingException { client.send(message, sent); } @Override public void setAttribute(String key, Object value) { client.setAttribute(key, value); } @Override public void removeAttribute(String key) { client.removeAttribute(key); } /** * close() is not idempotent any longer */ @Override public void close() { close(0); } @Override public void close(int timeout) { if (referenceCount.decrementAndGet() <= 0) { if (timeout == 0) { client.close(); } else { client.close(timeout); } replaceWithLazyClient(); } } @Override public void startClose() { client.startClose(); } /** * when closing the client, the client needs to be set to LazyConnectExchangeClient, and if a new call is made, * the client will "resurrect". * * @return */ private void replaceWithLazyClient() { // start warning at second replaceWithLazyClient() if (disconnectCount.getAndIncrement() % warningPeriod == 1) { logger.warn( PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); } // the order of judgment in the if statement cannot be changed. if (!(client instanceof LazyConnectExchangeClient)) { client = new LazyConnectExchangeClient(url, client.getExchangeHandler()); } } @Override public boolean isClosed() { return client.isClosed(); } /** * The reference count of current ExchangeClient, connection will be closed if all invokers destroyed. */ public void incrementAndGetCount() { referenceCount.incrementAndGet(); } public int getCount() { return referenceCount.get(); } public int getShutdownWaitTime() { return shutdownWaitTime; } public void setShutdownWaitTime(int shutdownWaitTime) { this.shutdownWaitTime = shutdownWaitTime; } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupportFactory.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupportFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.rpc.executor.ExecutorSupport; import org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory; public class DubboIsolationExecutorSupportFactory implements IsolationExecutorSupportFactory { @Override public ExecutorSupport createIsolationExecutorSupport(URL url) { return new DubboIsolationExecutorSupport(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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.rpc.GracefulShutdown; import org.apache.dubbo.rpc.ProtocolServer; import java.nio.channels.ClosedChannelException; import java.util.Collection; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; import static org.apache.dubbo.common.constants.CommonConstants.WRITEABLE_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class DubboGracefulShutdown implements GracefulShutdown { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboGracefulShutdown.class); private final DubboProtocol dubboProtocol; public DubboGracefulShutdown(DubboProtocol dubboProtocol) { this.dubboProtocol = dubboProtocol; } @Override public void readonly() { sendEvent(READONLY_EVENT); } @Override public void writeable() { sendEvent(WRITEABLE_EVENT); } private void sendEvent(String event) { try { for (ProtocolServer server : dubboProtocol.getServers()) { Collection<Channel> channels = server.getRemotingServer().getChannels(); Request request = new Request(); request.setEvent(event); request.setTwoWay(false); request.setVersion(Version.getProtocolVersion()); for (Channel channel : channels) { try { if (channel.isConnected()) { channel.send( request, channel.getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { if (e.getCause() instanceof ClosedChannelException) { // ignore ClosedChannelException which means the connection has been closed. continue; } logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "send cannot write message error.", e); } } } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "send cannot write message error.", 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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.url.component.ServiceConfigURL; 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.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.Transporter; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.PortUnificationExchanger; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; 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.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.protocol.AbstractProtocol; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; 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.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; import static org.apache.dubbo.remoting.Constants.CODEC_KEY; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_HEARTBEAT; import static org.apache.dubbo.remoting.Constants.DEFAULT_REMOTING_CLIENT; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_KEY; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_REMOTING_SERVER; 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.STUB_EVENT_METHODS_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_SHARE_CONNECTIONS; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_DISCONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; /** * dubbo protocol support. */ public class DubboProtocol extends AbstractProtocol { public static final String NAME = "dubbo"; public static final int DEFAULT_PORT = 20880; private static final String IS_CALLBACK_SERVICE_INVOKE = "_isCallBackServiceInvoke"; /** * <host:port,Exchanger> * Map<String, List<ReferenceCountExchangeClient> */ private final Map<String, SharedClientsProvider> referenceClientMap = new ConcurrentHashMap<>(); private final AtomicBoolean destroyed = new AtomicBoolean(); private final ExchangeHandler requestHandler; public DubboProtocol(FrameworkModel frameworkModel) { requestHandler = new ExchangeHandlerAdapter(frameworkModel) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object message) throws RemotingException { if (!(message instanceof Invocation)) { throw new RemotingException( channel, "Unsupported request: " + (message == null ? null : (message.getClass().getName() + ": " + message)) + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress()); } Invocation inv = (Invocation) message; Invoker<?> invoker = inv.getInvoker() == null ? getInvoker(channel, inv) : inv.getInvoker(); // switch TCCL if (invoker.getUrl().getServiceModel() != null) { Thread.currentThread() .setContextClassLoader( invoker.getUrl().getServiceModel().getClassLoader()); } // need to consider backward-compatibility if it's a callback if (Boolean.TRUE.toString().equals(inv.getObjectAttachmentWithoutConvert(IS_CALLBACK_SERVICE_INVOKE))) { String methodsStr = invoker.getUrl().getParameters().get("methods"); boolean hasMethod = false; if (methodsStr == null || !methodsStr.contains(",")) { hasMethod = inv.getMethodName().equals(methodsStr); } else { String[] methods = methodsStr.split(","); for (String method : methods) { if (inv.getMethodName().equals(method)) { hasMethod = true; break; } } } if (!hasMethod) { logger.warn( PROTOCOL_FAILED_REFER_INVOKER, "", "", new IllegalStateException("The methodName " + inv.getMethodName() + " not found in callback service interface ,invoke will be ignored." + " please update the api interface. url is:" + invoker.getUrl()) + " ,invocation is :" + inv); return null; } } RpcContext.getServiceContext().setRemoteAddress(channel.getRemoteAddress()); Result result = invoker.invoke(inv); return result.thenApply(Function.identity()); } @Override public void received(Channel channel, Object message) throws RemotingException { if (message instanceof Invocation) { reply((ExchangeChannel) channel, message); } else { super.received(channel, message); } } @Override public void connected(Channel channel) throws RemotingException { invoke(channel, ON_CONNECT_KEY); } @Override public void disconnected(Channel channel) throws RemotingException { if (logger.isDebugEnabled()) { logger.debug("disconnected from " + channel.getRemoteAddress() + ",url:" + channel.getUrl()); } invoke(channel, ON_DISCONNECT_KEY); } private void invoke(Channel channel, String methodKey) { Invocation invocation = createInvocation(channel, channel.getUrl(), methodKey); if (invocation != null) { try { if (Boolean.TRUE.toString().equals(invocation.getAttachment(STUB_EVENT_KEY))) { tryToGetStubService(channel, invocation); } received(channel, invocation); } catch (Throwable t) { logger.warn( PROTOCOL_FAILED_REFER_INVOKER, "", "", "Failed to invoke event method " + invocation.getMethodName() + "(), cause: " + t.getMessage(), t); } } } private void tryToGetStubService(Channel channel, Invocation invocation) throws RemotingException { try { Invoker<?> invoker = getInvoker(channel, invocation); } catch (RemotingException e) { String serviceKey = serviceKey( 0, (String) invocation.getObjectAttachmentWithoutConvert(PATH_KEY), (String) invocation.getObjectAttachmentWithoutConvert(VERSION_KEY), (String) invocation.getObjectAttachmentWithoutConvert(GROUP_KEY)); throw new RemotingException( channel, "The stub service[" + serviceKey + "] is not found, it may not be exported yet"); } } /** * FIXME channel.getUrl() always binds to a fixed service, and this service is random. * we can choose to use a common service to carry onConnect event if there's no easy way to get the specific * service this connection is binding to. * @param channel * @param url * @param methodKey * @return */ private Invocation createInvocation(Channel channel, URL url, String methodKey) { String method = url.getParameter(methodKey); if (method == null || method.length() == 0) { return null; } RpcInvocation invocation = new RpcInvocation( url.getServiceModel(), method, url.getParameter(INTERFACE_KEY), "", new Class<?>[0], new Object[0]); invocation.setAttachment(PATH_KEY, url.getPath()); invocation.setAttachment(GROUP_KEY, url.getGroup()); invocation.setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY)); invocation.setAttachment(VERSION_KEY, url.getVersion()); if (url.getParameter(STUB_EVENT_KEY, false)) { invocation.setAttachment(STUB_EVENT_KEY, Boolean.TRUE.toString()); } return invocation; } }; this.frameworkModel = frameworkModel; this.frameworkModel.getBeanFactory().registerBean(new DubboGracefulShutdown(this)); } /** * @deprecated Use {@link DubboProtocol#getDubboProtocol(ScopeModel)} instead */ @Deprecated public static DubboProtocol getDubboProtocol() { return (DubboProtocol) FrameworkModel.defaultModel() .getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME, false); } public static DubboProtocol getDubboProtocol(ScopeModel scopeModel) { return (DubboProtocol) scopeModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); } private boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); return url.getPort() == address.getPort() && NetUtils.filterLocalHost(channel.getUrl().getIp()) .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } Invoker<?> getInvoker(Channel channel, Invocation inv) throws RemotingException { boolean isCallBackServiceInvoke; boolean isStubServiceInvoke; int port = channel.getLocalAddress().getPort(); String path = (String) inv.getObjectAttachmentWithoutConvert(PATH_KEY); // if it's stub service on client side(after enable stubevent, usually is set up onconnect or ondisconnect // method) isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getObjectAttachmentWithoutConvert(STUB_EVENT_KEY)); if (isStubServiceInvoke) { // when a stub service export to local, it usually can't be exposed to port port = 0; } // if it's callback service on client side isCallBackServiceInvoke = isClientSide(channel) && !isStubServiceInvoke; if (isCallBackServiceInvoke) { path += "." + inv.getObjectAttachmentWithoutConvert(CALLBACK_SERVICE_KEY); inv.setObjectAttachment(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); } String serviceKey = serviceKey(port, path, (String) inv.getObjectAttachmentWithoutConvert(VERSION_KEY), (String) inv.getObjectAttachmentWithoutConvert(GROUP_KEY)); DubboExporter<?> exporter = (DubboExporter<?>) exporterMap.get(serviceKey); if (exporter == null) { throw new RemotingException( channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + getInvocationWithoutData(inv)); } Invoker<?> invoker = exporter.getInvoker(); inv.setServiceModel(invoker.getUrl().getServiceModel()); return invoker; } public Collection<Invoker<?>> getInvokers() { return Collections.unmodifiableCollection(invokers); } @Override public int getDefaultPort() { return DEFAULT_PORT; } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { checkDestroyed(); URL url = invoker.getUrl(); // export service. String key = serviceKey(url); DubboExporter<T> exporter = new DubboExporter<>(invoker, key, exporterMap); // export a stub service for dispatching event boolean isStubSupportEvent = url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT); boolean isCallbackService = url.getParameter(IS_CALLBACK_SERVICE, false); if (isStubSupportEvent && !isCallbackService) { String stubServiceMethods = url.getParameter(STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0) { if (logger.isWarnEnabled()) { logger.warn( PROTOCOL_UNSUPPORTED, "", "", "consumer [" + url.getParameter(INTERFACE_KEY) + "], has set stub proxy support event ,but no stub methods founded."); } } } openServer(url); optimizeSerialization(url); return exporter; } private void openServer(URL url) { checkDestroyed(); // find server. String key = url.getAddress(); // client can export a service which only for server to invoke boolean isServer = url.getParameter(IS_SERVER_KEY, true); if (isServer) { ProtocolServer server = serverMap.get(key); if (server == null) { synchronized (this) { server = serverMap.get(key); if (server == null) { serverMap.put(key, createServer(url)); return; } } } // server supports reset, use together with override server.reset(url); } } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException(getClass().getSimpleName() + " is destroyed"); } } private ProtocolServer createServer(URL url) { url = URLBuilder.from(url) // send readonly event when server closes, it's enabled by default .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) // enable heartbeat by default .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT)) .addParameter(CODEC_KEY, DubboCodec.NAME) .build(); String transporter = url.getParameter(SERVER_KEY, DEFAULT_REMOTING_SERVER); if (StringUtils.isNotEmpty(transporter) && !url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .hasExtension(transporter)) { throw new RpcException("Unsupported server type: " + transporter + ", url: " + url); } ExchangeServer server; try { server = Exchangers.bind(url, requestHandler); } catch (RemotingException e) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } transporter = url.getParameter(CLIENT_KEY); if (StringUtils.isNotEmpty(transporter) && !url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .hasExtension(transporter)) { throw new RpcException("Unsupported client type: " + transporter); } DubboProtocolServer protocolServer = new DubboProtocolServer(server); loadServerProperties(protocolServer); return protocolServer; } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { checkDestroyed(); return protocolBindingRefer(type, url); } @Override public <T> Invoker<T> protocolBindingRefer(Class<T> serviceType, URL url) throws RpcException { checkDestroyed(); optimizeSerialization(url); // create rpc invoker. DubboInvoker<T> invoker = new DubboInvoker<>(serviceType, url, getClients(url), invokers); invokers.add(invoker); return invoker; } private ClientsProvider getClients(URL url) { int connections = url.getParameter(CONNECTIONS_KEY, 0); // whether to share connection // if not configured, connection is shared, otherwise, one connection for one service if (connections == 0) { /* * The xml configuration should have a higher priority than properties. */ String shareConnectionsStr = StringUtils.isBlank(url.getParameter(SHARE_CONNECTIONS_KEY, (String) null)) ? ConfigurationUtils.getProperty( url.getOrDefaultApplicationModel(), SHARE_CONNECTIONS_KEY, DEFAULT_SHARE_CONNECTIONS) : url.getParameter(SHARE_CONNECTIONS_KEY, (String) null); connections = Integer.parseInt(shareConnectionsStr); return getSharedClient(url, connections); } List<ExchangeClient> clients = IntStream.range(0, connections).mapToObj((i) -> initClient(url)).collect(Collectors.toList()); return new ExclusiveClientsProvider(clients); } /** * Get shared connection * * @param url * @param connectNum connectNum must be greater than or equal to 1 */ @SuppressWarnings("unchecked") private SharedClientsProvider getSharedClient(URL url, int connectNum) { String key = url.getAddress(); // connectNum must be greater than or equal to 1 int expectedConnectNum = Math.max(connectNum, 1); return referenceClientMap.compute(key, (originKey, originValue) -> { if (originValue != null && originValue.increaseCount()) { return originValue; } else { return new SharedClientsProvider( this, originKey, buildReferenceCountExchangeClientList(url, expectedConnectNum)); } }); } protected void scheduleRemoveSharedClient(String key, SharedClientsProvider sharedClient) { this.frameworkModel .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedExecutor() .submit(() -> referenceClientMap.remove(key, sharedClient)); } /** * Bulk build client * * @param url * @param connectNum * @return */ private List<ReferenceCountExchangeClient> buildReferenceCountExchangeClientList(URL url, int connectNum) { List<ReferenceCountExchangeClient> clients = new ArrayList<>(); for (int i = 0; i < connectNum; i++) { clients.add(buildReferenceCountExchangeClient(url)); } return clients; } /** * Build a single client * * @param url * @return */ private ReferenceCountExchangeClient buildReferenceCountExchangeClient(URL url) { ExchangeClient exchangeClient = initClient(url); ReferenceCountExchangeClient client = new ReferenceCountExchangeClient(exchangeClient, DubboCodec.NAME); // read configs int shutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(url.getScopeModel()); client.setShutdownWaitTime(shutdownTimeout); return client; } /** * Create new connection * * @param url */ private ExchangeClient initClient(URL url) { /* * Instance of url is InstanceAddressURL, so addParameter actually adds parameters into ServiceInstance, * which means params are shared among different services. Since client is shared among services this is currently not a problem. */ String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT)); // BIO is not allowed since it has severe performance issue. if (StringUtils.isNotEmpty(str) && !url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .hasExtension(str)) { throw new RpcException("Unsupported client type: " + str + "," + " supported client type is " + StringUtils.join( url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .getSupportedExtensions(), " ")); } try { ScopeModel scopeModel = url.getScopeModel(); int heartbeat = UrlUtils.getHeartbeat(url); // Replace InstanceAddressURL with ServiceConfigURL. url = new ServiceConfigURL( DubboCodec.NAME, url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), url.getAllParameters()); url = url.addParameter(CODEC_KEY, DubboCodec.NAME); // enable heartbeat by default url = url.addParameterIfAbsent(HEARTBEAT_KEY, Integer.toString(heartbeat)); url = url.setScopeModel(scopeModel); // connection should be lazy return url.getParameter(LAZY_CONNECT_KEY, false) ? new LazyConnectExchangeClient(url, requestHandler) : Exchangers.connect(url, requestHandler); } catch (RemotingException e) { throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e); } } @Override @SuppressWarnings("unchecked") public void destroy() { if (!destroyed.compareAndSet(false, true)) { return; } if (logger.isInfoEnabled()) { logger.info("Destroying protocol [" + this.getClass().getSimpleName() + "] ..."); } for (String key : new ArrayList<>(serverMap.keySet())) { ProtocolServer protocolServer = serverMap.remove(key); if (protocolServer == null) { continue; } RemotingServer server = protocolServer.getRemotingServer(); try { if (logger.isInfoEnabled()) { logger.info("Closing dubbo server: " + server.getLocalAddress()); } server.close(ConfigurationUtils.reCalShutdownTime(getServerShutdownTimeout(protocolServer))); } catch (Throwable t) { logger.warn( PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Close dubbo server [" + server.getLocalAddress() + "] failed: " + t.getMessage(), t); } } serverMap.clear(); for (String key : new ArrayList<>(referenceClientMap.keySet())) { SharedClientsProvider clients = referenceClientMap.remove(key); clients.forceClose(); } PortUnificationExchanger.close(); referenceClientMap.clear(); super.destroy(); } /** * only log body in debugger mode for size & security consideration. * * @param invocation * @return */ private Invocation getInvocationWithoutData(Invocation invocation) { if (logger.isDebugEnabled()) { return invocation; } if (invocation instanceof RpcInvocation) { RpcInvocation rpcInvocation = (RpcInvocation) invocation; rpcInvocation.setArguments(null); return rpcInvocation; } return invocation; } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolServer.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.ProtocolServer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DubboProtocolServer implements ProtocolServer { private final RemotingServer server; private String address; private final Map<String, Object> attributes = new ConcurrentHashMap<>(); public DubboProtocolServer(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 reset(URL url) { server.reset(url); } @Override public void close() { server.close(); } @Override public Map<String, Object> getAttributes() { return attributes; } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.common.utils.AtomicPositiveInteger; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; 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.protocol.AbstractInvoker; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; 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.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * DubboInvoker */ public class DubboInvoker<T> extends AbstractInvoker<T> { private final ClientsProvider clientsProvider; private final AtomicPositiveInteger index = new AtomicPositiveInteger(); private final ReentrantLock destroyLock = new ReentrantLock(); private final Set<Invoker<?>> invokers; private final int serverShutdownTimeout; private static final boolean setFutureWhenSync = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty( CommonConstants.ThirdPartyProperty.SET_FUTURE_IN_SYNC_MODE, "true")); public DubboInvoker(Class<T> serviceType, URL url, ClientsProvider clientsProvider) { this(serviceType, url, clientsProvider, null); } public DubboInvoker(Class<T> serviceType, URL url, ClientsProvider clientsProvider, Set<Invoker<?>> invokers) { super(serviceType, url, new String[] {INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); this.clientsProvider = clientsProvider; this.invokers = invokers; this.serverShutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(getUrl().getScopeModel()); } @Override protected Result doInvoke(final Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; final String methodName = RpcUtils.getMethodName(invocation); inv.setAttachment(PATH_KEY, getUrl().getPath()); inv.setAttachment(VERSION_KEY, version); ExchangeClient currentClient; List<? extends ExchangeClient> exchangeClients = clientsProvider.getClients(); if (exchangeClients.size() == 1) { currentClient = exchangeClients.get(0); } else { currentClient = exchangeClients.get(index.getAndIncrement() % exchangeClients.size()); } RpcContext.getServiceContext().setLocalAddress(currentClient.getLocalAddress()); try { boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); int timeout = RpcUtils.calculateTimeout(getUrl(), invocation, methodName, 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)); Integer payload = getUrl().getParameter(PAYLOAD, Integer.class); Request request = new Request(); if (payload != null) { request.setPayload(payload); } request.setData(inv); request.setVersion(Version.getProtocolVersion()); if (isOneway) { boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); request.setTwoWay(false); currentClient.send(request, isSent); return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { request.setTwoWay(true); ExecutorService executor = getCallbackExecutor(getUrl(), inv); CompletableFuture<AppResponse> appResponseFuture = currentClient.request(request, timeout, executor).thenApply(AppResponse.class::cast); // 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, inv); result.setExecutor(executor); return result; } } catch (TimeoutException e) { throw new RpcException( RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + RpcUtils.getMethodName(invocation) + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (RemotingException e) { String remoteExpMsg = "Failed to invoke remote method: " + RpcUtils.getMethodName(invocation) + ", provider: " + getUrl() + ", cause: " + e.getMessage(); if (e.getCause() instanceof IOException && e.getCause().getCause() instanceof SerializationException) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, remoteExpMsg, e); } else { throw new RpcException(RpcException.NETWORK_EXCEPTION, remoteExpMsg, e); } } } @Override public boolean isAvailable() { if (!super.isAvailable()) { return false; } for (ExchangeClient client : clientsProvider.getClients()) { if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { // cannot write == not Available ? return true; } } return false; } @Override public void destroy() { // in order to avoid closing a client multiple times, a counter is used in case of connection per jvm, every // time when client.close() is called, counter counts down once, and when counter reaches zero, client will be // closed. if (!super.isDestroyed()) { // double check to avoid dup close destroyLock.lock(); try { if (super.isDestroyed()) { return; } super.destroy(); if (invokers != null) { invokers.remove(this); } clientsProvider.close(ConfigurationUtils.reCalShutdownTime(serverShutdownTimeout)); } finally { destroyLock.unlock(); } } } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.extension.SPI; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.rpc.Invocation; import java.io.InputStream; import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK; /** * Extension of Byte Accessor, holding attributes as RpcInvocation objects * so that the decoded service can be used more flexibly * @since 3.2.0 */ @SPI(scope = FRAMEWORK) public interface ByteAccessor { /** * Get an enhanced DecodeableRpcInvocation subclass to allow custom decode. * The parameters are the same as {@link DecodeableRpcInvocation} */ DecodeableRpcInvocation getRpcInvocation(Channel channel, Request req, InputStream is, byte proto); /** * Get an enhanced DecodeableRpcResult subclass to allow custom decode. * The parameters are the same as {@link DecodeableRpcResult} */ DecodeableRpcResult getRpcResult(Channel channel, Response res, InputStream is, Invocation invocation, byte proto); }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.executor.AbstractIsolationExecutorSupport; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceModel; public class DubboIsolationExecutorSupport extends AbstractIsolationExecutorSupport { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboIsolationExecutorSupport.class); private final FrameworkServiceRepository frameworkServiceRepository; private final DubboProtocol dubboProtocol; public DubboIsolationExecutorSupport(URL url) { super(url); frameworkServiceRepository = url.getOrDefaultFrameworkModel().getServiceRepository(); dubboProtocol = DubboProtocol.getDubboProtocol(url.getOrDefaultFrameworkModel()); } @Override protected ProviderModel getProviderModel(Object data) { if (!(data instanceof Request)) { return null; } Request request = (Request) data; if (!(request.getData() instanceof DecodeableRpcInvocation)) { return null; } try { ((DecodeableRpcInvocation) request.getData()).fillInvoker(dubboProtocol); } catch (RemotingException e) { // ignore here, and this exception will being rethrow in DubboProtocol } ServiceModel serviceModel = ((Invocation) request.getData()).getServiceModel(); if (serviceModel instanceof ProviderModel) { return (ProviderModel) serviceModel; } String targetServiceUniqueName = ((Invocation) request.getData()).getTargetServiceUniqueName(); if (StringUtils.isNotEmpty(targetServiceUniqueName)) { return frameworkServiceRepository.lookupExportedService(targetServiceUniqueName); } 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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Version; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; 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.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.HeartBeatRequest; import org.apache.dubbo.remoting.exchange.HeartBeatResponse; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.codec.ExchangeCodec; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_BYTE_ACCESSOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_DECODE_IN_IO_THREAD; /** * Dubbo codec. */ public class DubboCodec extends ExchangeCodec { public static final String NAME = "dubbo"; public static final String DUBBO_VERSION = Version.getProtocolVersion(); public static final byte RESPONSE_WITH_EXCEPTION = 0; public static final byte RESPONSE_VALUE = 1; public static final byte RESPONSE_NULL_VALUE = 2; public static final byte RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS = 3; public static final byte RESPONSE_VALUE_WITH_ATTACHMENTS = 4; public static final byte RESPONSE_NULL_VALUE_WITH_ATTACHMENTS = 5; public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DubboCodec.class); private static final AtomicBoolean decodeInUserThreadLogged = new AtomicBoolean(false); private final CallbackServiceCodec callbackServiceCodec; private final FrameworkModel frameworkModel; private final ByteAccessor customByteAccessor; private static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io.thread"; public DubboCodec(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; callbackServiceCodec = new CallbackServiceCodec(frameworkModel); customByteAccessor = Optional.ofNullable(SystemPropertyConfigUtils.getSystemProperty(SYSTEM_BYTE_ACCESSOR_KEY)) .filter(StringUtils::isNotBlank) .map(key -> frameworkModel.getExtensionLoader(ByteAccessor.class).getExtension(key)) .orElse(null); } @Override protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } // get status. byte status = header[3]; res.setStatus(status); try { if (status == Response.OK) { Object data; if (res.isEvent()) { byte[] eventPayload = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat(eventPayload, proto)) { // heart beat response data is always null; data = null; } else { ObjectInput in = CodecSupport.deserialize( channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); data = decodeEventData(channel, in, eventPayload); } } else { DecodeableRpcResult result; Invocation inv = (Invocation) getRequestData(channel, res, id); if (channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD)) { if (customByteAccessor != null) { result = customByteAccessor.getRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } else { result = new DecodeableRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } result.decode(); } else { if (customByteAccessor != null) { result = customByteAccessor.getRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } else { result = new DecodeableRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } } data = result; } res.setResult(data); } else { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); res.setErrorMessage(in.readUTF()); } } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode response failed: " + t.getMessage(), t); } res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { // decode request. Request req; try { Object data; if ((flag & FLAG_EVENT) != 0) { byte[] eventPayload = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat(eventPayload, proto)) { // heart beat response data is always null; req = new HeartBeatRequest(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); ((HeartBeatRequest) req).setProto(proto); data = null; } else { req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); ObjectInput in = CodecSupport.deserialize( channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); data = decodeEventData(channel, in, eventPayload); } req.setEvent(true); } else { req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); // get data length. int len = Bytes.bytes2int(header, 12); req.setPayload(len); DecodeableRpcInvocation inv; if (isDecodeDataInIoThread(channel)) { if (customByteAccessor != null) { inv = customByteAccessor.getRpcInvocation( channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } else { inv = new DecodeableRpcInvocation( frameworkModel, channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } inv.decode(); } else { if (customByteAccessor != null) { inv = customByteAccessor.getRpcInvocation( channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } else { inv = new DecodeableRpcInvocation( frameworkModel, channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } } data = inv; } req.setData(data); } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode request failed: " + t.getMessage(), t); } // bad request req = new HeartBeatRequest(id); req.setBroken(true); req.setData(t); } return req; } } private boolean isDecodeDataInIoThread(Channel channel) { Object obj = channel.getAttribute(DECODE_IN_IO_THREAD_KEY); if (obj instanceof Boolean) { return (Boolean) obj; } String mode = ExecutorRepository.getMode(channel.getUrl().getOrDefaultApplicationModel()); boolean isIsolated = EXECUTOR_MANAGEMENT_MODE_ISOLATION.equals(mode); if (isIsolated && !decodeInUserThreadLogged.compareAndSet(false, true)) { channel.setAttribute(DECODE_IN_IO_THREAD_KEY, true); return true; } boolean decodeDataInIoThread = channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD); if (isIsolated && !decodeDataInIoThread) { log.info("Because thread pool isolation is enabled on the dubbo protocol, the body can only be decoded " + "on the io thread, and the parameter[" + DECODE_IN_IO_THREAD_KEY + "] will be ignored"); // Why? because obtaining the isolated thread pool requires the serviceKey of the service, // and this part must be decoded before it can be obtained (more see DubboExecutorSupport) channel.setAttribute(DECODE_IN_IO_THREAD_KEY, true); return true; } channel.setAttribute(DECODE_IN_IO_THREAD_KEY, decodeDataInIoThread); return decodeDataInIoThread; } private byte[] readMessageData(InputStream is) throws IOException { if (is.available() > 0) { byte[] result = new byte[is.available()]; is.read(result); return result; } return new byte[] {}; } @Override protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data, DUBBO_VERSION); } @Override protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeResponseData(channel, out, data, DUBBO_VERSION); } @Override protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { RpcInvocation inv = (RpcInvocation) data; out.writeUTF(version); // https://github.com/apache/dubbo/issues/6138 String serviceName = inv.getAttachment(INTERFACE_KEY); if (serviceName == null) { serviceName = inv.getAttachment(PATH_KEY); } out.writeUTF(serviceName); out.writeUTF(inv.getAttachment(VERSION_KEY)); out.writeUTF(inv.getMethodName()); out.writeUTF(inv.getParameterTypesDesc()); Object[] args = inv.getArguments(); if (args != null) { for (int i = 0; i < args.length; i++) { out.writeObject(callbackServiceCodec.encodeInvocationArgument(channel, inv, i)); } } out.writeAttachments(inv.getObjectAttachments()); } @Override protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { Result result = (Result) data; // currently, the version value in Response records the version of Request boolean attach = Version.isSupportResponseAttachment(version); Throwable th = result.getException(); if (th == null) { Object ret = result.getValue(); if (ret == null) { out.writeByte(attach ? RESPONSE_NULL_VALUE_WITH_ATTACHMENTS : RESPONSE_NULL_VALUE); } else { out.writeByte(attach ? RESPONSE_VALUE_WITH_ATTACHMENTS : RESPONSE_VALUE); out.writeObject(ret); } } else { out.writeByte(attach ? RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS : RESPONSE_WITH_EXCEPTION); out.writeThrowable(th); } if (attach) { // returns current version of Response to consumer side. result.getObjectAttachments().put(DUBBO_VERSION_KEY, Version.getProtocolVersion()); out.writeAttachments(result.getObjectAttachments()); } } @Override protected Serialization getSerialization(Channel channel, Request req) { if (!(req.getData() instanceof Invocation)) { return super.getSerialization(channel, req); } return DubboCodecSupport.getRequestSerialization(channel.getUrl(), (Invocation) req.getData()); } @Override protected Serialization getSerialization(Channel channel, Response res) { if (res instanceof HeartBeatResponse) { return CodecSupport.getSerializationById(((HeartBeatResponse) res).getProto()); } if (!(res.getResult() instanceof AppResponse)) { return super.getSerialization(channel, res); } return DubboCodecSupport.getResponseSerialization(channel.getUrl(), (AppResponse) res.getResult()); } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import static org.apache.dubbo.rpc.Constants.INPUT_KEY; import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; public final class DubboCountCodec implements Codec2 { private final DubboCodec codec; public DubboCountCodec(FrameworkModel frameworkModel) { codec = new DubboCodec(frameworkModel); } @Override public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException { if (msg instanceof MultiMessage) { MultiMessage multiMessage = (MultiMessage) msg; for (Object singleMessage : multiMessage) { codec.encode(channel, buffer, singleMessage); } } else { codec.encode(channel, buffer, msg); } } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int save = buffer.readerIndex(); MultiMessage result = MultiMessage.create(); do { Object obj = codec.decode(channel, buffer); if (Codec2.DecodeResult.NEED_MORE_INPUT == obj) { buffer.readerIndex(save); break; } else { result.addMessage(obj); logMessageLength(obj, buffer.readerIndex() - save); save = buffer.readerIndex(); } } while (true); if (result.isEmpty()) { return Codec2.DecodeResult.NEED_MORE_INPUT; } if (result.size() == 1) { return result.get(0); } return result; } private void logMessageLength(Object result, int bytes) { if (bytes <= 0) { return; } if (result instanceof Request) { try { ((RpcInvocation) ((Request) result).getData()).setAttachment(INPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } } else if (result instanceof Response) { try { ((AppResponse) ((Response) result).getResult()).setAttachment(OUTPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } } } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.AbstractExporter; import java.util.Map; /** * DubboExporter */ public class DubboExporter<T> extends AbstractExporter<T> { private final String key; private final Map<String, Exporter<?>> exporterMap; public DubboExporter(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, this); } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.BaseServiceMetadata; import org.apache.dubbo.common.URL; 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.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; 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.support.RpcUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CALLBACK_INSTANCES; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; 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.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_LOAD_MODEL; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_PROXY_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CHANNEL_CALLBACK_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; /** * callback service helper */ public class CallbackServiceCodec { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CallbackServiceCodec.class); private static final byte CALLBACK_NONE = 0x0; private static final byte CALLBACK_CREATE = 0x1; private static final byte CALLBACK_DESTROY = 0x2; private static final String INV_ATT_CALLBACK_KEY = "sys_callback_arg-"; private final ProxyFactory proxyFactory; private final Protocol protocolSPI; private final FrameworkModel frameworkModel; private final DubboProtocol dubboProtocol; public CallbackServiceCodec(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; proxyFactory = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); protocolSPI = frameworkModel.getExtensionLoader(Protocol.class).getExtension(DUBBO_PROTOCOL); dubboProtocol = (DubboProtocol) frameworkModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); } private static byte isCallBack(URL url, String protocolServiceKey, String methodName, int argIndex) { // parameter callback rule: method-name.parameter-index(starting from 0).callback byte isCallback = CALLBACK_NONE; if (url != null && url.hasServiceMethodParameter(protocolServiceKey, methodName)) { String callback = url.getServiceParameter(protocolServiceKey, methodName + "." + argIndex + ".callback"); if (callback != null) { if ("true".equalsIgnoreCase(callback)) { isCallback = CALLBACK_CREATE; } else if ("false".equalsIgnoreCase(callback)) { isCallback = CALLBACK_DESTROY; } } } return isCallback; } /** * export or unexport callback service on client side * * @param channel * @param url * @param clazz * @param inst * @param export * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes"}) private String exportOrUnexportCallbackService( Channel channel, RpcInvocation inv, URL url, Class clazz, Object inst, Boolean export) throws IOException { int instid = System.identityHashCode(inst); Map<String, String> params = new HashMap<>(3); // no need to new client again params.put(IS_SERVER_KEY, Boolean.FALSE.toString()); // mark it's a callback, for troubleshooting params.put(IS_CALLBACK_SERVICE, Boolean.TRUE.toString()); String group = (inv == null ? null : (String) inv.getObjectAttachmentWithoutConvert(GROUP_KEY)); if (group != null && group.length() > 0) { params.put(GROUP_KEY, group); } // add method, for verifying against method, automatic fallback (see dubbo protocol) params.put(METHODS_KEY, StringUtils.join(ClassUtils.getDeclaredMethodNames(clazz), ",")); Map<String, String> tmpMap = new HashMap<>(); if (url != null) { Map<String, String> parameters = url.getParameters(); if (parameters != null && !parameters.isEmpty()) { tmpMap.putAll(parameters); } } tmpMap.putAll(params); tmpMap.remove(VERSION_KEY); // doesn't need to distinguish version for callback tmpMap.remove(Constants.BIND_PORT_KEY); // callback doesn't needs bind.port tmpMap.put(INTERFACE_KEY, clazz.getName()); URL exportUrl = new ServiceConfigURL( DubboProtocol.NAME, channel.getLocalAddress().getAddress().getHostAddress(), channel.getLocalAddress().getPort(), clazz.getName() + "." + instid, tmpMap); // no need to generate multiple exporters for different channel in the same JVM, cache key cannot collide. String cacheKey = getClientSideCallbackServiceCacheKey(instid); String countKey = getClientSideCountKey(clazz.getName()); if (export) { // one channel can have multiple callback instances, no need to re-export for different instance. if (!channel.hasAttribute(cacheKey)) { if (!isInstancesOverLimit(channel, url, clazz.getName(), instid, false)) { ModuleModel moduleModel; if (inv.getServiceModel() == null) { // TODO should get scope model from url? moduleModel = ApplicationModel.defaultModel().getDefaultModule(); logger.error( PROTOCOL_FAILED_LOAD_MODEL, "", "", "Unable to get Service Model from Invocation. Please check if your invocation failed! " + "This error only happen in UT cases! Invocation:" + inv); } else { moduleModel = inv.getServiceModel().getModuleModel(); } ServiceDescriptor serviceDescriptor = moduleModel.getServiceRepository().registerService(clazz); ServiceMetadata serviceMetadata = new ServiceMetadata( clazz.getName() + "." + instid, exportUrl.getGroup(), exportUrl.getVersion(), clazz); String serviceKey = BaseServiceMetadata.buildServiceKey(exportUrl.getPath(), group, exportUrl.getVersion()); ProviderModel providerModel = new ProviderModel( serviceKey, inst, serviceDescriptor, moduleModel, serviceMetadata, ClassUtils.getClassLoader(clazz)); moduleModel.getServiceRepository().registerProvider(providerModel); exportUrl = exportUrl.setScopeModel(moduleModel); exportUrl = exportUrl.setServiceModel(providerModel); Invoker<?> invoker = proxyFactory.getInvoker(inst, clazz, exportUrl); // should destroy resource? Exporter<?> exporter = protocolSPI.export(invoker); // this is used for tracing if instid has published service or not. channel.setAttribute(cacheKey, exporter); logger.info("Export a callback service :" + exportUrl + ", on " + channel + ", url is: " + url); increaseInstanceCount(channel, countKey); } } } else { if (channel.hasAttribute(cacheKey)) { Exporter<?> exporter = (Exporter<?>) channel.getAttribute(cacheKey); exporter.unexport(); channel.removeAttribute(cacheKey); decreaseInstanceCount(channel, countKey); } } return String.valueOf(instid); } /** * refer or destroy callback service on server side * * @param url */ @SuppressWarnings("unchecked") private Object referOrDestroyCallbackService( Channel channel, URL url, Class<?> clazz, Invocation inv, int instid, boolean isRefer) { Object proxy; String invokerCacheKey = getServerSideCallbackInvokerCacheKey(channel, clazz.getName(), instid); String proxyCacheKey = getServerSideCallbackServiceCacheKey(channel, clazz.getName(), instid); proxy = channel.getAttribute(proxyCacheKey); String countkey = getServerSideCountKey(channel, clazz.getName()); if (isRefer) { if (proxy == null) { URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + INTERFACE_KEY + "=" + clazz.getName()); referurl = referurl.addParametersIfAbsent(url.getParameters()) .removeParameter(METHODS_KEY) .addParameter(SIDE_KEY, CONSUMER_SIDE); if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) { url.getOrDefaultApplicationModel() .getDefaultModule() .getServiceRepository() .registerService(clazz); @SuppressWarnings("rawtypes") Invoker<?> invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); FilterChainBuilder builder = getFilterChainBuilder(url); invoker = builder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); invoker = builder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CALLBACK); proxy = proxyFactory.getProxy(invoker); channel.setAttribute(proxyCacheKey, proxy); channel.setAttribute(invokerCacheKey, invoker); increaseInstanceCount(channel, countkey); // convert error fail fast . // ignore concurrent problem. Set<Invoker<?>> callbackInvokers = (Set<Invoker<?>>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers == null) { callbackInvokers = new ConcurrentHashSet<>(1); channel.setAttribute(CHANNEL_CALLBACK_KEY, callbackInvokers); } callbackInvokers.add(invoker); logger.info("method " + RpcUtils.getMethodName(inv) + " include a callback service :" + invoker.getUrl() + ", a proxy :" + invoker + " has been created."); } } } else { if (proxy != null) { Invoker<?> invoker = (Invoker<?>) channel.getAttribute(invokerCacheKey); try { Set<Invoker<?>> callbackInvokers = (Set<Invoker<?>>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers != null) { callbackInvokers.remove(invoker); } invoker.destroy(); } catch (Exception e) { logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); } // cancel refer, directly remove from the map channel.removeAttribute(proxyCacheKey); channel.removeAttribute(invokerCacheKey); decreaseInstanceCount(channel, countkey); } } return proxy; } private FilterChainBuilder getFilterChainBuilder(URL url) { return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel()) .getDefaultExtension(); } private static String getClientSideCallbackServiceCacheKey(int instid) { return CALLBACK_SERVICE_KEY + "." + instid; } private static String getServerSideCallbackServiceCacheKey(Channel channel, String interfaceClass, int instid) { return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + instid; } private static String getServerSideCallbackInvokerCacheKey(Channel channel, String interfaceClass, int instid) { return getServerSideCallbackServiceCacheKey(channel, interfaceClass, instid) + "." + "invoker"; } private static String getClientSideCountKey(String interfaceClass) { return CALLBACK_SERVICE_KEY + "." + interfaceClass + ".COUNT"; } private static String getServerSideCountKey(Channel channel, String interfaceClass) { return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + ".COUNT"; } private static boolean isInstancesOverLimit( Channel channel, URL url, String interfaceClass, int instid, boolean isServer) { Integer count = (Integer) channel.getAttribute( isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass)); int limit = url.getParameter(CALLBACK_INSTANCES_LIMIT_KEY, DEFAULT_CALLBACK_INSTANCES); if (count != null && count >= limit) { // client side error throw new IllegalStateException("interface " + interfaceClass + " `s callback instances num exceed providers limit :" + limit + " ,current num: " + (count + 1) + ". The new callback service will not work !!! you can cancel the callback service which exported before. channel :" + channel); } else { return false; } } private static void increaseInstanceCount(Channel channel, String countkey) { try { // ignore concurrent problem? Integer count = (Integer) channel.getAttribute(countkey); if (count == null) { count = 1; } else { count++; } channel.setAttribute(countkey, count); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", e.getMessage(), e); } } private static void decreaseInstanceCount(Channel channel, String countkey) { try { Integer count = (Integer) channel.getAttribute(countkey); if (count == null || count <= 0) { return; } else { count--; } channel.setAttribute(countkey, count); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", e.getMessage(), e); } } public Object encodeInvocationArgument(Channel channel, RpcInvocation inv, int paraIndex) throws IOException { // get URL directly URL url = inv.getInvoker() == null ? null : inv.getInvoker().getUrl(); byte callbackStatus = isCallBack(url, inv.getProtocolServiceKey(), RpcUtils.getMethodName(inv), paraIndex); Object[] args = inv.getArguments(); Class<?>[] pts = inv.getParameterTypes(); switch (callbackStatus) { case CallbackServiceCodec.CALLBACK_CREATE: inv.setAttachment( INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], true)); return null; case CallbackServiceCodec.CALLBACK_DESTROY: inv.setAttachment( INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], false)); return null; default: return args[paraIndex]; } } public Object decodeInvocationArgument( Channel channel, RpcInvocation inv, Class<?>[] pts, int paraIndex, Object inObject) throws IOException { // if it's a callback, create proxy on client side, callback interface on client side can be invoked through // channel // need get URL from channel and env when decode URL url = null; try { url = dubboProtocol.getInvoker(channel, inv).getUrl(); } catch (RemotingException e) { if (logger.isInfoEnabled()) { logger.info(e.getMessage(), e); } return inObject; } byte callbackstatus = isCallBack(url, inv.getProtocolServiceKey(), RpcUtils.getMethodName(inv), paraIndex); switch (callbackstatus) { case CallbackServiceCodec.CALLBACK_CREATE: try { return referOrDestroyCallbackService( channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), true); } catch (Exception e) { logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); throw new IOException(StringUtils.toString(e)); } case CallbackServiceCodec.CALLBACK_DESTROY: try { return referOrDestroyCallbackService( channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), false); } catch (Exception e) { throw new IOException(StringUtils.toString(e)); } default: return inObject; } } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Parameters; 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.utils.NetUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.rpc.RpcException; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.remoting.Constants.SEND_RECONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_LAZY_REQUEST_WITH_WARNING; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WARNING_KEY; /** * dubbo protocol support class. */ @SuppressWarnings("deprecation") final class LazyConnectExchangeClient implements ExchangeClient { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LazyConnectExchangeClient.class); private final boolean requestWithWarning; private final URL url; private final ExchangeHandler requestHandler; private final Lock connectLock = new ReentrantLock(); private static final int warningPeriod = 5000; private final boolean needReconnect; private volatile ExchangeClient client; private final AtomicLong warningCount = new AtomicLong(0); public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { // lazy connect, need set send.reconnect = true, to avoid channel bad status. this.url = url.addParameter(LAZY_CONNECT_KEY, true); this.needReconnect = url.getParameter(SEND_RECONNECT_KEY, false); this.requestHandler = requestHandler; this.requestWithWarning = url.getParameter(LAZY_REQUEST_WITH_WARNING_KEY, DEFAULT_LAZY_REQUEST_WITH_WARNING); } private void initClient() throws RemotingException { if (client != null) { return; } if (logger.isInfoEnabled()) { logger.info("Lazy connect to " + url); } connectLock.lock(); try { if (client != null) { return; } this.client = Exchangers.connect(url, requestHandler); } finally { connectLock.unlock(); } } @Override public CompletableFuture<Object> request(Object request) throws RemotingException { warning(); checkClient(); return client.request(request); } @Override public URL getUrl() { return url; } @Override public InetSocketAddress getRemoteAddress() { if (client == null) { return InetSocketAddress.createUnresolved(url.getHost(), url.getPort()); } else { return client.getRemoteAddress(); } } @Override public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException { warning(); checkClient(); return client.request(request, timeout); } @Override public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException { warning(); checkClient(); return client.request(request, executor); } @Override public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException { warning(); checkClient(); return client.request(request, timeout, executor); } /** * If {@link Constants.LAZY_REQUEST_WITH_WARNING_KEY} is configured, then warn once every 5000 invocations. */ private void warning() { if (requestWithWarning) { if (warningCount.get() % warningPeriod == 0) { logger.warn( PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); } warningCount.incrementAndGet(); } } @Override public ChannelHandler getChannelHandler() { checkClient(); return client.getChannelHandler(); } @Override public boolean isConnected() { if (client == null) { // Before the request arrives, LazyConnectExchangeClient always exists in a normal connection state // to prevent ReconnectTask from initiating a reconnection action. return true; } else { return client.isConnected(); } } @Override public InetSocketAddress getLocalAddress() { if (client == null) { return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0); } else { return client.getLocalAddress(); } } @Override public ExchangeHandler getExchangeHandler() { return requestHandler; } @Override public void send(Object message) throws RemotingException { checkClient(); client.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { checkClient(); client.send(message, sent); } @Override public boolean isClosed() { if (client != null) { return client.isClosed(); } else { return false; } } @Override public void close() { if (client != null) { client.close(); client = null; } } @Override public void close(int timeout) { if (client != null) { client.close(timeout); client = null; } } @Override public void startClose() { if (client != null) { client.startClose(); } } @Override public void reset(URL url) { checkClient(); client.reset(url); } @Override @Deprecated public void reset(Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public void reconnect() throws RemotingException { checkClient(); client.reconnect(); } @Override public Object getAttribute(String key) { if (client == null) { return null; } else { return client.getAttribute(key); } } @Override public void setAttribute(String key, Object value) { checkClient(); client.setAttribute(key, value); } @Override public void removeAttribute(String key) { checkClient(); client.removeAttribute(key); } @Override public boolean hasAttribute(String key) { if (client == null) { return false; } else { return client.hasAttribute(key); } } private void checkClient() { try { initClient(); } catch (Exception e) { throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e); } if (!isConnected() && !needReconnect) { throw new IllegalStateException("LazyConnectExchangeClient is not connected normally, " + "and send.reconnect is configured as false, the request fails quickly" + 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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; import java.util.List; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class ExclusiveClientsProvider implements ClientsProvider { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExclusiveClientsProvider.class); private final List<ExchangeClient> clients; public ExclusiveClientsProvider(List<ExchangeClient> clients) { this.clients = clients; } @Override public List<ExchangeClient> getClients() { return clients; } @Override public void close(int timeout) { for (ExchangeClient client : clients) { try { client.close(timeout); } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CacheableSupplier; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.Map; import java.util.function.Supplier; import static org.apache.dubbo.common.BaseServiceMetadata.keyWithoutGroup; import static org.apache.dubbo.common.URL.buildKey; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SERIALIZATION_SECURITY_CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { protected static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class); protected final transient Channel channel; protected final byte serializationType; protected final transient InputStream inputStream; protected final transient Request request; protected volatile boolean hasDecoded; protected final FrameworkModel frameworkModel; protected final transient Supplier<CallbackServiceCodec> callbackServiceCodecFactory; private static final boolean CHECK_SERIALIZATION = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty(SERIALIZATION_SECURITY_CHECK_KEY, "true")); public DecodeableRpcInvocation( FrameworkModel frameworkModel, Channel channel, Request request, InputStream is, byte id) { this.frameworkModel = frameworkModel; Assert.notNull(channel, "channel == null"); Assert.notNull(request, "request == null"); Assert.notNull(is, "inputStream == null"); this.channel = channel; this.request = request; this.inputStream = is; this.serializationType = id; this.callbackServiceCodecFactory = CacheableSupplier.newSupplier(() -> new CallbackServiceCodec(frameworkModel)); } @Override public void decode() throws Exception { if (!hasDecoded && channel != null && inputStream != null) { try { decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc invocation failed: " + e.getMessage(), e); } request.setBroken(true); request.setData(e); } finally { hasDecoded = true; } } } @Override public void encode(Channel channel, OutputStream output, Object message) throws IOException { throw new UnsupportedOperationException(); } @Override public Object decode(Channel channel, InputStream input) throws IOException { int contentLength = input.available(); getAttributes().put(Constants.CONTENT_LENGTH_KEY, contentLength); Object sslSession = channel.getAttribute(Constants.SSL_SESSION_KEY); if (null != sslSession) { put(Constants.SSL_SESSION_KEY, sslSession); } ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input); this.put(SERIALIZATION_ID_KEY, serializationType); String dubboVersion = in.readUTF(); request.setVersion(dubboVersion); setAttachment(DUBBO_VERSION_KEY, dubboVersion); String path = in.readUTF(); setAttachment(PATH_KEY, path); String version = in.readUTF(); setAttachment(VERSION_KEY, version); // Do provider-level payload checks. String keyWithoutGroup = keyWithoutGroup(path, version); checkPayload(keyWithoutGroup); setMethodName(in.readUTF()); String desc = in.readUTF(); setParameterTypesDesc(desc); ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); try { if (CHECK_SERIALIZATION) { PermittedSerializationKeeper keeper = frameworkModel.getBeanFactory().getBean(PermittedSerializationKeeper.class); if (!keeper.checkSerializationPermitted(keyWithoutGroup, serializationType)) { throw new IOException("Unexpected serialization id:" + serializationType + " received from network, please check if the peer send the right id."); } } Object[] args = DubboCodec.EMPTY_OBJECT_ARRAY; Class<?>[] pts = DubboCodec.EMPTY_CLASS_ARRAY; if (desc.length() > 0) { pts = drawPts(path, version, desc, pts); if (pts == DubboCodec.EMPTY_CLASS_ARRAY) { if (RpcUtils.isGenericCall(desc, getMethodName())) { // Should recreate here for each invocation because the parameterTypes may be changed by user. pts = new Class<?>[] {String.class, String[].class, Object[].class}; } else if (RpcUtils.isEcho(desc, getMethodName())) { pts = new Class<?>[] {Object.class}; } else { throw new IllegalArgumentException("Service not found:" + path + ", " + getMethodName()); } } args = drawArgs(in, pts); } setParameterTypes(pts); Map<String, Object> map = in.readAttachments(); if (CollectionUtils.isNotEmptyMap(map)) { addObjectAttachments(map); } decodeArgument(channel, pts, args); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read invocation data failed.", e)); } finally { Thread.currentThread().setContextClassLoader(originClassLoader); if (in instanceof Cleanable) { ((Cleanable) in).cleanup(); } } return this; } protected void decodeArgument(Channel channel, Class<?>[] pts, Object[] args) throws IOException { CallbackServiceCodec callbackServiceCodec = callbackServiceCodecFactory.get(); for (int i = 0; i < args.length; i++) { args[i] = callbackServiceCodec.decodeInvocationArgument(channel, this, pts, i, args[i]); } setArguments(args); String targetServiceName = buildKey(getAttachment(PATH_KEY), getAttachment(GROUP_KEY), getAttachment(VERSION_KEY)); setTargetServiceUniqueName(targetServiceName); } protected Class<?>[] drawPts(String path, String version, String desc, Class<?>[] pts) { FrameworkServiceRepository repository = frameworkModel.getServiceRepository(); List<ProviderModel> providerModels = repository.lookupExportedServicesWithoutGroup(keyWithoutGroup(path, version)); ServiceDescriptor serviceDescriptor = null; if (CollectionUtils.isNotEmpty(providerModels)) { for (ProviderModel providerModel : providerModels) { serviceDescriptor = providerModel.getServiceModel(); if (serviceDescriptor != null) { break; } } } if (serviceDescriptor == null) { // Unable to find ProviderModel from Exported Services for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { for (ModuleModel moduleModel : applicationModel.getModuleModels()) { serviceDescriptor = moduleModel.getServiceRepository().lookupService(path); if (serviceDescriptor != null) { break; } } } } if (serviceDescriptor != null) { MethodDescriptor methodDescriptor = serviceDescriptor.getMethod(getMethodName(), desc); if (methodDescriptor != null) { pts = methodDescriptor.getParameterClasses(); this.setReturnTypes(methodDescriptor.getReturnTypes()); // switch TCCL if (CollectionUtils.isNotEmpty(providerModels)) { if (providerModels.size() == 1) { Thread.currentThread() .setContextClassLoader(providerModels.get(0).getClassLoader()); } else { // try all providerModels' classLoader can load pts, use the first one for (ProviderModel providerModel : providerModels) { ClassLoader classLoader = providerModel.getClassLoader(); boolean match = true; for (Class<?> pt : pts) { try { if (!pt.equals(classLoader.loadClass(pt.getName()))) { match = false; } } catch (ClassNotFoundException e) { match = false; } } if (match) { Thread.currentThread().setContextClassLoader(classLoader); break; } } } } } } return pts; } protected Object[] drawArgs(ObjectInput in, Class<?>[] pts) throws IOException, ClassNotFoundException { Object[] args; args = new Object[pts.length]; for (int i = 0; i < args.length; i++) { args[i] = in.readObject(pts[i]); } return args; } private void checkPayload(String serviceKey) throws IOException { ProviderModel providerModel = frameworkModel.getServiceRepository().lookupExportedServiceWithoutGroup(serviceKey); if (providerModel != null) { String payloadStr = (String) providerModel.getServiceMetadata().getAttachments().get(PAYLOAD); if (payloadStr != null) { int payload = Integer.parseInt(payloadStr); if (payload <= 0) { return; } if (request.getPayload() > payload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException("Data length too large: " + request.getPayload() + ", max payload: " + payload + ", channel: " + channel); log.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } } } protected void fillInvoker(DubboProtocol dubboProtocol) throws RemotingException { this.setInvoker(dubboProtocol.getInvoker(channel, this)); } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeClient; import org.apache.dubbo.remoting.transport.ClientDelegate; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.support.RpcUtils; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.remoting.Constants.SENT_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; /** * Server push uses this Invoker to continuously push data to client. * Wrap the existing invoker on the channel. */ class ChannelWrappedInvoker<T> extends AbstractInvoker<T> { private final Channel channel; private final String serviceKey; private final ExchangeClient currentClient; ChannelWrappedInvoker(Class<T> serviceType, Channel channel, URL url, String serviceKey) { super(serviceType, url, new String[] {GROUP_KEY, TOKEN_KEY}); this.channel = channel; this.serviceKey = serviceKey; this.currentClient = new HeaderExchangeClient(new ChannelWrapper(this.channel), false); } @Override @SuppressWarnings("deprecation") protected Result doInvoke(Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; // use interface's name as service path to export if it's not found on client side inv.setAttachment(PATH_KEY, getInterface().getName()); inv.setAttachment(CALLBACK_SERVICE_KEY, serviceKey); Integer payload = getUrl().getParameter(PAYLOAD, Integer.class); Request request = new Request(); if (payload != null) { request.setPayload(payload); } request.setData(inv); request.setVersion(Version.getProtocolVersion()); try { if (RpcUtils.isOneway(getUrl(), inv)) { // may have concurrency issue currentClient.send( request, getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), SENT_KEY, false)); return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { CompletableFuture<AppResponse> appResponseFuture = currentClient.request(request).thenApply(AppResponse.class::cast); return new AsyncRpcResult(appResponseFuture, inv); } } catch (RpcException e) { throw e; } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, e.getMessage(), e); } catch (RemotingException e) { throw new RpcException(RpcException.NETWORK_EXCEPTION, e.getMessage(), e); } catch (Throwable e) { // here is non-biz exception, wrap it. throw new RpcException(e.getMessage(), e); } } @Override public void destroy() { // super.destroy(); // try { // channel.close(); // } catch (Throwable t) { // logger.warn(t.getMessage(), t); // } } public static class ChannelWrapper extends ClientDelegate { private final Channel channel; private final URL url; ChannelWrapper(Channel channel) { this.channel = channel; this.url = channel.getUrl().addParameter("codec", DubboCodec.NAME); } @Override public URL getUrl() { return url; } @Override public ChannelHandler getChannelHandler() { return channel.getChannelHandler(); } @Override public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } @Override public void close() { channel.close(); } @Override public boolean isClosed() { return channel == null || channel.isClosed(); } @Override public void reset(URL url) { throw new RpcException("ChannelInvoker can not reset."); } @Override public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } @Override public boolean isConnected() { return channel != null && channel.isConnected(); } @Override public boolean hasAttribute(String key) { return channel.hasAttribute(key); } @Override public Object getAttribute(String key) { return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { channel.setAttribute(key, value); } @Override public void removeAttribute(String key) { channel.removeAttribute(key); } @Override public void reconnect() throws RemotingException {} @Override public void send(Object message) throws RemotingException { channel.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { channel.send(message, sent); } } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.List; import java.util.Objects; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class SharedClientsProvider implements ClientsProvider { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SharedClientsProvider.class); private final DubboProtocol dubboProtocol; private final String addressKey; private final List<ReferenceCountExchangeClient> clients; public SharedClientsProvider( DubboProtocol dubboProtocol, String addressKey, List<ReferenceCountExchangeClient> clients) { this.dubboProtocol = dubboProtocol; this.addressKey = addressKey; this.clients = clients; } @Override public List<ReferenceCountExchangeClient> getClients() { return clients; } public synchronized boolean increaseCount() { if (checkClientCanUse(clients)) { batchClientRefIncr(clients); return true; } return false; } @Override public synchronized void close(int timeout) { for (ReferenceCountExchangeClient client : clients) { try { client.close(timeout); } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } if (!checkClientCanUse(clients)) { dubboProtocol.scheduleRemoveSharedClient(addressKey, this); } } public synchronized void forceClose() { for (ReferenceCountExchangeClient client : clients) { closeReferenceCountExchangeClient(client); } } /** * Check if the client list is all available * * @param referenceCountExchangeClients * @return true-available,false-unavailable */ private boolean checkClientCanUse(List<ReferenceCountExchangeClient> referenceCountExchangeClients) { if (CollectionUtils.isEmpty(referenceCountExchangeClients)) { return false; } // As long as one client is not available, you need to replace the unavailable client with the available one. return referenceCountExchangeClients.stream() .noneMatch(referenceCountExchangeClient -> referenceCountExchangeClient == null || referenceCountExchangeClient.getCount() <= 0 || referenceCountExchangeClient.isClosed()); } /** * Increase the reference Count if we create new invoker shares same connection, the connection will be closed without any reference. * * @param referenceCountExchangeClients */ private void batchClientRefIncr(List<ReferenceCountExchangeClient> referenceCountExchangeClients) { if (CollectionUtils.isEmpty(referenceCountExchangeClients)) { return; } referenceCountExchangeClients.stream() .filter(Objects::nonNull) .forEach(ReferenceCountExchangeClient::incrementAndGetCount); } /** * close ReferenceCountExchangeClient * * @param client */ private void closeReferenceCountExchangeClient(ReferenceCountExchangeClient client) { if (client == null) { return; } try { if (logger.isInfoEnabled()) { logger.info("Close dubbo connect: " + client.getLocalAddress() + "-->" + client.getRemoteAddress()); } client.close(ConfigurationUtils.reCalShutdownTime(client.getShutdownWaitTime())); // TODO /* * At this time, ReferenceCountExchangeClient#client has been replaced with LazyConnectExchangeClient. * Do you need to call client.close again to ensure that LazyConnectExchangeClient is also closed? */ } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ClientsProvider.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ClientsProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.remoting.exchange.ExchangeClient; import java.util.List; public interface ClientsProvider { List<? extends ExchangeClient> getClients(); void close(int timeout); }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.config.Configuration; 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.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SERIALIZATION_SECURITY_CHECK_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; public class DecodeableRpcResult extends AppResponse implements Codec, Decodeable { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcResult.class); private final Channel channel; private final byte serializationType; private final InputStream inputStream; private final Response response; private final Invocation invocation; private volatile boolean hasDecoded; public DecodeableRpcResult(Channel channel, Response response, InputStream is, Invocation invocation, byte id) { Assert.notNull(channel, "channel == null"); Assert.notNull(response, "response == null"); Assert.notNull(is, "inputStream == null"); this.channel = channel; this.response = response; this.inputStream = is; this.invocation = invocation; this.serializationType = id; } @Override public void encode(Channel channel, OutputStream output, Object message) throws IOException { throw new UnsupportedOperationException(); } @Override public Object decode(Channel channel, InputStream input) throws IOException { if (log.isDebugEnabled()) { Thread thread = Thread.currentThread(); log.debug("Decoding in thread -- [" + thread.getName() + "#" + thread.getId() + "]"); } int contentLength = input.available(); setAttribute(Constants.CONTENT_LENGTH_KEY, contentLength); // switch TCCL if (invocation != null && invocation.getServiceModel() != null) { Thread.currentThread() .setContextClassLoader(invocation.getServiceModel().getClassLoader()); } ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input); byte flag = in.readByte(); switch (flag) { case DubboCodec.RESPONSE_NULL_VALUE: break; case DubboCodec.RESPONSE_VALUE: handleValue(in); break; case DubboCodec.RESPONSE_WITH_EXCEPTION: handleException(in); break; case DubboCodec.RESPONSE_NULL_VALUE_WITH_ATTACHMENTS: handleAttachment(in); break; case DubboCodec.RESPONSE_VALUE_WITH_ATTACHMENTS: handleValue(in); handleAttachment(in); break; case DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS: handleException(in); handleAttachment(in); break; default: throw new IOException("Unknown result flag, expect '0' '1' '2' '3' '4' '5', but received: " + flag); } if (in instanceof Cleanable) { ((Cleanable) in).cleanup(); } return this; } @Override public void decode() throws Exception { if (!hasDecoded && channel != null && inputStream != null) { try { if (invocation != null) { Configuration systemConfiguration = null; try { systemConfiguration = ConfigurationUtils.getSystemConfiguration( channel.getUrl().getScopeModel()); } catch (Exception e) { // Because the Environment may be destroyed during the offline process, the configuration cannot // be obtained. // Exceptions are ignored here, and normal decoding is guaranteed. } if (systemConfiguration == null || systemConfiguration.getBoolean(SERIALIZATION_SECURITY_CHECK_KEY, true)) { Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { if ((byte) serializationTypeObj != serializationType) { throw new IOException("Unexpected serialization id:" + serializationType + " received from network, please check if the peer send the right id."); } } } } decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc result failed: " + e.getMessage(), e); } response.setStatus(Response.CLIENT_ERROR); response.setErrorMessage(StringUtils.toString(e)); } finally { hasDecoded = true; } } } private void handleValue(ObjectInput in) throws IOException { try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value; if (ArrayUtils.isEmpty(returnTypes)) { // happens when generic invoke or void return value = in.readObject(); } else if (returnTypes.length == 1) { value = in.readObject((Class<?>) returnTypes[0]); } else { value = in.readObject((Class<?>) returnTypes[0], returnTypes[1]); } setValue(value); } catch (ClassNotFoundException e) { rethrow(e); } } private void handleException(ObjectInput in) throws IOException { try { setException(in.readThrowable()); } catch (ClassNotFoundException e) { rethrow(e); } } private void handleAttachment(ObjectInput in) throws IOException { try { addObjectAttachments(in.readAttachments()); } catch (ClassNotFoundException e) { rethrow(e); } } private void rethrow(Exception e) throws IOException { throw new IOException(StringUtils.toString("Read response data failed.", 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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public interface Constants { String SHARE_CONNECTIONS_KEY = "shareconnections"; /** * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. */ String DEFAULT_SHARE_CONNECTIONS = "1"; String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; boolean DEFAULT_DECODE_IN_IO_THREAD = false; /** * callback inst id */ String CALLBACK_SERVICE_KEY = "callback.service.instid"; String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; String IS_CALLBACK_SERVICE = "is_callback_service"; /** * Invokers in channel's callback */ String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; /** * when this warning rises from invocation, program probably have a bug. */ String LAZY_REQUEST_WITH_WARNING_KEY = "lazyclient_request_with_warning"; boolean DEFAULT_LAZY_REQUEST_WITH_WARNING = false; String ON_CONNECT_KEY = "onconnect"; String ON_DISCONNECT_KEY = "ondisconnect"; String ASYNC_METHOD_INFO = "async-method-info"; }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Filter; 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 org.apache.dubbo.rpc.support.RpcUtils; import java.util.ArrayList; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; @Activate(group = CommonConstants.PROVIDER) public class TraceFilter implements Filter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TraceFilter.class); private static final String TRACE_MAX = "trace.max"; private static final String TRACE_COUNT = "trace.count"; private static final ConcurrentMap<String, Set<Channel>> TRACERS = new ConcurrentHashMap<>(); public static void addTracer(Class<?> type, String method, Channel channel, int max) { channel.setAttribute(TRACE_MAX, max); channel.setAttribute(TRACE_COUNT, new AtomicInteger()); String key = StringUtils.isNotEmpty(method) ? type.getName() + "." + method : type.getName(); Set<Channel> channels = ConcurrentHashMapUtils.computeIfAbsent(TRACERS, key, k -> new ConcurrentHashSet<>()); channels.add(channel); } public static void removeTracer(Class<?> type, String method, Channel channel) { channel.removeAttribute(TRACE_MAX); channel.removeAttribute(TRACE_COUNT); String key = StringUtils.isNotEmpty(method) ? type.getName() + "." + method : type.getName(); Set<Channel> channels = TRACERS.get(key); if (channels != null) { channels.remove(channel); } } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { long start = System.currentTimeMillis(); Result result = invoker.invoke(invocation); long end = System.currentTimeMillis(); if (TRACERS.size() > 0) { String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation); Set<Channel> channels = TRACERS.get(key); if (CollectionUtils.isEmpty(channels)) { key = invoker.getInterface().getName(); channels = TRACERS.get(key); } if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : new ArrayList<>(channels)) { if (channel.isConnected()) { try { int max = 1; Integer m = (Integer) channel.getAttribute(TRACE_MAX); if (m != null) { max = m; } int count; AtomicInteger c = (AtomicInteger) channel.getAttribute(TRACE_COUNT); if (c == null) { c = new AtomicInteger(); channel.setAttribute(TRACE_COUNT, c); } count = c.getAndIncrement(); if (count < max) { String prompt = channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); channel.send( "\r\n" + RpcContext.getServiceContext().getRemoteAddress() + " -> " + invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation) + "(" + JsonUtils.toJson(invocation.getArguments()) + ")" + " -> " + JsonUtils.toJson(result.getValue()) + "\r\nelapsed: " + (end - start) + " ms." + "\r\n\r\n" + prompt); } if (count >= max - 1) { channels.remove(channel); } } catch (Throwable e) { channels.remove(channel); logger.warn(PROTOCOL_FAILED_PARSE, "", "", e.getMessage(), e); } } else { channels.remove(channel); } } } } return result; } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.pu; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import java.nio.ByteBuffer; import static java.lang.Math.min; public class DubboDetector implements ProtocolDetector { private final ChannelBuffer Preface = new ByteBufferBackedChannelBuffer(ByteBuffer.wrap(new byte[] {(byte) 0xda, (byte) 0xbb})); @Override public Result detect(ChannelBuffer in) { int prefaceLen = Preface.readableBytes(); int bytesRead = min(in.readableBytes(), prefaceLen); if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, Preface, bytesRead)) { return Result.unrecognized(); } if (bytesRead == prefaceLen) { return Result.recognized(); } return Result.needMoreData(); } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.pu; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.api.AbstractWireProtocol; import org.apache.dubbo.remoting.api.pu.ChannelOperator; import java.util.ArrayList; import java.util.List; @Activate public class DubboWireProtocol extends AbstractWireProtocol { public DubboWireProtocol() { super(new DubboDetector()); } @Override public void configServerProtocolHandler(URL url, ChannelOperator operator) { List<ChannelHandler> handlers = new ArrayList<>(); // operator(for now nettyOperator)'s duties // 1. config codec2 for the protocol(load by extension loader) // 2. config handlers passed by wire protocol // ( for triple, some h2 netty handler and logic handler to handle connection; // for dubbo, nothing, an empty handlers is used to trigger operator logic) // 3. config Dubbo Inner handler(for dubbo protocol, this handler handles connection) operator.configChannelHandler(handlers); } }
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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; @Activate public class ThreadPoolStatusChecker implements StatusChecker { private final ApplicationModel applicationModel; public ThreadPoolStatusChecker(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @Override public Status check() { DataStore dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); Map<String, Object> executors = dataStore.get(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY); StringBuilder msg = new StringBuilder(); Status.Level level = Status.Level.OK; for (Map.Entry<String, Object> entry : executors.entrySet()) { String port = entry.getKey(); ExecutorService executor = (ExecutorService) entry.getValue(); if (executor instanceof ThreadPoolExecutor) { ThreadPoolExecutor tp = (ThreadPoolExecutor) executor; boolean ok = tp.getActiveCount() < tp.getMaximumPoolSize() - 1; Status.Level lvl = Status.Level.OK; if (!ok) { level = Status.Level.WARN; lvl = Status.Level.WARN; } if (msg.length() > 0) { msg.append(';'); } msg.append("Pool status:") .append(lvl) .append(", max:") .append(tp.getMaximumPoolSize()) .append(", core:") .append(tp.getCorePoolSize()) .append(", largest:") .append(tp.getLargestPoolSize()) .append(", active:") .append(tp.getActiveCount()) .append(", task:") .append(tp.getTaskCount()) .append(", service port: ") .append(port); } } return msg.length() == 0 ? new Status(Status.Level.UNKNOWN) : new Status(level, msg.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-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java
dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import java.util.List; @Activate public class ServerStatusChecker implements StatusChecker { @Override public Status check() { List<ProtocolServer> servers = DubboProtocol.getDubboProtocol().getServers(); if (servers == null || servers.isEmpty()) { return new Status(Status.Level.UNKNOWN); } Status.Level level = Status.Level.OK; StringBuilder buf = new StringBuilder(); for (ProtocolServer protocolServer : servers) { RemotingServer server = protocolServer.getRemotingServer(); if (!server.isBound()) { level = Status.Level.ERROR; buf.setLength(0); buf.append(server.getLocalAddress()); break; } if (buf.length() > 0) { buf.append(','); } buf.append(server.getLocalAddress()); buf.append("(clients:"); buf.append(server.getChannels().size()); buf.append(')'); } return new Status(level, buf.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/test/java/org/apache/dubbo/rpc/RpcStatusTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.support.DemoService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link RpcStatus} */ class RpcStatusTest { @Test void testBeginCountEndCount() { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91031, DemoService.class.getName()); String methodName = "testBeginCountEndCount"; int max = 2; RpcStatus.removeStatus(url); RpcStatus.removeStatus(url, methodName); boolean flag = RpcStatus.beginCount(url, methodName, max); RpcStatus urlRpcStatus = RpcStatus.getStatus(url); RpcStatus methodRpcStatus = RpcStatus.getStatus(url, methodName); Assertions.assertTrue(flag); Assertions.assertNotNull(urlRpcStatus); Assertions.assertNotNull(methodRpcStatus); Assertions.assertEquals(urlRpcStatus.getActive(), 1); Assertions.assertEquals(methodRpcStatus.getActive(), 1); RpcStatus.endCount(url, methodName, 1000, true); Assertions.assertEquals(urlRpcStatus.getActive(), 0); Assertions.assertEquals(methodRpcStatus.getActive(), 0); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertTrue(flag); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertTrue(flag); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertFalse(flag); } @Test void testBeginCountEndCountInMultiThread() throws Exception { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91032, DemoService.class.getName()); String methodName = "testBeginCountEndCountInMultiThread"; RpcStatus.removeStatus(url); RpcStatus.removeStatus(url, methodName); int max = 50; int threadNum = 10; AtomicInteger successCount = new AtomicInteger(); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch endLatch = new CountDownLatch(threadNum); List<Thread> threadList = new ArrayList<>(threadNum); for (int i = 0; i < threadNum; i++) { Thread thread = new Thread(() -> { try { startLatch.await(); for (int j = 0; j < 100; j++) { boolean flag = RpcStatus.beginCount(url, methodName, max); if (flag) { successCount.incrementAndGet(); } } endLatch.countDown(); } catch (Exception e) { // ignore } }); threadList.add(thread); } threadList.forEach(Thread::start); startLatch.countDown(); endLatch.await(); Assertions.assertEquals(successCount.get(), max); } @Test void testStatistics() { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91033, DemoService.class.getName()); String methodName = "testStatistics"; int max = 0; RpcStatus.removeStatus(url); RpcStatus.removeStatus(url, methodName); RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.endCount(url, methodName, 1000, true); RpcStatus.endCount(url, methodName, 2000, true); RpcStatus.endCount(url, methodName, 3000, false); RpcStatus.endCount(url, methodName, 4000, false); RpcStatus urlRpcStatus = RpcStatus.getStatus(url); RpcStatus methodRpcStatus = RpcStatus.getStatus(url, methodName); for (RpcStatus rpcStatus : Arrays.asList(urlRpcStatus, methodRpcStatus)) { Assertions.assertEquals(rpcStatus.getActive(), 0); Assertions.assertEquals(rpcStatus.getTotal(), 4); Assertions.assertEquals(rpcStatus.getTotalElapsed(), 10000); Assertions.assertEquals(rpcStatus.getMaxElapsed(), 4000); Assertions.assertEquals(rpcStatus.getAverageElapsed(), 2500); Assertions.assertEquals(rpcStatus.getAverageTps(), 0); Assertions.assertEquals(rpcStatus.getSucceeded(), 2); Assertions.assertEquals(rpcStatus.getSucceededElapsed(), 3000); Assertions.assertEquals(rpcStatus.getSucceededMaxElapsed(), 2000); Assertions.assertEquals(rpcStatus.getSucceededAverageElapsed(), 1500); Assertions.assertEquals(rpcStatus.getFailed(), 2); Assertions.assertEquals(rpcStatus.getFailedElapsed(), 7000); Assertions.assertEquals(rpcStatus.getFailedMaxElapsed(), 4000); Assertions.assertEquals(rpcStatus.getFailedAverageElapsed(), 3500); } } }
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/test/java/org/apache/dubbo/rpc/DemoRequest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/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; 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-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RpcContextTest { @Test void testGetContext() { RpcContext rpcContext = RpcContext.getClientAttachment(); Assertions.assertNotNull(rpcContext); RpcContext.removeClientAttachment(); // if null, will return the initialize value. // Assertions.assertNull(RpcContext.getContext()); Assertions.assertNotNull(RpcContext.getClientAttachment()); Assertions.assertNotEquals(rpcContext, RpcContext.getClientAttachment()); RpcContext serverRpcContext = RpcContext.getServerContext(); Assertions.assertNotNull(serverRpcContext); RpcContext.removeServerContext(); Assertions.assertNotEquals(serverRpcContext, RpcContext.getServerContext()); } @Test void testAddress() { RpcContext context = RpcContext.getServiceContext(); context.setLocalAddress("127.0.0.1", 20880); Assertions.assertEquals(20880, context.getLocalAddress().getPort()); Assertions.assertEquals("127.0.0.1:20880", context.getLocalAddressString()); context.setRemoteAddress("127.0.0.1", 20880); Assertions.assertEquals(20880, context.getRemoteAddress().getPort()); Assertions.assertEquals("127.0.0.1:20880", context.getRemoteAddressString()); context.setRemoteAddress("127.0.0.1", -1); context.setLocalAddress("127.0.0.1", -1); Assertions.assertEquals(0, context.getRemoteAddress().getPort()); Assertions.assertEquals(0, context.getLocalAddress().getPort()); Assertions.assertEquals("127.0.0.1", context.getRemoteHostName()); Assertions.assertEquals("127.0.0.1", context.getLocalHostName()); } @Test void testCheckSide() { RpcContext context = RpcContext.getServiceContext(); // TODO fix npe // context.isProviderSide(); context.setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1")); Assertions.assertFalse(context.isConsumerSide()); Assertions.assertTrue(context.isProviderSide()); context.setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); Assertions.assertTrue(context.isConsumerSide()); Assertions.assertFalse(context.isProviderSide()); } @Test void testAttachments() { RpcContext context = RpcContext.getClientAttachment(); Map<String, Object> map = new HashMap<>(); map.put("_11", "1111"); map.put("_22", "2222"); map.put(".33", "3333"); context.setObjectAttachments(map); Assertions.assertEquals(map, context.getObjectAttachments()); Assertions.assertEquals("1111", context.getAttachment("_11")); context.setAttachment("_11", "11.11"); Assertions.assertEquals("11.11", context.getAttachment("_11")); context.setAttachment(null, "22222"); context.setAttachment("_22", null); Assertions.assertEquals("22222", context.getAttachment(null)); Assertions.assertNull(context.getAttachment("_22")); Assertions.assertNull(context.getAttachment("_33")); Assertions.assertEquals("3333", context.getAttachment(".33")); context.clearAttachments(); Assertions.assertNull(context.getAttachment("_11")); } @Test void testObject() { RpcContext context = RpcContext.getClientAttachment(); Map<String, Object> map = new HashMap<String, Object>(); map.put("_11", "1111"); map.put("_22", "2222"); map.put(".33", "3333"); map.forEach(context::set); Assertions.assertEquals(map, context.get()); Assertions.assertEquals("1111", context.get("_11")); context.set("_11", "11.11"); Assertions.assertEquals("11.11", context.get("_11")); context.set(null, "22222"); context.set("_22", null); Assertions.assertEquals("22222", context.get(null)); Assertions.assertNull(context.get("_22")); Assertions.assertNull(context.get("_33")); Assertions.assertEquals("3333", context.get(".33")); map.keySet().forEach(context::remove); Assertions.assertNull(context.get("_11")); RpcContext.removeContext(); } @Test void testAsync() { RpcContext rpcContext = RpcContext.getServiceContext(); Assertions.assertFalse(rpcContext.isAsyncStarted()); AsyncContext asyncContext = RpcContext.startAsync(); Assertions.assertTrue(rpcContext.isAsyncStarted()); asyncContext.write(new Object()); Assertions.assertTrue( ((AsyncContextImpl) asyncContext).getInternalFuture().isDone()); rpcContext.stopAsync(); Assertions.assertTrue(rpcContext.isAsyncStarted()); RpcContext.removeContext(); } @Test void testAsyncCall() { CompletableFuture<String> rpcFuture = RpcContext.getClientAttachment().asyncCall(() -> { throw new NullPointerException(); }); rpcFuture.whenComplete((rpcResult, throwable) -> { Assertions.assertNull(rpcResult); Assertions.assertTrue(throwable instanceof RpcException); Assertions.assertTrue(throwable.getCause() instanceof NullPointerException); }); Assertions.assertThrows(ExecutionException.class, rpcFuture::get); rpcFuture = rpcFuture.exceptionally(throwable -> "mock success"); Assertions.assertEquals("mock success", rpcFuture.join()); } @Test void testObjectAttachment() { RpcContext rpcContext = RpcContext.getClientAttachment(); rpcContext.setAttachment("objectKey1", "value1"); rpcContext.setAttachment("objectKey2", "value2"); rpcContext.setAttachment("objectKey3", 1); // object Assertions.assertEquals("value1", rpcContext.getObjectAttachment("objectKey1")); Assertions.assertEquals("value2", rpcContext.getAttachment("objectKey2")); Assertions.assertNull(rpcContext.getAttachment("objectKey3")); Assertions.assertEquals(1, rpcContext.getObjectAttachment("objectKey3")); Assertions.assertEquals(3, rpcContext.getObjectAttachments().size()); rpcContext.clearAttachments(); Assertions.assertEquals(0, rpcContext.getObjectAttachments().size()); HashMap<String, Object> map = new HashMap<>(); map.put("mapKey1", 1); map.put("mapKey2", "mapValue2"); rpcContext.setObjectAttachments(map); Assertions.assertEquals(map, rpcContext.getObjectAttachments()); } @Test public void say() { final String key = "user-attachment"; final String value = "attachment-value"; RpcContext.getServerContext().setObjectAttachment(key, value); final String returned = (String) RpcContext.getServerContext().getObjectAttachment(key); Assertions.assertEquals(value, returned); RpcContext.getServerContext().remove(key); } @Test void testRestore() {} @Test public void testRpcServerContextAttachment() { RpcContextAttachment attachment = RpcContext.getServerContext(); attachment.setAttachment("key_1", "value_1"); attachment.setAttachment("key_2", "value_2"); Assertions.assertEquals("value_1", attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("aaa")); attachment.removeAttachment("key_1"); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals("value_2", attachment.getAttachment("key_2")); Object obj = new Object(); attachment.setObjectAttachment("key_3", obj); Assertions.assertEquals(obj, attachment.getObjectAttachment("key_3")); attachment.removeAttachment("key_3"); Assertions.assertEquals(null, attachment.getObjectAttachment("key_3")); Assertions.assertThrows(RuntimeException.class, () -> attachment.copyOf(true)); Assertions.assertThrows(RuntimeException.class, attachment::isValid); Map<String, String> map = new HashMap<>(); map.put("key_4", "value_4"); map.put("key_5", "value_5"); attachment.setAttachments(map); Assertions.assertEquals(attachment.getAttachments(), attachment.getObjectAttachments()); Assertions.assertEquals(attachment.getAttachments(), attachment.get()); Map<String, String> map1 = attachment.getAttachments(); Assertions.assertEquals("value_4", map1.get("key_4")); Assertions.assertEquals("value_5", map1.get("key_5")); attachment.clearAttachments(); Assertions.assertEquals(attachment, attachment.removeAttachment("key_4")); Assertions.assertEquals(attachment, attachment.removeAttachment("key_5")); attachment.set("key_6", "value_6"); Assertions.assertEquals("value_6", attachment.get("key_6")); attachment.clearAttachments(); Map<String, Object> objectMap = new HashMap<>(); objectMap.put("key_7", "value_7"); objectMap.put("key_8", "value_8"); attachment.setObjectAttachments(objectMap); Map<String, String> objectMap1 = attachment.getAttachments(); Assertions.assertEquals("value_7", objectMap1.get("key_7")); Assertions.assertEquals("value_8", objectMap1.get("key_8")); attachment.clearAttachments(); } @Test public void testRpcServerContextClearAttachment() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); attachment.setAttachment("key_1", "value_1"); attachment.setAttachment("key_2", "value_2"); attachment.setAttachment("key_3", "value_3"); attachment.clearAttachments(); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("key_2")); Assertions.assertEquals(null, attachment.getAttachment("key_3")); attachment.setObjectAttachment("key_1", "value_1"); attachment.setObjectAttachment("key_2", "value_2"); attachment.setObjectAttachment("key_3", "value_3"); attachment.clearAttachments(); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("key_2")); Assertions.assertEquals(null, attachment.getAttachment("key_3")); } @Test public void testAsyncContext() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); AsyncContext asyncContext = new AsyncContextImpl(); attachment.setAsyncContext(asyncContext); asyncContext.start(); Assertions.assertTrue(attachment.isAsyncStarted()); Assertions.assertEquals(asyncContext, attachment.getAsyncContext()); Assertions.assertTrue(attachment.stopAsync()); } @Test public void testObjectAttachmentMap() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put("key_1", "value_1"); Set<String> keySet = objectAttachmentMap.keySet(); Assertions.assertEquals(true, keySet.contains("key_1")); Collection<Object> valueSet = objectAttachmentMap.values(); Assertions.assertEquals(true, valueSet.contains("value_1")); Set<Map.Entry<String, Object>> entrySet = objectAttachmentMap.entrySet(); Map.Entry<String, Object> entry = entrySet.iterator().next(); Assertions.assertEquals("key_1", entry.getKey()); Assertions.assertEquals("value_1", entry.getValue()); Assertions.assertEquals(true, objectAttachmentMap.containsKey("key_1")); Assertions.assertEquals(true, objectAttachmentMap.containsValue("value_1")); Assertions.assertEquals("value_1", objectAttachmentMap.get("key_1")); Assertions.assertEquals(null, objectAttachmentMap.get("key_2")); objectAttachmentMap.remove("key_1"); Assertions.assertEquals(null, objectAttachmentMap.get("key_1")); Map<String, String> map = new HashMap<>(); map.put("key_3", "value_3"); map.put("key_4", "value_4"); objectAttachmentMap.putAll(map); Assertions.assertEquals("value_3", objectAttachmentMap.get("key_3")); Assertions.assertEquals("value_4", objectAttachmentMap.get("key_4")); Assertions.assertEquals(null, objectAttachmentMap.remove(new Object())); objectAttachmentMap.clear(); } @Test public void testClearAttachmentMap() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put("key_1", "value_1"); objectAttachmentMap.put("key_2", "value_2"); objectAttachmentMap.put("key_3", "value_3"); Assertions.assertEquals(3, objectAttachmentMap.size()); objectAttachmentMap.clear(); Assertions.assertEquals(null, objectAttachmentMap.get(new Object())); Assertions.assertEquals(0, objectAttachmentMap.size()); Assertions.assertEquals(true, objectAttachmentMap.isEmpty()); } }
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/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link PenetrateAttachmentSelector} */ class PenetrateAttachmentSelectorTest { @Test void test() { ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader = ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); Set<String> supportedSelectors = selectorExtensionLoader.getSupportedExtensions(); Map<String, Object> allSelected = new HashMap<>(); if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (String supportedSelector : supportedSelectors) { Map<String, Object> selected = selectorExtensionLoader.getExtension(supportedSelector).select(null, null, null); allSelected.putAll(selected); } } Assertions.assertEquals(allSelected.get("testKey"), "testVal"); } @Test public void testSelectReverse() { ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader = ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); Set<String> supportedSelectors = selectorExtensionLoader.getSupportedExtensions(); Map<String, Object> allSelected = new HashMap<>(); if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (String supportedSelector : supportedSelectors) { Map<String, Object> selected = selectorExtensionLoader.getExtension(supportedSelector).selectReverse(null, null, null); allSelected.putAll(selected); } } Assertions.assertEquals(allSelected.get("reverseKey"), "reverseVal"); } }
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/test/java/org/apache/dubbo/rpc/AppResponseTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.HashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assumptions.assumeFalse; class AppResponseTest { @Test void testAppResponseWithNormalException() { NullPointerException npe = new NullPointerException(); AppResponse appResponse = new AppResponse(npe); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length > 1); } /** * please run this test in Run mode */ @Test void testAppResponseWithEmptyStackTraceException() { Throwable throwable = buildEmptyStackTraceException(); assumeFalse(throwable == null); AppResponse appResponse = new AppResponse(throwable); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertEquals(0, stackTrace.length); } @Test void testSetExceptionWithNormalException() { NullPointerException npe = new NullPointerException(); AppResponse appResponse = new AppResponse(); appResponse.setException(npe); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length > 1); } /** * please run this test in Run mode */ @Test void testSetExceptionWithEmptyStackTraceException() { Throwable throwable = buildEmptyStackTraceException(); assumeFalse(throwable == null); AppResponse appResponse = new AppResponse(); appResponse.setException(throwable); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertEquals(0, stackTrace.length); } private Throwable buildEmptyStackTraceException() { // begin to construct a NullPointerException with empty stackTrace Throwable throwable = null; Long begin = System.currentTimeMillis(); while (System.currentTimeMillis() - begin < 60000) { try { ((Object) null).getClass(); } catch (Exception e) { if (e.getStackTrace().length == 0) { throwable = e; break; } } } /** * maybe there is -XX:-OmitStackTraceInFastThrow or run in Debug mode */ if (throwable == null) { return null; } // end construct a NullPointerException with empty stackTrace return throwable; } @Test void testObjectAttachment() { AppResponse response = new AppResponse(); response.setAttachment("objectKey1", "value1"); response.setAttachment("objectKey2", "value2"); response.setAttachment("objectKey3", 1); // object Assertions.assertEquals("value1", response.getObjectAttachment("objectKey1")); Assertions.assertEquals("value2", response.getAttachment("objectKey2")); Assertions.assertNull(response.getAttachment("objectKey3")); Assertions.assertEquals(1, response.getObjectAttachment("objectKey3")); Assertions.assertEquals(3, response.getObjectAttachments().size()); HashMap<String, Object> map = new HashMap<>(); map.put("mapKey1", 1); map.put("mapKey2", "mapValue2"); response.setObjectAttachments(map); Assertions.assertEquals(map, response.getObjectAttachments()); } }
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/test/java/org/apache/dubbo/rpc/FutureContextTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/FutureContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class FutureContextTest { @Test void testFutureContext() throws Exception { Thread thread1 = new Thread(() -> { FutureContext.getContext().setFuture(CompletableFuture.completedFuture("future from thread1")); try { Thread.sleep(500); Assertions.assertEquals( "future from thread1", FutureContext.getContext().getCompletableFuture().get()); } catch (Exception e) { e.printStackTrace(); } }); thread1.start(); Thread.sleep(100); Thread thread2 = new Thread(() -> { CompletableFuture future = FutureContext.getContext().getCompletableFuture(); Assertions.assertNull(future); FutureContext.getContext().setFuture(CompletableFuture.completedFuture("future from thread2")); }); thread2.start(); Thread.sleep(1000); } }
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/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TimeoutCountDownTest { @Test void testTimeoutCountDown() throws InterruptedException { TimeoutCountDown timeoutCountDown = TimeoutCountDown.newCountDown(5, TimeUnit.SECONDS); Assertions.assertEquals(5 * 1000, timeoutCountDown.getTimeoutInMilli()); Assertions.assertFalse(timeoutCountDown.isExpired()); Assertions.assertTrue(timeoutCountDown.timeRemaining(TimeUnit.SECONDS) > 0); Assertions.assertTrue(timeoutCountDown.elapsedMillis() < TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); Thread.sleep(6 * 1000); Assertions.assertTrue(timeoutCountDown.isExpired()); Assertions.assertTrue(timeoutCountDown.timeRemaining(TimeUnit.SECONDS) <= 0); Assertions.assertTrue(timeoutCountDown.elapsedMillis() > TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.Arrays; import java.util.HashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class RpcInvocationTest { @Test void testAttachment() { RpcInvocation invocation = new RpcInvocation(); invocation.setAttachment("objectKey1", "value1"); invocation.setAttachment("objectKey2", "value2"); invocation.setAttachment("objectKey3", 1); // object Assertions.assertEquals("value1", invocation.getObjectAttachment("objectKey1")); Assertions.assertEquals("value2", invocation.getAttachment("objectKey2")); Assertions.assertNull(invocation.getAttachment("objectKey3")); Assertions.assertEquals(1, invocation.getObjectAttachment("objectKey3")); Assertions.assertEquals(3, invocation.getObjectAttachments().size()); HashMap<String, Object> map = new HashMap<>(); map.put("mapKey1", 1); map.put("mapKey2", "mapValue2"); invocation.setObjectAttachments(map); Assertions.assertEquals(map, invocation.getObjectAttachments()); } @Test void testInvokers() { RpcInvocation rpcInvocation = new RpcInvocation(); Invoker invoker1 = Mockito.mock(Invoker.class); Invoker invoker2 = Mockito.mock(Invoker.class); Invoker invoker3 = Mockito.mock(Invoker.class); rpcInvocation.addInvokedInvoker(invoker1); rpcInvocation.addInvokedInvoker(invoker2); rpcInvocation.addInvokedInvoker(invoker3); rpcInvocation.addInvokedInvoker(invoker3); Assertions.assertEquals( Arrays.asList(invoker1, invoker2, invoker3, invoker3), rpcInvocation.getInvokedInvokers()); } }
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/test/java/org/apache/dubbo/rpc/CancellationContextTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CancellationContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.concurrent.CountDownLatch; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link CancellationContext} */ class CancellationContextTest { @Test void test() throws Exception { CancellationContext cancellationContext = new CancellationContext(); CountDownLatch latch = new CountDownLatch(2); cancellationContext.addListener(rpcServiceContext -> { latch.countDown(); }); cancellationContext.addListener(rpcServiceContext -> { latch.countDown(); }); RuntimeException runtimeException = new RuntimeException(); cancellationContext.cancel(runtimeException); latch.await(); Assertions.assertNull(cancellationContext.getListeners()); Assertions.assertTrue(cancellationContext.isCancelled()); Assertions.assertEquals(cancellationContext.getCancellationCause(), runtimeException); } @Test void testAddListenerAfterCancel() throws Exception { CancellationContext cancellationContext = new CancellationContext(); cancellationContext.cancel(null); CountDownLatch latch = new CountDownLatch(1); cancellationContext.addListener(rpcServiceContext -> { latch.countDown(); }); latch.await(); } }
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/test/java/org/apache/dubbo/rpc/CustomArgument.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CustomArgument.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc; import org.apache.dubbo.rpc.support.Type; import java.io.Serializable; @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; public CustomArgument() {} public CustomArgument(Type type, String name) { super(); this.type = type; this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/TrieTreeTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/TrieTreeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class TrieTreeTest { private TrieTree trie; @BeforeEach void setUp() { // Initialize the set of words before each test Set<String> words = new HashSet<>(); words.add("apple"); words.add("App-le"); words.add("apply"); words.add("app_le.juice"); words.add("app-LE_juice"); // Initialize TrieTree trie = new TrieTree(words); } @Test void testSearchValidWords() { // Test valid words assertTrue(trie.search("apple")); assertTrue(trie.search("App-LE")); assertTrue(trie.search("apply")); assertTrue(trie.search("app_le.juice")); assertTrue(trie.search("app-LE_juice")); } @Test void testSearchInvalidWords() { // Test invalid words assertFalse(trie.search("app")); // Invalid character test assertFalse(trie.search("app%le")); } }
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/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; public class BlockMyInvoker<T> extends MyInvoker<T> { private long blockTime = 100; public BlockMyInvoker(URL url, long blockTime) { super(url); this.blockTime = blockTime; } public BlockMyInvoker(URL url, boolean hasException, long blockTime) { super(url, hasException); this.blockTime = blockTime; } @Override public Result invoke(Invocation invocation) throws RpcException { AppResponse result = new AppResponse(); if (!hasException) { try { Thread.sleep(blockTime); } catch (InterruptedException e) { } result.setValue("Dubbo"); } else { result.setException(new RuntimeException("mocked exception")); } return AsyncRpcResult.newDefaultAsyncResult(result, invocation); } public long getBlockTime() { return blockTime; } public void setBlockTime(long blockTime) { this.blockTime = blockTime; } }
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/test/java/org/apache/dubbo/rpc/support/Type.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.support; 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-api/src/test/java/org/apache/dubbo/rpc/support/IEcho.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.support; 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-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.PenetrateAttachmentSelector; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcContextAttachment; import java.util.Map; public class PenetrateAttachmentSelectorMock implements PenetrateAttachmentSelector { @Override public Map<String, Object> select( Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment) { Map<String, Object> objectAttachments = RpcContext.getServerAttachment().getObjectAttachments(); objectAttachments.put("testKey", "testVal"); return objectAttachments; } @Override public Map<String, Object> selectReverse( Invocation invocation, RpcContextAttachment clientResponseContext, RpcContextAttachment serverResponseContext) { Map<String, Object> objectAttachments = RpcContext.getServerResponseContext().getObjectAttachments(); objectAttachments.put("reverseKey", "reverseVal"); return objectAttachments; } }
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/test/java/org/apache/dubbo/rpc/support/Person.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/Person.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import java.io.Serializable; /** * Person.java */ public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.support; import org.apache.dubbo.rpc.CustomArgument; import org.apache.dubbo.rpc.RpcContext; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; 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.info("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 Type enumlength(Type type) { return type; } public int stringLength(String str) { return str.length(); } public String get(CustomArgument arg1) { return arg1.toString(); } public byte getbyte(byte arg) { return arg; } public Person getPerson(Person person) { return person; } @Override public String testReturnType(String str) { return null; } @Override public List<String> testReturnType1(String str) { return null; } @Override public CompletableFuture<String> testReturnType2(String str) { return null; } @Override public CompletableFuture<List<String>> testReturnType3(String str) { return null; } @Override public CompletableFuture testReturnType4(String str) { return CompletableFuture.completedFuture(""); } @Override public CompletableFuture<Map<String, String>> testReturnType5(String str) { return null; } @Override public void $invoke(String s1, String s2) {} }
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/test/java/org/apache/dubbo/rpc/support/LocalException.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/LocalException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; public class LocalException extends RuntimeException { public LocalException(String message) { super(message); } }
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/test/java/org/apache/dubbo/rpc/support/DemoService.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.support; import org.apache.dubbo.rpc.CustomArgument; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; 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); // Type enumlength(Type type); String get(CustomArgument arg1); byte getbyte(byte arg); Person getPerson(Person person); String testReturnType(String str); List<String> testReturnType1(String str); CompletableFuture<String> testReturnType2(String str); CompletableFuture<List<String>> testReturnType3(String str); CompletableFuture testReturnType4(String str); CompletableFuture<Map<String, String>> testReturnType5(String str); void $invoke(String s1, String s2); }
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/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.InvokeMode; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class RpcUtilsTest { /** * regular scenario: async invocation in URL * verify: 1. whether invocationId is set correctly, 2. idempotent or not */ Invoker createMockInvoker(URL url) { Invoker invoker = createMockInvoker(); given(invoker.getUrl()).willReturn(url); return invoker; } Invoker createMockInvoker() { return mock(Invoker.class); } @Test void testAttachInvocationIdIfAsync_normal() { URL url = URL.valueOf("dubbo://localhost/?test.async=true"); Map<String, Object> attachments = new HashMap<>(); attachments.put("aa", "bb"); Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {}, attachments); RpcUtils.attachInvocationIdIfAsync(url, inv); long id1 = RpcUtils.getInvocationId(inv); RpcUtils.attachInvocationIdIfAsync(url, inv); long id2 = RpcUtils.getInvocationId(inv); assertEquals(id1, id2); // verify if it's idempotent assertTrue(id1 >= 0); assertEquals("bb", attachments.get("aa")); } /** * scenario: sync invocation, no attachment added by default * verify: no id attribute added in attachment */ @Test void testAttachInvocationIdIfAsync_sync() { URL url = URL.valueOf("dubbo://localhost/"); Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {}); RpcUtils.attachInvocationIdIfAsync(url, inv); assertNull(RpcUtils.getInvocationId(inv)); } /** * scenario: async invocation, add attachment by default * verify: no error report when the original attachment is null */ @Test void testAttachInvocationIdIfAsync_nullAttachments() { URL url = URL.valueOf("dubbo://localhost/?test.async=true"); Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {}); RpcUtils.attachInvocationIdIfAsync(url, inv); assertTrue(RpcUtils.getInvocationId(inv) >= 0L); } /** * scenario: explicitly configure to not add attachment * verify: no id attribute added in attachment */ @Test void testAttachInvocationIdIfAsync_forceNotAttache() { URL url = URL.valueOf("dubbo://localhost/?test.async=true&" + AUTO_ATTACH_INVOCATIONID_KEY + "=false"); Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {}); RpcUtils.attachInvocationIdIfAsync(url, inv); assertNull(RpcUtils.getInvocationId(inv)); } /** * scenario: explicitly configure to add attachment * verify: id attribute added in attachment */ @Test void testAttachInvocationIdIfAsync_forceAttache() { URL url = URL.valueOf("dubbo://localhost/?" + AUTO_ATTACH_INVOCATIONID_KEY + "=true"); Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {}); RpcUtils.attachInvocationIdIfAsync(url, inv); assertNotNull(RpcUtils.getInvocationId(inv)); } @Test void testGetReturnType() { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); // void sayHello(String name); RpcInvocation inv = new RpcInvocation( "sayHello", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Class<?> returnType = RpcUtils.getReturnType(inv); Assertions.assertNull(returnType); // String echo(String text); RpcInvocation inv1 = new RpcInvocation("echo", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Class<?> returnType1 = RpcUtils.getReturnType(inv1); Assertions.assertNotNull(returnType1); Assertions.assertEquals(String.class, returnType1); // int getSize(String[] strs); RpcInvocation inv2 = new RpcInvocation( "getSize", serviceName, "", new Class<?>[] {String[].class}, null, null, invoker, null); Class<?> returnType2 = RpcUtils.getReturnType(inv2); Assertions.assertNotNull(returnType2); Assertions.assertEquals(int.class, returnType2); // Person getPerson(Person person); RpcInvocation inv3 = new RpcInvocation( "getPerson", serviceName, "", new Class<?>[] {Person.class}, null, null, invoker, null); Class<?> returnType3 = RpcUtils.getReturnType(inv3); Assertions.assertNotNull(returnType3); Assertions.assertEquals(Person.class, returnType3); // List<String> testReturnType1(String str); RpcInvocation inv4 = new RpcInvocation( "testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Class<?> returnType4 = RpcUtils.getReturnType(inv4); Assertions.assertNotNull(returnType4); Assertions.assertEquals(List.class, returnType4); } @Test void testGetReturnTypesUseCache() throws Exception { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); RpcInvocation inv = new RpcInvocation( "testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNotNull(types); Assertions.assertEquals(2, types.length); Assertions.assertEquals(String.class, types[0]); Assertions.assertEquals(String.class, types[1]); Assertions.assertArrayEquals(types, inv.getReturnTypes()); RpcInvocation inv1 = new RpcInvocation( "testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNotNull(types1); Assertions.assertEquals(2, types1.length); Assertions.assertEquals(List.class, types1[0]); Assertions.assertEquals( demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); Assertions.assertArrayEquals(types1, inv1.getReturnTypes()); RpcInvocation inv2 = new RpcInvocation( "testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNotNull(types2); Assertions.assertEquals(2, types2.length); Assertions.assertEquals(String.class, types2[0]); Assertions.assertEquals(String.class, types2[1]); Assertions.assertArrayEquals(types2, inv2.getReturnTypes()); RpcInvocation inv3 = new RpcInvocation( "testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNotNull(types3); Assertions.assertEquals(2, types3.length); Assertions.assertEquals(List.class, types3[0]); java.lang.reflect.Type genericReturnType3 = demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]); Assertions.assertArrayEquals(types3, inv3.getReturnTypes()); RpcInvocation inv4 = new RpcInvocation( "testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNotNull(types4); Assertions.assertEquals(2, types4.length); Assertions.assertNull(types4[0]); Assertions.assertNull(types4[1]); Assertions.assertArrayEquals(types4, inv4.getReturnTypes()); RpcInvocation inv5 = new RpcInvocation( "testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNotNull(types5); Assertions.assertEquals(2, types5.length); Assertions.assertEquals(Map.class, types5[0]); java.lang.reflect.Type genericReturnType5 = demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]); Assertions.assertArrayEquals(types5, inv5.getReturnTypes()); } @Test void testGetReturnTypesWithoutCache() throws Exception { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); RpcInvocation inv = new RpcInvocation( "testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv.setReturnTypes(null); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNotNull(types); Assertions.assertEquals(2, types.length); Assertions.assertEquals(String.class, types[0]); Assertions.assertEquals(String.class, types[1]); RpcInvocation inv1 = new RpcInvocation( "testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv1.setReturnTypes(null); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNotNull(types1); Assertions.assertEquals(2, types1.length); Assertions.assertEquals(List.class, types1[0]); Assertions.assertEquals( demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); RpcInvocation inv2 = new RpcInvocation( "testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv2.setReturnTypes(null); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNotNull(types2); Assertions.assertEquals(2, types2.length); Assertions.assertEquals(String.class, types2[0]); Assertions.assertEquals(String.class, types2[1]); RpcInvocation inv3 = new RpcInvocation( "testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv3.setReturnTypes(null); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNotNull(types3); Assertions.assertEquals(2, types3.length); Assertions.assertEquals(List.class, types3[0]); java.lang.reflect.Type genericReturnType3 = demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]); RpcInvocation inv4 = new RpcInvocation( "testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv4.setReturnTypes(null); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNotNull(types4); Assertions.assertEquals(2, types4.length); Assertions.assertNull(types4[0]); Assertions.assertNull(types4[1]); RpcInvocation inv5 = new RpcInvocation( "testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv5.setReturnTypes(null); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNotNull(types5); Assertions.assertEquals(2, types5.length); Assertions.assertEquals(Map.class, types5[0]); java.lang.reflect.Type genericReturnType5 = demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]); } @Test void testGetReturnTypesWhenGeneric() throws Exception { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); RpcInvocation inv = new RpcInvocation( "testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv.setMethodName($INVOKE); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNull(types); RpcInvocation inv1 = new RpcInvocation( "testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv1.setMethodName($INVOKE); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNull(types1); RpcInvocation inv2 = new RpcInvocation( "testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv2.setMethodName($INVOKE); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNull(types2); RpcInvocation inv3 = new RpcInvocation( "testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv3.setMethodName($INVOKE); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNull(types3); RpcInvocation inv4 = new RpcInvocation( "testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv4.setMethodName($INVOKE); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNull(types4); RpcInvocation inv5 = new RpcInvocation( "testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv5.setMethodName($INVOKE); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNull(types5); } @Test void testGetParameterTypes() { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); // void sayHello(String name); RpcInvocation inv1 = new RpcInvocation( "sayHello", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Class<?>[] parameterTypes1 = RpcUtils.getParameterTypes(inv1); Assertions.assertNotNull(parameterTypes1); Assertions.assertEquals(1, parameterTypes1.length); Assertions.assertEquals(String.class, parameterTypes1[0]); // long timestamp(); RpcInvocation inv2 = new RpcInvocation("timestamp", serviceName, "", null, null, null, invoker, null); Class<?>[] parameterTypes2 = RpcUtils.getParameterTypes(inv2); Assertions.assertEquals(0, parameterTypes2.length); // Type enumlength(Type... types); RpcInvocation inv3 = new RpcInvocation( "enumlength", serviceName, "", new Class<?>[] {Type.class, Type.class}, null, null, invoker, null); Class<?>[] parameterTypes3 = RpcUtils.getParameterTypes(inv3); Assertions.assertNotNull(parameterTypes3); Assertions.assertEquals(2, parameterTypes3.length); Assertions.assertEquals(Type.class, parameterTypes3[0]); Assertions.assertEquals(Type.class, parameterTypes3[1]); // byte getbyte(byte arg); RpcInvocation inv4 = new RpcInvocation("getbyte", serviceName, "", new Class<?>[] {byte.class}, null, null, invoker, null); Class<?>[] parameterTypes4 = RpcUtils.getParameterTypes(inv4); Assertions.assertNotNull(parameterTypes4); Assertions.assertEquals(1, parameterTypes4.length); Assertions.assertEquals(byte.class, parameterTypes4[0]); // void $invoke(String s1, String s2); RpcInvocation inv5 = new RpcInvocation( "$invoke", serviceName, "", new Class<?>[] {String.class, String[].class}, new Object[] {"method", new String[] {"java.lang.String", "void", "java.lang.Object"}}, null, invoker, null); Class<?>[] parameterTypes5 = RpcUtils.getParameterTypes(inv5); Assertions.assertNotNull(parameterTypes5); Assertions.assertEquals(3, parameterTypes5.length); Assertions.assertEquals(String.class, parameterTypes5[0]); Assertions.assertEquals(void.class, parameterTypes5[1]); Assertions.assertEquals(Object.class, parameterTypes5[2]); } @Test void testGet_$invokeAsync_ParameterTypes() { Object[] args = new Object[] {"hello", true, 520}; Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv = new RpcInvocation( "$invokeAsync", serviceName, "", new Class<?>[] {String.class, String[].class, Object[].class}, new Object[] { "method", new String[] {"java.lang.String", "java.lang.Boolean", "java.lang.Integer"}, args }, null, invoker, null); Class<?>[] parameterTypes = RpcUtils.getParameterTypes(inv); for (int i = 0; i < args.length; i++) { Assertions.assertNotNull(parameterTypes[i]); Assertions.assertEquals(args[i].getClass(), parameterTypes[i]); } } @ParameterizedTest @CsvSource({"echo", "stringLength", "testReturnType"}) public void testGetMethodName(String methodName) { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv1 = new RpcInvocation( methodName, serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); String actual = RpcUtils.getMethodName(inv1); Assertions.assertNotNull(actual); Assertions.assertEquals(methodName, actual); } @ParameterizedTest @CsvSource({"hello", "apache", "dubbo"}) public void testGet_$invoke_MethodName(String method) { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv = new RpcInvocation( "$invoke", serviceName, "", new Class<?>[] {String.class, String[].class}, new Object[] {method, new String[] {"java.lang.String", "void", "java.lang.Object"}}, null, invoker, null); String actual = RpcUtils.getMethodName(inv); Assertions.assertNotNull(actual); Assertions.assertEquals(method, actual); } @ParameterizedTest @CsvSource({"hello", "apache", "dubbo"}) public void testGet_$invokeAsync_MethodName(String method) { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv = new RpcInvocation( "$invokeAsync", serviceName, "", new Class<?>[] {String.class, String[].class}, new Object[] {method, new String[] {"java.lang.String", "void", "java.lang.Object"}}, null, invoker, null); String actual = RpcUtils.getMethodName(inv); Assertions.assertNotNull(actual); Assertions.assertEquals(method, actual); } @Test void testGet_$invoke_Arguments() { Object[] args = new Object[] {"hello", "dubbo", 520}; Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv = new RpcInvocation( "$invoke", serviceName, "", new Class<?>[] {String.class, String[].class, Object[].class}, new Object[] {"method", new String[] {}, args}, null, invoker, null); Object[] arguments = RpcUtils.getArguments(inv); for (int i = 0; i < args.length; i++) { Assertions.assertNotNull(arguments[i]); Assertions.assertEquals( args[i].getClass().getName(), arguments[i].getClass().getName()); Assertions.assertEquals(args[i], arguments[i]); } } @Test void testGet_$invokeAsync_Arguments() { Object[] args = new Object[] {"hello", "dubbo", 520}; Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv = new RpcInvocation( "$invokeAsync", serviceName, "", new Class<?>[] {String.class, String[].class, Object[].class}, new Object[] {"method", new String[] {}, args}, null, invoker, null); Object[] arguments = RpcUtils.getArguments(inv); for (int i = 0; i < args.length; i++) { Assertions.assertNotNull(arguments[i]); Assertions.assertEquals( args[i].getClass().getName(), arguments[i].getClass().getName()); Assertions.assertEquals(args[i], arguments[i]); } } @Test void testIsAsync() { Object[] args = new Object[] {"hello", "dubbo", 520}; Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); URL url = URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"); RpcInvocation inv = new RpcInvocation( "test", serviceName, "", new Class<?>[] {String.class, String[].class, Object[].class}, new Object[] {"method", new String[] {}, args}, null, invoker, null); Assertions.assertFalse(RpcUtils.isAsync(url, inv)); inv.setInvokeMode(InvokeMode.ASYNC); Assertions.assertTrue(RpcUtils.isAsync(url, inv)); } @Test void testIsGenericCall() { Assertions.assertTrue( RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invoke")); Assertions.assertTrue( RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invokeAsync")); Assertions.assertFalse( RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "testMethod")); } @Test void testIsEcho() { Assertions.assertTrue(RpcUtils.isEcho("Ljava/lang/Object;", "$echo")); Assertions.assertFalse(RpcUtils.isEcho("Ljava/lang/Object;", "testMethod")); Assertions.assertFalse(RpcUtils.isEcho("Ljava/lang/String;", "$echo")); } @Test void testIsReturnTypeFuture() { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); RpcInvocation inv = new RpcInvocation( "testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Assertions.assertFalse(RpcUtils.isReturnTypeFuture(inv)); ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); repository.registerService(demoServiceClass); inv = new RpcInvocation( "testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); Assertions.assertTrue(RpcUtils.isReturnTypeFuture(inv)); } }
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/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; public class RuntimeExceptionInvoker extends MyInvoker { public RuntimeExceptionInvoker(URL url) { super(url); } @Override public Result invoke(Invocation invocation) throws RpcException { throw new RuntimeException("Runtime 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/test/java/org/apache/dubbo/rpc/support/MockInvocation.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ public class MockInvocation extends RpcInvocation { private Map<String, Object> attachments; public MockInvocation() { attachments = new HashMap<>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } @Override public String getServiceName() { return "DemoService"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {"aa"}; } public Map<String, String> getAttachments() { return new AttachmentsAdapter.ObjectToStringMap(attachments); } @Override public Map<String, Object> getObjectAttachments() { return attachments; } @Override public void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override public void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { attachments.put(key, value); } @Override public void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setObjectAttachmentIfAbsent(String key, Object value) { attachments.put(key, value); } public Invoker<?> getInvoker() { return null; } @Override public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key) { return attachments.get(key); } public String getAttachment(String key, String defaultValue) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key, Object defaultValue) { Object result = attachments.get(key); if (result == null) { return defaultValue; } return result; } }
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/test/java/org/apache/dubbo/rpc/support/MyInvoker.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.RpcException; import java.util.concurrent.CompletableFuture; /** * MockInvoker.java */ public class MyInvoker<T> implements Invoker<T> { URL url; Class<T> type; boolean hasException = false; boolean destroyed = false; public MyInvoker(URL url) { this.url = url; type = (Class<T>) DemoService.class; } public MyInvoker(URL url, boolean hasException) { this.url = url; type = (Class<T>) DemoService.class; this.hasException = hasException; } @Override public Class<T> getInterface() { return type; } public URL getUrl() { return url; } @Override public boolean isAvailable() { return false; } @Override public Result invoke(Invocation invocation) throws RpcException { AppResponse result = new AppResponse(); if (!hasException) { result.setValue("alibaba"); } else { result.setException(new RuntimeException("mocked exception")); } return new AsyncRpcResult(CompletableFuture.completedFuture(result), invocation); } @Override public void destroy() { destroyed = true; } public boolean isDestroyed() { return destroyed; } @Override public String toString() { return "MyInvoker.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/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.support; public class DemoServiceStub extends DemoServiceImpl { private DemoService demoService; public DemoServiceStub(DemoService demoService) { this.demoService = demoService; } public DemoService getDemoService() { return demoService; } }
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/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; 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.support.DemoService; import org.apache.dubbo.rpc.support.LocalException; import com.alibaba.com.caucho.hessian.HessianException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ExceptionFilterTest { @SuppressWarnings("unchecked") @Test void testRpcException() { Logger failLogger = mock(Logger.class); FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger); RpcContext.getServiceContext().setRemoteAddress("127.0.0.1", 1234); RpcException exception = new RpcException("TestRpcException"); ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation( "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"}); Invoker<DemoService> invoker = mock(Invoker.class); given(invoker.getInterface()).willReturn(DemoService.class); given(invoker.invoke(eq(invocation))).willThrow(exception); try { exceptionFilter.invoke(invoker, invocation); } catch (RpcException e) { assertEquals("TestRpcException", e.getMessage()); exceptionFilter.mockLogger(failsafeLogger); exceptionFilter.onError(e, invoker, invocation); } failsafeLogger.error( CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), eq(exception)); RpcContext.removeContext(); } @SuppressWarnings("unchecked") @Test void testJavaException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation( "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"}); AppResponse appResponse = new AppResponse(); appResponse.setException(new IllegalArgumentException("java")); Invoker<DemoService> invoker = mock(Invoker.class); when(invoker.invoke(invocation)).thenReturn(appResponse); when(invoker.getInterface()).thenReturn(DemoService.class); Result newResult = exceptionFilter.invoke(invoker, invocation); Assertions.assertEquals(appResponse.getException(), newResult.getException()); } @SuppressWarnings("unchecked") @Test void testRuntimeException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation( "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"}); AppResponse appResponse = new AppResponse(); appResponse.setException(new LocalException("localException")); Invoker<DemoService> invoker = mock(Invoker.class); when(invoker.invoke(invocation)).thenReturn(appResponse); when(invoker.getInterface()).thenReturn(DemoService.class); Result newResult = exceptionFilter.invoke(invoker, invocation); Assertions.assertEquals(appResponse.getException(), newResult.getException()); } @SuppressWarnings("unchecked") @Test void testConvertToRunTimeException() throws Exception { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation( "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"}); AppResponse mockRpcResult = new AppResponse(); mockRpcResult.setException(new HessianException("hessian")); Result mockAsyncResult = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); Invoker<DemoService> invoker = mock(Invoker.class); when(invoker.invoke(invocation)).thenReturn(mockAsyncResult); when(invoker.getInterface()).thenReturn(DemoService.class); Result asyncResult = exceptionFilter.invoke(invoker, invocation); AppResponse appResponse = (AppResponse) asyncResult.get(); exceptionFilter.onResponse(appResponse, invoker, invocation); Assertions.assertFalse(appResponse.getException() instanceof HessianException); Assertions.assertEquals(appResponse.getException().getClass(), RuntimeException.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-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; 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.utils.DubboAppender; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.support.AccessLogData; import org.apache.dubbo.rpc.support.MockInvocation; import org.apache.dubbo.rpc.support.MyInvoker; import java.lang.reflect.Field; import java.util.Map; import java.util.Queue; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * AccessLogFilterTest.java */ class AccessLogFilterTest { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger("mock.dubbo.access.log"); AccessLogFilter accessLogFilter = new AccessLogFilter(); // TODO how to assert thread action @Test @SuppressWarnings("unchecked") public void testDefault() throws NoSuchFieldException, IllegalAccessException { URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"); Invoker<AccessLogFilterTest> invoker = new MyInvoker<AccessLogFilterTest>(url); Invocation invocation = new MockInvocation(); Field field = AccessLogFilter.class.getDeclaredField("logEntries"); field.setAccessible(true); assertTrue(((Map) field.get(accessLogFilter)).isEmpty()); accessLogFilter.invoke(invoker, invocation); Map<String, Queue<AccessLogData>> logs = (Map<String, Queue<AccessLogData>>) field.get(accessLogFilter); assertFalse(logs.isEmpty()); assertFalse(logs.get("true").isEmpty()); AccessLogData log = logs.get("true").iterator().next(); assertEquals("org.apache.dubbo.rpc.support.DemoService", log.getServiceName()); } @Test void testCustom() { DubboAppender.doStart(); ErrorTypeAwareLogger originalLogger = AccessLogFilter.logger; long originalInterval = AccessLogFilter.getInterval(); AccessLogFilter.setInterval(500); AccessLogFilter.logger = logger; AccessLogFilter customAccessLogFilter = new AccessLogFilter(); try { URL url = URL.valueOf("test://test:11/test?accesslog=custom-access.log"); Invoker<AccessLogFilterTest> invoker = new MyInvoker<>(url); Invocation invocation = new MockInvocation(); customAccessLogFilter.invoke(invoker, invocation); sleep(); assertEquals(1, LogUtil.findMessage("Change of accesslog file path not allowed")); } finally { customAccessLogFilter.destroy(); DubboAppender.clear(); AccessLogFilter.logger = originalLogger; AccessLogFilter.setInterval(originalInterval); } AccessLogFilter.setInterval(500); AccessLogFilter.logger = logger; AccessLogFilter customAccessLogFilter2 = new AccessLogFilter(); try { URL url2 = URL.valueOf("test://test:11/test?accesslog=custom-access.log&accesslog.fixed.path=false"); Invoker<AccessLogFilterTest> invoker = new MyInvoker<>(url2); Invocation invocation = new MockInvocation(); customAccessLogFilter2.invoke(invoker, invocation); sleep(); assertEquals(1, LogUtil.findMessage("Accesslog file path changed to")); } finally { customAccessLogFilter2.destroy(); DubboAppender.clear(); AccessLogFilter.logger = originalLogger; AccessLogFilter.setInterval(originalInterval); } } private void sleep() { try { Thread.sleep(600); } catch (InterruptedException e) { e.printStackTrace(); } } }
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/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Person; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.mockito.Mockito.any; import static org.mockito.Mockito.when; class GenericImplFilterTest { private GenericImplFilter genericImplFilter = new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule()); @Test void testInvoke() throws Exception { RpcInvocation invocation = new RpcInvocation( "getPerson", "org.apache.dubbo.rpc.support.DemoService", "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[] {Person.class}, new Object[] {new Person("dubbo", 10)}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); AppResponse mockRpcResult = new AppResponse(person); when(invoker.invoke(any(Invocation.class))) .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); Result asyncResult = genericImplFilter.invoke(invoker, invocation); Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(Person.class, result.getValue().getClass()); Assertions.assertEquals(10, ((Person) result.getValue()).getAge()); } @Test @Disabled("Apache Generic Exception not support cast exception now") void testInvokeWithException1() throws Exception { RpcInvocation invocation = new RpcInvocation( "getPerson", "org.apache.dubbo.rpc.support.DemoService", "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[] {Person.class}, new Object[] {new Person("dubbo", 10)}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed"))); when(invoker.invoke(any(Invocation.class))) .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); Result asyncResult = genericImplFilter.invoke(invoker, invocation); Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(RuntimeException.class, result.getException().getClass()); } @Test void testInvokeWithException2() throws Exception { RpcInvocation invocation = new RpcInvocation( "getPerson", "org.apache.dubbo.rpc.support.DemoService", "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[] {Person.class}, new Object[] {new Person("dubbo", 10)}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed"))); when(invoker.invoke(any(Invocation.class))) .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); Result asyncResult = genericImplFilter.invoke(invoker, invocation); Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(GenericException.class, result.getException().getClass()); } @Test void testInvokeWith$Invoke() throws Exception { Method genericInvoke = GenericService.class.getMethods()[0]; Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); RpcInvocation invocation = new RpcInvocation( $INVOKE, GenericService.class.getName(), "org.apache.dubbo.rpc.support.DemoService:dubbo", genericInvoke.getParameterTypes(), new Object[] {"getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person}}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); genericImplFilter.invoke(invoker, invocation); Assertions.assertEquals("true", invocation.getAttachment(GENERIC_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-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; class TokenFilterTest { private TokenFilter tokenFilter = new TokenFilter(); @Test void testInvokeWithToken() throws Exception { String token = "token"; Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token); when(invoker.getUrl()).thenReturn(url); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getObjectAttachmentWithoutConvert(TOKEN_KEY)).thenReturn(token); Result result = tokenFilter.invoke(invoker, invocation); Assertions.assertEquals("result", result.getValue()); } @Test void testInvokeWithWrongToken() throws Exception { Assertions.assertThrows(RpcException.class, () -> { String token = "token"; Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token); when(invoker.getUrl()).thenReturn(url); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Map<String, Object> attachments = new HashMap<>(); attachments.put(TOKEN_KEY, "wrongToken"); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getObjectAttachments()).thenReturn(attachments); tokenFilter.invoke(invoker, invocation); }); } @Test void testInvokeWithoutToken() throws Exception { Assertions.assertThrows(RpcException.class, () -> { String token = "token"; Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token); when(invoker.getUrl()).thenReturn(url); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Invocation invocation = Mockito.mock(Invocation.class); tokenFilter.invoke(invoker, invocation); }); } }
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/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.RpcInvocation; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Type; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * CompatibleFilterTest.java */ class CompatibleFilterFilterTest { private CompatibleFilter compatibleFilter = new CompatibleFilter(); private Invocation invocation; private Invoker invoker; @AfterEach public void tearDown() { Mockito.reset(invocation, invoker); } @Test void testInvokerGeneric() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("$enumlength"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result filterResult = compatibleFilter.invoke(invoker, invocation); assertEquals(filterResult, result); } @Test void testResultHasException() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("enumlength"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setException(new RuntimeException()); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result filterResult = compatibleFilter.invoke(invoker, invocation); assertEquals(filterResult, result); } @Test void testInvokerJsonPojoSerialization() throws Exception { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("enumlength"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Type[].class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("High"); AsyncRpcResult defaultAsyncResult = AsyncRpcResult.newDefaultAsyncResult(result, invocation); given(invoker.invoke(invocation)).willReturn(defaultAsyncResult); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&serialization=json"); given(invoker.getUrl()).willReturn(url); Result asyncResult = compatibleFilter.invoke(invoker, invocation); AppResponse appResponse = (AppResponse) asyncResult.get(); compatibleFilter.onResponse(appResponse, invoker, invocation); assertEquals(Type.High, appResponse.getValue()); } @Test void testInvokerNonJsonEnumSerialization() throws Exception { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("enumlength"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Type[].class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("High"); AsyncRpcResult defaultAsyncResult = AsyncRpcResult.newDefaultAsyncResult(result, invocation); given(invoker.invoke(invocation)).willReturn(defaultAsyncResult); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result asyncResult = compatibleFilter.invoke(invoker, invocation); AppResponse appResponse = (AppResponse) asyncResult.get(); compatibleFilter.onResponse(appResponse, invoker, invocation); assertEquals(Type.High, appResponse.getValue()); } @Test void testInvokerNonJsonNonPojoSerialization() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("echo"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue(new String[] {"High"}); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result filterResult = compatibleFilter.invoke(invoker, invocation); assertArrayEquals(new String[] {"High"}, (String[]) filterResult.getValue()); } @Test void testInvokerNonJsonPojoSerialization() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("echo"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("hello"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result filterResult = compatibleFilter.invoke(invoker, invocation); assertEquals("hello", filterResult.getValue()); } }
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/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Person; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; class GenericFilterTest { GenericFilter genericFilter = new GenericFilter(); @Test void testInvokeWithDefault() throws Exception { Method genericInvoke = GenericService.class.getMethods()[0]; Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); RpcInvocation invocation = new RpcInvocation( $INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { "getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person} }); URL url = URL.valueOf( "test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))) .thenReturn(AsyncRpcResult.newDefaultAsyncResult(new Person("person", 10), invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); Result asyncResult = genericFilter.invoke(invoker, invocation); AppResponse appResponse = (AppResponse) asyncResult.get(); genericFilter.onResponse(appResponse, invoker, invocation); Assertions.assertEquals(HashMap.class, appResponse.getValue().getClass()); Assertions.assertEquals(10, ((HashMap) appResponse.getValue()).get("age")); } @Test void testInvokeWithJavaException() throws Exception { // temporary enable native java generic serialize System.setProperty(ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, "true"); Assertions.assertThrows(RpcException.class, () -> { Method genericInvoke = GenericService.class.getMethods()[0]; Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); RpcInvocation invocation = new RpcInvocation( $INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { "getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person} }); invocation.setAttachment(GENERIC_KEY, GENERIC_SERIALIZATION_NATIVE_JAVA); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); genericFilter.invoke(invoker, invocation); }); System.clearProperty(ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE); } @Test void testInvokeWithMethodNamtNot$Invoke() { Method genericInvoke = GenericService.class.getMethods()[0]; Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); RpcInvocation invocation = new RpcInvocation( "sayHi", GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { "getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person} }); URL url = URL.valueOf( "test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); Result result = genericFilter.invoke(invoker, invocation); Assertions.assertEquals(Person.class, result.getValue().getClass()); Assertions.assertEquals(10, ((Person) (result.getValue())).getAge()); } @Test void testInvokeWithMethodArgumentSizeIsNot3() { Method genericInvoke = GenericService.class.getMethods()[0]; Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); RpcInvocation invocation = new RpcInvocation( $INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { "getPerson", new String[] {Person.class.getCanonicalName()} }); URL url = URL.valueOf( "test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); Result result = genericFilter.invoke(invoker, invocation); Assertions.assertEquals(Person.class, result.getValue().getClass()); Assertions.assertEquals(10, ((Person) (result.getValue())).getAge()); } }
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/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Filter; 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.model.ApplicationModel; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.MockInvocation; import org.apache.dubbo.rpc.support.MyInvoker; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * ContextFilterTest.java * TODO need to enhance assertion */ class ContextFilterTest { Filter contextFilter = new ContextFilter(ApplicationModel.defaultModel()); Invoker<DemoService> invoker; Invocation invocation; @SuppressWarnings("unchecked") @Test void testSetContext() { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("$enumlength"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class}); given(invocation.getArguments()).willReturn(new Object[] {"hello"}); given(invocation.getObjectAttachments()).willReturn(null); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); contextFilter.invoke(invoker, invocation); assertNotNull(RpcContext.getServiceContext().getInvoker()); } @Test void testWithAttachments() { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); assertNotNull(RpcContext.getServiceContext().getInvoker()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false