name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
dubbo_CodecSupport_getPayload_rdh
/** * Read all payload to byte[] * * @param is * @return * @throws IOException */ public static byte[] getPayload(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = getBuffer(is.available()); int len; while ((len = is.read(buffer)) > (-1)) { baos.write(buffer, 0, len); } baos.flush(); return baos.toByteArray(); }
3.26
dubbo_CodecSupport_getNullBytesOf_rdh
/** * Get the null object serialize result byte[] of Serialization from the cache, * if not, generate it first. * * @param s * Serialization Instances * @return serialize result of null object */ public static byte[] getNullBytesOf(Serialization s) { return ConcurrentHashMapUtils.computeIfAbsent(ID_NULLBYTES_MAP, s.getContentTypeId(), k -> {// Pre-generated Null object bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] nullBytes = new byte[0]; try { ObjectOutput out = s.serialize(null, baos); out.writeObject(null); out.flushBuffer(); nullBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_SERIALIZATION, "", "", ("Serialization extension " + s.getClass().getName()) + " not support serializing null object, return an empty bytes instead."); } return nullBytes; }); }
3.26
dubbo_DubboConfigBeanInitializer_prepareDubboConfigBeans_rdh
/** * Initializes there Dubbo's Config Beans before @Reference bean autowiring */private void prepareDubboConfigBeans() { logger.info("loading dubbo config beans ..."); // Make sure all these config beans are initialed and registered to ConfigManager // load application config beans loadConfigBeansOfType(ApplicationConfig.class, configManager); loadConfigBeansOfType(RegistryConfig.class, configManager); loadConfigBeansOfType(ProtocolConfig.class, configManager); loadConfigBeansOfType(MonitorConfig.class, configManager); loadConfigBeansOfType(ConfigCenterBean.class, configManager); loadConfigBeansOfType(MetadataReportConfig.class, configManager); loadConfigBeansOfType(MetricsConfig.class, configManager); loadConfigBeansOfType(TracingConfig.class, configManager); loadConfigBeansOfType(SslConfig.class, configManager); // load module config beans loadConfigBeansOfType(ModuleConfig.class, moduleModel.getConfigManager());loadConfigBeansOfType(ProviderConfig.class, moduleModel.getConfigManager()); loadConfigBeansOfType(ConsumerConfig.class, moduleModel.getConfigManager()); // load ConfigCenterBean from properties, fix https://github.com/apache/dubbo/issues/9207 List<ConfigCenterBean> configCenterBeans = configManager.loadConfigsOfTypeFromProps(ConfigCenterBean.class); for (ConfigCenterBean configCenterBean : configCenterBeans) { String beanName = (configCenterBean.getId() != null) ? configCenterBean.getId() : "configCenterBean"; beanFactory.initializeBean(configCenterBean, beanName); } logger.info("dubbo config beans are loaded."); }
3.26
dubbo_ReferenceBeanManager_transformName_rdh
// convert reference name/alias to referenceBeanName private String transformName(String referenceBeanNameOrAlias) { return referenceAliasMap.getOrDefault(referenceBeanNameOrAlias, referenceBeanNameOrAlias); }
3.26
dubbo_ReferenceBeanManager_prepareReferenceBeans_rdh
/** * Initialize all reference beans, call at Dubbo starting * * @throws Exception */ public void prepareReferenceBeans() throws Exception { initialized = true; for (ReferenceBean referenceBean : getReferences()) { initReferenceBean(referenceBean); } }
3.26
dubbo_ReferenceBeanManager_initReferenceBean_rdh
/** * NOTE: This method should only call after all dubbo config beans and all property resolvers is loaded. * * @param referenceBean * @throws Exception */ public synchronized void initReferenceBean(ReferenceBean referenceBean) throws Exception { if (referenceBean.getReferenceConfig() != null) { return; }// TOTO check same unique service name but difference reference key (means difference attributes). // reference key String referenceKey = getReferenceKeyByBeanName(referenceBean.getId()); if (StringUtils.isEmpty(referenceKey)) { referenceKey = ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext); } ReferenceConfig referenceConfig = referenceConfigMap.get(referenceKey); if (referenceConfig == null) { // create real ReferenceConfig Map<String, Object> referenceAttributes = ReferenceBeanSupport.getReferenceAttributes(referenceBean); referenceConfig = ReferenceCreator.create(referenceAttributes, applicationContext).defaultInterfaceClass(referenceBean.getObjectType()).build(); // set id if it is not a generated name if ((referenceBean.getId() != null) && (!referenceBean.getId().contains("#"))) { referenceConfig.setId(referenceBean.getId()); } // cache referenceConfig referenceConfigMap.put(referenceKey, referenceConfig); // register ReferenceConfig moduleModel.getConfigManager().addReference(referenceConfig); moduleModel.getDeployer().setPending(); } // associate referenceConfig to referenceBean referenceBean.setKeyAndReferenceConfig(referenceKey, referenceConfig); }
3.26
dubbo_EdsEndpointManager_getEdsListeners_rdh
// for test static ConcurrentHashMap<String, Consumer<Map<String, EndpointResult>>> getEdsListeners() { return EDS_LISTENERS; }
3.26
dubbo_EdsEndpointManager_getEndpointListeners_rdh
// for test static ConcurrentHashMap<String, Set<EdsEndpointListener>> getEndpointListeners() { return ENDPOINT_LISTENERS; }
3.26
dubbo_NacosServiceName_isConcrete_rdh
/** * Is the concrete service name or not * * @return if concrete , return <code>true</code>, or <code>false</code> */ public boolean isConcrete() { return (isConcrete(serviceInterface) && isConcrete(version)) && isConcrete(group); }
3.26
dubbo_NacosServiceName_valueOf_rdh
/** * Build an instance of {@link NacosServiceName} * * @param url * @return */ public static NacosServiceName valueOf(URL url) { return new NacosServiceName(url); }
3.26
dubbo_NettyBackedChannelBuffer_clear_rdh
// AbstractChannelBuffer @Override public void clear() { buffer.clear(); }
3.26
dubbo_DataParseUtils_writeFormContent_rdh
/** * content-type form * * @param formData * @param outputStream * @throws Exception */ public static void writeFormContent(Map formData, OutputStream outputStream) throws Exception { outputStream.write(serializeForm(formData, Charset.defaultCharset()).getBytes());}
3.26
dubbo_DataParseUtils_serializeForm_rdh
// TODO file multipart public static String serializeForm(Map formData, Charset charset) { StringBuilder builder = new StringBuilder(); formData.forEach((name, values) -> { if (name == null) { return; } ((List) (values)).forEach(value -> { try { if (builder.length() != 0) { builder.append('&'); } builder.append(URLEncoder.encode(((String) (name)), charset.name())); if (value != null) { builder.append('='); builder.append(URLEncoder.encode(String.valueOf(value), charset.name())); } } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } }); }); return builder.toString(); }
3.26
dubbo_DataParseUtils_writeTextContent_rdh
/** * content-type text * * @param object * @param outputStream * @throws IOException */ public static void writeTextContent(Object object, OutputStream outputStream) throws IOException { outputStream.write(objectTextConvertToByteArray(object)); }
3.26
dubbo_ThreadlessExecutor_waitAndDrain_rdh
/** * Waits until there is a task, executes the task and all queued tasks (if there're any). The task is either a normal * response or a timeout response. */ public void waitAndDrain(long deadline) throws InterruptedException { throwIfInterrupted(); Runnable runnable = queue.poll(); if (runnable == null) {if (waiter.compareAndSet(null, Thread.currentThread())) {try { while (((runnable = queue.poll()) == null) && (waiter.get() == Thread.currentThread())) { long restTime = deadline - System.nanoTime(); if (restTime <= 0) { return; } LockSupport.parkNanos(this, restTime); throwIfInterrupted(); } } finally { waiter.compareAndSet(Thread.currentThread(), null); } } } do { if (runnable != null) { runnable.run(); } } while ((runnable = queue.poll()) != null ); }
3.26
dubbo_ThreadlessExecutor_shutdown_rdh
/** * The following methods are still not supported */ @Override public void shutdown() { shutdownNow(); }
3.26
dubbo_AbstractRegistryFactory_createRegistryCacheKey_rdh
/** * Create the key for the registries cache. * This method may be overridden by the sub-class. * * @param url * the registration {@link URL url} * @return non-null */ protected String createRegistryCacheKey(URL url) { return url.toServiceStringWithoutResolving(); }
3.26
dubbo_ServiceAnnotationPostProcessor_buildServiceBeanDefinition_rdh
/** * Build the {@link AbstractBeanDefinition Bean Definition} * * @param serviceAnnotationAttributes * @param serviceInterface * @param refServiceBeanName * @return * @since 2.7.3 */ private AbstractBeanDefinition buildServiceBeanDefinition(Map<String, Object> serviceAnnotationAttributes, String serviceInterface, String refServiceBeanName) { BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); String[] ignoreAttributeNames = ObjectUtils.of("provider", "monitor", "application", "module", "registry", "protocol", "methods", "interfaceName", "parameters", "executor"); propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); // set config id, for ConfigManager cache key // builder.addPropertyValue("id", beanName); // References "ref" property to annotated-@Service Bean addPropertyReference(builder, "ref", refServiceBeanName); // Set interface builder.addPropertyValue("interface", serviceInterface); // Convert parameters into map builder.addPropertyValue("parameters", DubboAnnotationUtils.convertParameters(((String[]) (serviceAnnotationAttributes.get("parameters"))))); // Add methods parameters List<MethodConfig> methodConfigs = convertMethodConfigs(serviceAnnotationAttributes.get("methods")); if (!methodConfigs.isEmpty()) { builder.addPropertyValue("methods", methodConfigs); } // convert provider to providerIds String providerConfigId = ((String) (serviceAnnotationAttributes.get("provider"))); if (StringUtils.hasText(providerConfigId)) { addPropertyValue(builder, "providerIds", providerConfigId); } // Convert registry[] to registryIds String[] registryConfigIds = ((String[]) (serviceAnnotationAttributes.get("registry"))); if ((registryConfigIds != null) && (registryConfigIds.length > 0)) { resolveStringArray(registryConfigIds); builder.addPropertyValue("registryIds", StringUtils.join(registryConfigIds, ',')); } // Convert protocol[] to protocolIds String[] protocolConfigIds = ((String[]) (serviceAnnotationAttributes.get("protocol"))); if ((protocolConfigIds != null) && (protocolConfigIds.length > 0)) { resolveStringArray(protocolConfigIds); builder.addPropertyValue("protocolIds", StringUtils.join(protocolConfigIds, ',')); }// TODO Could we ignore these attributes: applicatin/monitor/module ? Use global config // monitor reference String monitorConfigId = ((String) (serviceAnnotationAttributes.get("monitor"))); if (StringUtils.hasText(monitorConfigId)) { addPropertyReference(builder, "monitor", monitorConfigId); } // module reference String moduleConfigId = ((String) (serviceAnnotationAttributes.get("module"))); if (StringUtils.hasText(moduleConfigId)) { addPropertyReference(builder, "module", moduleConfigId); } String executorBeanName = ((String) (serviceAnnotationAttributes.get("executor"))); if (StringUtils.hasText(executorBeanName)) { addPropertyReference(builder, "executor", executorBeanName); } return builder.getBeanDefinition(); }
3.26
dubbo_ServiceAnnotationPostProcessor_processAnnotatedBeanDefinition_rdh
/** * process @DubboService at java-config @bean method * <pre class="code"> * &#064;Configuration * public class ProviderConfig { * * &#064;Bean * &#064;DubboService(group="demo", version="1.2.3") * public DemoService demoService() { * return new DemoServiceImpl(); * } * * } * </pre> * * @param refServiceBeanName * @param refServiceBeanDefinition * @param attributes */ private void processAnnotatedBeanDefinition(String refServiceBeanName, AnnotatedBeanDefinition refServiceBeanDefinition, Map<String, Object> attributes) { Map<String, Object> serviceAnnotationAttributes = new LinkedHashMap<>(attributes); // get bean class from return type String returnTypeName = SpringCompatUtils.getFactoryMethodReturnType(refServiceBeanDefinition); Class<?> beanClass = resolveClassName(returnTypeName, classLoader); String serviceInterface = resolveInterfaceName(serviceAnnotationAttributes, beanClass); // ServiceBean Bean name String serviceBeanName = m0(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, refServiceBeanName); // set id serviceBeanDefinition.getPropertyValues().add(Constants.ID, serviceBeanName); registerServiceBeanDefinition(serviceBeanName, serviceBeanDefinition, serviceInterface); }
3.26
dubbo_ServiceAnnotationPostProcessor_processScannedBeanDefinition_rdh
/** * Registers {@link ServiceBean} from new annotated {@link Service} {@link BeanDefinition} * * @param beanDefinitionHolder * @see ServiceBean * @see BeanDefinition */ private void processScannedBeanDefinition(BeanDefinitionHolder beanDefinitionHolder) { Class<?> beanClass = resolveClass(beanDefinitionHolder); Annotation service = findServiceAnnotation(beanClass); // The attributes of @Service annotation Map<String, Object> serviceAnnotationAttributes = AnnotationUtils.getAttributes(service, true); String serviceInterface = resolveInterfaceName(serviceAnnotationAttributes, beanClass); String annotatedServiceBeanName = beanDefinitionHolder.getBeanName(); // ServiceBean Bean name String beanName = m0(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, annotatedServiceBeanName); registerServiceBeanDefinition(beanName, serviceBeanDefinition, serviceInterface); }
3.26
dubbo_ServiceAnnotationPostProcessor_resolveBeanNameGenerator_rdh
/** * It'd be better to use BeanNameGenerator instance that should reference * {@link ConfigurationClassPostProcessor#componentScanBeanNameGenerator}, * thus it maybe a potential problem on bean name generation. * * @param registry * {@link BeanDefinitionRegistry} * @return {@link BeanNameGenerator} instance * @see SingletonBeanRegistry * @see AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR * @see ConfigurationClassPostProcessor#processConfigBeanDefinitions * @since 2.5.8 */ private BeanNameGenerator resolveBeanNameGenerator(BeanDefinitionRegistry registry) { BeanNameGenerator beanNameGenerator = null; if (registry instanceof SingletonBeanRegistry) { SingletonBeanRegistry singletonBeanRegistry = SingletonBeanRegistry.class.cast(registry); beanNameGenerator = ((BeanNameGenerator) (singletonBeanRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR))); } if (beanNameGenerator == null) { if (logger.isInfoEnabled()) { logger.info(("BeanNameGenerator bean can't be found in BeanFactory with name [" + CONFIGURATION_BEAN_NAME_GENERATOR) + "]"); logger.info(("BeanNameGenerator will be a instance of " + AnnotationBeanNameGenerator.class.getName()) + " , it maybe a potential problem on bean name generation."); } beanNameGenerator = new AnnotationBeanNameGenerator(); } return beanNameGenerator; }
3.26
dubbo_ServiceAnnotationPostProcessor_findServiceAnnotation_rdh
/** * Find the {@link Annotation annotation} of @Service * * @param beanClass * the {@link Class class} of Bean * @return <code>null</code> if not found * @since 2.7.3 */ private Annotation findServiceAnnotation(Class<?> beanClass) { return serviceAnnotationTypes.stream().map(annotationType -> ClassUtils.isPresent("org.springframework.core.annotation.AnnotatedElementUtils", Thread.currentThread().getContextClassLoader()) && ReflectUtils.hasMethod(AnnotatedElementUtils.class, "findMergedAnnotation") ? AnnotatedElementUtils.findMergedAnnotation(beanClass, annotationType) : utils.AnnotationUtils.findAnnotation(beanClass, annotationType)).filter(Objects::nonNull).findFirst().orElse(null); }
3.26
dubbo_ServiceAnnotationPostProcessor_m0_rdh
/** * Generates the bean name of {@link ServiceBean} * * @param serviceAnnotationAttributes * @param serviceInterface * the class of interface annotated {@link Service} * @return ServiceBean@interfaceClassName#annotatedServiceBeanName * @since 2.7.3 */ private String m0(Map<String, Object> serviceAnnotationAttributes, String serviceInterface) { ServiceBeanNameBuilder builder = create(serviceInterface, environment).group(((String) (serviceAnnotationAttributes.get("group")))).version(((String) (serviceAnnotationAttributes.get("version")))); return builder.build(); }
3.26
dubbo_ServiceAnnotationPostProcessor_findServiceBeanDefinitionHolders_rdh
/** * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated * {@link Service} Annotation. * * @param scanner * {@link ClassPathBeanDefinitionScanner} * @param packageToScan * pachage to scan * @param registry * {@link BeanDefinitionRegistry} * @return non-null * @since 2.5.8 */ private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders(ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator) { Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan); Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<>(beanDefinitions.size());for (BeanDefinition beanDefinition : beanDefinitions) { String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry); BeanDefinitionHolder v19 = new BeanDefinitionHolder(beanDefinition, beanName); beanDefinitionHolders.add(v19); } return beanDefinitionHolders; }
3.26
dubbo_ServiceAnnotationPostProcessor_getServiceAnnotationAttributes_rdh
/** * Get dubbo service annotation class at java-config @bean method * * @return return service annotation attributes map if found, or return null if not found. */ private Map<String, Object> getServiceAnnotationAttributes(BeanDefinition beanDefinition) { if (beanDefinition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedBeanDefinition = ((AnnotatedBeanDefinition) (beanDefinition)); MethodMetadata factoryMethodMetadata = SpringCompatUtils.getFactoryMethodMetadata(annotatedBeanDefinition); if (factoryMethodMetadata != null) { // try all dubbo service annotation types for (Class<? extends Annotation> annotationType : serviceAnnotationTypes) { if (factoryMethodMetadata.isAnnotated(annotationType.getName())) { // Since Spring 5.2 // return // factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap(); // Compatible with Spring 4.x Map<String, Object> annotationAttributes = factoryMethodMetadata.getAnnotationAttributes(annotationType.getName()); return filterDefaultValues(annotationType, annotationAttributes); } } } } return null; }
3.26
dubbo_ServiceAnnotationPostProcessor_scanServiceBeans_rdh
/** * Scan and registers service beans whose classes was annotated {@link Service} * * @param packagesToScan * The base packages to scan * @param registry * {@link BeanDefinitionRegistry} */ private void scanServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) { scanned = true; if (CollectionUtils.isEmpty(packagesToScan)) { if (logger.isWarnEnabled()) {logger.warn(CONFIG_NO_BEANS_SCANNED, "", "", "packagesToScan is empty , ServiceBean registry will be ignored!"); } return; } DubboClassPathBeanDefinitionScanner scanner = new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader); BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry); scanner.setBeanNameGenerator(beanNameGenerator); for (Class<? extends Annotation> annotationType : serviceAnnotationTypes) { scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType)); } ScanExcludeFilter scanExcludeFilter = new ScanExcludeFilter(); scanner.addExcludeFilter(scanExcludeFilter); for (String packageToScan : packagesToScan) { // avoid duplicated scans if (servicePackagesHolder.isPackageScanned(packageToScan)) { if (logger.isInfoEnabled()) { logger.info("Ignore package who has already bean scanned: " + packageToScan); } continue; } // Registers @Service Bean first scanner.scan(packageToScan); // Finds all BeanDefinitionHolders of @Service whether @ComponentScan scans or not. Set<BeanDefinitionHolder> beanDefinitionHolders = findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator); if (!CollectionUtils.isEmpty(beanDefinitionHolders)) { if (logger.isInfoEnabled()) { List<String> serviceClasses = new ArrayList<>(beanDefinitionHolders.size()); for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { serviceClasses.add(beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } logger.info((((("Found " + beanDefinitionHolders.size()) + " classes annotated by Dubbo @Service under package [") + packageToScan) + "]: ") + serviceClasses); } for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { processScannedBeanDefinition(beanDefinitionHolder); servicePackagesHolder.addScannedClass(beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } } else if (logger.isWarnEnabled()) { logger.warn(CONFIG_NO_ANNOTATIONS_FOUND, "No annotations were found on the class", "", (("No class annotated by Dubbo @DubboService or @Service was found under package [" + packageToScan) + "], ignore re-scanned classes: ") + scanExcludeFilter.getExcludedCount()); } servicePackagesHolder.addScannedPackage(packageToScan); } }
3.26
dubbo_TripleServerStream_responsePlainTextError_rdh
/** * Error before create server stream, http plain text will be returned * * @param code * code of error * @param status * status of error */ private void responsePlainTextError(int code, TriRpcStatus status) { ChannelFuture checkResult = preCheck(); if (!checkResult.isSuccess()) { return; } Http2Headers headers = new DefaultHttp2Headers(true).status(String.valueOf(code)).setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code).set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.description).set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.TEXT_PLAIN_UTF8); f0.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, headers, false)); f0.enqueue(TextDataQueueCommand.createCommand(tripleStreamChannelFuture, status.description, true)); }
3.26
dubbo_TripleServerStream_supportContentType_rdh
/** * must starts from application/grpc */ private boolean supportContentType(String contentType) { if (contentType == null) { return false; } return contentType.startsWith(TripleConstant.APPLICATION_GRPC); }
3.26
dubbo_TripleServerStream_responseErr_rdh
/** * Error in create stream, unsupported config or triple protocol error. There is no return value * because stream will be reset if send trailers failed. * * @param status * status of error */private void responseErr(TriRpcStatus status) { Http2Headers trailers = new DefaultHttp2Headers().status(OK.codeAsText()).set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO).setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code).set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toEncodedMessage()); sendTrailers(trailers); }
3.26
dubbo_AbstractConfigManager_addConfig_rdh
/** * Add the dubbo {@link AbstractConfig config} * * @param config * the dubbo {@link AbstractConfig config} */ public final <T extends AbstractConfig> T addConfig(AbstractConfig config) { if (config == null) { return null; } // ignore MethodConfig if (!isSupportConfigType(config.getClass())) { throw new IllegalArgumentException("Unsupported config type: " + config); } if (config.getScopeModel() != scopeModel) { config.setScopeModel(scopeModel); } Map<String, AbstractConfig> configsMap = configsCache.computeIfAbsent(getTagName(config.getClass()), type -> new ConcurrentHashMap<>()); // fast check duplicated equivalent config before write lock if (!((config instanceof ReferenceConfigBase) || (config instanceof ServiceConfigBase))) { for (AbstractConfig value : configsMap.values()) { if (value.equals(config)) { return ((T) (value)); } } } // lock by config type synchronized(configsMap) { return ((T) (addIfAbsent(config, configsMap))); } }
3.26
dubbo_AbstractConfigManager_getConfig_rdh
/** * Get config instance by id or by name * * @param cls * Config type * @param idOrName * the id or name of the config * @return */ public <T extends AbstractConfig> Optional<T> getConfig(Class<T> cls, String idOrName) { T config = getConfigById(getTagName(cls), idOrName); if (config == null) { config = getConfigByName(cls, idOrName); } return ofNullable(config); }
3.26
dubbo_AbstractConfigManager_getConfigIdsFromProps_rdh
/** * Search props and extract config ids of specify type. * <pre> * # properties * dubbo.registries.registry1.address=xxx * dubbo.registries.registry2.port=xxx * * # extract * Set configIds = getConfigIds(RegistryConfig.class) * * # result * configIds: ["registry1", "registry2"] * </pre> * * @param clazz * config type * @return ids of specify config type */ private Set<String> getConfigIdsFromProps(Class<? extends AbstractConfig> clazz) { String prefix = ((CommonConstants.DUBBO + ".") + AbstractConfig.getPluralTagName(clazz)) + "."; return ConfigurationUtils.getSubIds(environment.getConfigurationMaps(), prefix); }
3.26
dubbo_AbstractConfigManager_removeConfig_rdh
/** * In some scenario, we may need to add and remove ServiceConfig or ReferenceConfig dynamically. * * @param config * the config instance to remove. * @return */ public boolean removeConfig(AbstractConfig config) { if (config == null) { return false; } Map<String, AbstractConfig> configs = configsCache.get(getTagName(config.getClass())); if (CollectionUtils.isNotEmptyMap(configs)) { // lock by config type synchronized(configs) { return removeIfAbsent(config, configs); } } return false; }
3.26
dubbo_AbstractConfigManager_addIfAbsent_rdh
/** * Add config * * @param config * @param configsMap * @return the existing equivalent config or the new adding config * @throws IllegalStateException */ private <C extends AbstractConfig> C addIfAbsent(C config, Map<String, C> configsMap) throws IllegalStateException { if ((config == null) || (configsMap == null)) { return config; } // find by value Optional<C> prevConfig = findDuplicatedConfig(configsMap, config); if (prevConfig.isPresent()) {return prevConfig.get(); } String key = config.getId(); if (key == null) { do {// generate key if id is not set key = generateConfigId(config); } while (configsMap.containsKey(key) );} C existedConfig = configsMap.get(key); if ((existedConfig != null) && (!isEquals(existedConfig, config))) { String type = config.getClass().getSimpleName(); logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", String.format("Duplicate %s found, there already has one default %s or more than two %ss have the same id, " + "you can try to give each %s a different id, override previous config with later config. id: %s, prev: %s, later: %s", type, type, type, type, key, existedConfig, config)); } // override existed config if any configsMap.put(key, config); return config; }
3.26
dubbo_AbstractConfigManager_isNeedValidation_rdh
/** * The component configuration that does not affect the main process does not need to be verified. * * @param config * @param <T> * @return */protected <T extends AbstractConfig> boolean isNeedValidation(T config) { if (config instanceof MetadataReportConfig) { return false; } return true;}
3.26
dubbo_AbstractConfigManager_isRequired_rdh
/** * The configuration that does not affect the main process is not necessary. * * @param clazz * @param <T> * @return */ protected <T extends AbstractConfig> boolean isRequired(Class<T> clazz) { if (((((clazz == RegistryConfig.class) || (clazz == MetadataReportConfig.class)) || (clazz == MonitorConfig.class)) || (clazz == MetricsConfig.class)) || (clazz == TracingConfig.class)) { return false; } return true;}
3.26
dubbo_AbstractConfigManager_getConfigByName_rdh
/** * Get config by name if existed * * @param cls * @param name * @return */ protected <C extends AbstractConfig> C getConfigByName(Class<? extends C> cls, String name) { Map<String, ? extends C> configsMap = getConfigsMap(cls); if (configsMap.isEmpty()) { return null; } // try to find config by name if (ReflectUtils.hasMethod(cls, CONFIG_NAME_READ_METHOD)) { List<C> list = configsMap.values().stream().filter(cfg -> name.equals(getConfigName(cfg))).collect(Collectors.toList()); if (list.size() > 1) { throw new IllegalStateException(((("Found more than one config by name: " + name) + ", instances: ") + list) + ". Please remove redundant configs or get config by id."); } else if (list.size() == 1) { return list.get(0); } }return null; }
3.26
dubbo_AbstractConfigManager_getConfigById_rdh
/** * Get config by id * * @param configType * @param id * @return */ protected <C extends AbstractConfig> C getConfigById(String configType, String id) { return ((C) (getConfigsMap(configType).get(id))); }
3.26
dubbo_JCacheFactory_createCache_rdh
/** * Takes url as an method argument and return new instance of cache store implemented by JCache. * * @param url * url of the method * @return JCache instance of cache */ @Overrideprotected Cache createCache(URL url) { return new JCache(url); }
3.26
dubbo_EnvironmentAdapter_getExtraAttributes_rdh
/** * 1. OS Environment: DUBBO_LABELS=tag=pre;key=value * 2. JVM Options: -Denv_keys = DUBBO_KEY1, DUBBO_KEY2 * * @param params * information of this Dubbo process, currently includes application name and host address. */ @Override public Map<String, String> getExtraAttributes(Map<String, String> params) { Map<String, String> parameters = new HashMap<>(); String rawLabels = ConfigurationUtils.getProperty(applicationModel, DUBBO_LABELS); if (StringUtils.isNotEmpty(rawLabels)) { String[] labelPairs = SEMICOLON_SPLIT_PATTERN.split(rawLabels); for (String pair : labelPairs) { String[] label = EQUAL_SPLIT_PATTERN.split(pair); if (label.length == 2) { parameters.put(label[0], label[1]); } } } String rawKeys = ConfigurationUtils.getProperty(applicationModel, DUBBO_ENV_KEYS); if (StringUtils.isNotEmpty(rawKeys)) { String[] keys = COMMA_SPLIT_PATTERN.split(rawKeys); for (String v7 : keys) { String value = ConfigurationUtils.getProperty(applicationModel, v7); if (value != null) { // since 3.2 parameters.put(v7.toLowerCase(), value); // upper-case key kept for compatibility parameters.put(v7, value); } }} return parameters; }
3.26
dubbo_RoundRobinLoadBalance_getInvokerAddrList_rdh
/** * get invoker addr list cached for specified invocation * <p> * <b>for unit test only</b> * * @param invokers * @param invocation * @return */ protected <T> Collection<String> getInvokerAddrList(List<Invoker<T>> invokers, Invocation invocation) { String key = (invokers.get(0).getUrl().getServiceKey() + ".") + RpcUtils.getMethodName(invocation); Map<String, WeightedRoundRobin> map = methodWeightMap.get(key); if (map != null) { return map.keySet(); } return null; }
3.26
dubbo_Bytes_short2bytes_rdh
/** * to byte array. * * @param v * value. * @param b * byte array. */ public static void short2bytes(short v, byte[] b) { short2bytes(v, b, 0); }
3.26
dubbo_Bytes_base642bytes_rdh
/** * from base64 string. * * @param str * base64 string. * @param off * offset. * @param len * length. * @param code * base64 code(0-63 is base64 char,64 is pad char). * @return byte array. */ public static byte[] base642bytes(final String str, final int off, final int len, final char[] code) { if (off < 0) { throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len); } if (len == 0) { return new byte[0]; }if ((off + len) > str.length()) { throw new IndexOutOfBoundsException("base642bytes: offset + length > string length."); } if (code.length < 64) {throw new IllegalArgumentException("Base64 code length < 64."); } int rem = len % 4; if (rem == 1) { throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1."); } int num = len / 4; int size = num * 3; if (code.length > 64) { if (rem != 0) { throw new IllegalArgumentException("base642bytes: base64 string length error."); } char pc = code[64]; if (str.charAt((off + len) - 2) == pc) { size -= 2; --num; rem = 2; } else if (str.charAt((off + len) - 1) == pc) { size--; --num; rem = 3; } } else if (rem == 2) { size++; } else if (rem == 3) { size += 2; } int r = off; int w = 0; byte[] b = new byte[size]; for (int i = 0; i < num; i++) { int c1 = indexOf(code, str.charAt(r++)); int c2 = indexOf(code, str.charAt(r++)); int c3 = indexOf(code, str.charAt(r++)); int c4 = indexOf(code, str.charAt(r++)); b[w++] = ((byte) ((c1 << 2) | (c2 >> 4))); b[w++] = ((byte) ((c2 << 4) | (c3 >> 2))); b[w++] = ((byte) ((c3 << 6) | c4)); } if (rem == 2) { int c1 = indexOf(code, str.charAt(r++)); int c2 = indexOf(code, str.charAt(r++)); b[w++] = ((byte) ((c1 << 2) | (c2 >> 4))); } else if (rem == 3) { int c1 = indexOf(code, str.charAt(r++)); int c2 = indexOf(code, str.charAt(r++)); int c3 = indexOf(code, str.charAt(r++)); b[w++] = ((byte) ((c1 << 2) | (c2 >> 4))); b[w++] = ((byte) ((c2 << 4) | (c3 >> 2))); } return b; }
3.26
dubbo_Bytes_bytes2short_rdh
/** * to short. * * @param b * byte array. * @param off * offset. * @return short. */ public static short bytes2short(byte[] b, int off) {return ((short) (((b[off + 1] & 0xff) << 0) + (b[off + 0] << 8))); }
3.26
dubbo_Bytes_zip_rdh
/** * zip. * * @param bytes * source. * @return compressed byte array. * @throws IOException */ public static byte[] zip(byte[] bytes) throws IOException { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(); OutputStream os = new DeflaterOutputStream(bos); try { os.write(bytes); } finally {os.close(); bos.close(); }return bos.toByteArray(); }
3.26
dubbo_Bytes_m2_rdh
/** * from base64 string. * * @param str * base64 string. * @param offset * offset. * @param length * length. * @return byte array. */ public static byte[] m2(String str, int offset, int length) { return base642bytes(str, offset, length, C64); }
3.26
dubbo_Bytes_bytes2float_rdh
/** * to int. * * @param b * byte array. * @param off * offset. * @return int. */ public static float bytes2float(byte[] b, int off) { int i = ((((b[off + 3] & 0xff) << 0) + ((b[off + 2] & 0xff) << 8)) + ((b[off + 1] & 0xff) << 16)) + (b[off + 0] << 24); return Float.intBitsToFloat(i); }
3.26
dubbo_Bytes_double2bytes_rdh
/** * to byte array. * * @param v * value. * @param b * byte array. * @param off * array offset. */ public static void double2bytes(double v, byte[] b, int off) { long j = Double.doubleToLongBits(v); b[off + 7] = ((byte) (j)); b[off + 6] = ((byte) (j >>> 8)); b[off + 5] = ((byte) (j >>> 16)); b[off + 4] = ((byte) (j >>> 24)); b[off + 3] = ((byte) (j >>> 32)); b[off + 2] = ((byte) (j >>> 40)); b[off + 1] = ((byte) (j >>> 48)); b[off + 0] = ((byte) (j >>> 56)); }
3.26
dubbo_Bytes_bytes2base64_rdh
/** * to base64 string. * * @param bs * byte array. * @param off * offset. * @param len * length. * @param code * base64 code(0-63 is base64 char,64 is pad char). * @return base64 string. */ public static String bytes2base64(final byte[] bs, final int off, final int len, final char[] code) { if (off < 0) { throw new IndexOutOfBoundsException("bytes2base64: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("bytes2base64: length < 0, length is " + len); } if ((off + len) > bs.length) {throw new IndexOutOfBoundsException("bytes2base64: offset + length > array length."); } if (code.length < 64) {throw new IllegalArgumentException("Base64 code length < 64."); } boolean pad = code.length > 64;// has pad char. int num = len / 3; int rem = len % 3; int r = off; int w = 0; char[] cs = new char[(num * 4) + (rem == 0 ? 0 : pad ? 4 : rem + 1)]; for (int i = 0; i < num; i++) { int b1 = bs[r++] & MASK8; int b2 = bs[r++] & MASK8; int b3 = bs[r++] & MASK8; cs[w++] = code[b1 >> 2]; cs[w++] = code[((b1 << 4) & MASK6) | (b2 >> 4)]; cs[w++] = code[((b2 << 2) & MASK6) | (b3 >> 6)]; cs[w++] = code[b3 & MASK6]; } if (rem == 1) { int b1 = bs[r++] & MASK8; cs[w++] = code[b1 >> 2]; cs[w++] = code[(b1 << 4) & MASK6]; if (pad) { cs[w++] = code[64]; cs[w++] = code[64]; } } else if (rem == 2) { int b1 = bs[r++] & MASK8; int b2 = bs[r++] & MASK8; cs[w++] = code[b1 >> 2]; cs[w++] = code[((b1 << 4) & MASK6) | (b2 >> 4)]; cs[w++] = code[(b2 << 2) & MASK6]; if (pad) { cs[w++] = code[64]; } }return new String(cs); }
3.26
dubbo_Bytes_bytes2long_rdh
/** * to long. * * @param b * byte array. * @param off * offset. * @return long. */ public static long bytes2long(byte[] b, int off) { return ((((((((b[off + 7] & 0xffL) << 0) + ((b[off + 6] & 0xffL) << 8)) + ((b[off + 5] & 0xffL) << 16)) + ((b[off + 4] & 0xffL) << 24)) + ((b[off + 3] & 0xffL) << 32)) + ((b[off + 2] & 0xffL) << 40)) + ((b[off + 1] & 0xffL) << 48)) + (((long) (b[off + 0])) << 56); }
3.26
dubbo_Bytes_m0_rdh
/** * to byte array. * * @param v * value. * @return byte[]. */ public static byte[] m0(short v) { byte[] ret = new byte[]{ 0, 0 }; short2bytes(v, ret); return ret; }
3.26
dubbo_Bytes_int2bytes_rdh
/** * to byte array. * * @param v * value. * @param b * byte array. * @param off * array offset. */ public static void int2bytes(int v, byte[] b, int off) {b[off + 3] = ((byte) (v)); b[off + 2] = ((byte) (v >>> 8)); b[off + 1] = ((byte) (v >>> 16)); b[off + 0] = ((byte) (v >>> 24)); }
3.26
dubbo_Bytes_getMD5_rdh
/** * get md5. * * @param is * input stream. * @return MD5 byte array. */ public static byte[] getMD5(InputStream is) throws IOException { return getMD5(is, 1024 * 8); }
3.26
dubbo_Bytes_bytes2hex_rdh
/** * to hex string. * * @param bs * byte array. * @param off * offset. * @param len * length. * @return hex string. */ public static String bytes2hex(byte[] bs, int off, int len) { if (off < 0) { throw new IndexOutOfBoundsException("bytes2hex: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("bytes2hex: length < 0, length is " + len); }if ((off + len) > bs.length) { throw new IndexOutOfBoundsException("bytes2hex: offset + length > array length."); }byte b; int r = off; int w = 0; char[] cs = new char[len * 2]; for (int i = 0; i < len; i++) {b = bs[r++]; cs[w++] = BASE16[(b >> 4) & MASK4]; cs[w++] = BASE16[b & MASK4]; } return new String(cs); }
3.26
dubbo_Bytes_bytes2int_rdh
/** * to int. * * @param b * byte array. * @param off * offset. * @return int. */ public static int bytes2int(byte[] b, int off) { return ((((b[off + 3] & 0xff) << 0) + ((b[off + 2] & 0xff) << 8)) + ((b[off + 1] & 0xff) << 16)) + (b[off + 0] << 24); }
3.26
dubbo_Bytes_unzip_rdh
/** * unzip. * * @param bytes * compressed byte array. * @return byte uncompressed array. * @throws IOException */ public static byte[] unzip(byte[] bytes) throws IOException { UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes); UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(); InputStream is = new InflaterInputStream(bis); try { IOUtils.write(is, bos);return bos.toByteArray(); } finally { is.close(); bis.close(); bos.close(); } }
3.26
dubbo_Bytes_m1_rdh
/** * to base64 string. * * @param b * byte array. * @return base64 string. */ public static String m1(byte[] b, int offset, int length) { return bytes2base64(b, offset, length, BASE64); }
3.26
dubbo_Bytes_hex2bytes_rdh
/** * from hex string. * * @param str * hex string. * @param off * offset. * @param len * length. * @return byte array. */ public static byte[] hex2bytes(final String str, final int off, int len) { if ((len & 1) == 1) { throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1."); }if (off < 0) { throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len); } if ((off + len) > str.length()) { throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length."); } int num = len / 2; int r = off; int w = 0; byte[] b = new byte[num]; for (int i = 0; i < num; i++) { b[w++] = ((byte) ((hex(str.charAt(r++)) << 4) | hex(str.charAt(r++)))); } return b; }
3.26
dubbo_Bytes_copyOf_rdh
/** * byte array copy. * * @param src * src. * @param length * new length. * @return new byte array. */ public static byte[] copyOf(byte[] src, int length) { byte[] dest = new byte[length]; System.arraycopy(src, 0, dest, 0, Math.min(src.length, length)); return dest; }
3.26
dubbo_Bytes_long2bytes_rdh
/** * to byte array. * * @param v * value. * @param b * byte array. * @param off * array offset. */ public static void long2bytes(long v, byte[] b, int off) { b[off + 7] = ((byte) (v)); b[off + 6] = ((byte) (v >>> 8)); b[off + 5] = ((byte) (v >>> 16)); b[off + 4] = ((byte) (v >>> 24)); b[off + 3] = ((byte) (v >>> 32)); b[off + 2] = ((byte) (v >>> 40)); b[off + 1] = ((byte) (v >>> 48)); b[off + 0] = ((byte) (v >>> 56)); }
3.26
dubbo_Bytes_float2bytes_rdh
/** * to byte array. * * @param v * value. * @param b * byte array. * @param off * array offset. */ public static void float2bytes(float v, byte[] b, int off) { int i = Float.floatToIntBits(v); b[off + 3] = ((byte) (i)); b[off + 2] = ((byte) (i >>> 8));b[off + 1] = ((byte) (i >>> 16)); b[off + 0] = ((byte) (i >>> 24)); }
3.26
dubbo_Bytes_bytes2double_rdh
/** * to long. * * @param b * byte array. * @param off * offset. * @return double. */ public static double bytes2double(byte[] b, int off) { long j = ((((((((b[off + 7] & 0xffL) << 0) + ((b[off + 6] & 0xffL) << 8)) + ((b[off + 5] & 0xffL) << 16)) + ((b[off + 4] & 0xffL) << 24)) + ((b[off + 3] & 0xffL) << 32)) + ((b[off + 2] & 0xffL) << 40)) + ((b[off + 1] & 0xffL) << 48)) + (((long) (b[off + 0])) << 56); return Double.longBitsToDouble(j); }
3.26
dubbo_ModuleConfigManager_getDefaultConsumer_rdh
/** * Only allows one default ConsumerConfig */ public Optional<ConsumerConfig> getDefaultConsumer() { List<ConsumerConfig> consumerConfigs = getDefaultConfigs(getConfigsMap(getTagName(ConsumerConfig.class))); if (CollectionUtils.isNotEmpty(consumerConfigs)) { return Optional.of(consumerConfigs.get(0)); } return Optional.empty(); }
3.26
dubbo_ModuleConfigManager_m0_rdh
// ServiceConfig correlative methods public void m0(ServiceConfigBase<?> serviceConfig) { addConfig(serviceConfig); }
3.26
dubbo_ModuleConfigManager_findDuplicatedInterfaceConfig_rdh
/** * check duplicated ReferenceConfig/ServiceConfig * * @param config */ private AbstractInterfaceConfig findDuplicatedInterfaceConfig(AbstractInterfaceConfig config) { String uniqueServiceName; Map<String, AbstractInterfaceConfig> configCache; if (config instanceof ReferenceConfigBase) { return null; } else if (config instanceof ServiceConfigBase) { ServiceConfigBase serviceConfig = ((ServiceConfigBase) (config)); uniqueServiceName = serviceConfig.getUniqueServiceName(); configCache = serviceConfigCache; } else { throw new IllegalArgumentException("Illegal type of parameter 'config' : " + config.getClass().getName()); } AbstractInterfaceConfig prevConfig = configCache.putIfAbsent(uniqueServiceName, config); if (prevConfig != null) { if (prevConfig == config) { return prevConfig; } if (prevConfig.equals(config)) { // Is there any problem with ignoring duplicate and equivalent but different ReferenceConfig instances? if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Ignore duplicated and equal config: " + config); } return prevConfig; } String configType = config.getClass().getSimpleName(); String msg = ((((((((((("Found multiple " + configType) + "s with unique service name [") + uniqueServiceName) + "], previous: ") + prevConfig) + ", later: ") + config) + ". ") + "There can only be one instance of ") + configType) + " with the same triple (group, interface, version). ") + "If multiple instances are required for the same interface, please use a different group or version."; if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg);} if (!this.ignoreDuplicatedInterface) { throw new IllegalStateException(msg); } } return prevConfig; }
3.26
dubbo_ModuleConfigManager_getApplicationConfigManager_rdh
// // Delegate read application configs // public ConfigManager getApplicationConfigManager() { return f0; }
3.26
dubbo_ModuleConfigManager_getDefaultProvider_rdh
/** * Only allows one default ProviderConfig */ public Optional<ProviderConfig> getDefaultProvider() { List<ProviderConfig> providerConfigs = getDefaultConfigs(getConfigsMap(getTagName(ProviderConfig.class)));if (CollectionUtils.isNotEmpty(providerConfigs)) { return Optional.of(providerConfigs.get(0)); } return Optional.empty(); }
3.26
dubbo_ModuleConfigManager_addConsumer_rdh
// ConsumerConfig correlative methods public void addConsumer(ConsumerConfig consumerConfig) { addConfig(consumerConfig); }
3.26
dubbo_ModuleConfigManager_addReference_rdh
// ReferenceConfig correlative methods public void addReference(ReferenceConfigBase<?> referenceConfig) { addConfig(referenceConfig); }
3.26
dubbo_ConcurrentHashMapUtils_computeIfAbsent_rdh
/** * A temporary workaround for Java 8 ConcurrentHashMap#computeIfAbsent specific performance issue: JDK-8161372.</br> * * @see <a href="https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a> */ public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K key, Function<? super K, ? extends V> func) { Objects.requireNonNull(func); if (JRE.JAVA_8.isCurrentVersion()) { V v = map.get(key); if (null == v) { // issue#11986 lock bug // v = map.computeIfAbsent(key, func); // this bug fix methods maybe cause `func.apply` multiple calls. v = func.apply(key); if (null == v) { return null; } final V res = map.putIfAbsent(key, v); if (null != res) { // if pre value present, means other thread put value already, and putIfAbsent not effect // return exist value return res; } // if pre value is null, means putIfAbsent effected, return current value } return v; } else { return map.computeIfAbsent(key, func); } }
3.26
dubbo_Utf8Utils_isOneByte_rdh
/** * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ private static boolean isOneByte(byte b) { return b >= 0; }
3.26
dubbo_Utf8Utils_isNotTrailingByte_rdh
/** * Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ private static boolean isNotTrailingByte(byte b) { return b > ((byte) (0xbf)); }
3.26
dubbo_Utf8Utils_isThreeBytes_rdh
/** * Returns whether this is a three-byte codepoint with the form '110XXXXX'. */ private static boolean isThreeBytes(byte b) {return b < ((byte) (0xf0)); }
3.26
dubbo_Utf8Utils_trailingByteValue_rdh
/** * Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ private static int trailingByteValue(byte b) { return b & 0x3f; }
3.26
dubbo_Utf8Utils_isTwoBytes_rdh
/** * Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */ private static boolean isTwoBytes(byte b) { return b < ((byte) (0xe0)); }
3.26
dubbo_ExecutorUtil_m0_rdh
/** * append thread name with url address * * @return new url with updated thread name */ public static URL m0(URL url, String defaultName) { String v3 = url.getParameter(THREAD_NAME_KEY, defaultName); v3 = (v3 + "-") + url.getAddress(); url = url.addParameter(THREAD_NAME_KEY, v3); return url; }
3.26
dubbo_ExecutorUtil_gracefulShutdown_rdh
/** * Use the shutdown pattern from: * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html * * @param executor * the Executor to shutdown * @param timeout * the timeout in milliseconds before termination */ public static void gracefulShutdown(Executor executor, int timeout) { if ((!(executor instanceof ExecutorService)) || isTerminated(executor)) { return; } final ExecutorService es = ((ExecutorService) (executor)); try { // Disable new tasks from being submitted es.shutdown(); } catch (SecurityException | NullPointerException ex2) { return; } try { // Wait a while for existing tasks to terminate if (!es.awaitTermination(timeout, TimeUnit.MILLISECONDS)) { es.shutdownNow(); } } catch (InterruptedException ex) { es.shutdownNow(); Thread.currentThread().interrupt(); } if (!isTerminated(es)) { newThreadToCloseExecutor(es); } }
3.26
dubbo_MultiValueConverter_find_rdh
/** * Find the {@link MultiValueConverter} instance from {@link ExtensionLoader} with the specified source and target type * * @param sourceType * the source type * @param targetType * the target type * @return <code>null</code> if not found * @see ExtensionLoader#getSupportedExtensionInstances() * @since 2.7.8 * @deprecated will be removed in 3.3.0 */ @Deprecated static MultiValueConverter<?> find(Class<?> sourceType, Class<?> targetType) { return FrameworkModel.defaultModel().getExtensionLoader(MultiValueConverter.class).getSupportedExtensionInstances().stream().filter(converter -> converter.accept(sourceType, targetType)).findFirst().orElse(null); }
3.26
dubbo_MultiValueConverter_convertIfPossible_rdh
/** * * @deprecated will be removed in 3.3.0 */@Deprecated static <T> T convertIfPossible(Object source, Class<?> multiValueType, Class<?> elementType) { Class<?> sourceType = source.getClass(); MultiValueConverter converter = find(sourceType, multiValueType); if (converter != null) { return ((T) (converter.convert(source, multiValueType, elementType))); } return null; }
3.26
dubbo_ClientStreamObserver_disableAutoRequest_rdh
/** * Swaps to manual flow control where no message will be delivered to {@link StreamObserver#onNext(Object)} unless it is {@link #request request()}ed. Since {@code request()} may not be called before the call is started, a number of initial requests may be * specified. */ default void disableAutoRequest() { disableAutoFlowControl(); }
3.26
dubbo_MergerFactory_getActualTypeArgument_rdh
/** * get merger's actual type argument (same as return type) * * @param mergerCls * @return */ private Class<?> getActualTypeArgument(Class<? extends Merger> mergerCls) { Class<?> v5 = mergerCls; while (v5 != Object.class) { Type[] interfaceTypes = v5.getGenericInterfaces(); ParameterizedType mergerType; for (Type it : interfaceTypes) {if ((it instanceof ParameterizedType) && ((mergerType = ((ParameterizedType) (it))).getRawType() == Merger.class)) { Type typeArg = mergerType.getActualTypeArguments()[0]; return TypeUtils.getRawClass(typeArg); } } v5 = v5.getSuperclass(); } return null; }
3.26
dubbo_MergerFactory_getMerger_rdh
/** * Find the merger according to the returnType class, the merger will * merge an array of returnType into one * * @param returnType * the merger will return this type * @return the merger which merges an array of returnType into one, return null if not exist * @throws IllegalArgumentException * if returnType is null */public <T> Merger<T> getMerger(Class<T> returnType) { if (returnType == null) { throw new IllegalArgumentException("returnType is null"); } if (CollectionUtils.isEmptyMap(MERGER_CACHE)) { loadMergers(); } Merger merger = MERGER_CACHE.get(returnType); if ((merger == null) && returnType.isArray()) {merger = ArrayMerger.INSTANCE; } return merger; }
3.26
dubbo_ConfigurableMetadataServiceExporter_generateMethodConfig_rdh
/** * Generate Method Config for Service Discovery Metadata <p/> * <p> * Make {@link MetadataService} support argument callback, * used to notify {@link org.apache.dubbo.registry.client.ServiceInstance}'s * metadata change event * * @since 3.0 */ private List<MethodConfig> generateMethodConfig() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("getAndListenInstanceMetadata"); ArgumentConfig v2 = new ArgumentConfig(); v2.setIndex(1);v2.setCallback(true); methodConfig.setArguments(Collections.singletonList(v2)); return Collections.singletonList(methodConfig); }
3.26
dubbo_ConfigurableMetadataServiceExporter_setMetadataService_rdh
// for unit test public void setMetadataService(MetadataServiceDelegation metadataService) { this.metadataService = metadataService; }
3.26
dubbo_AbstractH2TransportListener_headersToMap_rdh
/** * Parse metadata to a KV pairs map. * * @param trailers * the metadata from remote * @return KV pairs map */ protected Map<String, Object> headersToMap(Http2Headers trailers, Supplier<Object> convertUpperHeaderSupplier) { if (trailers == null) { return Collections.emptyMap(); } Map<String, Object> v0 = new HashMap<>(trailers.size()); for (Map.Entry<CharSequence, CharSequence> header : trailers) { String key = header.getKey().toString(); if (key.endsWith(TripleConstant.HEADER_BIN_SUFFIX) && (key.length() > TripleConstant.HEADER_BIN_SUFFIX.length())) {try { String realKey = key.substring(0, key.length() - TripleConstant.HEADER_BIN_SUFFIX.length()); byte[] value = StreamUtils.decodeASCIIByte(header.getValue()); v0.put(realKey, value); } catch (Exception e) { LOGGER.error(PROTOCOL_FAILED_PARSE, "", "", "Failed to parse response attachment key=" + key, e); } } else { v0.put(key, header.getValue().toString()); } } // try converting upper key Object obj = convertUpperHeaderSupplier.get(); if (obj == null) { return v0; } if (obj instanceof String) { String json = TriRpcStatus.decodeMessage(((String) (obj))); Map<String, String> map = JsonUtils.toJavaObject(json, Map.class); for (Map.Entry<String, String> v8 : map.entrySet()) { Object v9 = v0.remove(v8.getKey()); if (v9 != null) { v0.put(v8.getValue(), v9); } } } else { // If convertUpperHeaderSupplier does not return String, just fail... // Internal invocation, use INTERNAL_ERROR instead. LOGGER.error(INTERNAL_ERROR, "wrong internal invocation", "", "Triple convertNoLowerCaseHeader error, obj is not String"); } return v0; }
3.26
MagicPlugin_ExprActiveSpell_acceptChange_rdh
// Eclipse detects the parent return type of this function as @NonNull // which is not correct. @SuppressWarnings("null") @Nullable @Override public Class<?>[] acceptChange(@Nonnull Changer.ChangeMode mode) { if ((mode != ChangeMode.SET) && (mode != ChangeMode.REMOVE_ALL)) return null; return new Class<?>[]{ String.class }; }
3.26
MagicPlugin_ExprActiveSpell_convert_rdh
// Eclipse detects the parent return type of this function as @NonNull // which is not correct. @SuppressWarnings("null") @Nullable @Override public String convert(final Player p) { assert false; return null; }
3.26
MagicPlugin_HeroesSpellSkill_getSkillName_rdh
/** * This code is redudant, but unfortunately it needs to be since we need to know the * skill name for the super() constructor call. */ private static String getSkillName(Heroes heroes, String spellKey) { Plugin magicPlugin = heroes.getServer().getPluginManager().getPlugin("Magic"); if ((magicPlugin == null) || ((!(magicPlugin instanceof MagicAPI)) && (!magicPlugin.isEnabled()))) { heroes.getLogger().warning("MagicHeroes skills require the Magic plugin"); throw new RuntimeException("MagicHeroes skills require the Magic plugin");} MagicAPI api = ((MagicAPI) (magicPlugin)); MageController controller = api.getController(); // This is unfortunately needed because Heroes tries to load these skills before // Magic has loaded spell configs ((MagicController) (controller)).checkPostStartupLoad(); SpellTemplate spellTemplate = controller.getSpellTemplate(spellKey); if (spellTemplate == null) { controller.getLogger().warning("Failed to load Magic skill spell: " + spellKey); throw new RuntimeException("Failed to load Magic skill spell: " + spellKey); } String baseName = ChatColor.stripColor(spellTemplate.getName().replace(" ", "")); return controller.getHeroesSkillPrefix() + baseName; }
3.26
MagicPlugin_CompatibilityUtilsBase_checkChunk_rdh
/** * Take care if setting generate to false, the chunk will load but not show as loaded */ @Override public boolean checkChunk(World world, int chunkX, int chunkZ, boolean generate) { if (!world.isChunkLoaded(chunkX, chunkZ)) { loadChunk(world, chunkX, chunkZ, generate);return false; } return isReady(world.getChunkAt(chunkX, chunkZ)); }
3.26
MagicPlugin_CompatibilityUtilsBase_toMinecraftAttribute_rdh
// Taken from CraftBukkit code. protected String toMinecraftAttribute(Attribute attribute) { String bukkit = attribute.name(); int first = bukkit.indexOf('_'); int second = bukkit.indexOf('_', first + 1); StringBuilder sb = new StringBuilder(bukkit.toLowerCase(Locale.ENGLISH)); sb.setCharAt(first, '.'); if (second != (-1)) { sb.deleteCharAt(second); sb.setCharAt(second, bukkit.charAt(second + 1)); } return sb.toString(); }
3.26
MagicPlugin_CompatibilityUtilsBase_loadChunk_rdh
/** * This will load chunks asynchronously if possible. * * <p>But note that it will never be truly asynchronous, it is important not to call this in a tight retry loop, * the main server thread needs to free up to actually process the async chunk loads. */ @Override public void loadChunk(World world, int x, int z, boolean generate, Consumer<Chunk> consumer) { PaperUtils paperUtils = platform.getPaperUtils(); if (paperUtils == null) { Chunk chunk = world.getChunkAt(x, z); chunk.load(); if (consumer != null) {consumer.accept(chunk); } return; } final LoadingChunk loading = new LoadingChunk(world, x, z); Integer requestCount = loadingChunks.get(loading); if (requestCount != null) { requestCount++; if (requestCount > MAX_CHUNK_LOAD_TRY) {platform.getLogger().warning("Exceeded retry count for asynchronous chunk load, loading synchronously"); if (!hasDumpedStack) { hasDumpedStack = true; Thread.dumpStack(); } Chunk chunk = world.getChunkAt(x, z); chunk.load(); if (consumer != null) { consumer.accept(chunk); } loadingChunks.remove(loading);return; }loadingChunks.put(loading, requestCount); return; } loadingChunks.put(loading, 1); paperUtils.loadChunk(world, x, z, generate, chunk -> {loadingChunks.remove(loading); if (consumer != null) { consumer.accept(chunk); } }); }
3.26
MagicPlugin_EntityController_onEntityDeath_rdh
/** * This death handler is for mobs and players alike */ @EventHandler(priority = EventPriority.LOWEST) public void onEntityDeath(EntityDeathEvent event) { Entity entity = event.getEntity(); boolean isPlayer = entity instanceof Player;if (isPlayer) { EntityDamageEvent.DamageCause cause = (entity.getLastDamageCause() == null) ? null : entity.getLastDamageCause().getCause(); controller.info((((("* Processing death of " + entity.getName()) + " from ") + cause) + " with drops: ") + event.getDrops().size(), 15); } Long spawnerId = CompatibilityLib.getEntityMetadataUtils().getLong(entity, MagicMetaKeys.AUTOMATION); if (spawnerId != null) { MagicBlock magicBlock = controller.getActiveAutomaton(spawnerId); if (magicBlock != null) { magicBlock.onSpawnDeath(); } } // Just don't ever clear player death drops, for real if (!isPlayer) { if (CompatibilityLib.getEntityMetadataUtils().getBoolean(entity, MagicMetaKeys.NO_DROPS)) { event.setDroppedExp(0); event.getDrops().clear(); } else { UndoList pendingUndo = controller.getEntityUndo(entity); if ((pendingUndo != null) && pendingUndo.isUndoType(entity.getType())) { event.getDrops().clear(); } } } else { // Clean up metadata that shouldn't be on players CompatibilityLib.getEntityMetadataUtils().remove(entity, MagicMetaKeys.NO_DROPS);} EntityDamageEvent damageEvent = event.getEntity().getLastDamageCause(); if (damageEvent instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent dbe = ((EntityDamageByEntityEvent) (damageEvent)); Entity damager = dbe.getDamager(); damager = controller.getDamageSource(damager); if (damager != null) { Mage damagerMage = controller.getRegisteredMage(damager); if (damagerMage != null) { damagerMage.trigger("kill"); } } } Mage mage = controller.getRegisteredMage(entity); if (mage == null) return; mage.deactivateAllSpells(); mage.onDeath(event); if (isPlayer) { controller.info("* Mage class handled death, drops now: " + event.getDrops().size(), 15); } if (event instanceof PlayerDeathEvent) { PlayerDeathEvent playerDeath = ((PlayerDeathEvent) (event)); handlePlayerDeath(playerDeath.getEntity(), mage, playerDeath.getDrops(), playerDeath.getKeepInventory()); } }
3.26
MagicPlugin_EntityController_handlePlayerDeath_rdh
/** * This death handler fires right away to close the wand inventory before other plugin * see the drops. */ public void handlePlayerDeath(Player player, Mage mage, List<ItemStack> drops, boolean isKeepInventory) { Wand wand = mage.getActiveWand(); // First, deactivate the active wand. // If it had a spell inventory open, restore the survival inventory // If keepInventory is not set, add the survival inventory to drops if (wand != null) { // Retrieve stored inventory before deactivating the wand if (mage.hasStoredInventory()) { controller.info("** Wand inventory was open, clearing drops: " + drops.size(), 15); // Remove the wand inventory from drops drops.clear(); // Deactivate the wand. wand.deactivate(); // Add restored inventory back to drops if (!isKeepInventory) { ItemStack[] stored = player.getInventory().getContents(); for (ItemStack stack : stored) { if (stack != null) { // Since armor is not stored in the wand inventory it will be removed from drops // and added back in, hopefully that causes no issues drops.add(stack); } } } controller.info("** Restored inventory added to drops: " + drops.size(), 15); } else { wand.deactivate(); } } if (isKeepInventory) { controller.info("** Keep inventory is set,", 15); return;} // The Equip action and other temporary item-giving spells will have given items to the respawn inventory // on death. Let's take those items out and add them to drops int dropSize = drops.size(); mage.addRespawnInventories(drops); mage.restoreRespawnInventories(); dropSize = drops.size() - dropSize; controller.info((("** Dropping " + dropSize) + " items that were given on death, drops now: ") + drops.size(), 15); // Now check for undroppable items. // Remove them from the inventory and drops list, and store them to give back on respawn // It should be OK if some plugin wants to come in after this and turn keep inventory back on, // it'll keep the inventory without any of the "keep" items (since we removed them), and hopefully // Things will merge back together properly in the end. PlayerInventory inventory = player.getInventory(); ItemStack[] contents = inventory.getContents(); for (int index = 0; index < contents.length; index++) { ItemStack itemStack = contents[index]; if ((itemStack == null) || (itemStack.getType() == Material.AIR)) continue; // Remove temporary items from inventory and drops if (CompatibilityLib.getItemUtils().isTemporary(itemStack)) {ItemStack replacement = CompatibilityLib.getItemUtils().getReplacement(itemStack); if (!CompatibilityLib.getItemUtils().isEmpty(replacement)) { drops.add(replacement); } drops.remove(itemStack); controller.info((((("** Removing temporary item from drops: " + TextUtils.nameItem(itemStack)) + " (replaced with ") + TextUtils.nameItem(itemStack)) + ") drops now: ") + drops.size(), 15); contents[index] = null; continue;} // Save "keep" items to return on respawn boolean keepItem = CompatibilityLib.getNBTUtils().getBoolean(itemStack, "keep", false);if (((!keepItem) && keepWandsOnDeath) && Wand.isWand(itemStack)) keepItem = true; if (keepItem) { mage.addToRespawnInventory(index, itemStack); contents[index] = null; drops.remove(itemStack); controller.info(((("** Removing keep item from drops: " + TextUtils.nameItem(itemStack)) + ChatColor.RESET) + ", drops now: ") + drops.size(), 15); } else if (Wand.isSkill(itemStack)) { drops.remove(itemStack); contents[index] = null; controller.info(((("** Removing skill item from drops: " + TextUtils.nameItem(itemStack)) + ChatColor.RESET) + ", drops now: ") + drops.size(), 15); } }inventory.setContents(contents); controller.info("** Done processing death with drops remaining: " + drops.size(), 15); }
3.26
MagicPlugin_BaseSpell_onCancelSelection_rdh
/** * Called when a material selection spell is cancelled mid-selection. */public boolean onCancelSelection() { return false; }
3.26
MagicPlugin_BaseSpell_castMessage_rdh
/* Functions to send text to player- use these to respect "quiet" and "silent" modes. */ /** * Send a message to a player when a spell is cast. * * @param message * The message to send */ @Override public void castMessage(String message) { Wand activeWand = mage.getActiveWand(); // First check wand if (((!loud) && (activeWand != null)) && (!activeWand.showCastMessages())) return; if ((((!quiet) && canSendMessage()) && (message != null)) && (message.length() > 0)) { if (currentCast != null) { message = currentCast.parameterize(message);} mage.castMessage(message); lastMessageSent = System.currentTimeMillis(); }}
3.26
MagicPlugin_BaseSpell_initialize_rdh
/** * Used internally to initialize the Spell, do not call. * * @param instance * The spells instance */ @Override public void initialize(MageController instance) { this.controller = instance; }
3.26
MagicPlugin_BaseSpell_updateItem_rdh
// Returns non-null if the item needs an update... not sure this is needed, looks like it's just for skulls though public ItemStack updateItem(ItemStack spellItem, boolean canCast) { ItemStack needsUpdate = null; MaterialAndData disabledIcon = getDisabledIcon(); MaterialAndData spellIcon = getIcon(); String urlIcon = getIconURL(); String disabledUrlIcon = getDisabledIconURL(); boolean usingURLIcon = useUrlIcon(mage); if (((disabledIcon != null) && (spellIcon != null)) && (!usingURLIcon)) { if ((!canCast) || (!isEnabled())) { if (disabledIcon.isValid() && disabledIcon.isDifferent(spellItem)) { disabledIcon.applyToItem(spellItem);} } else if (spellIcon.isValid() && spellIcon.isDifferent(spellItem)) { spellIcon.applyToItem(spellItem); } } else if (((usingURLIcon && (disabledUrlIcon != null)) && (!disabledUrlIcon.isEmpty())) && DefaultMaterials.isSkull(spellItem.getType())) { String currentURL = CompatibilityLib.getInventoryUtils().getSkullURL(spellItem); if (!canCast) { if (!disabledUrlIcon.equals(currentURL)) {spellItem = CompatibilityLib.getInventoryUtils().setSkullURL(spellItem, disabledUrlIcon); needsUpdate = spellItem; } } else if (!urlIcon.equals(currentURL)) { spellItem = CompatibilityLib.getInventoryUtils().setSkullURL(spellItem, urlIcon); needsUpdate = spellItem; } } return needsUpdate; }
3.26
MagicPlugin_BaseSpell_m0_rdh
// Material @Deprecated public boolean m0(Material mat) { if ((mage != null) && mage.isSuperPowered()) { return true; } if ((passthroughMaterials != null) && passthroughMaterials.testMaterial(mat)) { return true; } return (preventPassThroughMaterials == null) || (!preventPassThroughMaterials.testMaterial(mat)); }
3.26
MagicPlugin_BaseSpell_onPlayerQuit_rdh
/** * Listener method, called on player quit for registered spells. * * @param event * The player who just quit */ public void onPlayerQuit(PlayerQuitEvent event) { }
3.26
MagicPlugin_BaseSpell_clone_rdh
// // Cloneable implementation // @Nullable @Override public Object clone() { try { return super.clone();} catch (CloneNotSupportedException ex) { return null; } }
3.26