name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
dubbo_ReflectUtils_isInstance_rdh
/** * Check if one object is the implementation for a given interface. * <p> * This method will not trigger classloading for the given interface, therefore it will not lead to error when * the given interface is not visible by the classloader * * @param obj * Object to examine * @param interfaceClazzName * The given interface * @return true if the object implements the given interface, otherwise return false */ public static boolean isInstance(Object obj, String interfaceClazzName) { for (Class<?> clazz = obj.getClass(); (clazz != null) && (!clazz.equals(Object.class)); clazz = clazz.getSuperclass()) { Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> itf : interfaces) { if (itf.getName().equals(interfaceClazzName)) { return true; } } } return false; }
3.26
dubbo_ReflectUtils_findHierarchicalTypes_rdh
/** * Find the hierarchical types from the source {@link Class class} by specified {@link Class type}. * * @param sourceClass * the source {@link Class class} * @param matchType * the type to match * @param <T> * the type to match * @return non-null read-only {@link Set} * @since 2.7.5 */ public static <T> Set<Class<T>> findHierarchicalTypes(Class<?> sourceClass, Class<T> matchType) { if (sourceClass == null) { return Collections.emptySet(); }Set<Class<T>> hierarchicalTypes = new LinkedHashSet<>(); if (matchType.isAssignableFrom(sourceClass)) { hierarchicalTypes.add(((Class<T>) (sourceClass))); } // Find all super classes hierarchicalTypes.addAll(findHierarchicalTypes(sourceClass.getSuperclass(), matchType)); return unmodifiableSet(hierarchicalTypes); }
3.26
dubbo_ReflectUtils_makeAccessible_rdh
/** * Copy from org.springframework.util.ReflectionUtils. * Make the given method accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * * @param method * the method to make accessible * @see java.lang.reflect.Method#setAccessible */ // on JDK 9 @SuppressWarnings("deprecation") public static void makeAccessible(Method method) { if (((!Modifier.isPublic(method.getModifiers())) || (!Modifier.isPublic(method.getDeclaringClass().getModifiers()))) && (!method.isAccessible())) { method.setAccessible(true); } }
3.26
dubbo_ReflectUtils_getDesc_rdh
/** * get constructor desc. * "()V", "(Ljava/lang/String;I)V" * * @param c * constructor. * @return desc */ public static String getDesc(final CtConstructor c) throws NotFoundException { StringBuilder ret = new StringBuilder("("); CtClass[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append('V'); return ret.toString(); }
3.26
dubbo_ReflectUtils_name2desc_rdh
/** * name to desc. * java.util.Map[][] => "[[Ljava/util/Map;" * * @param name * name. * @return desc. */ public static String name2desc(String name) { StringBuilder v45 = new StringBuilder(); int c = 0; int index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } while ((c--) > 0) { v45.append('['); } if ("void".equals(name)) { v45.append(JVM_VOID); } else if ("boolean".equals(name)) { v45.append(JVM_BOOLEAN); } else if ("byte".equals(name)) { v45.append(JVM_BYTE); } else if ("char".equals(name)) { v45.append(JVM_CHAR); } else if ("double".equals(name)) { v45.append(JVM_DOUBLE); } else if ("float".equals(name)) { v45.append(JVM_FLOAT); } else if ("int".equals(name)) { v45.append(JVM_INT); } else if ("long".equals(name)) { v45.append(JVM_LONG); } else if ("short".equals(name)) { v45.append(JVM_SHORT); } else { v45.append('L').append(name.replace('.', '/')).append(';'); } return v45.toString(); }
3.26
dubbo_ReflectUtils_getDescWithoutMethodName_rdh
/** * get method desc. * "(I)I", "()V", "(Ljava/lang/String;Z)V". * * @param m * method. * @return desc. */ public static String getDescWithoutMethodName(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(); ret.append('('); CtClass[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); }
3.26
dubbo_ReflectUtils_findParameterizedTypes_rdh
/** * Find the {@link Set} of {@link ParameterizedType} * * @param sourceClass * the source {@link Class class} * @return non-null read-only {@link Set} * @since 2.7.5 */ public static Set<ParameterizedType> findParameterizedTypes(Class<?> sourceClass) { // Add Generic Interfaces List<Type> genericTypes = new LinkedList<>(asList(sourceClass.getGenericInterfaces())); // Add Generic Super Class genericTypes.add(sourceClass.getGenericSuperclass()); Set<ParameterizedType> parameterizedTypes = // cast to ParameterizedType // filter ParameterizedType genericTypes.stream().filter(type -> type instanceof ParameterizedType).map(ParameterizedType.class::cast).collect(Collectors.toSet()); if (parameterizedTypes.isEmpty()) { // If not found, try to search super types recursively genericTypes.stream().filter(type -> type instanceof Class).map(Class.class::cast).forEach(superClass -> parameterizedTypes.addAll(findParameterizedTypes(superClass))); } return unmodifiableSet(parameterizedTypes);// build as a Set }
3.26
dubbo_ReflectUtils_desc2name_rdh
/** * desc to name. * "[[I" => "int[][]" * * @param desc * desc. * @return name. */ public static String desc2name(String desc) { StringBuilder sb = new StringBuilder(); int c = desc.lastIndexOf('[') + 1; if (desc.length() == (c + 1)) { switch (desc.charAt(c)) { case JVM_VOID : { sb.append("void"); break; } case JVM_BOOLEAN : { sb.append("boolean"); break; } case JVM_BYTE : { sb.append("byte"); break; } case JVM_CHAR : { sb.append("char"); break; } case JVM_DOUBLE : { sb.append("double"); break; }case JVM_FLOAT : { sb.append("float"); break; } case JVM_INT : { sb.append("int"); break; } case JVM_LONG : { sb.append("long"); break; } case JVM_SHORT : { sb.append("short"); break; } default : throw new RuntimeException(); } } else { sb.append(desc.substring(c + 1, desc.length() - 1).replace('/', '.')); } while ((c--) > 0) { sb.append("[]"); } return sb.toString(); }
3.26
dubbo_ReflectUtils_name2class_rdh
/** * name to class. * "boolean" => boolean.class * "java.util.Map[][]" => java.util.Map[][].class * * @param cl * ClassLoader instance. * @param name * name. * @return Class instance. */ private static Class<?> name2class(ClassLoader cl, String name) throws ClassNotFoundException { int c = 0; int index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } if (c > 0) { StringBuilder sb = new StringBuilder(); while ((c--) > 0) { sb.append('['); } if ("void".equals(name)) { sb.append(JVM_VOID); } else if ("boolean".equals(name)) { sb.append(JVM_BOOLEAN); } else if ("byte".equals(name)) { sb.append(JVM_BYTE); } else if ("char".equals(name)) { sb.append(JVM_CHAR); } else if ("double".equals(name)) { sb.append(JVM_DOUBLE); } else if ("float".equals(name)) { sb.append(JVM_FLOAT); } else if ("int".equals(name)) { sb.append(JVM_INT); } else if ("long".equals(name)) { sb.append(JVM_LONG); } else if ("short".equals(name)) { sb.append(JVM_SHORT); } else { // "java.lang.Object" ==> "Ljava.lang.Object;" sb.append('L').append(name).append(';'); } name = sb.toString(); } else { if ("void".equals(name)) { return void.class; } if ("boolean".equals(name)) { return boolean.class; } if ("byte".equals(name)) { return byte.class; } if ("char".equals(name)) { return char.class;} if ("double".equals(name)) { return double.class; } if ("float".equals(name)) { return float.class; } if ("int".equals(name)) { return int.class; } if ("long".equals(name)) { return long.class; } if ("short".equals(name)) { return short.class;} } if (cl == null) { cl = ClassUtils.getClassLoader(); } return Class.forName(name, true, cl); }
3.26
dubbo_ReflectUtils_getAllFieldNames_rdh
/** * Get all field names of target type * * @param type * @return */ public static Set<String> getAllFieldNames(Class<?> type) {Set<String> fieldNames = new HashSet<>(); for (Field field : type.getDeclaredFields()) { fieldNames.add(field.getName()); } Set<Class<?>> allSuperClasses = ClassUtils.getAllSuperClasses(type); for (Class<?> aClass : allSuperClasses) { for (Field field : aClass.getDeclaredFields()) { fieldNames.add(field.getName()); } } return fieldNames; }
3.26
dubbo_ReflectUtils_hasMethod_rdh
/** * Check target bean class whether has specify method * * @param beanClass * @param methodName * @return */ public static boolean hasMethod(Class<?> beanClass, String methodName) { try { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); Optional<MethodDescriptor> descriptor = Stream.of(beanInfo.getMethodDescriptors()).filter(methodDescriptor -> methodName.equals(methodDescriptor.getName())).findFirst(); return descriptor.isPresent(); } catch (Exception e) { } return false; }
3.26
dubbo_ReflectUtils_m0_rdh
/** * get name. * java.lang.Object[][].class => "java.lang.Object[][]" * * @param c * class. * @return name. */ public static String m0(Class<?> c) { if (c.isArray()) { StringBuilder sb = new StringBuilder(); do { sb.append("[]"); c = c.getComponentType(); } while (c.isArray() ); return c.getName() + sb.toString(); } return c.getName(); }
3.26
dubbo_ReflectUtils_desc2class_rdh
/** * desc to class. * "[Z" => boolean[].class * "[[Ljava/util/Map;" => java.util.Map[][].class * * @param cl * ClassLoader instance. * @param desc * desc. * @return Class instance. * @throws ClassNotFoundException */ private static Class<?> desc2class(ClassLoader cl, String desc) throws ClassNotFoundException { switch (desc.charAt(0)) { case JVM_VOID : return void.class; case JVM_BOOLEAN : return boolean.class; case JVM_BYTE : return byte.class; case JVM_CHAR : return char.class; case JVM_DOUBLE : return double.class; case JVM_FLOAT : return float.class; case JVM_INT : return int.class; case JVM_LONG : return long.class; case JVM_SHORT : return short.class; case 'L' : // "Ljava/lang/Object;" ==> "java.lang.Object" desc = desc.substring(1, desc.length() - 1).replace('/', '.'); break; case '[' : // "[[Ljava/lang/Object;" ==> "[[Ljava.lang.Object;" desc = desc.replace('/', '.'); break; default : throw new ClassNotFoundException("Class not found: " + desc);} if (cl == null) { cl = ClassUtils.getClassLoader(); } return Class.forName(desc, true, cl); }
3.26
dubbo_ReflectUtils_desc2classArray_rdh
/** * get class array instance. * * @param cl * ClassLoader instance. * @param desc * desc. * @return Class[] class array. * @throws ClassNotFoundException */ private static Class<?>[] desc2classArray(ClassLoader cl, String desc) throws ClassNotFoundException { if (desc.length() == 0) { return EMPTY_CLASS_ARRAY; } List<Class<?>> cs = new ArrayList<>(); Matcher m = f0.matcher(desc); while (m.find()) { cs.add(desc2class(cl, m.group())); } return cs.toArray(EMPTY_CLASS_ARRAY);}
3.26
dubbo_ReflectUtils_findMethodByMethodSignature_rdh
/** * Find method from method signature * * @param clazz * Target class to find method * @param methodName * Method signature, e.g.: method1(int, String). It is allowed to provide method name only, e.g.: method2 * @return target method * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws IllegalStateException * when multiple methods are found (overridden method when parameter info is not provided) * @deprecated Recommend {@link MethodUtils#findMethod(Class, String, Class[])} */ @Deprecatedpublic static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { Method method; if (parameterTypes == null) { List<Method> finded = new ArrayList<>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException((("No such method " + methodName) + " in class ") + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); }method = clazz.getMethod(methodName, types); } return method; }
3.26
dubbo_ReflectUtils_getName_rdh
/** * get method name. * "void do(int)", "void do()", "int do(java.lang.String,boolean)" * * @param m * method. * @return name. */ public static String getName(final Method m) { StringBuilder ret = new StringBuilder(); ret.append(m0(m.getReturnType())).append(' '); ret.append(m.getName()).append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) {ret.append(','); } ret.append(m0(parameterTypes[i])); } ret.append(')'); return ret.toString(); }
3.26
dubbo_AbstractConfigurator_isV27ConditionMatchOrUnset_rdh
/** * Check if v2.7 configurator rule is set and can be matched. * * @param url * the configurator rule url * @return true if v2.7 configurator rule is not set or the rule can be matched. */ private boolean isV27ConditionMatchOrUnset(URL url) { String providers = configuratorUrl.getParameter(OVERRIDE_PROVIDERS_KEY); if (StringUtils.isNotEmpty(providers)) { boolean match = false; String[] providerAddresses = providers.split(CommonConstants.COMMA_SEPARATOR); for (String address : providerAddresses) { if ((((address.equals(url.getAddress()) || address.equals(ANYHOST_VALUE)) || address.equals((ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR) + ANY_VALUE)) || address.equals((ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR) + url.getPort())) || address.equals(url.getHost())) { match = true; } } if (!match) { logger.debug((("Cannot apply configurator rule, provider address mismatch, current address " + url.getAddress()) + ", address in rule is ") + providers); return false; } } String configApplication = configuratorUrl.getApplication(configuratorUrl.getUsername()); String currentApplication = url.getApplication(url.getUsername()); if (((configApplication != null) && (!ANY_VALUE.equals(configApplication))) && (!configApplication.equals(currentApplication))) { logger.debug((("Cannot apply configurator rule, application name mismatch, current application is " + currentApplication) + ", application in rule is ") + configApplication); return false; } String configServiceKey = configuratorUrl.getServiceKey(); String currentServiceKey = url.getServiceKey(); if ((!ANY_VALUE.equals(configServiceKey)) && (!configServiceKey.equals(currentServiceKey))) { logger.debug((("Cannot apply configurator rule, service mismatch, current service is " + currentServiceKey) + ", service in rule is ") + configServiceKey); return false; }return true; }
3.26
dubbo_DefaultApplicationDeployer_start_rdh
/** * Start the bootstrap * * @return */ @Overridepublic Future start() { synchronized(startLock) {if ((isStopping() || isStopped()) || isFailed()) { throw new IllegalStateException(getIdentifier() + " is stopping or stopped, can not start again"); } try { // maybe call start again after add new module, check if any new module boolean hasPendingModule = hasPendingModule(); if (isStarting()) { // currently, is starting, maybe both start by module and application // if it has new modules, start them if (hasPendingModule) { startModules(); } // if it is starting, reuse previous startFuture return startFuture; } // if is started and no new module, just return if (isStarted() && (!hasPendingModule)) { return CompletableFuture.completedFuture(false); }// pending -> starting : first start app // started -> starting : re-start app onStarting(); initialize(); doStart(); } catch (Throwable e) { m2(getIdentifier() + " start failure", e); throw e; }
3.26
dubbo_DefaultApplicationDeployer_supportsExtension_rdh
/** * Supports the extension with the specified class and name * * @param extensionClass * the {@link Class} of extension * @param name * the name of extension * @return if supports, return <code>true</code>, or <code>false</code> * @since 2.7.8 */ private boolean supportsExtension(Class<?> extensionClass, String name) { if (isNotEmpty(name)) { ExtensionLoader<?> extensionLoader = getExtensionLoader(extensionClass); return extensionLoader.hasExtension(name); } return false; }
3.26
dubbo_DefaultApplicationDeployer_isRegisterConsumerInstance_rdh
/** * Close registration of instance for pure Consumer process by setting registerConsumer to 'false' * by default is true. */ private boolean isRegisterConsumerInstance() { Boolean registerConsumer = getApplication().getRegisterConsumer(); if (registerConsumer == null) { return true; } return Boolean.TRUE.equals(registerConsumer); }
3.26
dubbo_DefaultApplicationDeployer_useRegistryAsConfigCenterIfNecessary_rdh
/** * For compatibility purpose, use registry as the default config center when * there's no config center specified explicitly and * useAsConfigCenter of registryConfig is null or true */ private void useRegistryAsConfigCenterIfNecessary() { // we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated. if (environment.getDynamicConfiguration().isPresent()) { return;} if (CollectionUtils.isNotEmpty(configManager.getConfigCenters())) { return; } // load registry configManager.loadConfigsOfTypeFromProps(RegistryConfig.class); List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries(); if (defaultRegistries.size() > 0) { defaultRegistries.stream().filter(this::isUsedRegistryAsConfigCenter).map(this::registryAsConfigCenter).forEach(configCenter -> { if (configManager.getConfigCenter(configCenter.getId()).isPresent()) { return; } configManager.addConfigCenter(configCenter); logger.info("use registry as config-center: " + configCenter); });} }
3.26
dubbo_DefaultApplicationDeployer_getDynamicConfiguration_rdh
/** * Get the instance of {@link DynamicConfiguration} by the specified connection {@link URL} of config-center * * @param connectionURL * of config-center * @return non-null * @since 2.7.5 */ private DynamicConfiguration getDynamicConfiguration(URL connectionURL) { String protocol = connectionURL.getProtocol(); DynamicConfigurationFactory factory = ConfigurationUtils.getDynamicConfigurationFactory(applicationModel, protocol); return factory.getDynamicConfiguration(connectionURL); }
3.26
dubbo_DefaultApplicationDeployer_isUsedRegistryAsCenter_rdh
/** * Is used the specified registry as a center infrastructure * * @param registryConfig * the {@link RegistryConfig} * @param usedRegistryAsCenter * the configured value on * @param centerType * the type name of center * @param extensionClass * an extension class of a center infrastructure * @return * @since 2.7.8 */ private boolean isUsedRegistryAsCenter(RegistryConfig registryConfig, Supplier<Boolean> usedRegistryAsCenter, String centerType, Class<?> extensionClass) { final boolean supported; Boolean configuredValue = usedRegistryAsCenter.get(); if (configuredValue != null) { // If configured, take its value. supported = configuredValue.booleanValue(); } else { // Or check the extension existence String protocol = registryConfig.getProtocol(); supported = supportsExtension(extensionClass, protocol);if (logger.isInfoEnabled()) { logger.info(format("No value is configured in the registry, the %s extension[name : %s] %s as the %s center", extensionClass.getSimpleName(), protocol, supported ? "supports" : "does not support", centerType)); } } if (logger.isInfoEnabled()) { logger.info(format("The registry[%s] will be %s as the %s center", registryConfig, supported ? "used" : "not used", centerType)); } return supported; }
3.26
dubbo_AbstractDynamicConfiguration_getGroup_rdh
/** * Get the group from {@link URL the specified connection URL} * * @param url * {@link URL the specified connection URL} * @return non-null * @since 2.7.8 */ protected static String getGroup(URL url) { String group = getParameter(url, GROUP_PARAM_NAME, null); return StringUtils.isBlank(group) ? getParameter(url, GROUP_KEY, DEFAULT_GROUP) : group; } /** * Get the timeout from {@link URL the specified connection URL} * * @param url * {@link URL the specified connection URL}
3.26
dubbo_AbstractDynamicConfiguration_m0_rdh
/** * Executes the {@link Callable} with the specified timeout * * @param task * the {@link Callable task} * @param timeout * timeout in milliseconds * @param <V> * the type of computing result * @return the computing result */ protected final <V> V m0(Callable<V> task, long timeout) { V value = null; try { if (timeout < 1) { // less or equal 0 value = task.call(); } else { Future<V> future = workersThreadPool.submit(task); value = future.get(timeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } return value; }
3.26
dubbo_AbstractDynamicConfiguration_getDefaultTimeout_rdh
/** * * @return the default timeout * @since 2.7.8 */@Override public long getDefaultTimeout() {return getTimeout(); }
3.26
dubbo_AbstractDynamicConfiguration_execute_rdh
/** * Executes the {@link Runnable} with the specified timeout * * @param task * the {@link Runnable task} * @param timeout * timeout in milliseconds */protected final void execute(Runnable task, long timeout) { m0(() -> { task.run(); return null; }, timeout); }
3.26
dubbo_AbstractDynamicConfiguration_getDefaultGroup_rdh
/** * * @return the default group * @since 2.7.8 */@Override public String getDefaultGroup() { return getGroup(); }
3.26
dubbo_RpcStatus_getStatus_rdh
/** * * @param url * @param methodName * @return status */ public static RpcStatus getStatus(URL url, String methodName) { String uri = url.toIdentityString(); ConcurrentMap<String, RpcStatus> map = ConcurrentHashMapUtils.computeIfAbsent(METHOD_STATISTICS, uri, k -> new ConcurrentHashMap<>()); return ConcurrentHashMapUtils.computeIfAbsent(map, methodName, k -> new RpcStatus()); }
3.26
dubbo_RpcStatus_getTotalElapsed_rdh
/** * get total elapsed. * * @return total elapsed */public long getTotalElapsed() { return totalElapsed.get(); }
3.26
dubbo_RpcStatus_removeStatus_rdh
/** * * @param url */ public static void removeStatus(URL url, String methodName) { String uri = url.toIdentityString(); ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri); if (map != null) { map.remove(methodName);} }
3.26
dubbo_RpcStatus_getFailed_rdh
/** * get failed. * * @return failed */ public int getFailed() { return failed.get(); }
3.26
dubbo_RpcStatus_get_rdh
/** * get value. * * @param key * @return value */ public Object get(String key) { return values.get(key); }
3.26
dubbo_RpcStatus_getSucceededAverageElapsed_rdh
/** * get succeeded average elapsed. * * @return succeeded average elapsed */ public long getSucceededAverageElapsed() { long succeeded = getSucceeded(); if (succeeded == 0) { return 0; } return getSucceededElapsed() / succeeded; }
3.26
dubbo_RpcStatus_getFailedMaxElapsed_rdh
/** * get failed max elapsed. * * @return failed max elapsed */ public long getFailedMaxElapsed() { return failedMaxElapsed.get(); }
3.26
dubbo_RpcStatus_m0_rdh
/** * * @param url * @param elapsed * @param succeeded */ public static void m0(URL url, String methodName, long elapsed, boolean succeeded) { endCount(getStatus(url), elapsed, succeeded); endCount(getStatus(url, methodName), elapsed, succeeded); }
3.26
dubbo_RpcStatus_getSucceededMaxElapsed_rdh
/** * get succeeded max elapsed. * * @return succeeded max elapsed. */ public long getSucceededMaxElapsed() { return succeededMaxElapsed.get(); }
3.26
dubbo_RpcStatus_getSucceeded_rdh
/** * get succeeded. * * @return succeeded */public long getSucceeded() { return getTotal() - getFailed(); }
3.26
dubbo_RpcStatus_m1_rdh
/** * Calculate average TPS (Transaction per second). * * @return tps */ public long m1() { if (getTotalElapsed() >= 1000L) { return getTotal() / (getTotalElapsed() / 1000L); } return getTotal();}
3.26
dubbo_RpcStatus_getFailedAverageElapsed_rdh
/** * get failed average elapsed. * * @return failed average elapsed */ public long getFailedAverageElapsed() { long failed = getFailed(); if (failed == 0) { return 0; } return getFailedElapsed() / failed; }
3.26
dubbo_LruCache_get_rdh
/** * API to return stored value using a key against the calling thread specific store. * * @param key * Unique identifier for cache lookup * @return Return stored object against key */ @Override public Object get(Object key) { return store.get(key); }
3.26
dubbo_LruCache_put_rdh
/** * API to store value against a key in the calling thread scope. * * @param key * Unique identifier for the object being store. * @param value * Value getting store */@Override public void put(Object key, Object value) { store.put(key, value); }
3.26
dubbo_NetUtils_isValidAddress_rdh
/** * Tells whether the address to test is an invalid address. * * @implNote Pattern matching only. * @param address * address to test * @return true if invalid */ public static boolean isValidAddress(String address) { return ADDRESS_PATTERN.matcher(address).matches(); }
3.26
dubbo_NetUtils_m1_rdh
/** * Tells whether the port to test is an invalid port. * * @implNote Numeric comparison only. * @param port * port to test * @return true if invalid */public static boolean m1(int port) { return (port < MIN_PORT) || (port > MAX_PORT); }
3.26
dubbo_NetUtils_findNetworkInterface_rdh
/** * Get the suitable {@link NetworkInterface} * * @return If no {@link NetworkInterface} is available , return <code>null</code> * @since 2.7.6 */ public static NetworkInterface findNetworkInterface() { List<NetworkInterface> validNetworkInterfaces = emptyList(); try { validNetworkInterfaces = getValidNetworkInterfaces(); } catch (Throwable e) { logger.warn(e); } NetworkInterface result = null; // Try to find the preferred one for (NetworkInterface networkInterface : validNetworkInterfaces) { if (isPreferredNetworkInterface(networkInterface)) { result = networkInterface; break; } } if (result == null) { // If not found, try to get the first one for (NetworkInterface networkInterface : validNetworkInterfaces) {Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { Optional<InetAddress> addressOp = m2(addresses.nextElement()); if (addressOp.isPresent()) { try { if (addressOp.get().isReachable(100)) { return networkInterface; } } catch (IOException e) { // ignore } } } } } if (result == null) { result = first(validNetworkInterfaces); } return result; }
3.26
dubbo_NetUtils_getValidNetworkInterfaces_rdh
/** * Get the valid {@link NetworkInterface network interfaces} * * @return the valid {@link NetworkInterface}s * @throws SocketException * SocketException if an I/O error occurs. * @since 2.7.6 */ private static List<NetworkInterface> getValidNetworkInterfaces() throws SocketException { List<NetworkInterface> validNetworkInterfaces = new LinkedList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (ignoreNetworkInterface(networkInterface)) { // ignore continue; } validNetworkInterfaces.add(networkInterface); } return validNetworkInterfaces; } /** * Is preferred {@link NetworkInterface} or not * * @param networkInterface * {@link NetworkInterface} * @return if the name of the specified {@link NetworkInterface} matches the property value from {@link CommonConstants#DUBBO_PREFERRED_NETWORK_INTERFACE}
3.26
dubbo_NetUtils_getLocalAddress_rdh
/** * Find first valid IP from local network card * * @return first valid local IP */ public static InetAddress getLocalAddress() { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getLocalAddress0(); LOCAL_ADDRESS = localAddress; return localAddress; }
3.26
dubbo_NetUtils_matchIpRange_rdh
/** * * @param pattern * @param host * @param port * @return * @throws UnknownHostException */ public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException { if ((pattern == null) || (host == null)) {throw new IllegalArgumentException((("Illegal Argument pattern or hostName. Pattern:" + pattern) + ", Host:") + host); } pattern = pattern.trim(); if ("*.*.*.*".equals(pattern) || "*".equals(pattern)) { return true; } InetAddress inetAddress = InetAddress.getByName(host); boolean isIpv4 = isValidV4Address(inetAddress); String[] hostAndPort = getPatternHostAndPort(pattern, isIpv4); if ((hostAndPort[1] != null) && (!hostAndPort[1].equals(String.valueOf(port)))) { return false; } pattern = hostAndPort[0]; String splitCharacter = SPLIT_IPV4_CHARACTER; if (!isIpv4) { splitCharacter = SPLIT_IPV6_CHARACTER;} String[] v61 = pattern.split(splitCharacter); // check format of pattern checkHostPattern(pattern, v61, isIpv4); host = inetAddress.getHostAddress(); if (pattern.equals(host)) { return true; } // short name condition if (!ipPatternContainExpression(pattern)) { InetAddress patternAddress = InetAddress.getByName(pattern); return patternAddress.getHostAddress().equals(host); } String[] ipAddress = host.split(splitCharacter); for (int i = 0; i < v61.length; i++) { if ("*".equals(v61[i]) || v61[i].equals(ipAddress[i])) { continue; } else if (v61[i].contains("-")) { String[] rangeNumStrs = StringUtils.split(v61[i], '-'); if (rangeNumStrs.length != 2) {throw new IllegalArgumentException("There is wrong format of ip Address: " + v61[i]); } Integer min = getNumOfIpSegment(rangeNumStrs[0], isIpv4); Integer max = getNumOfIpSegment(rangeNumStrs[1], isIpv4); Integer ip = getNumOfIpSegment(ipAddress[i], isIpv4); if ((ip < min) || (ip > max)) { return false; } } else if ("0".equals(ipAddress[i]) && ((("0".equals(v61[i]) || "00".equals(v61[i])) || "000".equals(v61[i])) || "0000".equals(v61[i]))) { continue; } else if (!v61[i].equals(ipAddress[i])) { return false; } } return true;}
3.26
dubbo_NetUtils_getIpByHost_rdh
/** * * @param hostName * @return ip address or hostName if UnknownHostException */ public static String getIpByHost(String hostName) { try { return InetAddress.getByName(hostName).getHostAddress(); } catch (UnknownHostException e) { return hostName; } }
3.26
dubbo_NetUtils_isPortInUsed_rdh
/** * Check the port whether is in use in os * * @param port * port to check * @return true if it's occupied */ public static boolean isPortInUsed(int port) { try (ServerSocket ignored = new ServerSocket(port)) { return false;} catch (IOException e) { // continue } return true; }
3.26
dubbo_NetUtils_isPreferIPV6Address_rdh
/** * Check if an ipv6 address * * @return true if it is reachable */ static boolean isPreferIPV6Address() { return Boolean.getBoolean("java.net.preferIPv6Addresses"); }/** * normalize the ipv6 Address, convert scope name to scope id. * e.g. * convert * fe80:0:0:0:894:aeec:f37d:23e1%en0 * to * fe80:0:0:0:894:aeec:f37d:23e1%5 * <p> * The %5 after ipv6 address is called scope id. * see java doc of {@link Inet6Address}
3.26
dubbo_NetUtils_isMulticastAddress_rdh
/** * is multicast address or not * * @param host * ipv4 address * @return {@code true} if is multicast address */ public static boolean isMulticastAddress(String host) { int i = host.indexOf('.'); if (i > 0) { String prefix = host.substring(0, i); if (StringUtils.isNumber(prefix)) { int p = Integer.parseInt(prefix); return (p >= 224) && (p <= 239); } } return false; }
3.26
dubbo_FileCacheStoreFactory_getCacheMap_rdh
/** * for unit test only */ @Deprecated static Map<String, FileCacheStore> getCacheMap() { return f0; }
3.26
dubbo_PermissionLevel_from_rdh
// find the permission level by the level value, if not found, return default PUBLIC level public static PermissionLevel from(String permissionLevel) { if (StringUtils.isNumber(permissionLevel)) { return Arrays.stream(values()).filter(p -> String.valueOf(p.getLevel()).equals(permissionLevel.trim())).findFirst().orElse(PUBLIC); } return Arrays.stream(values()).filter(p -> p.name().equalsIgnoreCase(String.valueOf(permissionLevel).trim())).findFirst().orElse(PUBLIC); }
3.26
dubbo_ApplicationConfig_getQosEnableCompatible_rdh
/** * The format is the same as the springboot, including: getQosEnableCompatible(), getQosPortCompatible(), getQosAcceptForeignIpCompatible(). * * @return */ @Parameter(key = QOS_ENABLE_COMPATIBLE, excluded = true, attribute = false) public Boolean getQosEnableCompatible() { return getQosEnable(); }
3.26
dubbo_BeanRegistrar_hasAlias_rdh
/** * Detect the alias is present or not in the given bean name from {@link AliasRegistry} * * @param registry * {@link AliasRegistry} * @param beanName * the bean name * @param alias * alias to test * @return if present, return <code>true</code>, or <code>false</code> */ public static boolean hasAlias(AliasRegistry registry, String beanName, String alias) { return (hasText(beanName) && hasText(alias)) && containsElement(registry.getAliases(beanName), alias); }
3.26
dubbo_NacosConnectionManager_createNamingService_rdh
/** * Create an instance of {@link NamingService} from specified {@link URL connection url} * * @return {@link NamingService} */ protected NamingService createNamingService() { Properties nacosProperties = buildNacosProperties(this.connectionURL); NamingService namingService = null; try { for (int i = 0; i < (retryTimes + 1); i++) { namingService = NacosFactory.createNamingService(nacosProperties); String serverStatus = namingService.getServerStatus(); boolean namingServiceAvailable = testNamingService(namingService); if ((!check) || (UP.equals(serverStatus) && namingServiceAvailable)) { break; } else { logger.warn(LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", (((((((("Failed to connect to nacos naming server. " + "Server status: ") + serverStatus) + ". ") + "Naming Service Available: ") + namingServiceAvailable) + ". ") + (i < retryTimes ? ("Dubbo will try to retry in " + sleepMsBetweenRetries) + ". " : "Exceed retry max times.")) + "Try times: ") + (i + 1)); } namingService.shutDown(); namingService = null; Thread.sleep(sleepMsBetweenRetries); } } catch (NacosException e) { if (logger.isErrorEnabled()) { logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getErrMsg(), e); } } catch (InterruptedException e) { logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos naming service client.", e); Thread.currentThread().interrupt(); throw new IllegalStateException(e); } if (namingService == null) { logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to create nacos naming service client. Reason: server status check failed."); throw new IllegalStateException("Failed to create nacos naming service client. Reason: server status check failed."); } return namingService; }
3.26
dubbo_AbstractInvoker_getCallbackExecutor_rdh
// -- Protected api protected ExecutorService getCallbackExecutor(URL url, Invocation inv) { if (InvokeMode.SYNC == RpcUtils.getInvokeMode(getUrl(), inv)) { return new ThreadlessExecutor(); } return ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()).getExecutor(url); }
3.26
dubbo_AbstractInvoker_attachInvocationSerializationId_rdh
/** * Attach Invocation Serialization id * <p> * <ol> * <li>Obtain the value from <code>prefer_serialization</code></li> * <li>If the preceding information is not obtained, obtain the value from <code>serialization</code></li> * <li>If neither is obtained, use the default value</li> * </ol> * </p> * * @param inv * inv */ private void attachInvocationSerializationId(RpcInvocation inv) { Byte serializationId = UrlUtils.serializationId(getUrl()); if (serializationId != null) { inv.put(SERIALIZATION_ID_KEY, serializationId); } }
3.26
dubbo_AbstractInvoker_getInterface_rdh
// -- Public api @Override public Class<T> getInterface() { return type; }
3.26
dubbo_DubboComponentScanRegistrar_registerServiceAnnotationPostProcessor_rdh
/** * Registers {@link ServiceAnnotationPostProcessor} * * @param packagesToScan * packages to scan without resolving placeholders * @param registry * {@link BeanDefinitionRegistry} * @since 2.5.8 */ private void registerServiceAnnotationPostProcessor(Set<String> packagesToScan, BeanDefinitionRegistry registry) { BeanDefinitionBuilder builder = rootBeanDefinition(ServiceAnnotationPostProcessor.class); builder.addConstructorArgValue(packagesToScan);builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);}
3.26
dubbo_AbstractDubboConfigBinder_getPropertySources_rdh
/** * Get multiple {@link PropertySource propertySources} * * @return multiple {@link PropertySource propertySources} */ protected Iterable<PropertySource<?>> getPropertySources() { return f0; }
3.26
dubbo_LazyConnectExchangeClient_warning_rdh
/** * If {@link Constants.LAZY_REQUEST_WITH_WARNING_KEY} is configured, then warn once every 5000 invocations. */ private void warning() { if (requestWithWarning) { if ((f0.get() % warningPeriod) == 0) { logger.warn(PROTOCOL_FAILED_REQUEST, "", "", ((url.getAddress() + " ") + url.getServiceKey()) + " safe guard client , should not be called ,must have a bug."); } f0.incrementAndGet();} }
3.26
dubbo_ResteasyContext_getExtension_rdh
/** * return extensions that are filtered by extension type * * @param extension * @param <T> * @return */ default <T> List<T> getExtension(ServiceDeployer serviceDeployer, Class<T> extension) { return serviceDeployer.getExtensions(extension); }
3.26
dubbo_ServiceModel_getServiceConfig_rdh
/** * ServiceModel should be decoupled from AbstractInterfaceConfig and removed in a future version * * @return */ @Deprecated public ServiceConfigBase<?> getServiceConfig() { if (config == null) { return null; } if (config instanceof ServiceConfigBase) { return ((ServiceConfigBase<?>) (config)); } else { throw new IllegalArgumentException("Current ServiceModel is not a ProviderModel"); } }
3.26
dubbo_ServiceModel_getServiceMetadata_rdh
/** * * @return serviceMetadata */ public ServiceMetadata getServiceMetadata() { return serviceMetadata; }
3.26
dubbo_ServiceModel_getReferenceConfig_rdh
/** * ServiceModel should be decoupled from AbstractInterfaceConfig and removed in a future version * * @return */ @Deprecated public ReferenceConfigBase<?> getReferenceConfig() { if (config == null) { return null; } if (config instanceof ReferenceConfigBase) { return ((ReferenceConfigBase<?>) (config)); } else { throw new IllegalArgumentException("Current ServiceModel is not a ConsumerModel"); } }
3.26
dubbo_ZookeeperRegistry_fetchLatestAddresses_rdh
/** * When zookeeper connection recovered from a connection loss, it needs to fetch the latest provider list. * re-register watcher is only a side effect and is not mandate. */private void fetchLatestAddresses() { // subscribe Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed()); if (!recoverSubscribed.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Fetching the latest urls of " + recoverSubscribed.keySet()); } for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { removeFailedSubscribed(url, listener); addFailedSubscribed(url, listener); } } } }
3.26
dubbo_AbstractDependencyFilterMojo_getFilters_rdh
/** * Return artifact filters configured for this MOJO. * * @param additionalFilters * optional additional filters to apply * @return the filters */ private FilterArtifacts getFilters(ArtifactsFilter... additionalFilters) { FilterArtifacts filters = new FilterArtifacts(); for (ArtifactsFilter additionalFilter : additionalFilters) { filters.addFilter(additionalFilter); }filters.addFilter(new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); if ((this.includes != null) && (!this.includes.isEmpty())) {filters.addFilter(new IncludeFilter(this.includes)); } if ((this.excludes != null) && (!this.excludes.isEmpty())) { filters.addFilter(new ExcludeFilter(this.excludes)); } return filters; }
3.26
dubbo_MonitorFilter_getConcurrent_rdh
/** * concurrent counter * * @param invoker * @param invocation * @return */ private AtomicInteger getConcurrent(Invoker<?> invoker, Invocation invocation) {String key = (invoker.getInterface().getName() + ".") + RpcUtils.getMethodName(invocation); return ConcurrentHashMapUtils.computeIfAbsent(concurrents, key, k -> new AtomicInteger()); }
3.26
dubbo_MonitorFilter_invoke_rdh
/** * The invocation interceptor,it will collect the invoke data about this invocation and send it to monitor center * * @param invoker * service * @param invocation * invocation. * @return {@link Result} the invoke result * @throws RpcException */ @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (invoker.getUrl().hasAttribute(MONITOR_KEY)) { invocation.put(MONITOR_FILTER_START_TIME, System.currentTimeMillis());invocation.put(MONITOR_REMOTE_HOST_STORE, RpcContext.getServiceContext().getRemoteHost()); // count up getConcurrent(invoker, invocation).incrementAndGet(); } ServiceModel serviceModel = invoker.getUrl().getServiceModel(); if (serviceModel instanceof ProviderModel) { ((ProviderModel) (serviceModel)).updateLastInvokeTime(); } // proceed invocation chain return invoker.invoke(invocation); }
3.26
dubbo_MonitorFilter_collect_rdh
/** * The collector logic, it will be handled by the default monitor * * @param invoker * @param invocation * @param result * the invocation result * @param remoteHost * the remote host address * @param start * the timestamp the invocation begin * @param error * if there is an error on the invocation */ private void collect(Invoker<?> invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { try { Object monitorUrl; monitorUrl = invoker.getUrl().getAttribute(MONITOR_KEY); if (monitorUrl instanceof URL) { Monitor monitor = monitorFactory.getMonitor(((URL) (monitorUrl))); if (monitor == null) { return; } URL statisticsUrl = createStatisticsUrl(invoker, invocation, result, remoteHost, start, error); monitor.collect(statisticsUrl.toSerializableURL()); } } catch (Throwable t) { logger.warn(COMMON_MONITOR_EXCEPTION, "", "", (("Failed to monitor count service " + invoker.getUrl()) + ", cause: ") + t.getMessage(), t); } }
3.26
dubbo_LockUtils_getSingletonMutex_rdh
/** * Get the mutex to lock the singleton in the specified {@link ApplicationContext} */ public static synchronized Object getSingletonMutex(ApplicationContext applicationContext) {DefaultSingletonBeanRegistry autowireCapableBeanFactory = ((DefaultSingletonBeanRegistry) (applicationContext.getAutowireCapableBeanFactory())); try { return autowireCapableBeanFactory.getSingletonMutex(); } catch (Throwable t1) { try { // try protected Method method = DefaultSingletonBeanRegistry.class.getDeclaredMethod("getSingletonMutex"); method.setAccessible(true); return method.invoke(autowireCapableBeanFactory); } catch (Throwable t2) { // Before Spring 4.2, there is no getSingletonMutex method if (!autowireCapableBeanFactory.containsSingleton(DUBBO_SINGLETON_MUTEX_KEY)) { autowireCapableBeanFactory.registerSingleton(DUBBO_SINGLETON_MUTEX_KEY, new Object()); } return autowireCapableBeanFactory.getSingleton(DUBBO_SINGLETON_MUTEX_KEY); } } }
3.26
dubbo_ProviderConfig_getExportBackground_rdh
/** * * @deprecated replace with {@link ModuleConfig#getBackground()} * @see ModuleConfig#getBackground() */ @Deprecated @Parameter(key = EXPORT_BACKGROUND_KEY, excluded = true) public Boolean getExportBackground() { return exportBackground;} /** * Whether export should run in background or not. * * @deprecated replace with {@link ModuleConfig#setBackground(Boolean)}
3.26
dubbo_DefaultFilterChainBuilder_buildClusterInvokerChain_rdh
/** * build consumer cluster filter chain */ @Override public <T> ClusterInvoker<T> buildClusterInvokerChain(final ClusterInvoker<T> originalInvoker, String key, String group) { ClusterInvoker<T> last = originalInvoker; URL url = originalInvoker.getUrl(); List<ModuleModel> moduleModels = getModuleModelsFromUrl(url); List<ClusterFilter> filters; if ((moduleModels != null) && (moduleModels.size() == 1)) { filters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModels.get(0)).getActivateExtension(url, key, group); } else if ((moduleModels != null) && (moduleModels.size() > 1)) { filters = new ArrayList<>(); List<ExtensionDirector> directors = new ArrayList<>(); for (ModuleModel moduleModel : moduleModels) { List<ClusterFilter> tempFilters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModel).getActivateExtension(url, key, group); filters.addAll(tempFilters); directors.add(moduleModel.getExtensionDirector()); } filters = sortingAndDeduplication(filters, directors); } else { filters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, null).getActivateExtension(url, key, group); } if (!CollectionUtils.isEmpty(filters)) { for (int i = filters.size() - 1; i >= 0; i--) { final ClusterFilter filter = filters.get(i); final Invoker<T> next = last; last = new CopyOfClusterFilterChainNode<>(originalInvoker, next, filter); } return new ClusterCallbackRegistrationInvoker<>(originalInvoker, last, filters); } return last; }
3.26
dubbo_DefaultFilterChainBuilder_getModuleModelsFromUrl_rdh
/** * When the application-level service registration and discovery strategy is adopted, the URL will be of type InstanceAddressURL, * and InstanceAddressURL belongs to the application layer and holds the ApplicationModel, * but the filter is at the module layer and holds the ModuleModel, * so it needs to be based on the url in the ScopeModel type to parse out all the moduleModels held by the url * to obtain the filter configuration. * * @param url * URL * @return All ModuleModels in the url */ private List<ModuleModel> getModuleModelsFromUrl(URL url) { List<ModuleModel> moduleModels = null; ScopeModel scopeModel = url.getScopeModel(); if (scopeModel instanceof ApplicationModel) { moduleModels = ((ApplicationModel) (scopeModel)).getPubModuleModels();} else if (scopeModel instanceof ModuleModel) { moduleModels = new ArrayList<>(); moduleModels.add(((ModuleModel) (scopeModel))); } return moduleModels; }
3.26
dubbo_ServiceDiscoveryFactory_getExtension_rdh
/** * Get the extension instance of {@link ServiceDiscoveryFactory} by {@link URL#getProtocol() the protocol} * * @param registryURL * the {@link URL} to connect the registry * @return non-null */ static ServiceDiscoveryFactory getExtension(URL registryURL) { String protocol = registryURL.getProtocol(); ExtensionLoader<ServiceDiscoveryFactory> loader = registryURL.getOrDefaultApplicationModel().getExtensionLoader(ServiceDiscoveryFactory.class); return loader.getOrDefaultExtension(protocol); }
3.26
dubbo_AbstractStateRouter_setNextRouter_rdh
/** * Next Router node state is maintained by AbstractStateRouter and this method is not allow to override. * If a specified router wants to control the behaviour of continue route or not, * please override {@link AbstractStateRouter#supportContinueRoute()} */ @Override public final void setNextRouter(StateRouter<T> nextRouter) { this.nextRouter = nextRouter; }
3.26
dubbo_AbstractStateRouter_continueRoute_rdh
/** * Call next router to get result * * @param invokers * current router filtered invokers */protected final BitList<Invoker<T>> continueRoute(BitList<Invoker<T>> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder<RouterSnapshotNode<T>> nodeHolder) { if (nextRouter != null) { return nextRouter.route(invokers, url, invocation, needToPrintMessage, nodeHolder); } else { return invokers; } }
3.26
dubbo_AbstractStateRouter_supportContinueRoute_rdh
/** * Whether current router's implementation support call * {@link AbstractStateRouter#continueRoute(BitList, URL, Invocation, boolean, Holder)} * by router itself. * * @return support or not */ protected boolean supportContinueRoute() { return false; }
3.26
dubbo_JsonUtils_setJson_rdh
/** * * @deprecated for uts only */ @Deprecated protected static void setJson(JSON json) { JsonUtils.json = json; }
3.26
dubbo_MulticastRegistry_m0_rdh
/** * Remove the expired providers(if clean is true), leave the multicast group and close the multicast socket. */ @Override public void m0() { super.destroy(); try { ExecutorUtil.cancelScheduledFuture(cleanFuture); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } try { multicastSocket.leaveGroup(multicastAddress); multicastSocket.close(); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } ExecutorUtil.gracefulShutdown(cleanExecutor, cleanPeriod); }
3.26
dubbo_MulticastRegistry_clean_rdh
/** * Remove the expired providers, only when "clean" parameter is true. */ private void clean() { if (admin) { for (Set<URL> providers : new HashSet<Set<URL>>(received.values())) { for (URL url : new HashSet<URL>(providers)) { if (isExpired(url)) { if (logger.isWarnEnabled()) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", "Clean expired provider " + url); } doUnregister(url); } } } } }
3.26
dubbo_RequestEvent_toRequestErrorEvent_rdh
/** * Acts on MetricsClusterFilter to monitor exceptions that occur before request execution */ public static RequestEvent toRequestErrorEvent(ApplicationModel applicationModel, String appName, MetricsDispatcher metricsDispatcher, Invocation invocation, String side, int code, boolean serviceLevel) { RequestEvent event = new RequestEvent(applicationModel, appName, metricsDispatcher, null, REQUEST_ERROR_EVENT); event.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); event.putAttachment(MetricsConstants.INVOCATION_SIDE, side); event.putAttachment(MetricsConstants.INVOCATION, invocation); event.putAttachment(MetricsConstants.INVOCATION_REQUEST_ERROR, code); event.putAttachment(MetricsConstants.METHOD_METRICS, new MethodMetric(applicationModel, invocation, serviceLevel)); return event; }
3.26
dubbo_CollectionUtils_isEmpty_rdh
/** * Return {@code true} if the supplied Collection is {@code null} or empty. * Otherwise, return {@code false}. * * @param collection * the Collection to check * @return whether the given Collection is empty */public static boolean isEmpty(Collection<?> collection) { return (collection == null) || collection.isEmpty(); }
3.26
dubbo_CollectionUtils_isNotEmptyMap_rdh
/** * Return {@code true} if the supplied Map is {@code not null} or not empty. * Otherwise, return {@code false}. * * @param map * the Map to check * @return whether the given Map is not empty */ public static boolean isNotEmptyMap(Map map) { return !isEmptyMap(map); }
3.26
dubbo_CollectionUtils_equals_rdh
/** * Compares the specified collection with another, the main implementation references * {@link AbstractSet} * * @param one * {@link Collection} * @param another * {@link Collection} * @return if equals, return <code>true</code>, or <code>false</code> * @since 2.7.6 */ public static boolean equals(Collection<?> one, Collection<?> another) { if (one == another) { return true; } if (isEmpty(one) && isEmpty(another)) { return true;} if (size(one) != size(another)) { return false; } try { return one.containsAll(another); } catch (ClassCastException | NullPointerException unused) { return false; } }
3.26
dubbo_CollectionUtils_ofSet_rdh
/** * Convert to multiple values to be {@link LinkedHashSet} * * @param values * one or more values * @param <T> * the type of <code>values</code> * @return read-only {@link Set} */ public static <T> Set<T> ofSet(T... values) { int size = (values == null) ? 0 : values.length; if (size < 1) { return emptySet(); } float loadFactor = 1.0F / ((size + 1) * 1.0F); if (loadFactor > 0.75F) { loadFactor = 0.75F; } Set<T> elements = new LinkedHashSet<>(size, loadFactor); for (int i = 0; i < size; i++) { elements.add(values[i]); } return unmodifiableSet(elements); }
3.26
dubbo_CollectionUtils_isNotEmpty_rdh
/** * Return {@code true} if the supplied Collection is {@code not null} or not empty. * Otherwise, return {@code false}. * * @param collection * the Collection to check * @return whether the given Collection is not empty */ public static boolean isNotEmpty(Collection<?> collection) { return !isEmpty(collection); }
3.26
dubbo_CollectionUtils_size_rdh
/** * Get the size of the specified {@link Collection} * * @param collection * the specified {@link Collection} * @return must be positive number * @since 2.7.6 */ public static int size(Collection<?> collection) { return collection == null ? 0 : collection.size(); }
3.26
dubbo_CollectionUtils_flip_rdh
/** * Flip the specified {@link Map} * * @param map * The specified {@link Map},Its value must be unique * @param <K> * The key type of specified {@link Map} * @param <V> * The value type of specified {@link Map} * @return {@link Map} */ @SuppressWarnings("unchecked") public static <K, V> Map<V, K> flip(Map<K, V> map) { if (isEmptyMap(map)) { return ((Map<V, K>) (map)); } Set<V> set = new HashSet<>(map.values());if (set.size() != map.size()) { throw new IllegalArgumentException("The map value must be unique."); } return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); }
3.26
dubbo_CollectionUtils_addAll_rdh
/** * Add the multiple values into {@link Collection the specified collection} * * @param collection * {@link Collection the specified collection} * @param values * the multiple values * @param <T> * the type of values * @return the effected count after added * @since 2.7.6 */ public static <T> int addAll(Collection<T> collection, T... values) { int size = (values == null) ? 0 : values.length; if ((collection == null) || (size < 1)) { return 0; } int effectedCount = 0; for (int i = 0; i < size; i++) { if (collection.add(values[i])) { effectedCount++; } } return effectedCount; }
3.26
dubbo_CollectionUtils_first_rdh
/** * Take the first element from the specified collection * * @param values * the collection object * @param <T> * the type of element of collection * @return if found, return the first one, or <code>null</code> * @since 2.7.6 */ public static <T> T first(Collection<T> values) {if (isEmpty(values)) { return null; } if (values instanceof List) { List<T> list = ((List<T>) (values)); return list.get(0); } else { return values.iterator().next(); } }
3.26
dubbo_CollectionUtils_isEmptyMap_rdh
/** * Return {@code true} if the supplied Map is {@code null} or empty. * Otherwise, return {@code false}. * * @param map * the Map to check * @return whether the given Map is empty */ public static boolean isEmptyMap(Map map) { return (map == null) || (map.size() == 0); }
3.26
dubbo_Help_mainHelp_rdh
/* output main help */private String mainHelp() { final TTable tTable = new TTable(new TTable.ColumnDefine[]{ new TTable.ColumnDefine(Align.RIGHT), new TTable.ColumnDefine(80, false, Align.LEFT) }); final List<Class<?>> classes = commandHelper.getAllCommandClass(); Collections.sort(classes, new Comparator<Class<?>>() { @Override public int compare(Class<?> o1, Class<?> o2) { final Integer o1s = o1.getAnnotation(Cmd.class).sort(); final Integer o2s = o2.getAnnotation(Cmd.class).sort(); return o1s.compareTo(o2s); } }); for (Class<?> clazz : classes) { if (clazz.isAnnotationPresent(Cmd.class)) { final Cmd cmd = clazz.getAnnotation(Cmd.class); tTable.addRow(cmd.name(), cmd.summary()); } } return tTable.padding(1).rendering(); }
3.26
dubbo_InternalServiceConfigBuilder_getRelatedOrDefaultProtocol_rdh
/** * Get other configured protocol from environment in priority order. If get nothing, use default dubbo. * * @return */ private String getRelatedOrDefaultProtocol() { String protocol = ""; // <dubbo:consumer/> List<ModuleModel> moduleModels = applicationModel.getPubModuleModels(); protocol = moduleModels.stream().map(ModuleModel::getConfigManager).map(ModuleConfigManager::getConsumers).filter(CollectionUtils::isNotEmpty).flatMap(Collection::stream).map(ConsumerConfig::getProtocol).filter(StringUtils::isNotEmpty).filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p)).findFirst().orElse(""); // <dubbo:provider/> if (StringUtils.isEmpty(protocol)) { Stream<ProviderConfig> providerConfigStream = moduleModels.stream().map(ModuleModel::getConfigManager).map(ModuleConfigManager::getProviders).filter(CollectionUtils::isNotEmpty).flatMap(Collection::stream); protocol = providerConfigStream.filter(providerConfig -> (providerConfig.getProtocol() != null) || CollectionUtils.isNotEmpty(providerConfig.getProtocols())).map(providerConfig -> { if ((providerConfig.getProtocol() != null) && StringUtils.isNotEmpty(providerConfig.getProtocol().getName())) { return providerConfig.getProtocol().getName(); } else { return providerConfig.getProtocols().stream().map(ProtocolConfig::getName).filter(StringUtils::isNotEmpty).findFirst().orElse(""); } }).filter(StringUtils::isNotEmpty).filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p)).findFirst().orElse(""); } // <dubbo:protocol/> if (StringUtils.isEmpty(protocol)) { Collection<ProtocolConfig> protocols = applicationModel.getApplicationConfigManager().getProtocols(); if (CollectionUtils.isNotEmpty(protocols)) { protocol = protocols.stream().map(ProtocolConfig::getName).filter(StringUtils::isNotEmpty).filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p)).findFirst().orElse(""); } } // <dubbo:application/> if (StringUtils.isEmpty(protocol)) { protocol = getApplicationConfig().getProtocol(); if (StringUtils.isEmpty(protocol)) { Map<String, String> v5 = getApplicationConfig().getParameters(); if (CollectionUtils.isNotEmptyMap(v5)) { protocol = v5.get(APPLICATION_PROTOCOL_KEY);} } } return StringUtils.isNotEmpty(protocol) && (!UNACCEPTABLE_PROTOCOL.contains(protocol)) ? protocol : DUBBO_PROTOCOL; }
3.26
dubbo_NacosMetadataReport_innerReceive_rdh
/** * receive * * @param dataId * data ID * @param group * group * @param configInfo * content */ @Override public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangedEvent event = new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue)); if (configInfo == null) { cacheData.remove(dataId); } else { cacheData.put(dataId, configInfo); } listeners.forEach(listener -> listener.process(event)); }
3.26
dubbo_StreamUtils_convertAttachment_rdh
/** * Parse and put the KV pairs into metadata. Ignore Http2 PseudoHeaderName and internal name. * Only raw byte array or string value will be put. * * @param headers * the metadata holder * @param attachments * KV pairs * @param needConvertHeaderKey * convert flag */ public static void convertAttachment(DefaultHttp2Headers headers, Map<String, Object> attachments, boolean needConvertHeaderKey) { if (attachments == null) { return; } Map<String, String> needConvertKey = new HashMap<>(); for (Map.Entry<String, Object> entry : attachments.entrySet()) {String key = lruHeaderMap.get(entry.getKey()); if (key == null) { final String lowerCaseKey = entry.getKey().toLowerCase(Locale.ROOT); lruHeaderMap.put(entry.getKey(), lowerCaseKey); key = lowerCaseKey; } if (TripleHeaderEnum.containsExcludeAttachments(key)) { continue; } final Object v = entry.getValue(); if (v == null) { continue; } if (needConvertHeaderKey && (!key.equals(entry.getKey()))) { needConvertKey.put(key, entry.getKey()); } convertSingleAttachment(headers, key, v); } if (!needConvertKey.isEmpty()) { String needConvertJson = JsonUtils.toJson(needConvertKey); headers.add(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader(), TriRpcStatus.encodeMessage(needConvertJson)); } }
3.26
dubbo_StreamUtils_convertSingleAttachment_rdh
/** * Convert each user's attach value to metadata * * @param headers * outbound headers * @param key * metadata key * @param v * metadata value (Metadata Only string and byte arrays are allowed) */ private static void convertSingleAttachment(DefaultHttp2Headers headers, String key, Object v) { try { if (((v instanceof String) || (v instanceof Number)) || (v instanceof Boolean)) {String str = v.toString(); headers.set(key, str); } else if (v instanceof byte[]) { String str = encodeBase64ASCII(((byte[]) (v))); headers.set(key + TripleConstant.HEADER_BIN_SUFFIX, str); } else { LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", (("Unsupported attachment k: " + key) + " class: ") + v.getClass().getName()); } } catch (Throwable t) { LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", (("Meet exception when convert single attachment key:" + key) + " value=") + v, t); } }
3.26
dubbo_CodecSupport_isHeartBeat_rdh
/** * Check if payload is null object serialize result byte[] of serialization * * @param payload * @param proto * @return */ public static boolean isHeartBeat(byte[] payload, byte proto) { return Arrays.equals(payload, getNullBytesOf(getSerializationById(proto))); }
3.26