name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
dubbo_Configurator_compareTo_rdh
/** * Sort by host, then by priority * 1. the url with a specific host ip should have higher priority than 0.0.0.0 * 2. if two url has the same host, compare by priority value; */ @Override default int compareTo(Configurator o) { if (o == null) { return -1; } int ipCompare = getUrl().getHost().compareTo(o.getUrl().getHost()); // host is the same, sort by priority if (ipCompare == 0) { int i = getUrl().getParameter(PRIORITY_KEY, 0); int v6 = o.getUrl().getParameter(PRIORITY_KEY, 0); return Integer.compare(i, v6); } else { return ipCompare; } }
3.26
dubbo_TTable_m0_rdh
/** * draw separation line */ private String m0(final int[] widthCacheArray) { final StringBuilder separationLineSB = new StringBuilder(); final int lastCol = indexLastCol(widthCacheArray); final int v32 = widthCacheArray.length; for (int colIndex = 0; colIndex < v32; colIndex++) { final int width = widthCacheArray[colIndex]; if (width <= 0) { continue; } final boolean isFirstCol = colIndex == 0; final boolean isLastCol = colIndex == lastCol; if (isFirstCol && border.m2(Border.BORDER_OUTER_LEFT)) { separationLineSB.append('+'); } if ((!isFirstCol) && border.m2(Border.BORDER_INNER_V)) { separationLineSB.append('+'); } separationLineSB.append(repeat("-", width + (2 * padding))); if (isLastCol && border.m2(Border.f1)) { separationLineSB.append('+'); }} return separationLineSB.toString(); }
3.26
dubbo_TTable_get_rdh
/** * get border style * * @return border style */ public int get() { return borders; }
3.26
dubbo_TTable_padding_rdh
/** * set padding * * @param padding * padding */ public TTable padding(int padding) { this.padding = padding; return this; }
3.26
dubbo_TTable_width_rdh
/** * visible width for the given string. * * for example: "abc\n1234"'s width is 4. * * @param string * the given string * @return visible width */ private static int width(String string) { int maxWidth = 0; try (Scanner scanner = new Scanner(new StringReader(string))) { while (scanner.hasNextLine()) { maxWidth = max(length(scanner.nextLine()), maxWidth); } } return maxWidth; }
3.26
dubbo_TTable_m1_rdh
/** * get border * * @return table border */ public Border m1() { return border; }
3.26
dubbo_TTable_getWidth_rdh
/** * get current width * * @return width */ public int getWidth() { // if not auto resize, return preset width if (!isAutoResize) { return f0; } // if it's auto resize, then calculate the possible max width int v39 = 0; for (String data : rows) { v39 = max(width(data), v39); } return v39; }
3.26
dubbo_TTable_getColumnCount_rdh
/** * get column count * * @return column count */ public int getColumnCount() { return columnDefineArray.length; }
3.26
dubbo_TTable_indexLastCol_rdh
/** * position to last column */ private int indexLastCol(final int[] widthCacheArray) { for (int colIndex = widthCacheArray.length - 1; colIndex >= 0; colIndex--) { final int width = widthCacheArray[colIndex]; if (width <= 0) {continue; }return colIndex; } return 0; }
3.26
dubbo_TTable_addRow_rdh
/** * Add a row */ public TTable addRow(Object... columnDataArray) { if (null != columnDataArray) { for (int index = 0; index < columnDefineArray.length; index++) { final ColumnDefine columnDefine = columnDefineArray[index]; if ((index < columnDataArray.length) && (null != columnDataArray[index])) { columnDefine.rows.add(replaceTab(columnDataArray[index].toString())); } else { columnDefine.rows.add(EMPTY_STRING);} } } return this; }
3.26
dubbo_TTable_replaceTab_rdh
/** * replace tab to four spaces * * @param string * the original string * @return the replaced string */ private static String replaceTab(String string) { return replace(string, "\t", " "); }
3.26
dubbo_TTable_m2_rdh
/** * whether has one of the specified border styles * * @param borderArray * border styles * @return whether has one of the specified border styles */ public boolean m2(int... borderArray) { if (null == borderArray) { return false; } for (int b : borderArray) { if ((this.borders & b) == b) { return true; } } return false; }
3.26
dubbo_TTable_getRowCount_rdh
/** * get rows for the current column * * @return current column's rows */ public int getRowCount() { return rows.size(); }
3.26
dubbo_TTable_set_rdh
/** * set border style * * @param border * border style * @return this */ public Border set(int border) { this.borders = border; return this; }
3.26
dubbo_NacosRegistry_notifySubscriber_rdh
/** * Notify the Enabled {@link Instance instances} to subscriber. * * @param url * {@link URL} * @param listener * {@link NotifyListener} * @param instances * all {@link Instance instances} */ private void notifySubscriber(URL url, String serviceName, NacosAggregateListener listener, Collection<Instance> instances) { List<Instance> enabledInstances = new LinkedList<>(instances); if (enabledInstances.size() > 0) { // Instances filterEnabledInstances(enabledInstances); } List<URL> aggregatedUrls = toUrlWithEmpty(url, listener.saveAndAggregateAllInstances(serviceName, enabledInstances)); this.notify(url, listener.getNotifyListener(), aggregatedUrls); } /** * Get the categories from {@link URL} * * @param url * {@link URL}
3.26
dubbo_NacosRegistry_getLegacySubscribedServiceName_rdh
/** * Get the legacy subscribed service name for compatible with Dubbo 2.7.3 and below * * @param url * {@link URL} * @return non-null * @since 2.7.6 */ private String getLegacySubscribedServiceName(URL url) { StringBuilder serviceNameBuilder = new StringBuilder(DEFAULT_CATEGORY); appendIfPresent(serviceNameBuilder, url, INTERFACE_KEY); appendIfPresent(serviceNameBuilder, url, VERSION_KEY); appendIfPresent(serviceNameBuilder, url, GROUP_KEY); return serviceNameBuilder.toString(); }
3.26
dubbo_NacosRegistry_m4_rdh
/** * Get the service names for Dubbo OPS * * @param url * {@link URL} * @return non-null */ private Set<String> m4(URL url) { Set<String> serviceNames = getAllServiceNames(); filterServiceNames(serviceNames, url); return serviceNames; }
3.26
dubbo_NacosRegistry_m0_rdh
/** * Since 2.7.6 the legacy service name will be added to serviceNames * to fix bug with https://github.com/apache/dubbo/issues/5442 * * @param url * @return */ private boolean m0(final URL url) { return (!m2(url)) && createServiceName(url).isConcrete(); }
3.26
dubbo_NacosRegistry_m1_rdh
/** * Get the service names from the specified {@link URL url} * * @param url * {@link URL} * @param listener * {@link NotifyListener} * @return non-null */ private Set<String> m1(URL url, NacosAggregateListener listener) { if (m2(url)) { m3(url, listener); return m4(url); } else { return getServiceNames0(url); } }
3.26
dubbo_NacosRegistry_isConformRules_rdh
/** * Verify whether it is a dubbo service * * @param serviceName * @return * @since 2.7.12 */ private boolean isConformRules(String serviceName) { return serviceName.split(NAME_SEPARATOR, -1).length == 4; }
3.26
dubbo_InvokerAndRestMethodMetadataPair_compareServiceMethod_rdh
/** * same interface & same method desc * * @param beforeMetadata * @return */ public boolean compareServiceMethod(InvokerAndRestMethodMetadataPair beforeMetadata) { Class currentServiceInterface = this.invoker.getInterface(); Class<?> beforeServiceInterface = beforeMetadata.getInvoker().getInterface(); if (!currentServiceInterface.equals(beforeServiceInterface)) { return false; } Method beforeServiceMethod = beforeMetadata.getRestMethodMetadata().getReflectMethod(); Method currentReflectMethod = this.restMethodMetadata.getReflectMethod(); if (beforeServiceMethod.getName().equals(currentReflectMethod.getName())// method name && // method param types Arrays.toString(beforeServiceMethod.getParameterTypes()).equals(Arrays.toString(currentReflectMethod.getParameterTypes()))) { return true; } return false; }
3.26
dubbo_AbstractDirectory_getCheckConnectivityPermit_rdh
/** * for ut only */ @Deprecated public Semaphore getCheckConnectivityPermit() {return checkConnectivityPermit;}
3.26
dubbo_AbstractDirectory_m0_rdh
/** * Refresh invokers from total invokers * 1. all the invokers in need to reconnect list should be removed in the valid invokers list * 2. all the invokers in disabled invokers list should be removed in the valid invokers list * 3. all the invokers disappeared from total invokers should be removed in the need to reconnect list * 4. all the invokers disappeared from total invokers should be removed in the disabled invokers list */ public void m0() { if (invokersInitialized) { refreshInvokerInternal(); } MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); }
3.26
dubbo_AbstractDirectory_getConnectivityCheckFuture_rdh
/** * for ut only */ @Deprecated public ScheduledFuture<?> getConnectivityCheckFuture() { return connectivityCheckFuture; }
3.26
dubbo_JValidationNew_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 JValidatorNew(url); }
3.26
dubbo_Stack_peek_rdh
/** * peek. * * @return the last element. */ public E peek() { if (mSize == 0) { throw new EmptyStackException(); } return mElements.get(mSize - 1); }
3.26
dubbo_Stack_get_rdh
/** * get. * * @param index * index. * @return element. */ public E get(int index) { if ((index >= mSize) || ((index + mSize) < 0)) { throw new IndexOutOfBoundsException((("Index: " + index) + ", Size: ") + mSize); } return index < 0 ? mElements.get(index + mSize) : mElements.get(index); }
3.26
dubbo_Stack_isEmpty_rdh
/** * is empty. * * @return empty or not. */ public boolean isEmpty() {return mSize == 0; }
3.26
dubbo_Stack_remove_rdh
/** * remove. * * @param index * @return element */ public E remove(int index) { if ((index >= mSize) || ((index + mSize) < 0)) { throw new IndexOutOfBoundsException((("Index: " + index) + ", Size: ") + mSize); } E ret = mElements.remove(index < 0 ? index + mSize : index); mSize--; return ret; }
3.26
dubbo_Stack_set_rdh
/** * set. * * @param index * index. * @param value * element. * @return old element. */ public E set(int index, E value) { if ((index >= mSize) || ((index + mSize) < 0)) { throw new IndexOutOfBoundsException((("Index: " + index) + ", Size: ") + mSize); } return mElements.set(index < 0 ? index + mSize : index, value); }
3.26
dubbo_Stack_m0_rdh
/** * push. * * @param ele */ public void m0(E ele) { if (mElements.size() > mSize) { mElements.set(mSize, ele); } else { mElements.add(ele); } mSize++; }
3.26
dubbo_DefaultExecutorRepository_getExecutorKey_rdh
/** * Return the executor key based on the type (internal or biz) of the current service. * * @param url * @return */private String getExecutorKey(URL url) { if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) { return CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; } return EXECUTOR_SERVICE_COMPONENT_KEY; }
3.26
dubbo_DefaultExecutorRepository_createExecutorIfAbsent_rdh
/** * Get called when the server or client instance initiating. * * @param url * @return */ @Override public synchronized ExecutorService createExecutorIfAbsent(URL url) { String v0 = getExecutorKey(url); ConcurrentMap<String, ExecutorService> executors = ConcurrentHashMapUtils.computeIfAbsent(data, v0, k -> new ConcurrentHashMap<>()); String executorCacheKey = getExecutorSecondKey(url); url = setThreadNameIfAbsent(url, executorCacheKey); URL finalUrl = url; ExecutorService executor = ConcurrentHashMapUtils.computeIfAbsent(executors, executorCacheKey, k -> createExecutor(finalUrl)); // If executor has been shut down, create a new one if (executor.isShutdown() || executor.isTerminated()) { executors.remove(executorCacheKey); executor = createExecutor(url); executors.put(executorCacheKey, executor); } dataStore.put(v0, executorCacheKey, executor); return executor; }
3.26
dubbo_ServiceConfig_init_rdh
/** * for early init serviceMetadata */ public void init() { if (this.initialized.compareAndSet(false, true)) { // load ServiceListeners from extension ExtensionLoader<ServiceListener> extensionLoader = this.getExtensionLoader(ServiceListener.class); this.serviceListeners.addAll(extensionLoader.getSupportedExtensionInstances()); } initServiceMetadata(provider); serviceMetadata.setServiceType(getInterfaceClass()); serviceMetadata.setTarget(getRef()); serviceMetadata.generateServiceKey(); }
3.26
dubbo_ServiceConfig_findConfiguredHosts_rdh
/** * Register & bind IP address for service provider, can be configured separately. * Configuration priority: environment variables -> java system properties -> host property in config file -> * /etc/hosts -> default network address -> first available network address * * @param protocolConfig * @param map * @return */ private static String findConfiguredHosts(ProtocolConfig protocolConfig, ProviderConfig provider, Map<String, String> map) { boolean anyhost = false; String hostToBind = getValueFromConfig(protocolConfig, DUBBO_IP_TO_BIND); if (StringUtils.isNotEmpty(hostToBind) && isInvalidLocalHost(hostToBind)) { throw new IllegalArgumentException((("Specified invalid bind ip from property:" + DUBBO_IP_TO_BIND) + ", value:") + hostToBind); } // if bind ip is not found in environment, keep looking up if (StringUtils.isEmpty(hostToBind)) { hostToBind = protocolConfig.getHost(); if ((provider != null) && StringUtils.isEmpty(hostToBind)) { hostToBind = provider.getHost(); } if (isInvalidLocalHost(hostToBind)) { anyhost = true; if (logger.isDebugEnabled()) { logger.debug("No valid ip found from environment, try to get local host."); } hostToBind = getLocalHost(); } } map.put(BIND_IP_KEY, hostToBind); // bind ip is not used for registry ip by default String hostToRegistry = getValueFromConfig(protocolConfig, DUBBO_IP_TO_REGISTRY); if (StringUtils.isNotEmpty(hostToRegistry) && isInvalidLocalHost(hostToRegistry)) { throw new IllegalArgumentException((("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY) + ", value:") + hostToRegistry); } else if (StringUtils.isEmpty(hostToRegistry)) { // bind ip is used as registry ip by default hostToRegistry = hostToBind; } map.put(ANYHOST_KEY, String.valueOf(anyhost)); return hostToRegistry; }
3.26
dubbo_ServiceConfig_isOnlyInJvm_rdh
/** * Determine if it is injvm * * @return */private boolean isOnlyInJvm() { return (getProtocols().size() == 1) && LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName()); }
3.26
dubbo_ServiceConfig_exportLocal_rdh
/** * always export injvm */ private void exportLocal(URL url) { URL local = URLBuilder.from(url).setProtocol(LOCAL_PROTOCOL).setHost(LOCALHOST_VALUE).setPort(0).build(); local = local.setScopeModel(getScopeModel()).setServiceModel(providerModel); local = local.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL); doExportUrl(local, false, RegisterTypeEnum.AUTO_REGISTER); logger.info((("Export dubbo service " + interfaceClass.getName()) + " to local registry url : ") + local); }
3.26
dubbo_AbstractClusterInvoker_setRemote_rdh
/** * Set the remoteAddress and remoteApplicationName so that filter can get them. */ private void setRemote(Invoker<?> invoker, Invocation invocation) { invocation.addInvokedInvoker(invoker); RpcServiceContext serviceContext = RpcContext.getServiceContext(); serviceContext.setRemoteAddress(invoker.getUrl().toInetSocketAddress()); serviceContext.setRemoteApplicationName(invoker.getUrl().getRemoteApplication()); }
3.26
dubbo_AbstractClusterInvoker_select_rdh
/** * Select a invoker using loadbalance policy.</br> * a) Firstly, select an invoker using loadbalance. If this invoker is in previously selected list, or, * if this invoker is unavailable, then continue step b (reselect), otherwise return the first selected invoker</br> * <p> * b) Reselection, the validation rule for reselection: selected > available. This rule guarantees that * the selected invoker has the minimum chance to be one in the previously selected list, and also * guarantees this invoker is available. * * @param loadbalance * load balance policy * @param invocation * invocation * @param invokers * invoker candidates * @param selected * exclude selected invokers or not * @return the invoker which will final to do invoke. * @throws RpcException * exception */ protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (CollectionUtils.isEmpty(invokers)) { return null; } String methodName = (invocation == null) ? StringUtils.EMPTY_STRING : RpcUtils.getMethodName(invocation); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, CLUSTER_STICKY_KEY, DEFAULT_CLUSTER_STICKY); // ignore overloaded method if ((stickyInvoker != null) && (!invokers.contains(stickyInvoker))) { stickyInvoker = null; } // ignore concurrency problem if ((sticky && (stickyInvoker != null)) && ((selected == null) || (!selected.contains(stickyInvoker)))) { if (availableCheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } Invoker<T> invoker = doSelect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; }
3.26
dubbo_AbstractClusterInvoker_reselect_rdh
/** * Reselect, use invokers not in `selected` first, if all invokers are in `selected`, * just pick an available one using loadbalance policy. * * @param loadbalance * load balance policy * @param invocation * invocation * @param invokers * invoker candidates * @param selected * exclude selected invokers or not * @param availableCheck * check invoker available if true * @return the reselect result to do invoke * @throws RpcException * exception */ private Invoker<T> reselect(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected, boolean availableCheck) throws RpcException { // Allocating one in advance, this list is certain to be used. List<Invoker<T>> reselectInvokers = new ArrayList<>(Math.min(invokers.size(), reselectCount)); // 1. Try picking some invokers not in `selected`. // 1.1. If all selectable invokers' size is smaller than reselectCount, just add all // 1.2. If all selectable invokers' size is greater than reselectCount, randomly select reselectCount. // The result size of invokers might smaller than reselectCount due to disAvailable or de-duplication // (might be zero). // This means there is probable that reselectInvokers is empty however all invoker list may contain // available invokers. // Use reselectCount can reduce retry times if invokers' size is huge, which may lead to long time // hang up. if (reselectCount >= invokers.size()) { for (Invoker<T> invoker : invokers) { // check if available if (availableCheck && (!invoker.isAvailable())) { // add to invalidate invoker invalidateInvoker(invoker); continue; } if ((selected == null) || (!selected.contains(invoker))) { reselectInvokers.add(invoker); } } } else { for (int i = 0; i < reselectCount; i++) { // select one randomly Invoker<T> invoker = invokers.get(ThreadLocalRandom.current().nextInt(invokers.size())); // check if available if (availableCheck && (!invoker.isAvailable())) { // add to invalidate invoker invalidateInvoker(invoker); continue; } // de-duplication if (((selected == null) || (!selected.contains(invoker))) || (!reselectInvokers.contains(invoker))) {reselectInvokers.add(invoker); } } } // 2. Use loadBalance to select one (all the reselectInvokers are available) if (!reselectInvokers.isEmpty()) { return loadbalance.select(reselectInvokers, getUrl(), invocation); } // 3. reselectInvokers is empty. Unable to find at least one available invoker. // Re-check all the selected invokers. If some in the selected list are available, add to reselectInvokers. if (selected != null) { for (Invoker<T> invoker : selected) { if (invoker.isAvailable()// available first && (!reselectInvokers.contains(invoker))) { reselectInvokers.add(invoker); } } } // 4. If reselectInvokers is not empty after re-check. // Pick an available invoker using loadBalance policy if (!reselectInvokers.isEmpty()) { return loadbalance.select(reselectInvokers, getUrl(), invocation);}// 5. No invoker match, return null. return null; }
3.26
dubbo_AbstractClusterInvoker_invokeWithContextAsync_rdh
/** * When using a thread pool to fork a child thread, ThreadLocal cannot be passed. * In this scenario, please use the invokeWithContextAsync method. * * @return */ protected Result invokeWithContextAsync(Invoker<T> invoker, Invocation invocation, URL consumerUrl) { Invoker<T> originInvoker = setContext(invoker, consumerUrl); Result result; try { result = invoker.invoke(invocation); } finally { clearContext(originInvoker); } return result; }
3.26
dubbo_AbstractClusterInvoker_initLoadBalance_rdh
/** * Init LoadBalance. * <p> * if invokers is not empty, init from the first invoke's url and invocation * if invokes is empty, init a default LoadBalance(RandomLoadBalance) * </p> * * @param invokers * invokers * @param invocation * invocation * @return LoadBalance instance. if not need init, return null. */ protected LoadBalance initLoadBalance(List<Invoker<T>> invokers, Invocation invocation) { ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(invocation.getModuleModel()); if (CollectionUtils.isNotEmpty(invokers)) { return applicationModel.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), LOADBALANCE_KEY, DEFAULT_LOADBALANCE)); } else { return applicationModel.getExtensionLoader(LoadBalance.class).getExtension(DEFAULT_LOADBALANCE); } }
3.26
dubbo_ServiceDefinitionBuilder_build_rdh
/** * Describe a Java interface in {@link ServiceDefinition}. * * @return Service description */ public static ServiceDefinition build(final Class<?> interfaceClass) { ServiceDefinition sd = new ServiceDefinition(); build(sd, interfaceClass); return sd; }
3.26
dubbo_DubboRelaxedBinding2AutoConfiguration_dubboBasePackages_rdh
/** * The bean is used to scan the packages of Dubbo Service classes * * @param environment * {@link Environment} instance * @return non-null {@link Set} * @since 2.7.8 */ @ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME) @Bean(name = BASE_PACKAGES_BEAN_NAME) public Set<String> dubboBasePackages(ConfigurableEnvironment environment) { PropertyResolver v2 = dubboScanBasePackagesPropertyResolver(environment); return v2.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); }
3.26
dubbo_ServiceDeployer_getExtensions_rdh
/** * get extensions by type * * @param extensionClass * @param <T> * @return */ // TODO add javax.annotation.Priority sort public <T> List<T> getExtensions(Class<T> extensionClass) { ArrayList<T> exts = new ArrayList<>(); if (extensions.isEmpty()) { return exts; }for (Object extension : extensions) { if (extensionClass.isAssignableFrom(extension.getClass())) { exts.add(((T) (extension))); } } return exts; }
3.26
dubbo_LfuCacheFactory_createCache_rdh
/** * Takes url as an method argument and return new instance of cache store implemented by LfuCache. * * @param url * url of the method * @return ThreadLocalCache instance of cache */ @Override protected Cache createCache(URL url) { return new LfuCache(url); }
3.26
dubbo_Configuration_getString_rdh
/** * Get a string associated with the given configuration key. * * @param key * The configuration key. * @return The associated string. */ default String getString(String key) { return convert(String.class, key, null); }
3.26
dubbo_Invoker_invoke_rdh
// This method will never be called for a legacy invoker. @Override default Result invoke(Invocation invocation) throws RpcException { return null; }
3.26
dubbo_DubboMergingDigest_setMinMax_rdh
/** * Over-ride the min and max values for testing purposes */ @SuppressWarnings("SameParameterValue") void setMinMax(double min, double max) { this.min = min; this.max = max; }
3.26
dubbo_DubboMergingDigest_recordAllData_rdh
/** * Turns on internal data recording. */@Override public TDigest recordAllData() { super.recordAllData(); data = new ArrayList<>(); tempData = new ArrayList<>(); return this; }
3.26
dubbo_DubboMergingDigest_compress_rdh
/** * Merges any pending inputs and compresses the data down to the public setting. * Note that this typically loses a bit of precision and thus isn't a thing to * be doing all the time. It is best done only when we want to show results to * the outside world. */ @Override public void compress() { mergeNewValues(true, publicCompression); }
3.26
dubbo_DubboServiceAddressURL_equals_rdh
/** * ignore consumer url compare. * It's only meaningful for comparing two AddressURLs related to the same consumerURL. * * @param obj * @return */ @Override public boolean equals(Object obj) { if (this == obj) {return true; } if (obj == null) { return false; } if (!(obj instanceof DubboServiceAddressURL)) { return false; } if (overrideURL == null) { return super.equals(obj); } else { DubboServiceAddressURL other = ((DubboServiceAddressURL) (obj)); boolean overrideEquals = Objects.equals(overrideURL.getParameters(), other.getOverrideURL().getParameters()); if (!overrideEquals) { return false; } Map<String, String> params = this.getParameters();for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (overrideURL.getParameters().containsKey(key)) { continue; } if (!entry.getValue().equals(other.getUrlParam().getParameter(key))) {return false; } } } return true; }
3.26
dubbo_DubboServiceAddressURL_getAllParameters_rdh
/** * The returned parameters is imprecise regarding override priorities of consumer url and provider url. * This method is only used to pass the configuration in the 'client'. */ @Overridepublic Map<String, String> getAllParameters() { Map<String, String> allParameters = new HashMap<>(((int) ((super.getParameters().size() / 0.75) + 1))); allParameters.putAll(super.getParameters()); if (consumerURL != null) { allParameters.putAll(consumerURL.getParameters());} if (overrideURL != null) { allParameters.putAll(overrideURL.getParameters()); }return Collections.unmodifiableMap(allParameters); }
3.26
dubbo_DubboConfigBeanDefinitionConflictApplicationListener_resolveUniqueApplicationConfigBean_rdh
/** * Resolve the unique {@link ApplicationConfig} Bean * * @param registry * {@link BeanDefinitionRegistry} instance * @param beanFactory * {@link ConfigurableListableBeanFactory} instance * @see EnableDubboConfig */ private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, ListableBeanFactory beanFactory) { String[] beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length < 2) { // If the number of ApplicationConfig beans is less than two, return immediately. return; } Environment environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class); // Remove ApplicationConfig Beans that are configured by "dubbo.application.*" Stream.of(beansNames).filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName)).forEach(registry::removeBeanDefinition); beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length > 1) { throw new IllegalStateException(String.format("There are more than one instances of %s, whose bean definitions : %s", ApplicationConfig.class.getSimpleName(), Stream.of(beansNames).map(registry::getBeanDefinition).collect(Collectors.toList()))); } }
3.26
dubbo_LoggerFactory_getLogger_rdh
/** * Get logger provider * * @param key * the returned logger will be named after key * @return logger provider */ public static Logger getLogger(String key) { return ConcurrentHashMapUtils.computeIfAbsent(LOGGERS, key, k -> new FailsafeLogger(LoggerFactory.loggerAdapter.getLogger(k))); }
3.26
dubbo_LoggerFactory_getLevel_rdh
/** * Get logging level * * @return logging level */ public static Level getLevel() { return loggerAdapter.getLevel(); }
3.26
dubbo_LoggerFactory_setLoggerAdapter_rdh
/** * Set logger provider * * @param loggerAdapter * logger provider */ public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { if (loggerAdapter != null) { if (loggerAdapter == LoggerFactory.loggerAdapter) { return; } loggerAdapter.getLogger(LoggerFactory.class.getName()); LoggerFactory.loggerAdapter = loggerAdapter; for (Map.Entry<String, FailsafeLogger> entry : LOGGERS.entrySet()) { entry.getValue().setLogger(LoggerFactory.loggerAdapter.getLogger(entry.getKey())); } } }
3.26
dubbo_LoggerFactory_getAvailableAdapter_rdh
/** * Get the available adapter names * * @return available adapter names */ public static List<String> getAvailableAdapter() { Map<Class<? extends LoggerAdapter>, String> candidates = new HashMap<>(); candidates.put(Log4jLoggerAdapter.class, "log4j"); candidates.put(Slf4jLoggerAdapter.class, "slf4j"); candidates.put(Log4j2LoggerAdapter.class, "log4j2"); candidates.put(JclLoggerAdapter.class, "jcl"); candidates.put(JdkLoggerAdapter.class, "jdk"); List<String> result = new LinkedList<>(); for (Map.Entry<Class<? extends LoggerAdapter>, String> entry : candidates.entrySet()) { try { LoggerAdapter loggerAdapter = entry.getKey().getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); result.add(entry.getValue()); } catch (Exception ignored) { // ignored } } return result; }
3.26
dubbo_LoggerFactory_setLevel_rdh
/** * Set the current logging level * * @param level * logging level */ public static void setLevel(Level level) { loggerAdapter.setLevel(level); }
3.26
dubbo_LoggerFactory_getErrorTypeAwareLogger_rdh
/** * Get error type aware logger by a String key. * * @param key * the returned logger will be named after key * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(String key) { return ConcurrentHashMapUtils.computeIfAbsent(ERROR_TYPE_AWARE_LOGGERS, key, k -> new FailsafeErrorTypeAwareLogger(LoggerFactory.loggerAdapter.getLogger(k))); }
3.26
dubbo_LoggerFactory_getFile_rdh
/** * Get the current logging file * * @return current logging file */ public static File getFile() { return loggerAdapter.getFile(); }
3.26
dubbo_LoggerFactory_getCurrentAdapter_rdh
/** * Get the current adapter name * * @return current adapter name */ public static String getCurrentAdapter() { Map<Class<? extends LoggerAdapter>, String> candidates = new HashMap<>(); candidates.put(Log4jLoggerAdapter.class, "log4j"); candidates.put(Slf4jLoggerAdapter.class, "slf4j"); candidates.put(Log4j2LoggerAdapter.class, "log4j2"); candidates.put(JclLoggerAdapter.class, "jcl"); candidates.put(JdkLoggerAdapter.class, "jdk"); String name = candidates.get(loggerAdapter.getClass()); if (name == null) { name = loggerAdapter.getClass().getSimpleName(); } return name; }
3.26
dubbo_ReflectionBasedServiceDiscovery_getCachedServiceInstances_rdh
/** * UT used only */ @Deprecated public final ConcurrentHashMap<String, List<ServiceInstance>> getCachedServiceInstances() { return cachedServiceInstances; }
3.26
dubbo_DubboBootstrapStatedEvent_getDubboBootstrap_rdh
/** * Get {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} instance * * @return non-null */ public DubboBootstrap getDubboBootstrap() { return ((DubboBootstrap) (super.getSource())); }
3.26
dubbo_CacheableFailbackRegistry_createURL_rdh
/** * Create DubboServiceAddress object using provider url, consumer url, and extra parameters. * * @param rawProvider * provider url string * @param consumerURL * URL object of consumer * @param extraParameters * extra parameters * @return created DubboServiceAddressURL object */ protected ServiceAddressURL createURL(String rawProvider, URL consumerURL, Map<String, String> extraParameters) { boolean v17 = true; // use encoded value directly to avoid URLDecoder.decode allocation. int paramStartIdx = rawProvider.indexOf(ENCODED_QUESTION_MARK); if (paramStartIdx == (-1)) { // if ENCODED_QUESTION_MARK does not show, mark as not encoded. v17 = false; } // split by (encoded) question mark. // part[0] => protocol + ip address + interface. // part[1] => parameters (metadata). String[] parts = URLStrParser.parseRawURLToArrays(rawProvider, paramStartIdx); if (parts.length <= 1) { // 1-5 Received URL without any parameters. logger.warn(REGISTRY_NO_PARAMETERS_URL, "", "", "Received url without any parameters " + rawProvider); return DubboServiceAddressURL.valueOf(rawProvider, consumerURL); } String rawAddress = parts[0]; String rawParams = parts[1]; // Workaround for 'effectively final': duplicate the encoded variable. boolean isEncoded = v17; // PathURLAddress if it's using dubbo protocol. URLAddress address = ConcurrentHashMapUtils.computeIfAbsent(stringAddress, rawAddress, k -> URLAddress.parse(k, getDefaultURLProtocol(), isEncoded)); address.setTimestamp(System.currentTimeMillis()); URLParam param = ConcurrentHashMapUtils.computeIfAbsent(stringParam, rawParams, k -> URLParam.parse(k, isEncoded, extraParameters)); param.setTimestamp(System.currentTimeMillis()); // create service URL using cached address, param, and consumer URL. ServiceAddressURL cachedServiceAddressURL = createServiceURL(address, param, consumerURL); if (isMatch(consumerURL, cachedServiceAddressURL)) { return cachedServiceAddressURL; } return null; }
3.26
dubbo_TriHttp2RemoteFlowController_writeError_rdh
/** * Discards this {@link FlowControlled}, writing an error. If this frame is in the pending queue, * the unwritten bytes are removed from this branch of the priority tree. */ private void writeError(FlowControlled frame, Http2Exception cause) { assert ctx != null; decrementPendingBytes(frame.size(), true); frame.error(ctx, cause); }
3.26
dubbo_TriHttp2RemoteFlowController_writeAllocatedBytes_rdh
/** * Write the allocated bytes for this stream. * * @return the number of bytes written for a stream or {@code -1} if no write occurred. */ int writeAllocatedBytes(int allocated) { final int initialAllocated = allocated; int writtenBytes; // In case an exception is thrown we want to remember it and pass it to cancel(Throwable). Throwable cause = null; FlowControlled frame; try { assert !writing; writing = true; // Write the remainder of frames that we are allowed to boolean writeOccurred = false; while ((!cancelled) && ((frame = peek()) != null)) { int maxBytes = min(allocated, writableWindow()); if ((maxBytes <= 0) && (frame.size() > 0)) { // The frame still has data, but the amount of allocated bytes has been exhausted. // Don't write needless empty frames. break; } writeOccurred = true; int initialFrameSize = frame.size(); try { frame.write(ctx, max(0, maxBytes)); if (frame.size() == 0) { // This frame has been fully written, remove this frame and notify it. // Since we remove this frame first, we're guaranteed that its error // method will not be called when we call cancel. pendingWriteQueue.remove(); frame.writeComplete();} } finally { // Decrement allocated by how much was actually written. allocated -= initialFrameSize - frame.size(); } } if (!writeOccurred) {// Either there was no frame, or the amount of allocated bytes has been exhausted. return -1; } } catch (Throwable t) { // Mark the state as cancelled, we'll clear the pending queue via cancel() below. cancelled = true; cause = t; } finally { writing = false; // Make sure we always decrement the flow control windows // by the bytes written. writtenBytes = initialAllocated - allocated; decrementPendingBytes(writtenBytes, false); decrementFlowControlWindow(writtenBytes); // If a cancellation occurred while writing, call cancel again to // clear and error all of the pending writes. if (cancelled) { cancel(INTERNAL_ERROR, cause); } if (monitor.isOverFlowControl()) { cause = new Throwable(); cancel(FLOW_CONTROL_ERROR, cause); } } return writtenBytes; }
3.26
dubbo_TriHttp2RemoteFlowController_channelWritabilityChange_rdh
/** * Called when the writability of the underlying channel changes. * * @throws Http2Exception * If a write occurs and an exception happens in the write operation. */ void channelWritabilityChange() throws Http2Exception { }
3.26
dubbo_TriHttp2RemoteFlowController_stream_rdh
/** * The stream this state is associated with. */ @Override public Http2Stream stream() { return stream; }
3.26
dubbo_TriHttp2RemoteFlowController_peek_rdh
/** * Returns the head of the pending queue, or {@code null} if empty. */ private FlowControlled peek() { return pendingWriteQueue.peek(); } /** * Clears the pending queue and writes errors for each remaining frame. * * @param error * the {@link Http2Error} to use. * @param cause * the {@link Throwable}
3.26
dubbo_TriHttp2RemoteFlowController_markedWritability_rdh
/** * Save the state of writability. */ void markedWritability(boolean isWritable) { this.f0 = isWritable; }
3.26
dubbo_TriHttp2RemoteFlowController_enqueueFrame_rdh
/** * Adds the {@code frame} to the pending queue and increments the pending byte count. */ void enqueueFrame(FlowControlled frame) { FlowControlled last = pendingWriteQueue.peekLast(); if (last == null) { enqueueFrameWithoutMerge(frame); return; } int lastSize = last.size(); if (last.merge(ctx, frame)) {incrementPendingBytes(last.size() - lastSize, true); return;} enqueueFrameWithoutMerge(frame);}
3.26
dubbo_TriHttp2RemoteFlowController_channelHandlerContext_rdh
/** * {@inheritDoc } * <p> * Any queued {@link FlowControlled} objects will be sent. */ @Override public void channelHandlerContext(ChannelHandlerContext ctx) throws Http2Exception { this.ctx = checkNotNull(ctx, "ctx"); // Writing the pending bytes will not check writability change and instead a writability change notification // to be provided by an explicit call. channelWritabilityChanged();// Don't worry about cleaning up queued frames here if ctx is null. It is expected that all streams will be // closed and the queue cleanup will occur when the stream state transitions occur. // If any frames have been queued up, we should send them now that we have a channel context. if (isChannelWritable()) { writePendingBytes(); } }
3.26
dubbo_TriHttp2RemoteFlowController_writableWindow_rdh
/** * Returns the maximum writable window (minimum of the stream and connection windows). */ private int writableWindow() { return min(window, connectionWindowSize()); }
3.26
dubbo_TriHttp2RemoteFlowController_windowSize_rdh
/** * Set the initial window size for {@code state}. * * @param state * the state to change the initial window size for. * @param initialWindowSize * the size of the window in bytes. */ void windowSize(FlowState state, int initialWindowSize) { state.windowSize(initialWindowSize); }
3.26
dubbo_TriHttp2RemoteFlowController_incrementWindowSize_rdh
/** * Increment the window size for a particular stream. * * @param state * the state associated with the stream whose window is being incremented. * @param delta * The amount to increment by. * @throws Http2Exception * If this operation overflows the window for {@code state}. */ void incrementWindowSize(FlowState state, int delta) throws Http2Exception { state.incrementStreamWindow(delta); }
3.26
dubbo_TriHttp2RemoteFlowController_m0_rdh
/** * Add a frame to be sent via flow control. * * @param state * The state associated with the stream which the {@code frame} is associated with. * @param frame * the frame to enqueue. * @throws Http2Exception * If a writability error occurs. */ void m0(FlowState state, FlowControlled frame) throws Http2Exception { state.enqueueFrame(frame); }
3.26
dubbo_TriHttp2RemoteFlowController_stateCancelled_rdh
/** * Called when the state is cancelled. * * @param state * the state that was cancelled. */ void stateCancelled(FlowState state) { }
3.26
dubbo_TriHttp2RemoteFlowController_incrementStreamWindow_rdh
/** * Increments the flow control window for this stream by the given delta and returns the new value. */ int incrementStreamWindow(int delta) throws Http2Exception { if ((delta > 0) && ((Integer.MAX_VALUE - delta) < window)) { throw streamError(stream.id(), FLOW_CONTROL_ERROR, "Window size overflow for stream: %d", stream.id()); } window += delta; streamByteDistributor.updateStreamableBytes(this); return window; }
3.26
dubbo_TriHttp2RemoteFlowController_decrementFlowControlWindow_rdh
/** * Decrement the per stream and connection flow control window by {@code bytes}. */ private void decrementFlowControlWindow(int bytes) { try {int negativeBytes = -bytes; connectionState.incrementStreamWindow(negativeBytes); incrementStreamWindow(negativeBytes);} catch (Http2Exception e) { // Should never get here since we're decrementing. throw new IllegalStateException("Invalid window state when writing frame: " + e.getMessage(), e); } }
3.26
dubbo_TriHttp2RemoteFlowController_isWritable_rdh
/** * Determine if the stream associated with {@code state} is writable. * * @param state * The state which is associated with the stream to test writability for. * @return {@code true} if {@link FlowState#stream()} is writable. {@code false} otherwise. */ final boolean isWritable(FlowState state) { return isWritableConnection() && state.isWritable(); }
3.26
dubbo_TriHttp2RemoteFlowController_incrementPendingBytes_rdh
/** * Increment the total amount of pending bytes for all streams. When any stream's pending bytes changes * method should be called. * * @param delta * The amount to increment by. */ final void incrementPendingBytes(int delta) { totalPendingBytes += delta; // Notification of writibilty change should be delayed until the end of the top level event. // This is to ensure the flow controller is more consistent state before calling external listener methods. }
3.26
dubbo_Mixin_mixin_rdh
/** * mixin interface and delegates. * all class must be public. * * @param ics * interface class array. * @param dcs * delegate class array. * @param cl * class loader. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?>[] dcs, ClassLoader cl) {assertInterfaceArray(ics); long v0 = MIXIN_CLASS_COUNTER.getAndIncrement(); String pkg = null; ClassGenerator ccp = null; ClassGenerator ccm = null; try { ccp = ClassGenerator.newInstance(cl); // impl constructor StringBuilder code = new StringBuilder(); for (int i = 0; i < dcs.length; i++) { if (!Modifier.isPublic(dcs[i].getModifiers())) { String npkg = dcs[i].getPackage().getName(); if (pkg == null) { pkg = npkg; } else if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces class from different packages"); } } ccp.addField(((("private " + dcs[i].getName()) + " d") + i) + ";"); code.append('d').append(i).append(" = (").append(dcs[i].getName()).append(")$1[").append(i).append("];\n"); if (Mixin.MixinAware.class.isAssignableFrom(dcs[i])) { code.append('d').append(i).append(".setMixinInstance(this);\n"); } } ccp.addConstructor(Modifier.PUBLIC, new Class<?>[]{ Object[].class }, code.toString()); Class<?> neighbor = null; // impl methods. Set<String> worked = new HashSet<String>(); for (int i = 0; i < ics.length; i++) { if (!Modifier.isPublic(ics[i].getModifiers())) { String npkg = ics[i].getPackage().getName(); if (pkg == null) { pkg = npkg; neighbor = ics[i]; } else if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public delegate class from different packages"); } } ccp.addInterface(ics[i]); for (Method method : ics[i].getMethods()) { if ("java.lang.Object".equals(method.getDeclaringClass().getName())) { continue; } String desc = ReflectUtils.getDesc(method); if (worked.contains(desc)) { continue; } worked.add(desc); int ix = findMethod(dcs, desc); if (ix < 0) { throw new RuntimeException(("Missing method [" + desc) + "] implement."); } Class<?> rt = method.getReturnType(); String mn = method.getName(); if (Void.TYPE.equals(rt)) { ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), ((("d" + ix) + ".") + mn) + "($$);"); } else { ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), ((("return ($r)d" + ix) + ".") + mn) + "($$);"); }} } if (pkg == null) { pkg = PACKAGE_NAME; neighbor = Mixin.class; } // create MixinInstance class. String micn = (pkg + ".mixin") + v0; ccp.setClassName(micn); ccp.toClass(neighbor);// create Mixin class. String fcn = Mixin.class.getName() + v0; ccm = ClassGenerator.newInstance(cl); ccm.setClassName(fcn); ccm.addDefaultConstructor(); ccm.setSuperClass(Mixin.class.getName()); ccm.addMethod(("public Object newInstance(Object[] delegates){ return new " + micn) + "($1); }"); Class<?> mixin = ccm.toClass(Mixin.class); return ((Mixin) (mixin.getDeclaredConstructor().newInstance())); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e);} finally { // release ClassGenerator if (ccp != null) { ccp.release(); } if (ccm != null) { ccm.release(); } } }
3.26
dubbo_StandardMetadataServiceURLBuilder_getMetadataServiceURLsParams_rdh
/** * Get the multiple {@link URL urls'} parameters of {@link MetadataService MetadataService's} Metadata * * @param serviceInstance * the instance of {@link ServiceInstance} * @return non-null {@link Map}, the key is {@link URL#getProtocol() the protocol of URL}, the value is */ private Map<String, String> getMetadataServiceURLsParams(ServiceInstance serviceInstance) { Map<String, String> metadata = serviceInstance.getMetadata(); String param = metadata.get(METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME); return isBlank(param) ? emptyMap() : ((Map) (JsonUtils.toJavaObject(param, Map.class))); }
3.26
dubbo_TreePathDynamicConfiguration_getRootPath_rdh
/** * Get the root path from the specified {@link URL connection URl} * * @param url * the specified {@link URL connection URl} * @return non-null */ protected String getRootPath(URL url) { String rootPath = url.getParameter(CONFIG_ROOT_PATH_PARAM_NAME, buildRootPath(url)); rootPath = normalize(rootPath); int rootPathLength = rootPath.length(); if ((rootPathLength > 1) && rootPath.endsWith(PATH_SEPARATOR)) { rootPath = rootPath.substring(0, rootPathLength - 1); } return rootPath; }
3.26
dubbo_TreePathDynamicConfiguration_getConfigBasePath_rdh
/** * Get the config base path from the specified {@link URL connection URl} * * @param url * the specified {@link URL connection URl} * @return non-null */protected String getConfigBasePath(URL url) { String configBasePath = url.getParameter(CONFIG_BASE_PATH_PARAM_NAME, DEFAULT_CONFIG_BASE_PATH); if (StringUtils.isNotEmpty(configBasePath) && (!configBasePath.startsWith(PATH_SEPARATOR))) { configBasePath = PATH_SEPARATOR + configBasePath; } return configBasePath;}
3.26
dubbo_TreePathDynamicConfiguration_getConfigNamespace_rdh
/** * Get the namespace from the specified {@link URL connection URl} * * @param url * the specified {@link URL connection URl} * @return non-null */ protected String getConfigNamespace(URL url) { return url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP); }
3.26
dubbo_RouterChain_route_rdh
/** * * @deprecated use {@link RouterChain#getSingleChain(URL, BitList, Invocation)} and {@link SingleRouterChain#route(URL, BitList, Invocation)} instead */ @Deprecated public List<Invoker<T>> route(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) { return getSingleChain(url, availableInvokers, invocation).route(url, availableInvokers, invocation); }
3.26
dubbo_RouterChain_setInvokers_rdh
/** * Notify router chain of the initial addresses from registry at the first time. * Notify whenever addresses in registry change. */ public synchronized void setInvokers(BitList<Invoker<T>> invokers, Runnable switchAction) { try { // Lock to prevent directory continue list lock.writeLock().lock(); // Switch to back up chain. Will update main chain first. currentChain = backupChain; } finally {// Release lock to minimize the impact for each newly created invocations as much as possible. // Should not release lock until main chain update finished. Or this may cause long hang. lock.writeLock().unlock(); } // Refresh main chain. // No one can request to use main chain. `currentChain` is backup chain. `route` method cannot access main // chain. try { // Lock main chain to wait all invocation end // To wait until no one is using main chain. mainChain.getLock().writeLock().lock(); // refresh mainChain.setInvokers(invokers); } catch (Throwable t) { logger.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Error occurred when refreshing router chain.", t); throw t; } finally { // Unlock main chain mainChain.getLock().writeLock().unlock(); } // Set the reference of newly invokers to temp variable. // Reason: The next step will switch the invokers reference in directory, so we should check the // `availableInvokers` // argument when `route`. If the current invocation use newly invokers, we should use main chain to // route, and // this can prevent use newly invokers to route backup chain, which can only route origin invokers now. notifyingInvokers.set(invokers); // Switch the invokers reference in directory. // Cannot switch before update main chain or after backup chain update success. Or that will cause state // inconsistent. switchAction.run(); try { // Lock to prevent directory continue list // The invokers reference in directory now should be the newly one and should always use the newly one once // lock released. lock.writeLock().lock(); // Switch to main chain. Will update backup chain later. currentChain = mainChain; // Clean up temp variable. // `availableInvokers` check is useless now, because `route` method will no longer receive any // `availableInvokers` related // with the origin invokers. The getter of invokers reference in directory is locked now, and will return // newly invokers // once lock released. notifyingInvokers.set(null); } finally { // Release lock to minimize the impact for each newly created invocations as much as possible. // Will use newly invokers and main chain now. lock.writeLock().unlock(); } // Refresh main chain. // No one can request to use main chain. `currentChain` is main chain. `route` method cannot access backup // chain. try { // Lock main chain to wait all invocation end backupChain.getLock().writeLock().lock(); // refresh backupChain.setInvokers(invokers); } catch (Throwable t) {logger.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Error occurred when refreshing router chain.", t);throw t; } finally { // Unlock backup chain backupChain.getLock().writeLock().unlock(); } }
3.26
dubbo_DubboObservationDocumentation_asString_rdh
/** * The name of the (logical) method being called, must be equal to the $method part in the span name. * Example: "exampleMethod". */ f0() { @Override public String asString() { return "rpc.method"; }
3.26
dubbo_DubboDefaultPropertiesEnvironmentPostProcessor_setAllowBeanDefinitionOverriding_rdh
/** * Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be * <code>true</code> as default. * * @param defaultProperties * the default {@link Properties properties} * @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY * @since 2.7.1 */ private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) { defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString()); }
3.26
dubbo_DubboDefaultPropertiesEnvironmentPostProcessor_addOrReplace_rdh
/** * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map) * * @param propertySources * {@link MutablePropertySources} * @param map * Default Dubbo Properties */ private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) { MapPropertySource target = null; if (propertySources.contains(PROPERTY_SOURCE_NAME)) { PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME); if (source instanceof MapPropertySource) { target = ((MapPropertySource) (source)); for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); if (!target.containsProperty(key)) { target.getSource().put(key, entry.getValue()); } } } } if (target == null) { target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); } if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { propertySources.addLast(target); } }
3.26
dubbo_ServiceAnnotationResolver_resolveInterfaceClassName_rdh
/** * Resolve the class name of interface * * @return if not found, return <code>null</code> */ public String resolveInterfaceClassName() { Class interfaceClass; // first, try to get the value from "interfaceName" attribute String interfaceName = resolveAttribute("interfaceName"); if (isEmpty(interfaceName)) { // If not found, try "interfaceClass" interfaceClass = resolveAttribute("interfaceClass"); } else { interfaceClass = resolveClass(interfaceName, getClass().getClassLoader()); } if (isGenericClass(interfaceClass)) { interfaceName = interfaceClass.getName(); } else { interfaceName = null; } if (isEmpty(interfaceName)) { // If not fund, try to get the first interface from the service type Class[] v4 = serviceType.getInterfaces(); if (isNotEmpty(v4)) { interfaceName = v4[0].getName(); } } return interfaceName; }
3.26
dubbo_ServiceNameMapping_getDefaultExtension_rdh
/** * Get the default extension of {@link ServiceNameMapping} * * @return non-null {@link ServiceNameMapping} */ static ServiceNameMapping getDefaultExtension(ScopeModel scopeModel) { return ScopeModelUtil.getApplicationModel(scopeModel).getDefaultExtension(ServiceNameMapping.class); }
3.26
dubbo_ConcurrentHashSet_remove_rdh
/** * Removes the specified element from this set if it is present. More * formally, removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if this * set contains such an element. Returns <tt>true</tt> if this set contained * the element (or equivalently, if this set changed as a result of the * call). (This set will not contain the element once the call returns.) * * @param o * object to be removed from this set, if present * @return <tt>true</tt> if the set contained the specified element */ @Override public boolean remove(Object o) { return map.remove(o) == PRESENT; }
3.26
dubbo_ConcurrentHashSet_contains_rdh
/** * Returns <tt>true</tt> if this set contains the specified element. More * formally, returns <tt>true</tt> if and only if this set contains an * element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o * element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element */ @Override public boolean contains(Object o) { return map.containsKey(o); }
3.26
dubbo_ConcurrentHashSet_isEmpty_rdh
/** * Returns <tt>true</tt> if this set contains no elements. * * @return <tt>true</tt> if this set contains no elements */ @Override public boolean isEmpty() {return map.isEmpty(); }
3.26
dubbo_ConcurrentHashSet_size_rdh
/** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality) */ @Overridepublic int size() { return map.size(); }
3.26
dubbo_ConcurrentHashSet_clear_rdh
/** * Removes all of the elements from this set. The set will be empty after * this call returns. */ @Override public void clear() { map.clear(); }
3.26
dubbo_GlobalResourcesRepository_registerDisposable_rdh
/** * Register a one-off disposable, the disposable is removed automatically on first shutdown. * * @param disposable */ public void registerDisposable(Disposable disposable) { if (!oneoffDisposables.contains(disposable)) { synchronized(this) { if (!oneoffDisposables.contains(disposable)) { oneoffDisposables.add(disposable); } } } }
3.26