name
stringlengths 12
178
| code_snippet
stringlengths 8
36.5k
| score
float64 3.26
3.68
|
---|---|---|
dubbo_GlobalResourcesRepository_getGlobalReusedDisposables_rdh | // for test
public static List<Disposable> getGlobalReusedDisposables() {
return globalReusedDisposables;
} | 3.26 |
dubbo_GlobalResourcesRepository_getOneoffDisposables_rdh | // for test
public List<Disposable> getOneoffDisposables() {
return oneoffDisposables;
} | 3.26 |
dubbo_GlobalResourcesRepository_registerGlobalDisposable_rdh | /**
* Register a global reused disposable. The disposable will be executed when all dubbo FrameworkModels are destroyed.
* Note: the global disposable should be registered in static code, it's reusable and will not be removed when dubbo shutdown.
*
* @param disposable
*/
public static void registerGlobalDisposable(Disposable disposable) {
if (!globalReusedDisposables.contains(disposable)) {
synchronized(GlobalResourcesRepository.class) {
if (!globalReusedDisposables.contains(disposable)) {
globalReusedDisposables.add(disposable);
}
}
}
} | 3.26 |
dubbo_Curator5ZookeeperClient_getClient_rdh | /**
* just for unit test
*
* @return */
CuratorFramework getClient() {
return client;
} | 3.26 |
dubbo_FieldUtils_getDeclaredFields_rdh | /**
* The utilities class for the field in the package "javax.lang.model."
*
* @since 2.7.6
*/public interface FieldUtils {
static List<VariableElement> getDeclaredFields(Element element, Predicate<VariableElement>... fieldFilters) {
return element == null ? emptyList() : getDeclaredFields(element.asType(), fieldFilters);
} | 3.26 |
dubbo_FieldUtils_isEnumMemberField_rdh | /**
* is Enum's member field or not
*
* @param field
* {@link VariableElement} must be public static final fields
* @return if field is public static final, return <code>true</code>, or <code>false</code>
*/
static boolean isEnumMemberField(VariableElement field) {
if ((field == null) || (!isEnumType(field.getEnclosingElement()))) {
return false;
}
return ENUM_CONSTANT.equals(field.getKind());
} | 3.26 |
dubbo_NacosNamingServiceWrapper_m0_rdh | /**
* see https://github.com/apache/dubbo/issues/7129
* nacos service name just support `0-9a-zA-Z-._:`, grpc interface is inner interface, need compatible.
*/
private String m0(String serviceName) {
if (StringUtils.isEmpty(serviceName)) {
return null;
}
return serviceName.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL);
} | 3.26 |
dubbo_NacosNamingServiceWrapper_getRegisterStatus_rdh | /**
*
* @deprecated for uts only
*/
@Deprecated
protected Map<InstanceId, InstancesInfo> getRegisterStatus() {
return registerStatus;
} | 3.26 |
dubbo_FutureContext_setCompatibleFuture_rdh | /**
* Guarantee 'using org.apache.dubbo.rpc.RpcContext.getFuture() before proxy returns' can work, a typical scenario is:
* <pre>{@code public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* Future<Object> future = rpcContext.getFuture();
* if (future instanceof FutureAdapter) {
* ((FutureAdapter) future).getFuture().setCallback(new FinishSpanCallback(span));
* }
* ......
* }
* }}</pre>
*
* Start from 2.7.3, you don't have to get Future from RpcContext, we recommend using Result directly:
* <pre>{@code public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* result.getResponseFuture().whenComplete(new FinishSpanCallback(span));
* ......
* }
* }}</pre>
*/@Deprecated
public void setCompatibleFuture(CompletableFuture<?> compatibleFuture) {
this.f0 = compatibleFuture;
if (compatibleFuture != null) {
this.setFuture(new FutureAdapter(compatibleFuture));
}
} | 3.26 |
dubbo_FutureContext_getCompletableFuture_rdh | /**
* get future.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
try {
return ((CompletableFuture<T>) (future));
} finally
{
if (clearFutureAfterGet) {
this.future = null;
}
}
} | 3.26 |
dubbo_FutureContext_setFuture_rdh | /**
* set future.
*
* @param future
*/
public void setFuture(CompletableFuture<?> future) {
this.future = future;
} | 3.26 |
dubbo_HealthStatusManager_setStatus_rdh | /**
* Updates the status of the server.
*
* @param service
* the name of some aspect of the server that is associated with a health status.
* This name can have no relation with the gRPC services that the server is
* running with. It can also be an empty String {@code ""} per the gRPC
* specification.
* @param status
* is one of the values {@link HealthCheckResponse.ServingStatus#SERVING}, {@link HealthCheckResponse.ServingStatus#NOT_SERVING} and {@link HealthCheckResponse.ServingStatus#UNKNOWN}.
*/
public void setStatus(String service, HealthCheckResponse.ServingStatus status) {
healthService.setStatus(service, status);
} | 3.26 |
dubbo_HealthStatusManager_clearStatus_rdh | /**
* Clears the health status record of a service. The health service will respond with NOT_FOUND
* error on checking the status of a cleared service.
*
* @param service
* the name of some aspect of the server that is associated with a health status.
* This name can have no relation with the gRPC services that the server is
* running with. It can also be an empty String {@code ""} per the gRPC
* specification.
*/
public void clearStatus(String service) {
healthService.clearStatus(service);
} | 3.26 |
dubbo_HealthStatusManager_enterTerminalState_rdh | /**
* enterTerminalState causes the health status manager to mark all services as not serving, and
* prevents future updates to services. This method is meant to be called prior to server
* shutdown as a way to indicate that clients should redirect their traffic elsewhere.
*/
public void enterTerminalState() {healthService.enterTerminalState();
} | 3.26 |
dubbo_MeshEnvListener_isEnable_rdh | /**
*
* @return whether current environment support listen
*/
default boolean isEnable() {
return false;
} | 3.26 |
dubbo_InstanceAddressURL_getAnyMethodParameter_rdh | /**
* Gets method level value of the specified key.
*
* @param key
* @return */
@Override
public String getAnyMethodParameter(String key) {
if (consumerParamFirst(key))
{
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getAnyMethodParameter(key);
if (StringUtils.isNotEmpty(v)) {return v;
}
}
}
String suffix = "." + key;
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return null;
}
for (String fullKey : serviceInfo.getAllParams().keySet()) {
if (fullKey.endsWith(suffix)) {
return getParameter(fullKey);
}
}
}
return null;
} | 3.26 |
dubbo_InstanceAddressURL_hasServiceMethodParameter_rdh | /**
* method parameter only exists in ServiceInfo
*
* @param method
* @return */@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasServiceMethodParameter(protocolServiceKey, method)) {
return true;
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return false;
}
return serviceInfo.hasMethodParameter(method);
} | 3.26 |
dubbo_InstanceAddressURL_getServiceParameters_rdh | /**
* Avoid calling this method in RPC call.
*
* @return */
@Override
public Map<String, String> getServiceParameters(String protocolServiceKey) {
Map<String, String> instanceParams = getInstance().getAllParams();
Map<String, String> metadataParams = (metadataInfo == null) ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey);
int i = (instanceParams == null) ? 0 : instanceParams.size();int j = (metadataParams == null) ? 0 : metadataParams.size();
Map<String, String> params = new HashMap<>(((int) ((i + j) / 0.75)) + 1);if (instanceParams != null) {
params.putAll(instanceParams);
}
if (metadataParams != null) {
params.putAll(metadataParams);
}
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {Map<String,
String> consumerParams = new HashMap<>(consumerUrl.getParameters());
if (CollectionUtils.isNotEmpty(f0)) {
f0.forEach(consumerParams::remove);
}params.putAll(consumerParams);
}
return params;
} | 3.26 |
dubbo_InstanceAddressURL_getServiceMethodParameter_rdh | /**
* method parameter only exists in ServiceInfo
*
* @param method
* @param key
* @return */
@Override
public String getServiceMethodParameter(String protocolServiceKey, String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getServiceMethodParameter(protocolServiceKey, method, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
MetadataInfo.ServiceInfo v14 = getServiceInfo(protocolServiceKey);
if (null == v14) {
return getParameter(key);
}
String value = v14.getMethodParameter(method, key, null);
if (StringUtils.isNotEmpty(value)) {
return value;
}
return getParameter(key);
} | 3.26 |
dubbo_DubboBootstrap_provider_rdh | // {@link ProviderConfig} correlative methods
public DubboBootstrap provider(Consumer<ProviderBuilder> builderConsumer) {
provider(null, builderConsumer);
return this;} | 3.26 |
dubbo_DubboBootstrap_await_rdh | /**
* Block current thread to be await.
*
* @return {@link DubboBootstrap}
*/
public DubboBootstrap await() {
// if has been waited, no need to wait again, return immediately
if (!awaited.get()) {
if (!isStopped()) {
executeMutually(() -> {
while (!awaited.get()) {
if (logger.isInfoEnabled()) {logger.info(NAME + " awaiting ...");
}
try {
condition.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
}
return this;
} | 3.26 |
dubbo_DubboBootstrap_m2_rdh | // {@link ServiceConfig} correlative methods
public <S> DubboBootstrap m2(Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(null, consumerBuilder);
} | 3.26 |
dubbo_DubboBootstrap_getInstance_rdh | /**
* See {@link ApplicationModel} and {@link ExtensionLoader} for why DubboBootstrap is designed to be singleton.
*/
public static DubboBootstrap getInstance() {
if (instance == null) {
synchronized(DubboBootstrap.class) {
if (instance == null) {
instance = DubboBootstrap.getInstance(ApplicationModel.defaultModel());
}
}
}
return instance;
} | 3.26 |
dubbo_DubboBootstrap_metadataReport_rdh | // MetadataReportConfig correlative methods
public DubboBootstrap metadataReport(Consumer<MetadataReportBuilder> consumerBuilder) {
return metadataReport(null, consumerBuilder);
} | 3.26 |
dubbo_DubboBootstrap_isStopping_rdh | /**
*
* @return true if the dubbo application is stopping.
* @see #isStopped()
*/
public boolean isStopping() {
return applicationDeployer.isStopping();
} | 3.26 |
dubbo_DubboBootstrap_start_rdh | /**
* Start dubbo application
*
* @param wait
* If true, wait for startup to complete, or else no waiting.
* @return */
public DubboBootstrap start(boolean wait) {Future future = applicationDeployer.start();
if (wait) {
try {
future.get();
} catch (Exception e) {
throw new IllegalStateException("await dubbo application start finish failure", e);
}
}
return this;
} | 3.26 |
dubbo_DubboBootstrap_newModule_rdh | /* serve for builder apis, end */
public Module newModule() {
return new Module(applicationModel.newModule());
} | 3.26 |
dubbo_DubboBootstrap_registries_rdh | /**
* Add an instance of {@link RegistryConfig}
*
* @param registryConfigs
* the multiple instances of {@link RegistryConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registries(List<RegistryConfig> registryConfigs) {
if (CollectionUtils.isEmpty(registryConfigs)) {
return
this;
}
registryConfigs.forEach(this::registry);
return
this;
} | 3.26 |
dubbo_DubboBootstrap_configCenter_rdh | // module configs end
// {@link ConfigCenterConfig} correlative methods
public DubboBootstrap configCenter(Consumer<ConfigCenterBuilder>
consumerBuilder) {
return configCenter(null, consumerBuilder);
} | 3.26 |
dubbo_DubboBootstrap_isStopped_rdh | /**
*
* @return true if the dubbo application is stopping.
* @see #isStopped()
*/
public boolean isStopped() {
return applicationDeployer.isStopped();
} | 3.26 |
dubbo_DubboBootstrap_createApplicationBuilder_rdh | /* serve for builder apis, begin */
private ApplicationBuilder createApplicationBuilder(String name) {
return new ApplicationBuilder().name(name);
} | 3.26 |
dubbo_DubboBootstrap_reference_rdh | // {@link Reference} correlative methods
public <S> Module reference(Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(null, consumerBuilder);} | 3.26 |
dubbo_DubboBootstrap_registry_rdh | /**
* Add an instance of {@link RegistryConfig}
*
* @param registryConfig
* an instance of {@link RegistryConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(RegistryConfig registryConfig) {
registryConfig.setScopeModel(applicationModel);
configManager.addRegistry(registryConfig);
return this;
} | 3.26 |
dubbo_DubboBootstrap_isRunning_rdh | /**
*
* @return true if the dubbo application is starting or has been started.
*/public boolean isRunning() {
return applicationDeployer.isRunning();
} | 3.26 |
dubbo_DubboBootstrap_isStarted_rdh | /**
*
* @return true if the dubbo application has been started.
* @see #start()
* @see #isStarting()
*/ public boolean isStarted() {
return applicationDeployer.isStarted();
} | 3.26 |
dubbo_DubboBootstrap_consumer_rdh | // {@link ConsumerConfig} correlative methods
public Module consumer(Consumer<ConsumerBuilder> builderConsumer) {
return consumer(null, builderConsumer);
} | 3.26 |
dubbo_DubboBootstrap_isStarting_rdh | /**
*
* @return true if the dubbo application is starting.
* @see #isStarted()
*/
public boolean isStarting() {
return applicationDeployer.isStarting();
} | 3.26 |
dubbo_DubboBootstrap_m0_rdh | /**
* Initialize
*/
public void m0() {
applicationDeployer.initialize();
} | 3.26 |
dubbo_DubboBootstrap_service_rdh | // {@link ServiceConfig} correlative methods
public <S> Module service(Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(null, consumerBuilder);
} | 3.26 |
dubbo_DubboBootstrap_stop_rdh | /**
* Stop dubbo application
*
* @return * @throws IllegalStateException
*/
public DubboBootstrap stop() throws IllegalStateException {
destroy();
return this;
} | 3.26 |
dubbo_DubboBootstrap_application_rdh | /**
* Set the {@link ApplicationConfig}
*
* @param applicationConfig
* the {@link ApplicationConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(ApplicationConfig applicationConfig) {
applicationConfig.setScopeModel(applicationModel);
configManager.setApplication(applicationConfig);return this;} | 3.26 |
dubbo_DubboBootstrap_reset_rdh | /**
* Try reset dubbo status for new instance.
*
* @deprecated For testing purposes only
*/
@Deprecated
public static void reset(boolean
destroy) {
if (destroy) {
if (instance != null) {
instance.destroy();
instance = null;
}
FrameworkModel.destroyAll();
} else {
instance = null;}
ApplicationModel.reset();
} | 3.26 |
dubbo_Proxy_newInstance_rdh | /**
* get instance with special handler.
*
* @return instance.
*/
public Object newInstance(InvocationHandler handler) {
Constructor<?> constructor;
try {
constructor = classToCreate.getDeclaredConstructor(InvocationHandler.class);
return constructor.newInstance(handler);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
} | 3.26 |
dubbo_Proxy_getProxy_rdh | /**
* Get proxy.
*
* @param ics
* interface class array.
* @return Proxy instance.
*/
public static Proxy getProxy(Class<?>... ics) {
if (ics.length > MAX_PROXY_COUNT) {
throw new IllegalArgumentException("interface limit exceeded");
}
// ClassLoader from App Interface should support load some class from Dubbo
ClassLoader cl = ics[0].getClassLoader();
ProtectionDomain domain = ics[0].getProtectionDomain();
// use interface class name list as key.
String key = buildInterfacesKey(cl, ics);
// get cache by class loader.
final Map<String, Proxy> cache;synchronized(PROXY_CACHE_MAP) {
cache = PROXY_CACHE_MAP.computeIfAbsent(cl, k -> new ConcurrentHashMap<>());
}
Proxy proxy = cache.get(key);
if (proxy == null) {
synchronized(ics[0]) {
proxy = cache.get(key);
if (proxy ==
null) {
// create Proxy class.
proxy = new Proxy(buildProxyClass(cl, ics, domain));
cache.put(key, proxy);
}
}
}
return proxy;
} | 3.26 |
dubbo_ConfigUtils_getProperties_rdh | /**
* Get dubbo properties.
* It is not recommended using this method to modify dubbo properties.
*
* @return */
public static Properties getProperties(Set<ClassLoader> classLoaders) {
String path = System.getProperty(CommonConstants.DUBBO_PROPERTIES_KEY);
if (StringUtils.isEmpty(path)) {
path = System.getenv(CommonConstants.DUBBO_PROPERTIES_KEY);
if
(StringUtils.isEmpty(path)) {
path = CommonConstants.DEFAULT_DUBBO_PROPERTIES;
}
}
return ConfigUtils.loadProperties(classLoaders, path, false, true);
} | 3.26 |
dubbo_ConfigUtils_mergeValues_rdh | /**
* Insert default extension into extension list.
* <p>
* Extension list support<ul>
* <li>Special value <code><strong>default</strong></code>, means the location for default extensions.
* <li>Special symbol<code><strong>-</strong></code>, means remove. <code>-foo1</code> will remove default extension 'foo'; <code>-default</code> will remove all default extensions.
* </ul>
*
* @param type
* Extension type
* @param cfg
* Extension name list
* @param def
* Default extension list
* @return result extension list
*/
public static List<String> mergeValues(ExtensionDirector extensionDirector, Class<?> type, String cfg, List<String> def) {
List<String> defaults = new ArrayList<String>();
if (def != null) {
for (String name : def) {
if (extensionDirector.getExtensionLoader(type).hasExtension(name)) {
defaults.add(name);
}
}
}
List<String> names = new ArrayList<String>();
// add initial values
String[] configs = ((cfg == null) || (cfg.trim().length() == 0)) ? new String[0] : COMMA_SPLIT_PATTERN.split(cfg);
for (String config : configs) {
if ((config != null) && (config.trim().length() > 0)) {
names.add(config);
}
}// -default is not included
if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) {
// add default extension
int i = names.indexOf(DEFAULT_KEY);
if (i > 0) {
names.addAll(i, defaults);
} else {
names.addAll(0, defaults);
}
names.remove(DEFAULT_KEY);
} else {
names.remove(DEFAULT_KEY);
}
// merge - configuration
for (String name : new ArrayList<String>(names)) {
if (name.startsWith(REMOVE_VALUE_PREFIX)) {
names.remove(name);
names.remove(name.substring(1));
}
}
return names;
} | 3.26 |
dubbo_ConfigUtils_checkFileNameExist_rdh | /**
* check if the fileName can be found in filesystem
*
* @param fileName
* @return */
private static boolean checkFileNameExist(String fileName) {
File file = new File(fileName);
return file.exists();
} | 3.26 |
dubbo_RestProtocol_getContextPath_rdh | /**
* getPath() will return: [contextpath + "/" +] path
* 1. contextpath is empty if user does not set through ProtocolConfig or ProviderConfig
* 2. path will never be empty, its default value is the interface name.
*
* @return return path only if user has explicitly gave then a value.
*/
private String getContextPath(URL url) {
String contextPath = url.getPath();
if (contextPath != null) {
if (contextPath.equalsIgnoreCase(url.getParameter(INTERFACE_KEY))) {
return "";
}
if (contextPath.endsWith(url.getParameter(INTERFACE_KEY))) {
contextPath = contextPath.substring(0, contextPath.lastIndexOf(url.getParameter(INTERFACE_KEY)));
}
return contextPath.endsWith(PATH_SEPARATOR) ? contextPath.substring(0, contextPath.length() - 1) : contextPath;
} else {
return "";
}
} | 3.26 |
dubbo_RestProtocol_createReferenceCountedClient_rdh | /**
* create rest ReferenceCountedClient
*
* @param url
* @return * @throws RpcException
*/
private ReferenceCountedClient<? extends RestClient> createReferenceCountedClient(URL url) throws RpcException {
// url -> RestClient
RestClient restClient = clientFactory.createRestClient(url);
return new ReferenceCountedClient<>(restClient, clients, clientFactory, url);
} | 3.26 |
dubbo_DubboConfigDefaultPropertyValueBeanPostProcessor_getOrder_rdh | /**
*
* @return Higher than {@link InitDestroyAnnotationBeanPostProcessor#getOrder()}
* @see InitDestroyAnnotationBeanPostProcessor
* @see CommonAnnotationBeanPostProcessor
* @see PostConstruct
*/
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE + 1;
} | 3.26 |
dubbo_EnvironmentConfiguration_getenv_rdh | // Adapt to System api, design for unit test
protected String getenv(String key) {
return System.getenv(key);
} | 3.26 |
dubbo_EnvironmentConfiguration_getInternalProperty_rdh | /**
* Configuration from system environment
*/public class EnvironmentConfiguration implements Configuration {
@Override
public Object getInternalProperty(String key) {
String value = getenv(key);
if (StringUtils.isEmpty(value)) {
value = getenv(StringUtils.toOSStyleKey(key));
}
return value;} | 3.26 |
dubbo_LoadingStrategy_onlyExtensionClassLoaderPackages_rdh | /**
* To restrict some class that should load from Dubbo's ClassLoader.
* For example, we can restrict the class declaration in `org.apache.dubbo` package should
* be loaded from Dubbo's ClassLoader and users cannot declare these classes.
*
* @return class packages should load
* @since 3.0.4
*/
default String[] onlyExtensionClassLoaderPackages() {
return new String[]{ };
} | 3.26 |
dubbo_LoadingStrategy_includedPackagesInCompatibleType_rdh | /**
* To restrict some class that should not be loaded from `org.alibaba.dubbo`(for compatible purpose)
* package type SPI class.
* For example, we can restrict the implementation class which package is `org.xxx.xxx`
* can be loaded as SPI implementation
*
* @return packages can be loaded in `org.alibaba.dubbo`'s SPI
*/
default String[] includedPackagesInCompatibleType() {
// default match all
return null;
} | 3.26 |
dubbo_LoadingStrategy_includedPackages_rdh | /**
* To restrict some class that should not be loaded from `org.apache.dubbo` package type SPI class.
* For example, we can restrict the implementation class which package is `org.xxx.xxx`
* can be loaded as SPI implementation.
*
* @return packages can be loaded in `org.apache.dubbo`'s SPI
*/default String[] includedPackages() {
// default match all
return null;
} | 3.26 |
dubbo_DubboBootstrapStopedEvent_getDubboBootstrap_rdh | /**
* Get {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} instance
*
* @return non-null
*/
public DubboBootstrap getDubboBootstrap() {
return ((DubboBootstrap) (super.getSource()));
} | 3.26 |
dubbo_ServiceInvokeRestFilter_acceptSupportJudge_rdh | /**
* accept can not support will throw UnSupportAcceptException
*
* @param requestFacade
*/
private void acceptSupportJudge(RequestFacade requestFacade, Class<?> returnType) {
try {
// media type judge
getAcceptMediaType(requestFacade, returnType);
} catch (UnSupportContentTypeException e) {// return type judge
MediaType mediaType = HttpMessageCodecManager.typeSupport(returnType);
String accept = requestFacade.getHeader(RestHeaderEnum.ACCEPT.getHeader());
if ((mediaType == null) || (accept == null)) {
throw e;
}
if (!accept.contains(mediaType.value)) {
throw
e;
}
}
} | 3.26 |
dubbo_ServiceInvokeRestFilter_getAcceptMediaType_rdh | /**
* return first match , if any multiple content-type
*
* @param request
* @return */
public static MediaType getAcceptMediaType(RequestFacade request, Class<?> returnType) {
String accept = request.getHeader(RestHeaderEnum.ACCEPT.getHeader());accept = (Objects.isNull(accept)) ?
ALL_VALUE.value : accept;
MediaType mediaType = MediaTypeUtil.convertMediaType(returnType,
accept);
return mediaType;
} | 3.26 |
dubbo_ServiceInvokeRestFilter_executeResponseIntercepts_rdh | /**
* execute response Intercepts
*
* @param restFilterContext
* @throws Exception
*/
public void executeResponseIntercepts(RestInterceptContext restFilterContext) throws Exception {
for (RestResponseInterceptor restResponseInterceptor : restResponseInterceptors) {
restResponseInterceptor.intercept(restFilterContext);
if (restFilterContext.complete()) {
break;
}
}
} | 3.26 |
dubbo_ServiceInvokeRestFilter_writeResult_rdh | /**
* write return value by accept
*
* @param nettyHttpResponse
* @param request
* @param value
* @param returnType
* @throws Exception
*/
public static void writeResult(NettyHttpResponse nettyHttpResponse, RequestFacade<?> request, URL url, Object value, Class<?> returnType) throws Exception {
MediaType mediaType = getAcceptMediaType(request, returnType);
writeResult(nettyHttpResponse, url, value, returnType, mediaType);
} | 3.26 |
dubbo_FutureAdapter_cancel_rdh | // TODO figure out the meaning of cancel in DefaultFuture.
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
// Invocation invocation = invocationSoftReference.get();
// if (invocation != null) {
// invocation.getInvoker().invoke(cancel);
// }
return appResponseFuture.cancel(mayInterruptIfRunning);
} | 3.26 |
dubbo_ChannelBuffer_release_rdh | /**
* If this buffer is backed by an NIO direct buffer,
* in some scenarios it may be necessary to manually release.
*/
default void release() {
} | 3.26 |
dubbo_PayloadDropper_getRequestWithoutData_rdh | /**
* only log body in debugger mode for size & security consideration.
*
* @param message
* @return */
public static Object getRequestWithoutData(Object message) {
if (f0.isDebugEnabled()) {
return message;
}
if (message instanceof Request) {
Request request = ((Request) (message));
request.setData(null);
return request;
} else if (message instanceof Response) {
Response response = ((Response) (message));
response.setResult(null);
return response;
}
return message;
} | 3.26 |
dubbo_PathURLAddress_getIp_rdh | /**
* Fetch IP address for this URL.
* <p>
* Pls. note that IP should be used instead of Host when to compare with socket's address or to search in a map
* which use address as its key.
*
* @return ip in string format
*/
public String getIp() {
if (ip == null) {
ip = NetUtils.getIpByHost(getHost());
}
return ip;
} | 3.26 |
dubbo_AsyncRpcResult_m0_rdh | /**
* Notice the return type of {@link #getValue} is the actual type of the RPC method, not {@link AppResponse}
*
* @return */
@Override
public Object m0() {
return getAppResponse().getValue();
} | 3.26 |
dubbo_AsyncRpcResult_setValue_rdh | /**
* CompletableFuture can only be completed once, so try to update the result of one completed CompletableFuture will
* have no effect. To avoid this problem, we check the complete status of this future before update its value.
* <p>
* But notice that trying to give an uncompleted CompletableFuture a new specified value may face a race condition,
* because the background thread watching the real result will also change the status of this CompletableFuture.
* The result is you may lose the value you expected to set.
*
* @param value
*/
@Overridepublic void setValue(Object value) {
try {
if (responseFuture.isDone()) {
responseFuture.get().setValue(value);
} else {
AppResponse appResponse = new AppResponse(f0);
appResponse.setValue(value);
responseFuture.complete(appResponse);
}
} catch (Exception
e) {
// This should not happen in normal request process;
logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult.");throw new RpcException(e);
}} | 3.26 |
dubbo_AsyncRpcResult_get_rdh | /**
* This method will always return after a maximum 'timeout' waiting:
* 1. if value returns before timeout, return normally.
* 2. if no value returns after timeout, throw TimeoutException.
*
* @return * @throws InterruptedException
* @throws ExecutionException
*/@Override
public Result get() throws InterruptedException, ExecutionException {
if (executor instanceof ThreadlessExecutor) {
ThreadlessExecutor threadlessExecutor = ((ThreadlessExecutor) (executor)); try {
while ((!responseFuture.isDone()) && (!threadlessExecutor.isShutdown())) {
threadlessExecutor.waitAndDrain(Long.MAX_VALUE);
}
} finally {
threadlessExecutor.shutdown();
}
}
return responseFuture.get();
} | 3.26 |
dubbo_AsyncRpcResult_newDefaultAsyncResult_rdh | /**
* Some utility methods used to quickly generate default AsyncRpcResult instance.
*/
public static AsyncRpcResult newDefaultAsyncResult(AppResponse appResponse, Invocation
invocation) {
return new AsyncRpcResult(CompletableFuture.completedFuture(appResponse), invocation);
} | 3.26 |
dubbo_NettyChannel_getOrAddChannel_rdh | /**
* Get dubbo channel by netty channel through channel cache.
* Put netty channel into it if dubbo channel don't exist in the cache.
*
* @param ch
* netty channel
* @param url
* @param handler
* dubbo handler that contain netty's handler
* @return */
static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) {
if (ch == null) {
return null;
}
NettyChannel ret = CHANNEL_MAP.get(ch);
if (ret == null) {
NettyChannel nettyChannel = new NettyChannel(ch, url, handler);
if (ch.isActive()) {
nettyChannel.markActive(true);
ret = CHANNEL_MAP.putIfAbsent(ch, nettyChannel);
}
if
(ret ==
null) {
ret = nettyChannel;
}
} else {
ret.markActive(true);
}
return ret;
} | 3.26 |
dubbo_NettyChannel_send_rdh | /**
* Send message by netty and whether to wait the completion of the send.
*
* @param message
* message that need send.
* @param sent
* whether to ack async-sent
* @throws RemotingException
* throw RemotingException if wait until timeout or any exception thrown by method body that surrounded by try-catch.
*/
@Override
public void send(Object message, boolean sent) throws RemotingException {
// whether the channel is closed
super.send(message, sent);boolean success = true;
int timeout = 0;
try {
Object outputMessage = message;
if (!encodeInIOThread) {
ByteBuf buf
= channel.alloc().buffer();
ChannelBuffer buffer = new NettyBackedChannelBuffer(buf);
codec.encode(this, buffer, message);
outputMessage = buf;
}
ChannelFuture v9 = writeQueue.enqueue(outputMessage).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!(message instanceof Request)) {
return;
}
ChannelHandler handler = getChannelHandler();
if (future.isSuccess()) {
handler.sent(NettyChannel.this, message);
} else {
Throwable t = future.cause();
if (t == null) {
return;
}
Response response = buildErrorResponse(((Request) (message)), t);
handler.received(NettyChannel.this, response);
}
}
});
if (sent) {
// wait timeout ms
timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);success = v9.await(timeout);}
Throwable cause = v9.cause();
if (cause != null) {
throw cause;
}
} catch (Throwable e) {
removeChannelIfDisconnected(channel);
throw new RemotingException(this, (((("Failed to send message " + PayloadDropper.getRequestWithoutData(message)) + " to ") + getRemoteAddress()) + ", cause: ") + e.getMessage(), e);
}
if (!success) {
throw new RemotingException(this, ((((("Failed to send message " + PayloadDropper.getRequestWithoutData(message)) + " to ") + getRemoteAddress()) + "in timeout(") + timeout)
+ "ms) limit");
}
} | 3.26 |
dubbo_NettyChannel_removeChannelIfDisconnected_rdh | /**
* Remove the inactive channel.
*
* @param ch
* netty channel
*/
static void removeChannelIfDisconnected(Channel ch) {
if ((ch != null) && (!ch.isActive())) {
NettyChannel
v2 = CHANNEL_MAP.remove(ch);
if (v2 != null) {
v2.markActive(false);
}
}} | 3.26 |
dubbo_AbstractReferenceConfig_isGeneric_rdh | /**
*
* @deprecated Replace to {@link AbstractReferenceConfig#getGeneric()}
*/
@Deprecated
@Parameter(excluded = true, attribute = false)
public Boolean isGeneric() {
return this.generic != null ? ProtocolUtils.isGeneric(generic) : null;
}
/**
*
* @deprecated Replace to {@link AbstractReferenceConfig#setGeneric(String)} | 3.26 |
dubbo_AbstractReferenceConfig_setInjvm_rdh | /**
*
* @param injvm
* @deprecated instead, use the parameter <b>scope</b> to judge if it's in jvm, scope=local
*/
@Deprecated
public void setInjvm(Boolean injvm) {
this.injvm = injvm;
} | 3.26 |
dubbo_AbstractReferenceConfig_isInjvm_rdh | /**
*
* @return * @deprecated instead, use the parameter <b>scope</> to judge if it's in jvm, scope=local
*/
@Deprecated
public Boolean isInjvm() {
return injvm;
} | 3.26 |
dubbo_AwaitingNonWebApplicationListener_releaseOnExit_rdh | /**
*
* @param applicationContext
* @since 2.7.8
*/
private void releaseOnExit(ConfigurableApplicationContext applicationContext) {
ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(applicationContext);
if (applicationModel == null) {return;
}
ShutdownHookCallbacks shutdownHookCallbacks = applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class);
if (shutdownHookCallbacks != null) {shutdownHookCallbacks.addCallback(this::release);
}
} | 3.26 |
dubbo_ReactorClientCalls_manyToOne_rdh | /**
* Implements a stream -> unary call as Flux -> Mono
*
* @param invoker
* invoker
* @param requestFlux
* the flux with request
* @param methodDescriptor
* the method descriptor
* @return the mono with response
*/
public static <TRequest, TResponse, TInvoker> Mono<TResponse> manyToOne(Invoker<TInvoker> invoker, Flux<TRequest> requestFlux, StubMethodDescriptor methodDescriptor) {
try {
ClientTripleReactorSubscriber<TRequest> clientSubscriber = requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>());
ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>(s -> clientSubscriber.subscribe(((CallStreamObserver<TRequest>) (s))), clientSubscriber::cancel);
return Mono.from(clientPublisher).doOnSubscribe(dummy -> StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher));
} catch (Throwable throwable) {
return Mono.error(throwable);
}
} | 3.26 |
dubbo_ReactorClientCalls_oneToMany_rdh | /**
* Implements a unary -> stream call as Mono -> Flux
*
* @param invoker
* invoker
* @param monoRequest
* the mono with request
* @param methodDescriptor
* the method descriptor
* @return the flux with response
*/
public static <TRequest,
TResponse, TInvoker> Flux<TResponse> oneToMany(Invoker<TInvoker> invoker, Mono<TRequest> monoRequest, StubMethodDescriptor methodDescriptor) {
try {
return monoRequest.flatMapMany(request -> {
ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>();
StubInvocationUtil.serverStreamCall(invoker, methodDescriptor, request, clientPublisher);
return clientPublisher;
});
} catch (Throwable throwable) {
return Flux.error(throwable);
}
} | 3.26 |
dubbo_ReactorClientCalls_oneToOne_rdh | /**
* Implements a unary -> unary call as Mono -> Mono
*
* @param invoker
* invoker
* @param monoRequest
* the mono with request
* @param methodDescriptor
* the method descriptor
* @return the mono with response
*/
public static <TRequest, TResponse, TInvoker> Mono<TResponse> oneToOne(Invoker<TInvoker> invoker, Mono<TRequest> monoRequest, StubMethodDescriptor methodDescriptor) {
try {
return Mono.create(emitter -> monoRequest.subscribe(request -> StubInvocationUtil.unaryCall(invoker, methodDescriptor, request, new StreamObserver<TResponse>() {
@Override
public void onNext(TResponse tResponse) {
emitter.success(tResponse);
}
@Override
public void onError(Throwable throwable) {
emitter.error(throwable);
}
@Overridepublic void onCompleted() {
// Do nothing
}
}), emitter::error));
} catch (Throwable throwable) {
return Mono.error(throwable);
}
} | 3.26 |
dubbo_ReactorClientCalls_manyToMany_rdh | /**
* Implements a stream -> stream call as Flux -> Flux
*
* @param invoker
* invoker
* @param requestFlux
* the flux with request
* @param methodDescriptor
* the method descriptor
* @return the flux with response
*/
public static <TRequest, TResponse, TInvoker> Flux<TResponse> manyToMany(Invoker<TInvoker> invoker, Flux<TRequest> requestFlux, StubMethodDescriptor methodDescriptor) {
try {
ClientTripleReactorSubscriber<TRequest> clientSubscriber = requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>());
ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>(s -> clientSubscriber.subscribe(((CallStreamObserver<TRequest>) (s))), clientSubscriber::cancel);
return Flux.from(clientPublisher).doOnSubscribe(dummy -> StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher));
} catch (Throwable throwable) {
return Flux.error(throwable);
}
} | 3.26 |
dubbo_MetricsEventBus_post_rdh | /**
* Full lifecycle post, success and failure conditions can be customized
*
* @param event
* event to post.
* @param targetSupplier
* original processing result supplier
* @param trFunction
* Custom event success criteria, judged according to the returned boolean type
* @param <T>
* Biz result type
* @return Biz result
*/
public static <T>
T post(MetricsEvent event, Supplier<T> targetSupplier, Function<T, Boolean> trFunction) {
T result;
tryInvoke(() -> before(event));if (trFunction == null) {
try {
result = targetSupplier.get();
} catch (Throwable e) {
tryInvoke(() -> error(event));
throw e;
}
tryInvoke(() -> after(event, result));
} else {
// Custom failure status
result = targetSupplier.get();
if (trFunction.apply(result)) {
tryInvoke(() -> after(event, result));
} else {
tryInvoke(() -> error(event));
}}
return result;
} | 3.26 |
dubbo_MetricsEventBus_publish_rdh | /**
* Posts an event to all registered subscribers and only once.
*
* @param event
* event to post.
*/
public static void publish(MetricsEvent event) {
if (event.getSource() == null) {
return;
}
MetricsDispatcher v0 = event.getMetricsDispatcher();
Optional.ofNullable(v0).ifPresent(d -> {
tryInvoke(() -> d.publishEvent(event));
});
} | 3.26 |
dubbo_MetricsEventBus_before_rdh | /**
* Applicable to the scene where execution and return are separated,
* eventSaveRunner saves the event, so that the calculation rt is introverted
*/
public static void before(MetricsEvent event) {
MetricsDispatcher dispatcher = validate(event);
if (dispatcher == null)
return;
tryInvoke(() -> dispatcher.publishEvent(event));
} | 3.26 |
dubbo_PathAndInvokerMapper_m0_rdh | /**
* undeploy path metadata
*
* @param pathMatcher
*/
public void m0(PathMatcher pathMatcher) {
InvokerAndRestMethodMetadataPair containPathVariablePair = f0.remove(pathMatcher);
InvokerAndRestMethodMetadataPair unContainPathVariablePair = pathToServiceMapNoPathVariable.remove(pathMatcher);
logger.info((((("dubbo rest undeploy pathMatcher:" + pathMatcher) + ", and path variable method is :") + (containPathVariablePair == null ? null : containPathVariablePair.getRestMethodMetadata().getReflectMethod())) + ", and no path variable method is :") + (unContainPathVariablePair == null ? null : unContainPathVariablePair.getRestMethodMetadata().getReflectMethod()));} | 3.26 |
dubbo_PathAndInvokerMapper_addPathAndInvoker_rdh | /**
* deploy path metadata
*
* @param metadataMap
* @param invoker
*/
public void addPathAndInvoker(Map<PathMatcher, RestMethodMetadata> metadataMap, Invoker invoker) {
metadataMap.entrySet().stream().forEach(entry
-> {
PathMatcher pathMatcher = entry.getKey();
if (pathMatcher.hasPathVariable()) {
addPathMatcherToPathMap(pathMatcher, f0, InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue()));
} else {
addPathMatcherToPathMap(pathMatcher, pathToServiceMapNoPathVariable, InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue()));
}
});
} | 3.26 |
dubbo_PathAndInvokerMapper_getRestMethodMetadata_rdh | /**
* get rest method metadata by path matcher
*
* @param pathMatcher
* @return */
public InvokerAndRestMethodMetadataPair getRestMethodMetadata(PathMatcher pathMatcher) {
// first search from pathToServiceMapNoPathVariable
if (pathToServiceMapNoPathVariable.containsKey(pathMatcher)) {
return
pathToServiceMapNoPathVariable.get(pathMatcher);
}
// second search from pathToServiceMapContainPathVariable
if (f0.containsKey(pathMatcher)) {
return f0.get(pathMatcher);}
return null;
} | 3.26 |
dubbo_InternalThreadLocalMap_setIndexedVariable_rdh | /**
*
* @return {@code true} if and only if a new thread-local variable has been created
*/
public boolean setIndexedVariable(int index, Object value) {
Object[] lookup = indexedVariables;
if (index < lookup.length) {
Object oldValue = lookup[index];
lookup[index] = value;
return oldValue == UNSET;
} else {
expandIndexedVariableTableAndSet(index, value);
return true;
}
} | 3.26 |
dubbo_ExpiringCache_get_rdh | /**
* API to return stored value using a key against the calling thread specific store.
*
* @param key
* Unique identifier for cache lookup
* @return Return stored object against key
*/
@Override
public Object get(Object key) {
return store.get(key);
} | 3.26 |
dubbo_ReferenceConfigBase_getInterfaceClass_rdh | /**
* Get proxy interface class of this reference.
* The proxy interface class is used to create proxy instance.
*
* @return */
public Class<?> getInterfaceClass() {
if (interfaceClass != null) {
return interfaceClass;
}
String generic = getGeneric();
if (StringUtils.isBlank(generic) && (getConsumer() !=
null)) {
generic = getConsumer().getGeneric();
}
if (getInterfaceClassLoader() != null) {
interfaceClass = determineInterfaceClass(generic, interfaceName, getInterfaceClassLoader());
} else {
interfaceClass =
determineInterfaceClass(generic, interfaceName);}
return interfaceClass;
} | 3.26 |
dubbo_ReferenceConfigBase_determineInterfaceClass_rdh | /**
* Determine the interface of the proxy class
*
* @param generic
* @param interfaceName
* @return */
public static Class<?> determineInterfaceClass(String generic, String interfaceName) {
return determineInterfaceClass(generic, interfaceName, ClassUtils.getClassLoader());
} | 3.26 |
dubbo_ReferenceConfigBase_getServiceInterfaceClass_rdh | /**
* Get service interface class of this reference.
* The actual service type of remote provider.
*
* @return */
public Class<?> getServiceInterfaceClass() {
Class<?> actualInterface = interfaceClass;
if (interfaceClass == GenericService.class) {
try {
if (getInterfaceClassLoader() != null) {
actualInterface = Class.forName(interfaceName, false, getInterfaceClassLoader());
} else {
actualInterface = Class.forName(interfaceName);
}
} catch (ClassNotFoundException e) {
return null;
}
}
return actualInterface;
} | 3.26 |
dubbo_Version_getPrefixDigits_rdh | /**
* get prefix digits from given version string
*/
private static String getPrefixDigits(String v) {
Matcher matcher = PREFIX_DIGITS_PATTERN.matcher(v);
if (matcher.find()) {
return matcher.group(1);
}
return "";
} | 3.26 |
dubbo_Version_isRelease270OrHigher_rdh | /**
* Check the framework release version number to decide if it's 2.7.0 or higher
*/
public static boolean isRelease270OrHigher(String version) {
if (StringUtils.isEmpty(version)) {
return false;
}
return getIntVersion(version) >= 2070000;
} | 3.26 |
dubbo_Version_getFromFile_rdh | /**
* get version from file: path/to/group-module-x.y.z.jar, returns x.y.z
*/
private static String getFromFile(String file) {
// remove suffix ".jar": "path/to/group-module-x.y.z"
file = file.substring(0, file.length() - 4);
// remove path: "group-module-x.y.z"
int i = file.lastIndexOf('/');
if (i >= 0) {
file = file.substring(i + 1);
}// remove group: "module-x.y.z"
i = file.indexOf("-");
if (i >= 0) {
file = file.substring(i
+ 1);
}
// remove module: "x.y.z"
while ((file.length() > 0) && (!Character.isDigit(file.charAt(0)))) {
i = file.indexOf("-");
if (i >= 0) {
file = file.substring(i + 1);
} else {
break;
}
} return file;
} | 3.26 |
dubbo_Version_isRelease263OrHigher_rdh | /**
* Check the framework release version number to decide if it's 2.6.3 or higher
*
* @param version,
* the sdk version
*/
public static boolean isRelease263OrHigher(String version) {
return getIntVersion(version) >=
2060300;
} | 3.26 |
dubbo_ExceptionFilter_setLogger_rdh | // For test purpose
public void setLogger(ErrorTypeAwareLogger logger) {
this.logger = logger;
} | 3.26 |
dubbo_MetadataServiceDelegation_serviceName_rdh | /**
* Gets the current Dubbo Service name
*
* @return non-null
*/
@Override
public String serviceName()
{
return ApplicationModel.ofNullable(applicationModel).getApplicationName();
} | 3.26 |
dubbo_CuratorZookeeperClient_getClient_rdh | /**
* just for unit test
*
* @return */
CuratorFramework getClient() {
return client;
} | 3.26 |
dubbo_ThrowableFunction_execute_rdh | /**
* Executes {@link ThrowableFunction}
*
* @param t
* the function argument
* @param function
* {@link ThrowableFunction}
* @param <T>
* the source type
* @param <R>
* the return type
* @return the result after execution
*/
static <T, R> R execute(T t, ThrowableFunction<T, R> function) {
return function.execute(t);} | 3.26 |
dubbo_AbstractCluster_doInvoke_rdh | /**
* The only purpose is to build a interceptor chain, so the cluster related logic doesn't matter.
* Use ClusterInvoker<T> to replace AbstractClusterInvoker<T> in the future.
*/
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
return null;} | 3.26 |
dubbo_InmemoryConfiguration_addProperties_rdh | /**
* Add a set of properties into the store
*/
public void addProperties(Map<String, String> properties) {if (properties != null) {
this.store.putAll(properties);
}
} | 3.26 |