name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
dubbo_RpcContext_getResponse_rdh
/** * Get the response object of the underlying RPC protocol, e.g. HttpServletResponse * * @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type */ @SuppressWarnings("unchecked") public <T> T getResponse(Class<T> clazz) { return newRpcContext.getResponse(clazz); }
3.26
dubbo_RpcContext_getLocalAddress_rdh
/** * get local address. * * @return local address */ public InetSocketAddress getLocalAddress() { return newRpcContext.getLocalAddress();}
3.26
dubbo_RpcContext_set_rdh
/** * set value. * * @param key * @param value * @return context */ public RpcContext set(String key, Object value) { newRpcContext.set(key, value); return this; }
3.26
dubbo_RpcContext_m2_rdh
/** * is consumer side. * * @return consumer side. */ public boolean m2() { return newRpcContext.isConsumerSide(); }
3.26
dubbo_JValidation_createValidator_rdh
/** * Return new instance of {@link JValidator} * * @param url * Valid URL instance * @return Instance of JValidator */ @Override protected Validator createValidator(URL url) { return new JValidator(url); }
3.26
dubbo_FrameworkModel_destroyAll_rdh
/** * Destroy all framework model instances, shutdown dubbo engine completely. */ public static void destroyAll() {synchronized(globalLock) { for (FrameworkModel frameworkModel : new ArrayList<>(allInstances)) { frameworkModel.destroy(); } } }
3.26
dubbo_FrameworkModel_defaultApplication_rdh
/** * Get or create default application model * * @return */ public ApplicationModel defaultApplication() { ApplicationModel appModel = this.defaultAppModel; if (appModel == null) { // check destroyed before acquire inst lock, avoid blocking during destroying checkDestroyed(); resetDefaultAppModel(); if ((appModel = this.defaultAppModel) == null) { synchronized(instLock) { if (this.defaultAppModel == null) { this.defaultAppModel = newApplication(); } appModel = this.defaultAppModel; } } } Assert.notNull(appModel, "Default ApplicationModel is null"); return appModel; }
3.26
dubbo_FrameworkModel_defaultModel_rdh
/** * During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or ApplicationModel.defaultModel() * will return a broken model, maybe cause unpredictable problem. * Recommendation: Avoid using the default model as much as possible. * * @return the global default FrameworkModel */ public static FrameworkModel defaultModel() { FrameworkModel instance = defaultInstance; if (instance == null) { synchronized(globalLock) { resetDefaultFrameworkModel(); if (defaultInstance == null) { defaultInstance = new FrameworkModel(); } instance = defaultInstance; } } Assert.notNull(instance, "Default FrameworkModel is null"); return instance; }
3.26
dubbo_FrameworkModel_getAllInstances_rdh
/** * Get all framework model instances * * @return */ public static List<FrameworkModel> getAllInstances() { synchronized(globalLock) {return Collections.unmodifiableList(new ArrayList<>(allInstances)); } }
3.26
dubbo_FrameworkModel_getAllApplicationModels_rdh
/** * Get all application models including the internal application model. */public List<ApplicationModel> getAllApplicationModels() { synchronized(globalLock) { return Collections.unmodifiableList(applicationModels); } }
3.26
dubbo_FrameworkModel_tryDestroyProtocols_rdh
/** * Protocols are special resources that need to be destroyed as soon as possible. * * Since connections inside protocol are not classified by applications, trying to destroy protocols in advance might only work for singleton application scenario. */ void tryDestroyProtocols() {synchronized(instLock) { if (pubApplicationModels.size() == 0) { notifyProtocolDestroy(); } } }
3.26
dubbo_FrameworkModel_getApplicationModels_rdh
/** * Get all application models except for the internal application model. */ public List<ApplicationModel> getApplicationModels() { synchronized(globalLock) { return Collections.unmodifiableList(pubApplicationModels); } }
3.26
dubbo_MemorySafeLinkedBlockingQueue_getMaxFreeMemory_rdh
/** * get the max free memory. * * @return the max free memory limit */ public long getMaxFreeMemory() {return maxFreeMemory; }
3.26
dubbo_MemorySafeLinkedBlockingQueue_setMaxFreeMemory_rdh
/** * set the max free memory. * * @param maxFreeMemory * the max free memory */ public void setMaxFreeMemory(final int maxFreeMemory) { this.maxFreeMemory = maxFreeMemory; }
3.26
dubbo_MemorySafeLinkedBlockingQueue_setRejector_rdh
/** * set the rejector. * * @param rejector * the rejector */ public void setRejector(final Rejector<E> rejector) { this.rejector = rejector; }
3.26
dubbo_CompatibleTypeUtils_compatibleTypeConvert_rdh
/** * Compatible type convert. Null value is allowed to pass in. If no conversion is needed, then the original value * will be returned. * <p> * Supported compatible type conversions include (primary types and corresponding wrappers are not listed): * <ul> * <li> String -> char, enum, Date * <li> byte, short, int, long -> byte, short, int, long * <li> float, double -> float, double * </ul> */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (((value == null) || (type == null)) || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = ((String) (value)); if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } if (type.isEnum()) { return Enum.valueOf(((Class<Enum>) (type)), string); } if (type == BigInteger.class) { return new BigInteger(string);} if (type == BigDecimal.class) { return new BigDecimal(string); } if ((type == Short.class) || (type == short.class)) { return new Short(string); } if ((type == Integer.class) || (type == int.class)) { return new Integer(string); } if ((type == Long.class) || (type == long.class)) { return new Long(string); } if ((type == Double.class) || (type == double.class)) { return new Double(string); } if ((type == Float.class) || (type == float.class)) { return new Float(string); } if ((type == Byte.class) || (type == byte.class)) { return new Byte(string); } if ((type == Boolean.class) || (type == boolean.class)) { return Boolean.valueOf(string); } if ((((type == Date.class) || (type == Date.class)) || (type == Timestamp.class)) || (type == Time.class)) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); if (type == Date.class) { return new Date(date.getTime()); } if (type == Timestamp.class) {return new Timestamp(date.getTime()); } if (type == Time.class) { return new Time(date.getTime()); } return date; } catch (ParseException e) { throw new IllegalStateException((((("Failed to parse date " + value) + " by format ") + DATE_FORMAT) + ", cause: ") + e.getMessage(), e); } }if (type == LocalDateTime.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDateTime.parse(string); } if (type == LocalDate.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDate.parse(string); }if (type == LocalTime.class) { if (StringUtils.isEmpty(string)) { return null; } if (string.length() >= ISO_LOCAL_DATE_TIME_MIN_LEN) { return LocalDateTime.parse(string).toLocalTime(); } else { return LocalTime.parse(string); } } if (type == Class.class) { try { return ReflectUtils.name2class(string); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } }if (char[].class.equals(type)) { // Process string to char array for generic invoke // See // - https://github.com/apache/dubbo/issues/2003 int len = string.length(); char[] chars = new char[len]; string.getChars(0, len, chars, 0); return chars; } } if (value instanceof Number) { Number v4 = ((Number) (value)); if ((type == byte.class) || (type == Byte.class)) { return v4.byteValue(); } if ((type == short.class) || (type == Short.class)) { return v4.shortValue(); } if ((type == int.class) || (type == Integer.class)) { return v4.intValue(); } if ((type == long.class) || (type == Long.class)) { return v4.longValue(); } if ((type == float.class) || (type == Float.class)) { return v4.floatValue(); } if ((type == double.class) || (type == Double.class)) { return v4.doubleValue(); } if (type == BigInteger.class) { return BigInteger.valueOf(v4.longValue()); } if (type == BigDecimal.class) { return new BigDecimal(v4.toString()); } if (type == Date.class) { return new Date(v4.longValue()); } if ((type == boolean.class) || (type == Boolean.class)) { return 0 != v4.intValue(); } } if (value instanceof Collection) { Collection collection = ((Collection) (value)); if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } if (!type.isInterface()) { try { Collection result = ((Collection) (type.getDeclaredConstructor().newInstance())); result.addAll(collection);return result; } catch (Throwable ignored) { } } if (type == List.class) { return new ArrayList<Object>(collection); } if (type == Set.class) { return new HashSet<Object>(collection); } } if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { int length = Array.getLength(value); Collection collection; if (!type.isInterface()) { try { collection = ((Collection) (type.getDeclaredConstructor().newInstance())); } catch (Exception e) { collection = new ArrayList<Object>(length); } } else if (type == Set.class) { collection = new HashSet<Object>(Math.max(((int) (length / 0.75F)) + 1, 16)); } else { collection = new ArrayList<Object>(length); } for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
3.26
dubbo_AppScriptStateRouter_setScriptRule_rdh
// for testing purpose public void setScriptRule(ScriptRule scriptRule) { this.scriptRule = scriptRule; }
3.26
dubbo_ReferenceBean_getInterfaceClass_rdh
/** * The interface of this ReferenceBean, for injection purpose * * @return */ public Class<?> getInterfaceClass() { // Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() return interfaceClass; }
3.26
dubbo_ReferenceBean_createLazyProxy_rdh
/** * Create lazy proxy for reference. */private void createLazyProxy() { // set proxy interfaces // see also: org.apache.dubbo.rpc.proxy.AbstractProxyFactory.getProxy(org.apache.dubbo.rpc.Invoker<T>, boolean) List<Class<?>> interfaces = new ArrayList<>(); interfaces.add(interfaceClass); Class<?>[] internalInterfaces = AbstractProxyFactory.getInternalInterfaces(); Collections.addAll(interfaces, internalInterfaces); if (!StringUtils.isEquals(interfaceClass.getName(), interfaceName)) { // add service interface try {Class<?> serviceInterface = ClassUtils.forName(interfaceName, beanClassLoader); interfaces.add(serviceInterface); } catch (ClassNotFoundException e) { // generic call maybe without service interface class locally } } if (StringUtils.isEmpty(this.proxy) || CommonConstants.DEFAULT_PROXY.equalsIgnoreCase(this.proxy)) { generateFromJavassistFirst(interfaces); } if (this.lazyProxy == null) { generateFromJdk(interfaces); } }
3.26
dubbo_ReferenceBean_getObject_rdh
/** * Create bean instance. * * <p></p> * Why we need a lazy proxy? * * <p/> * When Spring searches beans by type, if Spring cannot determine the type of a factory bean, it may try to initialize it. * The ReferenceBean is also a FactoryBean. * <br/> * (This has already been resolved by decorating the BeanDefinition: {@link DubboBeanDefinitionParser#configReferenceBean}) * * <p/> * In addition, if some ReferenceBeans are dependent on beans that are initialized very early, * and dubbo config beans are not ready yet, there will be many unexpected problems if initializing the dubbo reference immediately. * * <p/> * When it is initialized, only a lazy proxy object will be created, * and dubbo reference-related resources will not be initialized. * <br/> * In this way, the influence of Spring is eliminated, and the dubbo configuration initialization is controllable. * * @see DubboConfigBeanInitializer * @see ReferenceBeanManager#initReferenceBean(ReferenceBean) * @see DubboBeanDefinitionParser#configReferenceBean */ @Override public T getObject() { if (lazyProxy == null) { createLazyProxy(); } return ((T) (lazyProxy)); }
3.26
dubbo_MetadataServiceNameMapping_m0_rdh
/** * Simply register to all metadata center */@Override public boolean m0(URL url) { if (CollectionUtils.isEmpty(applicationModel.getApplicationConfigManager().getMetadataConfigs())) { logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "No valid metadata config center found for mapping report."); return false; } String serviceInterface = url.getServiceInterface(); if (IGNORED_SERVICE_INTERFACES.contains(serviceInterface)) {return true; } boolean result = true; for (Map.Entry<String, MetadataReport> v2 : metadataReportInstance.getMetadataReports(true).entrySet()) { MetadataReport metadataReport = v2.getValue(); String appName = applicationModel.getApplicationName(); try { if (metadataReport.registerServiceAppMapping(serviceInterface, appName, url)) { // MetadataReport support directly register service-app mapping continue; }boolean succeeded = false; int currentRetryTimes = 1; String v7 = appName; do { ConfigItem configItem = metadataReport.getConfigItem(serviceInterface, DEFAULT_MAPPING_GROUP); String oldConfigContent = configItem.getContent(); if (StringUtils.isNotEmpty(oldConfigContent)) { String[] oldAppNames = oldConfigContent.split(","); if (oldAppNames.length > 0) { for (String oldAppName : oldAppNames) { if (oldAppName.equals(appName)) { succeeded = true; break; } } } if (succeeded) { break; } v7 = (oldConfigContent + COMMA_SEPARATOR) + appName; } succeeded = metadataReport.registerServiceAppMapping(serviceInterface, DEFAULT_MAPPING_GROUP, v7, configItem.getTicket()); if (!succeeded) { int waitTime = ThreadLocalRandom.current().nextInt(casRetryWaitTime); logger.info((((((((((((((((("Failed to publish service name mapping to metadata center by cas operation. " + "Times: ") + currentRetryTimes) + ". ") + "Next retry delay: ") + waitTime) + ". ") + "Service Interface: ") + serviceInterface) + ". ") + "Origin Content: ") + oldConfigContent) + ". ") + "Ticket: ") + configItem.getTicket()) + ". ") + "Excepted context: ") + v7);Thread.sleep(waitTime); } } while ((!succeeded) && ((currentRetryTimes++) <= casRetryTimes) ); if (!succeeded) { result = false; } } catch (Exception e) { result = false; logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Failed registering mapping to remote." + metadataReport, e); } } return result; }
3.26
dubbo_ClusterInterceptor_intercept_rdh
/** * Override this method or {@link #before(AbstractClusterInvoker, Invocation)} * and {@link #after(AbstractClusterInvoker, Invocation)} methods to add your own logic expected to be * executed before and after invoke. * * @param clusterInvoker * @param invocation * @return * @throws RpcException */ default Result intercept(AbstractClusterInvoker<?> clusterInvoker, Invocation invocation) throws RpcException { return clusterInvoker.invoke(invocation); }
3.26
dubbo_AbstractExporter_afterUnExport_rdh
/** * subclasses need to override this method to destroy resources. */ public void afterUnExport() { }
3.26
dubbo_AbstractMethodConfig_setMock_rdh
/** * Set the property "mock" * * @param mock * the value of mock * @since 2.7.6 * @deprecated use {@link #setMock(String)} instead */ @Deprecated public void setMock(Object mock) { if (mock == null) { return; } this.setMock(String.valueOf(mock)); }
3.26
dubbo_ServiceInstancesChangedEvent_getServiceInstances_rdh
/** * * @return all {@link ServiceInstance service instances} */ public List<ServiceInstance> getServiceInstances() { return serviceInstances; }
3.26
dubbo_ServiceInstancesChangedEvent_getServiceName_rdh
/** * * @return The name of service that was changed */ public String getServiceName() { return serviceName; }
3.26
dubbo_ReferenceConfig_m0_rdh
/** * if enable mesh mode, handle url. * * @param referenceParameters * referenceParameters */ private void m0(Map<String, String> referenceParameters) { if (!checkMeshConfig(referenceParameters)) { return; } if (StringUtils.isNotEmpty(url)) { // user specified URL, could be peer-to-peer address, or register center's address. if (logger.isInfoEnabled()) { logger.info("The url already exists, mesh no longer processes url: " + url); } return; } // get provider namespace if (@DubboReference, <reference provider-namespace="xx"/>) present String podNamespace = referenceParameters.get(RegistryConstants.PROVIDER_NAMESPACE); // get pod namespace from env if annotation not present the provider namespace if (StringUtils.isEmpty(podNamespace)) { if (StringUtils.isEmpty(System.getenv("POD_NAMESPACE"))) { if (logger.isWarnEnabled()) { logger.warn(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "Can not get env variable: POD_NAMESPACE, it may not be running in the K8S environment , " + "finally use 'default' replace."); } podNamespace = "default"; } else { podNamespace = System.getenv("POD_NAMESPACE"); }} // In mesh mode, providedBy equals K8S Service name. String providedBy = referenceParameters.get(PROVIDED_BY); // cluster_domain default is 'cluster.local',generally unchanged. String clusterDomain = Optional.ofNullable(System.getenv("CLUSTER_DOMAIN")).orElse(DEFAULT_CLUSTER_DOMAIN); // By VirtualService and DestinationRule, envoy will generate a new route rule,such as // 'demo.default.svc.cluster.local:80',the default port is 80. Integer meshPort = Optional.ofNullable(getProviderPort()).orElse(DEFAULT_MESH_PORT); // DubboReference default is -1, process it. meshPort = (meshPort > (-1)) ? meshPort : DEFAULT_MESH_PORT;// get mesh url. url = (((((((TRIPLE + "://") + providedBy) + ".") + podNamespace) + SVC) + clusterDomain) + ":") + meshPort; }
3.26
dubbo_ReferenceConfig_createInvoker_rdh
/** * \create a reference invoker */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void createInvoker() {if (urls.size() == 1) { URL curUrl = urls.get(0); invoker = protocolSPI.refer(interfaceClass, curUrl); // registry url, mesh-enable and unloadClusterRelated is true, not need Cluster. if ((!UrlUtils.isRegistry(curUrl)) && (!curUrl.getParameter(UNLOAD_CLUSTER_RELATED, false))) { List<Invoker<?>> invokers = new ArrayList<>(); invokers.add(invoker); invoker = Cluster.getCluster(getScopeModel(), Cluster.DEFAULT).join(new StaticDirectory(curUrl, invokers), true); } } else { List<Invoker<?>> invokers = new ArrayList<>(); URL registryUrl = null;for (URL url : urls) { // For multi-registry scenarios, it is not checked whether each referInvoker is available. // Because this invoker may become available later. invokers.add(protocolSPI.refer(interfaceClass, url)); if (UrlUtils.isRegistry(url)) { // use last registry url registryUrl = url; }} if (registryUrl != null) { // registry url is available // for multi-subscription scenario, use 'zone-aware' policy by default String cluster = registryUrl.getParameter(CLUSTER_KEY, ZoneAwareCluster.NAME); // The invoker wrap sequence would be: ZoneAwareClusterInvoker(StaticDirectory) -> // FailoverClusterInvoker // (RegistryDirectory, routing happens here) -> Invoker invoker = Cluster.getCluster(registryUrl.getScopeModel(), cluster, false).join(new StaticDirectory(registryUrl, invokers), false); } else { // not a registry url, must be direct invoke. if (CollectionUtils.isEmpty(invokers)) { throw new IllegalArgumentException("invokers == null"); } URL curUrl = invokers.get(0).getUrl(); String cluster = curUrl.getParameter(CLUSTER_KEY, Cluster.DEFAULT); invoker = Cluster.getCluster(getScopeModel(), cluster).join(new StaticDirectory(curUrl, invokers), true); } } }
3.26
dubbo_ReferenceConfig_configInitialized_rdh
/** * Return if ReferenceConfig has been initialized * Note: Cannot use `isInitilized` as it may be treated as a Java Bean property * * @return initialized */ @Transient public boolean configInitialized() { return initialized; }
3.26
dubbo_ReferenceConfig_getServices_rdh
/** * Get a string presenting the service names that the Dubbo interface subscribed. * If it is a multiple-values, the content will be a comma-delimited String. * * @return non-null * @see RegistryConstants#SUBSCRIBED_SERVICE_NAMES_KEY * @since 2.7.8 */ @Deprecated @Parameter(key = SUBSCRIBED_SERVICE_NAMES_KEY) public String getServices() { return services; }
3.26
dubbo_ReferenceConfig_getInvoker_rdh
/** * just for test * * @return */ @Deprecated @Transient public Invoker<?> getInvoker() { return invoker; }
3.26
dubbo_ReferenceConfig_createAsyncMethodInfo_rdh
/** * convert and aggregate async method info * * @return Map<String, AsyncMethodInfo> */ private Map<String, AsyncMethodInfo> createAsyncMethodInfo() { Map<String, AsyncMethodInfo> attributes = null; if (CollectionUtils.isNotEmpty(getMethods())) { attributes = new HashMap<>(16); for (MethodConfig methodConfig : getMethods()) { AsyncMethodInfo asyncMethodInfo = methodConfig.convertMethodConfig2AsyncInfo(); if (asyncMethodInfo != null) { attributes.put(methodConfig.getName(), asyncMethodInfo); } } } return attributes;}
3.26
dubbo_ReferenceConfig_checkAndUpdateSubConfigs_rdh
/** * This method should be called right after the creation of this class's instance, before any property in other config modules is used. * Check each config modules are created properly and override their properties if necessary. */ protected void checkAndUpdateSubConfigs() { if (StringUtils.isEmpty(interfaceName)) { throw new IllegalStateException("<dubbo:reference interface=\"\" /> interface not allow null!"); } // get consumer's global configuration completeCompoundConfigs(); // init some null configuration. List<ConfigInitializer> configInitializers = this.getExtensionLoader(ConfigInitializer.class).getActivateExtension(URL.valueOf("configInitializer://"), ((String[]) (null))); configInitializers.forEach(e -> e.initReferConfig(this)); if ((getGeneric() == null) && (getConsumer() != null)) { setGeneric(getConsumer().getGeneric()); } if (ProtocolUtils.isGeneric(generic)) { if ((interfaceClass != null) && (!interfaceClass.equals(GenericService.class))) { logger.warn(CONFIG_PROPERTY_CONFLICT, "", "", String.format(("Found conflicting attributes for interface type: [interfaceClass=%s] and [generic=%s], " + "because the 'generic' attribute has higher priority than 'interfaceClass', so change 'interfaceClass' to '%s'. ") + "Note: it will make this reference bean as a candidate bean of type '%s' instead of '%s' when resolving dependency in Spring.", interfaceClass.getName(), generic, GenericService.class.getName(), GenericService.class.getName(), interfaceClass.getName())); } interfaceClass = GenericService.class; } else { try { if ((getInterfaceClassLoader() != null) && ((interfaceClass == null) || (interfaceClass.getClassLoader() != getInterfaceClassLoader()))) { interfaceClass = Class.forName(interfaceName, true, getInterfaceClassLoader());} else if (interfaceClass == null) { interfaceClass = Class.forName(interfaceName, true, Thread.currentThread().getContextClassLoader());} } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } } checkStubAndLocal(interfaceClass); ConfigValidationUtils.checkMock(interfaceClass, this); if (StringUtils.isEmpty(url)) { checkRegistry(); }resolveFile(); ConfigValidationUtils.validateReferenceConfig(this); postProcessConfig();}
3.26
dubbo_ReferenceConfig_checkMeshConfig_rdh
/** * check if mesh config is correct * * @param referenceParameters * referenceParameters * @return mesh config is correct */ private boolean checkMeshConfig(Map<String, String> referenceParameters) { if (!"true".equals(referenceParameters.getOrDefault(MESH_ENABLE, "false"))) {// In mesh mode, unloadClusterRelated can only be false. referenceParameters.put(UNLOAD_CLUSTER_RELATED, "false"); return false; } getScopeModel().getConfigManager().getProtocol(TRIPLE).orElseThrow(() -> new IllegalStateException("In mesh mode, a triple protocol must be specified")); String providedBy = referenceParameters.get(PROVIDED_BY); if (StringUtils.isEmpty(providedBy)) { throw new IllegalStateException("In mesh mode, the providedBy of ReferenceConfig is must be set"); } return true; }
3.26
dubbo_ReferenceConfig_shouldJvmRefer_rdh
/** * Figure out should refer the service in the same JVM from configurations. The default behavior is true * 1. if injvm is specified, then use it * 2. then if a url is specified, then assume it's a remote call * 3. otherwise, check scope parameter * 4. if scope is not specified but the target service is provided in the same JVM, then prefer to make the local * call, which is the default behavior */ protected boolean shouldJvmRefer(Map<String, String> map) { boolean isJvmRefer; if (isInjvm() == null) { // if an url is specified, don't do local reference if (StringUtils.isNotEmpty(url)) { isJvmRefer = false; } else { // by default, reference local service if there is URL tmpUrl = new ServiceConfigURL("temp", "localhost", 0, map);isJvmRefer = InjvmProtocol.getInjvmProtocol(getScopeModel()).isInjvmRefer(tmpUrl); } } else { isJvmRefer = isInjvm(); } return isJvmRefer; }
3.26
dubbo_ReferenceConfig_setServices_rdh
/** * Set the service names that the Dubbo interface subscribed. * * @param services * If it is a multiple-values, the content will be a comma-delimited String. * @since 2.7.8 */ public void setServices(String services) { this.services = services; }
3.26
dubbo_ReferenceConfig_aggregateUrlFromRegistry_rdh
/** * Get URLs from the registry and aggregate them. */ private void aggregateUrlFromRegistry(Map<String, String> referenceParameters) { checkRegistry(); List<URL> us = ConfigValidationUtils.loadRegistries(this, false); if (CollectionUtils.isNotEmpty(us)) { for (URL u : us) { URL monitorUrl = ConfigValidationUtils.loadMonitor(this, u);if (monitorUrl != null) { u = u.putAttribute(MONITOR_KEY, monitorUrl); } u = u.setScopeModel(getScopeModel()); u = u.setServiceModel(consumerModel); if ((isInjvm() != null) && isInjvm()) { u = u.addParameter(LOCAL_PROTOCOL, true); } urls.add(u.putAttribute(REFER_KEY, referenceParameters)); } } if (urls.isEmpty() && shouldJvmRefer(referenceParameters)) { URL injvmUrl = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(referenceParameters); injvmUrl = injvmUrl.setScopeModel(getScopeModel()); injvmUrl = injvmUrl.setServiceModel(consumerModel); urls.add(injvmUrl.putAttribute(REFER_KEY, referenceParameters)); } if (urls.isEmpty()) { throw new IllegalStateException(((((("No such any registry to reference " + interfaceName) + " on the consumer ") + NetUtils.getLocalHost()) + " use dubbo version ") + Version.getVersion()) + ", please config <dubbo:registry address=\"...\" /> to your spring config."); } }
3.26
dubbo_ReferenceConfig_parseUrl_rdh
/** * Parse the directly configured url. */ private void parseUrl(Map<String, String> referenceParameters) { String[] us = SEMICOLON_SPLIT_PATTERN.split(url); if (ArrayUtils.isNotEmpty(us)) { for (String u : us) { URL url = URL.valueOf(u); if (StringUtils.isEmpty(url.getPath())) { url = url.setPath(interfaceName); } url = url.setScopeModel(getScopeModel()); url = url.setServiceModel(consumerModel); if (UrlUtils.isRegistry(url)) { urls.add(url.putAttribute(REFER_KEY, referenceParameters)); } else { URL peerUrl = getScopeModel().getApplicationModel().getBeanFactory().getBean(ClusterUtils.class).mergeUrl(url, referenceParameters); peerUrl = peerUrl.putAttribute(PEER_KEY, true); urls.add(peerUrl); } } } }
3.26
dubbo_ReferenceConfig_appendConfig_rdh
/** * Append all configuration required for service reference. * * @return reference parameters */ private Map<String, String> appendConfig() { Map<String, String> map = new HashMap<>(16); map.put(INTERFACE_KEY, interfaceName); map.put(SIDE_KEY, CONSUMER_SIDE); ReferenceConfigBase.appendRuntimeParameters(map); if (!ProtocolUtils.isGeneric(generic)) { String revision = Version.getVersion(interfaceClass, version); if (StringUtils.isNotEmpty(revision)) { map.put(REVISION_KEY, revision); } String[] methods = methods(interfaceClass); if (methods.length == 0) { logger.warn(CONFIG_NO_METHOD_FOUND, "", "", "No method found in service interface: " + interfaceClass.getName()); map.put(METHODS_KEY, ANY_VALUE); } else { map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR)); } } AbstractConfig.appendParameters(map, getApplication()); AbstractConfig.appendParameters(map, getModule()); AbstractConfig.appendParameters(map, consumer); AbstractConfig.appendParameters(map, this); appendMetricsCompatible(map);String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); } else if (isInvalidLocalHost(hostToRegistry)) { throw new IllegalArgumentException((("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY) + ", value:") + hostToRegistry); } map.put(REGISTER_IP_KEY, hostToRegistry); if (CollectionUtils.isNotEmpty(getMethods())) { for (MethodConfig methodConfig : getMethods()) { AbstractConfig.appendParameters(map, methodConfig, methodConfig.getName()); String retryKey = methodConfig.getName() + ".retry"; if (map.containsKey(retryKey)) {String retryValue = map.remove(retryKey); if ("false".equals(retryValue)) { map.put(methodConfig.getName() + ".retries", "0"); } } } } return map; }
3.26
dubbo_RegistryBuilder_transport_rdh
/** * * @param transport * @see #transporter(String) * @deprecated */ @Deprecated public RegistryBuilder transport(String transport) { this.transporter = transport; return getThis(); }
3.26
dubbo_RegistryBuilder_parameter_rdh
/** * * @param name * the parameter name * @param value * the parameter value * @return {@link RegistryBuilder} * @since 2.7.8 */ public RegistryBuilder parameter(String name, String value) { return appendParameter(name, value); }
3.26
dubbo_RegistryBuilder_wait_rdh
/** * * @param wait * @see ProviderBuilder#wait(Integer) * @deprecated */ @Deprecated public RegistryBuilder wait(Integer wait) { this.wait = wait; return getThis();}
3.26
dubbo_ClassUtils_isGenericClass_rdh
/** * Is generic class or not? * * @param type * the target type * @return if the target type is not null or <code>void</code> or Void.class, return <code>true</code>, or false * @since 2.7.6 */ public static boolean isGenericClass(Class<?> type) { return ((type != null) && (!void.class.equals(type))) && (!Void.class.equals(type)); }
3.26
dubbo_ClassUtils_resolveClass_rdh
/** * Resolve the {@link Class} by the specified name and {@link ClassLoader} * * @param className * the name of {@link Class} * @param classLoader * {@link ClassLoader} * @return If can't be resolved , return <code>null</code> * @since 2.7.6 */ public static Class<?> resolveClass(String className, ClassLoader classLoader) { Class<?> targetClass = null; try { targetClass = forName(className, classLoader); } catch (Exception ignored) { // Ignored }return targetClass;}
3.26
dubbo_ClassUtils_isPrimitive_rdh
/** * The specified type is primitive type or simple type * * @param type * the type to test * @return * @deprecated as 2.7.6, use {@link Class#isPrimitive()} plus {@link #isSimpleType(Class)} instead */ public static boolean isPrimitive(Class<?> type) { return (type != null) && (type.isPrimitive() || isSimpleType(type)); }
3.26
dubbo_ClassUtils_getAllInheritedTypes_rdh
/** * Get all inherited types from the specified type * * @param type * the specified type * @param typeFilters * the filters for types * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllInheritedTypes(Class<?> type, Predicate<Class<?>>... typeFilters) { // Add all super classes Set<Class<?>> types = new LinkedHashSet<>(getAllSuperClasses(type, typeFilters)); // Add all interface classes types.addAll(m0(type, typeFilters)); return unmodifiableSet(types); }
3.26
dubbo_ClassUtils_isTypeMatch_rdh
/** * We only check boolean value at this moment. * * @param type * @param value * @return */ public static boolean isTypeMatch(Class<?> type, String value) { if (((type == boolean.class) || (type == Boolean.class)) && (!("true".equals(value) || "false".equals(value)))) { return false; } return true; } /** * Get all super classes from the specified type * * @param type * the specified type * @param classFilters * the filters for classes * @return non-null read-only {@link Set}
3.26
dubbo_ClassUtils_forName_rdh
/** * Replacement for <code>Class.forName()</code> that also returns Class * instances for primitives (like "int") and array class names (like * "String[]"). * * @param name * the name of the Class * @param classLoader * the class loader to use (may be <code>null</code>, * which indicates the default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException * if the class was not found * @throws LinkageError * if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Class<?> clazz = resolvePrimitiveClassName(name); if (clazz != null) { return clazz; } // "java.lang.String[]" style arrays if (name.endsWith(ARRAY_SUFFIX)) { String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); }// "[Ljava.lang.String;" style arrays int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); if ((internalArrayMarker != (-1)) && name.endsWith(";")) { String elementClassName = null; if (internalArrayMarker == 0) { elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); } else if (name.startsWith("[")) { elementClassName = name.substring(1); } Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass();} ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getClassLoader(); }return classLoaderToUse.loadClass(name); } /** * Resolve the given class name as primitive class, if appropriate, * according to the JVM's naming rules for primitive classes. * <p> * Also supports the JVM's internal class names for primitive arrays. Does * <i>not</i> support the "[]" suffix notation for primitive arrays; this is * only supported by {@link #forName}
3.26
dubbo_ClassUtils_isSimpleType_rdh
/** * The specified type is simple type or not * * @param type * the type to test * @return if <code>type</code> is one element of {@link #SIMPLE_TYPES}, return <code>true</code>, or <code>false</code> * @see #SIMPLE_TYPES * @since 2.7.6 */ public static boolean isSimpleType(Class<?> type) { return SIMPLE_TYPES.contains(type); }
3.26
dubbo_ClassUtils_isAssignableFrom_rdh
/** * the semantics is same as {@link Class#isAssignableFrom(Class)} * * @param superType * the super type * @param targetType * the target type * @return see {@link Class#isAssignableFrom(Class)} * @since 2.7.6 */ public static boolean isAssignableFrom(Class<?> superType, Class<?> targetType) { // any argument is null if ((superType == null) || (targetType == null)) { return false; } // equals if (Objects.equals(superType, targetType)) { return true; } // isAssignableFrom return superType.isAssignableFrom(targetType); }
3.26
dubbo_ClassUtils_isPresent_rdh
/** * Test the specified class name is present in the {@link ClassLoader} * * @param className * the name of {@link Class} * @param classLoader * {@link ClassLoader} * @return If found, return <code>true</code> * @since 2.7.6 */ public static boolean isPresent(String className, ClassLoader classLoader) { try { forName(className, classLoader); } catch (Exception ignored) { // Ignored return false; } return true; }
3.26
dubbo_ClassUtils_m0_rdh
/** * Get all interfaces from the specified type * * @param type * the specified type * @param interfaceFilters * the filters for interfaces * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> m0(Class<?> type, Predicate<Class<?>>... interfaceFilters) { if ((type == null) || type.isPrimitive()) { return emptySet(); } Set<Class<?>> allInterfaces = new LinkedHashSet<>(); Set<Class<?>> resolved = new LinkedHashSet<>(); Queue<Class<?>> waitResolve = new LinkedList<>(); resolved.add(type); Class<?> clazz = type; while (clazz != null) { Class<?>[] interfaces = clazz.getInterfaces(); if (isNotEmpty(interfaces)) { // add current interfaces Arrays.stream(interfaces).filter(resolved::add).forEach(cls -> { allInterfaces.add(cls); waitResolve.add(cls); }); } // add all super classes to waitResolve getAllSuperClasses(clazz).stream().filter(resolved::add).forEach(waitResolve::add); clazz = waitResolve.poll(); } return filterAll(allInterfaces, interfaceFilters); }
3.26
dubbo_ClassUtils_getDeclaredMethodNames_rdh
/** * get method name array. * * @return method name array. */ public static String[] getDeclaredMethodNames(Class<?> tClass) { if (tClass == Object.class) { return OBJECT_METHODS; } Method[] methods = Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[]{ }); List<String> dmns = new ArrayList<>();// method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) {continue; } String mn = m.getName(); if (m.getDeclaringClass() == tClass) { dmns.add(mn); } } } dmns.sort(Comparator.naturalOrder()); return dmns.toArray(new String[0]); }
3.26
dubbo_ClientStream_onComplete_rdh
/** * Callback when request completed. * * @param status * response status * @param attachments * attachments received from remote peer * @param reserved * triple protocol reserved data */ default void onComplete(TriRpcStatus status, Map<String, Object> attachments, Map<String, String> reserved, boolean isReturnTriException) { onComplete(status, attachments); }
3.26
dubbo_AbstractZookeeperTransporter_getZookeeperClientMap_rdh
/** * for unit test * * @return */ public Map<String, ZookeeperClient> getZookeeperClientMap() { return zookeeperClientMap; }
3.26
dubbo_AbstractZookeeperTransporter_fetchAndUpdateZookeeperClientCache_rdh
/** * get the ZookeeperClient from cache, the ZookeeperClient must be connected. * <p> * It is not private method for unit test. * * @param addressList * @return */ public ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) {ZookeeperClient zookeeperClient = null; for (String address : addressList) { if (((zookeeperClient = zookeeperClientMap.get(address)) != null) && zookeeperClient.isConnected()) { break; } } // mapping new backup address if ((zookeeperClient != null) && zookeeperClient.isConnected()) { writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; }
3.26
dubbo_AbstractZookeeperTransporter_getURLBackupAddress_rdh
/** * get all zookeeper urls (such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999) * * @param url * such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999 * @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999 */ public List<String> getURLBackupAddress(URL url) { List<String> addressList = new ArrayList<>(); addressList.add(url.getAddress()); addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.emptyList())); String authPrefix = null; if (StringUtils.isNotEmpty(url.getUsername())) { StringBuilder buf = new StringBuilder(); buf.append(url.getUsername()); if (StringUtils.isNotEmpty(url.getPassword())) { buf.append(':'); buf.append(url.getPassword()); } buf.append('@'); authPrefix = buf.toString(); } if (StringUtils.isNotEmpty(authPrefix)) { List<String> authedAddressList = new ArrayList<>(addressList.size()); for (String addr : addressList) { authedAddressList.add(authPrefix + addr); } return authedAddressList; } return addressList; }
3.26
dubbo_AbstractZookeeperTransporter_writeToClientMap_rdh
/** * write address-ZookeeperClient relationship to Map * * @param addressList * @param zookeeperClient */ void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) { for (String address : addressList) { zookeeperClientMap.put(address, zookeeperClient); } }
3.26
dubbo_AbstractZookeeperTransporter_toClientURL_rdh
/** * redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter. * * @param url * @return */ URL toClientURL(URL url) { Map<String, String> v10 = new HashMap<>(); // for CuratorZookeeperClient if (url.getParameter(TIMEOUT_KEY) != null) { v10.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) { v10.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); } return new ServiceConfigURL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), ZookeeperTransporter.class.getName(), v10); }
3.26
dubbo_AbstractZookeeperTransporter_connect_rdh
/** * share connect for registry, metadata, etc.. * <p> * Make sure the connection is connected. * * @param url * @return */ @Override public ZookeeperClient connect(URL url) { ZookeeperClient zookeeperClient; // address format: {[username:password@]address} List<String> addressList = getURLBackupAddress(url); // The field define the zookeeper server , including protocol, host, port, username, password if (((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null) && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } // avoid creating too many connections, so add lock synchronized(zookeeperClientMap) { if (((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null) && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } zookeeperClient = createZookeeperClient(url); logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url); writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; }
3.26
dubbo_Server_start_rdh
/** * start server, bind port */ public void start() throws Throwable { if (!started.compareAndSet(false, true)) { return; } boss = new NioEventLoopGroup(1, new DefaultThreadFactory("qos-boss", true));worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true)); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.option(ChannelOption.SO_REUSEADDR, true); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new QosProcessHandler(frameworkModel, QosConfiguration.builder().welcome(welcome).acceptForeignIp(acceptForeignIp).acceptForeignIpWhitelist(acceptForeignIpWhitelist).anonymousAccessPermissionLevel(anonymousAccessPermissionLevel).anonymousAllowCommands(anonymousAllowCommands).build())); } }); try { if (StringUtils.isBlank(host)) { serverBootstrap.bind(port).sync(); } else { serverBootstrap.bind(host, port).sync(); } logger.info("qos-server bind localhost:" + port); } catch (Throwable throwable) { throw new QosBindException("qos-server can not bind localhost:" + port, throwable); } }
3.26
dubbo_Server_stop_rdh
/** * close server */ public void stop() { logger.info("qos-server stopped."); if (boss != null) { boss.shutdownGracefully(); } if (worker != null) { worker.shutdownGracefully(); } started.set(false); }
3.26
dubbo_Server_setWelcome_rdh
/** * welcome message */ public void setWelcome(String welcome) { this.welcome = welcome; }
3.26
dubbo_ReferenceBeanSupport_convertPropertyValues_rdh
/** * Convert to raw props, without parsing nested config objects */ public static Map<String, Object> convertPropertyValues(MutablePropertyValues propertyValues) { Map<String, Object> referenceProps = new LinkedHashMap<>(); for (PropertyValue propertyValue : propertyValues.getPropertyValueList()) { String propertyName = propertyValue.getName(); Object value = propertyValue.getValue(); if (ReferenceAttributes.METHODS.equals(propertyName) || ReferenceAttributes.ARGUMENTS.equals(propertyName)) { ManagedList managedList = ((ManagedList) (value)); List<Map<String, Object>> v33 = new ArrayList<>(); for (Object el : managedList) { Map<String, Object> element = convertPropertyValues(((BeanDefinitionHolder) (el)).getBeanDefinition().getPropertyValues()); element.remove(ReferenceAttributes.ID); v33.add(element); } value = v33.toArray(new Object[0]); } else if (ReferenceAttributes.PARAMETERS.equals(propertyName)) { value = createParameterMap(((ManagedMap) (value))); } // convert ref if (value instanceof RuntimeBeanReference) { RuntimeBeanReference beanReference = ((RuntimeBeanReference) (value)); value = beanReference.getBeanName(); } if ((value == null) || ((value instanceof String) && StringUtils.isBlank(((String) (value))))) { // ignore null or blank string continue; } referenceProps.put(propertyName, value); } return referenceProps; }
3.26
dubbo_Log4jLogger_getLogger_rdh
// test purpose only public Logger getLogger() { return logger; }
3.26
dubbo_ExpiringMap_startExpiring_rdh
/** * start expiring Thread */ public void startExpiring() { if (!running) { running = true; expirerThread.start(); } }
3.26
dubbo_ExpiringMap_getTimeToLive_rdh
/** * get time to live * * @return time to live */ public int getTimeToLive() { return ((int) (timeToLiveMillis)) / 1000;}
3.26
dubbo_ExpiringMap_setExpirationInterval_rdh
/** * set expiration interval * * @param expirationInterval * expiration interval (second) */ public void setExpirationInterval(long expirationInterval) { this.expirationIntervalMillis = expirationInterval * 1000; }
3.26
dubbo_ExpiringMap_getExpirationInterval_rdh
/** * get expiration interval * * @return expiration interval (second) */ public int getExpirationInterval() { return ((int) (expirationIntervalMillis)) / 1000; }
3.26
dubbo_ExpiringMap_isRunning_rdh
/** * get thread state * * @return thread state */ public boolean isRunning() { return running; }
3.26
dubbo_ExpiringMap_setTimeToLive_rdh
/** * update time to live * * @param timeToLive * time to live */ public void setTimeToLive(long timeToLive) { this.timeToLiveMillis = timeToLive * 1000;}
3.26
dubbo_ExpiringMap_startExpiryIfNotStarted_rdh
/** * start thread */ public void startExpiryIfNotStarted() { if (running && (timeToLiveMillis <= 0)) { return; } startExpiring(); }
3.26
dubbo_Router_route_rdh
// Add since 2.7.0 @Override default <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { List<Invoker<T>> invs = invokers.stream().map(invoker -> new CompatibleInvoker<T>(invoker)).collect(Collectors.toList()); List<Invoker<T>> res = this.route(invs, new DelegateURL(url), new CompatibleInvocation(invocation)); return res.stream().map(inv -> inv.getOriginal()).filter(Objects::nonNull).collect(Collectors.toList()); }
3.26
dubbo_TripleClientStream_createTransportListener_rdh
/** * * @return transport listener */ H2TransportListener createTransportListener() { return new ClientTransportListener(); }
3.26
dubbo_TripleClientStream_statusFromTrailers_rdh
/** * Extract the response status from trailers. */ private TriRpcStatus statusFromTrailers(Http2Headers trailers) { final Integer intStatus = trailers.getInt(TripleHeaderEnum.STATUS_KEY.getHeader()); TriRpcStatus status = (intStatus == null) ? null : TriRpcStatus.fromCode(intStatus); if (status != null) { final CharSequence message = trailers.get(TripleHeaderEnum.MESSAGE_KEY.getHeader()); if (message != null) { final String description = TriRpcStatus.decodeMessage(message.toString()); status = status.withDescription(description); } return status; } // No status; something is broken. Try to provide a rational error. if (headerReceived) { return TriRpcStatus.UNKNOWN.withDescription("missing GRPC status in response"); } Integer httpStatus = (trailers.status() == null) ? null : Integer.parseInt(trailers.status().toString()); if (httpStatus != null) {status = TriRpcStatus.fromCode(TriRpcStatus.httpStatusToGrpcCode(httpStatus)); } else { status = TriRpcStatus.INTERNAL.withDescription("missing HTTP status code"); } return status.appendDescription("missing GRPC status, inferred error from HTTP status code"); }
3.26
dubbo_ReferenceCountExchangeClient_close_rdh
/** * close() is not idempotent any longer */ @Override public void close() { close(0); }
3.26
dubbo_ReferenceCountExchangeClient_replaceWithLazyClient_rdh
/** * 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()); } }
3.26
dubbo_ReferenceBuilder_services_rdh
/** * * @param service * one service name * @param otherServices * other service names * @return {@link ReferenceBuilder} * @since 2.7.8 */ public ReferenceBuilder<T> services(String service, String... otherServices) { this.services = toCommaDelimitedString(service, otherServices); return getThis();}
3.26
dubbo_Predicates_alwaysFalse_rdh
/** * {@link Predicate} always return <code>false</code> * * @param <T> * the type to test * @return <code>false</code> */ static <T> Predicate<T> alwaysFalse() { return e -> false; }
3.26
dubbo_Predicates_and_rdh
/** * a composed predicate that represents a short-circuiting logical AND of {@link Predicate predicates} * * @param predicates * {@link Predicate predicates} * @param <T> * the type to test * @return non-null */ static <T> Predicate<T> and(Predicate<T>... predicates) { return of(predicates).reduce(Predicate::and).orElseGet(Predicates::alwaysTrue); }
3.26
dubbo_Predicates_or_rdh
/** * a composed predicate that represents a short-circuiting logical OR of {@link Predicate predicates} * * @param predicates * {@link Predicate predicates} * @param <T> * the detected type * @return non-null */ static <T> Predicate<T> or(Predicate<T>... predicates) { return of(predicates).reduce(Predicate::or).orElse(e -> true); }
3.26
dubbo_Predicates_alwaysTrue_rdh
/** * {@link Predicate} always return <code>true</code> * * @param <T> * the type to test * @return <code>true</code> */ static <T> Predicate<T> alwaysTrue() { return e -> true; }
3.26
dubbo_InternalThread_setThreadLocalMap_rdh
/** * Sets the internal data structure that keeps the threadLocal variables bound to this thread. * Note that this method is for internal use only, and thus is subject to change at any time. */ public final void setThreadLocalMap(InternalThreadLocalMap threadLocalMap) { this.threadLocalMap = threadLocalMap; }
3.26
dubbo_InternalThread_threadLocalMap_rdh
/** * Returns the internal data structure that keeps the threadLocal variables bound to this thread. * Note that this method is for internal use only, and thus is subject to change at any time. */ public final InternalThreadLocalMap threadLocalMap() { return threadLocalMap; }
3.26
dubbo_DubboBeanUtils_registerInfrastructureBean_rdh
/** * Register Infrastructure Bean * * @param beanDefinitionRegistry * {@link BeanDefinitionRegistry} * @param beanType * the type of bean * @param beanName * the name of bean * @return if it's a first time to register, return <code>true</code>, or <code>false</code> */ static boolean registerInfrastructureBean(BeanDefinitionRegistry beanDefinitionRegistry, String beanName, Class<?> beanType) { boolean registered = false; if (!beanDefinitionRegistry.containsBeanDefinition(beanName)) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition); registered = true; if (log.isDebugEnabled()) { log.debug(((("The Infrastructure bean definition [" + beanDefinition) + "with name [") + beanName) + "] has been registered."); }} return registered; }
3.26
dubbo_DubboBeanUtils_registerCommonBeans_rdh
/** * Register the common beans * * @param registry * {@link BeanDefinitionRegistry} * @see ReferenceAnnotationBeanPostProcessor * @see DubboConfigDefaultPropertyValueBeanPostProcessor * @see DubboConfigAliasPostProcessor */static void registerCommonBeans(BeanDefinitionRegistry registry) { registerInfrastructureBean(registry, ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); registerInfrastructureBean(registry, ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); // Since 2.5.7 Register @Reference Annotation Bean Processor as an infrastructure Bean registerInfrastructureBean(registry, ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); // TODO Whether DubboConfigAliasPostProcessor can be removed ? // Since 2.7.4 [Feature] https://github.com/apache/dubbo/issues/5093 registerInfrastructureBean(registry, DubboConfigAliasPostProcessor.BEAN_NAME, DubboConfigAliasPostProcessor.class);// register ApplicationListeners registerInfrastructureBean(registry, DubboDeployApplicationListener.class.getName(), DubboDeployApplicationListener.class); registerInfrastructureBean(registry, DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class); // Since 2.7.6 Register DubboConfigDefaultPropertyValueBeanPostProcessor as an infrastructure Bean registerInfrastructureBean(registry, DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME, DubboConfigDefaultPropertyValueBeanPostProcessor.class); // Dubbo config initializer registerInfrastructureBean(registry, DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class); // register infra bean if not exists later registerInfrastructureBean(registry, DubboInfraBeanRegisterPostProcessor.BEAN_NAME, DubboInfraBeanRegisterPostProcessor.class); }
3.26
dubbo_ServiceInstance_getMetadata_rdh
/** * Get the value of metadata by the specified name * * @param name * the specified name * @return the value of metadata if found, or <code>defaultValue</code> * @since 2.7.8 */ default String getMetadata(String name, String defaultValue) { return getMetadata().getOrDefault(name, defaultValue); }
3.26
dubbo_Holder_m0_rdh
/** * Helper Class for hold a value. */public class Holder<T> { private volatile T value; public void m0(T value) { this.value = value; }
3.26
dubbo_RandomLoadBalance_doSelect_rdh
/** * Select one invoker between a list using a random criteria * * @param invokers * List of possible invokers * @param url * URL * @param invocation * Invocation * @param <T> * @return The selected invoker */ @Override protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { // Number of invokers int length = invokers.size(); if (!needWeightLoadBalance(invokers, invocation)) { return invokers.get(ThreadLocalRandom.current().nextInt(length)); } // Every invoker has the same weight? boolean sameWeight = true; // the maxWeight of every invoker, the minWeight = 0 or the maxWeight of the last invoker int[] weights = new int[length]; // The sum of weights int totalWeight = 0; for (int i = 0; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); // Sum totalWeight += weight; // save for later use weights[i] = totalWeight; if (sameWeight && (totalWeight != (weight * (i + 1)))) { sameWeight = false;} } if ((totalWeight > 0) && (!sameWeight)) { // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on // totalWeight. int offset = ThreadLocalRandom.current().nextInt(totalWeight); // Return an invoker based on the random value. if (length <= 4) { for (int i = 0; i < length; i++) { if (offset < weights[i]) { return invokers.get(i); } } } else { int i = Arrays.binarySearch(weights, offset); if (i < 0) { i = (-i) - 1; } else { while (weights[i + 1] == offset) { i++; } i++; } return invokers.get(i); } } // If all invokers have the same weight value or totalWeight=0, return evenly. return invokers.get(ThreadLocalRandom.current().nextInt(length)); }
3.26
dubbo_MemoryLimitCalculator_defaultLimit_rdh
/** * By default, it takes 80% of the maximum available memory of the current JVM. * * @return available memory */ public static long defaultLimit() { checkAndScheduleRefresh(); return ((long) (maxAvailable() * 0.8)); }
3.26
dubbo_MemoryLimitCalculator_calculate_rdh
/** * Take the current JVM's maximum available memory * as a percentage of the result as the limit. * * @param percentage * percentage * @return available memory */ public static long calculate(final float percentage) { if ((percentage <= 0) || (percentage > 1)) { throw new IllegalArgumentException(); } checkAndScheduleRefresh(); return ((long) (maxAvailable() * percentage)); }
3.26
dubbo_ClassGenerator_toClass_rdh
/** * * @param neighbor * A class belonging to the same package that this * class belongs to. It is used to load the class. */ public Class<?> toClass(Class<?> neighbor) { return toClass(neighbor, mClassLoader, getClass().getProtectionDomain()); }
3.26
dubbo_AbstractMetricsListener_isSupport_rdh
/** * Whether to support the general determination of event points depends on the event type */ public boolean isSupport(MetricsEvent event) { Boolean eventMatch = eventMatchCache.computeIfAbsent(event.getClass(), clazz -> ReflectionUtils.match(getClass(), AbstractMetricsListener.class, event)); return event.isAvailable() && eventMatch; }
3.26
dubbo_SimpleReferenceCache_destroy_rdh
/** * clear and destroy one {@link ReferenceConfigBase} in the cache. * * @param referenceConfig * use for create key. */@Override public <T> void destroy(ReferenceConfigBase<T> referenceConfig) { String key = generator.generateKey(referenceConfig); Class<?> type = referenceConfig.getInterfaceClass(); destroy(key, type); } /** * clear and destroy all {@link ReferenceConfigBase}
3.26
dubbo_SimpleReferenceCache_m0_rdh
/** * Get the cache use specified {@link KeyGenerator}. * Create cache if not existed yet. */ public static SimpleReferenceCache m0(String name, KeyGenerator keyGenerator) {return ConcurrentHashMapUtils.computeIfAbsent(CACHE_HOLDER, name, k -> new SimpleReferenceCache(k, keyGenerator)); }
3.26
dubbo_SimpleReferenceCache_get_rdh
/** * Check and return existing ReferenceConfig and its corresponding proxy instance. * * @param type * service interface class * @param <T> * service interface type * @return the existing proxy instance of the same interface definition */ @Override @SuppressWarnings("unchecked") public <T> T get(Class<T> type) { List<ReferenceConfigBase<?>> v13 = referenceTypeMap.get(type); if (CollectionUtils.isNotEmpty(v13)) { return ((T) (v13.get(0).get())); } return null; }
3.26
dubbo_SimpleReferenceCache_getCache_rdh
/** * Get the cache use specified name and {@link KeyGenerator}. * Create cache if not existed yet. */ public static SimpleReferenceCache getCache(String name) { return m0(name, DEFAULT_KEY_GENERATOR);}
3.26
dubbo_Application_main_rdh
/** * In order to make sure multicast registry works, need to specify '-Djava.net.preferIPv4Stack=true' before * launch the application */ public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml"); context.start(); DemoService demoService = context.getBean("demoService", DemoService.class); GreetingService greetingService = context.getBean("greetingService", GreetingService.class); RestDemoService restDemoService = context.getBean("restDemoService", RestDemoService.class);TripleService tripleService = context.getBean("tripleService", TripleService.class); new Thread(() -> { while (true) { try { String greetings = greetingService.hello(); System.out.println(greetings + " from separated thread."); } catch (Exception e) { // e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } }).start(); new Thread(() -> { while (true) { try { Object restResult = restDemoService.sayHello("rest"); System.out.println(restResult + " from separated thread."); restResult = restDemoService.testBody5(TestPO.getInstance()); System.out.println(restResult + " from separated thread."); restResult = restDemoService.hello(1, 2); System.out.println(restResult + " from separated thread."); String form1 = restDemoService.testForm1("form1"); System.out.println(form1); MultivaluedHashMap multivaluedHashMap = new MultivaluedHashMap(); multivaluedHashMap.put("1", Arrays.asList("1")); multivaluedHashMap.put("2", Arrays.asList("2")); MultivaluedMap form2 = restDemoService.testForm2(multivaluedHashMap); System.out.println(form2); } catch (Exception e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } }).start(); while (true) { try { CompletableFuture<String> hello = demoService.sayHelloAsync("world"); System.out.println("result: " + hello.get()); String greetings = greetingService.hello(); System.out.println("result: " + greetings); } catch (Exception e) { // e.printStackTrace(); } Thread.sleep(5000); } }
3.26
dubbo_ConsumerModel_getMethodModel_rdh
/** * * @param method * methodName * @param argsType * method arguments type * @return */ public ConsumerMethodModel getMethodModel(String method, String[] argsType) { Optional<ConsumerMethodModel> consumerMethodModel = methodModels.entrySet().stream().filter(entry -> entry.getKey().getName().equals(method)).map(Map.Entry::getValue).filter(methodModel -> Arrays.equals(argsType, methodModel.getParameterTypes())).findFirst(); return consumerMethodModel.orElse(null);}
3.26
dubbo_CacheFilter_setCacheFactory_rdh
/** * Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured * cache attribute value. Dubbo will search for the class name implementing configured <b>cache</b> in file org.apache.dubbo.cache.CacheFactory * under META-INF sub folders. * * @param cacheFactory * instance of CacheFactory based on <b>cache</b> type */ public void setCacheFactory(CacheFactory cacheFactory) { this.cacheFactory = cacheFactory; }
3.26