name
stringlengths 12
178
| code_snippet
stringlengths 8
36.5k
| score
float64 3.26
3.68
|
---|---|---|
dubbo_ConsumerMethodModel_addAttribute_rdh | // public ConcurrentMap<String, Object> getAttributeMap() {
// return attributeMap;
// }
public void addAttribute(String key, Object value) {
this.attributeMap.put(key, value); } | 3.26 |
dubbo_MetadataService_getServiceDefinition_rdh | /**
* Interface definition.
*
* @return */
default String getServiceDefinition(String interfaceName, String version, String group) {
return getServiceDefinition(buildKey(interfaceName, group, version));
} | 3.26 |
dubbo_MetadataService_getExportedURLs_rdh | /**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code>, <code>group</code> and <code>version</code>
*
* @param serviceInterface
* The class name of Dubbo service interface
* @param group
* the Dubbo Service Group (optional)
* @param version
* the Dubbo Service Version (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface, String group, String version) {return getExportedURLs(serviceInterface, group,
version, null);
} | 3.26 |
dubbo_MetadataService_version_rdh | /**
* Gets the version of {@link MetadataService} that always equals {@link #VERSION}
*
* @return non-null
* @see #VERSION
*/
default String version() {
return
VERSION;
} | 3.26 |
dubbo_MetadataService_getSubscribedURLs_rdh | /**
* the list of String that presents all Dubbo subscribed {@link URL urls}
*
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getSubscribedURLs() {
throw new UnsupportedOperationException("This operation is not supported for consumer.");
} | 3.26 |
dubbo_MetadataService_toSortedStrings_rdh | /**
* Convert the specified {@link Stream} of {@link URL URLs} to be the {@link URL#toFullString() strings} presenting
* the {@link URL URLs}
*
* @param stream
* {@link Stream} of {@link URL}
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting
* @see URL#toFullString()
*/
static SortedSet<String> toSortedStrings(Stream<URL> stream) {
return unmodifiableSortedSet(stream.map(URL::toFullString).collect(TreeSet::new, Set::add, Set::addAll));
} | 3.26 |
dubbo_MetadataReport_publishAppMetadata_rdh | /**
* Application Metadata -- START
*/
default void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
} | 3.26 |
dubbo_MetadataReport_getServiceAppMapping_rdh | /**
* Service<-->Application Mapping -- START
*/
default Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
return Collections.emptySet();
} | 3.26 |
dubbo_LruCacheFactory_createCache_rdh | /**
* Takes url as an method argument and return new instance of cache store implemented by LruCache.
*
* @param url
* url of the method
* @return ThreadLocalCache instance of cache
*/
@Overrideprotected Cache createCache(URL url) {
return new LruCache(url);
} | 3.26 |
dubbo_DynamicConfiguration_getRuleKey_rdh | /**
* The format is '{interfaceName}:[version]:[group]'
*
* @return */
static String getRuleKey(URL url) {
return url.getColonSeparatedKey();
} | 3.26 |
dubbo_DynamicConfiguration_getConfigItem_rdh | /**
* get configItem which contains content and stat info.
*
* @param key
* @param group
* @return */
default ConfigItem getConfigItem(String key, String group) {
String content = getConfig(key, group);
return new ConfigItem(content, null);
} | 3.26 |
dubbo_DynamicConfiguration_getDefaultGroup_rdh | /**
* Get the default group for the operations
*
* @return The default value is {@link #DEFAULT_GROUP "dubbo"}
* @since 2.7.5
*/
default String getDefaultGroup() {
return DEFAULT_GROUP;
} | 3.26 |
dubbo_DynamicConfiguration_publishConfig_rdh | /**
* Publish Config mapped to the given key and the given group.
*
* @param key
* the key to represent a configuration
* @param group
* the group where the key belongs to
* @param content
* the content of configuration
* @return <code>true</code> if success, or <code>false</code>
* @throws UnsupportedOperationException
* If the under layer does not support
* @since 2.7.5
*/
default boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException {
return false;
} | 3.26 |
dubbo_DynamicConfiguration_removeConfig_rdh | /**
*
* @param key
* the key to represent a configuration
* @param group
* the group where the key belongs to
* @return <code>true</code> if success, or <code>false</code>
* @since 2.7.8
*/
default boolean removeConfig(String key, String group) {
return true;
} | 3.26 |
dubbo_DynamicConfiguration_close_rdh | /**
* Close the configuration
*
* @throws Exception
* @since 2.7.5
*/
@Override
default void close() throws Exception {
throw new UnsupportedOperationException();
} | 3.26 |
dubbo_DynamicConfiguration_addListener_rdh | /**
* {@link #addListener(String, String, ConfigurationListener)}
*
* @param key
* the key to represent a configuration
* @param listener
* configuration listener
*/
default void addListener(String key, ConfigurationListener listener) {
addListener(key,
getDefaultGroup(), listener);
} | 3.26 |
dubbo_DynamicConfiguration_getConfig_rdh | /**
* Get the configuration mapped to the given key and the given group with {@link #getDefaultTimeout() the default
* timeout}
*
* @param key
* the key to represent a configuration
* @param group
* the group where the key belongs to
* @return target configuration mapped to the given key and the given group
*/
default String getConfig(String key, String group) {
return getConfig(key, group, getDefaultTimeout());
} | 3.26 |
dubbo_DynamicConfiguration_getProperties_rdh | /**
* This method are mostly used to get a compound config file, such as a complete dubbo.properties file.
*
* @revision 2.7.4
*/
default String getProperties(String key, String group, long timeout) throws IllegalStateException {
return getConfig(key, group, timeout);
} | 3.26 |
dubbo_DynamicConfiguration_publishConfigCas_rdh | /**
* publish config mapped to this given key and given group with stat.
*
* @param key
* @param group
* @param content
* @param ticket
* @return * @throws UnsupportedOperationException
*/
default boolean publishConfigCas(String key, String group, String content,
Object ticket) throws UnsupportedOperationException {
return false;
} | 3.26 |
dubbo_DynamicConfiguration_removeListener_rdh | /**
* {@link #removeListener(String, String, ConfigurationListener)}
*
* @param key
* the key to represent a configuration
* @param listener
* configuration listener
*/
default void removeListener(String key, ConfigurationListener listener) {
removeListener(key, getDefaultGroup(), listener);
} | 3.26 |
dubbo_DubboProtocol_buildReferenceCountExchangeClientList_rdh | /**
* Bulk build client
*
* @param url
* @param connectNum
* @return */
private List<ReferenceCountExchangeClient> buildReferenceCountExchangeClientList(URL url, int connectNum) {
List<ReferenceCountExchangeClient> clients = new
ArrayList<>();
for (int i = 0; i < connectNum; i++) {
clients.add(buildReferenceCountExchangeClient(url));
}
return clients;
} | 3.26 |
dubbo_DubboProtocol_initClient_rdh | /**
* Create new connection
*
* @param url
*/
private ExchangeClient initClient(URL url) {
/* Instance of url is InstanceAddressURL, so addParameter actually adds parameters into ServiceInstance,
which means params are shared among different services. Since client is shared among services this is currently not a problem.
*/
String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT));
// BIO is not allowed since it has severe performance issue.
if (StringUtils.isNotEmpty(str) && (!url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).hasExtension(str))) {
throw new RpcException(((("Unsupported client type: " + str) + ",") + " supported client type is ") + StringUtils.join(url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).getSupportedExtensions(), " "));
}
try {
ScopeModel scopeModel = url.getScopeModel();
int heartbeat = UrlUtils.getHeartbeat(url);
// Replace InstanceAddressURL with ServiceConfigURL.
url = new ServiceConfigURL(DubboCodec.NAME, url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), url.getAllParameters());
url
= url.addParameter(CODEC_KEY, DubboCodec.NAME);
// enable heartbeat by default
url = url.addParameterIfAbsent(HEARTBEAT_KEY, Integer.toString(heartbeat));
url = url.setScopeModel(scopeModel);
// connection should be lazy
return url.getParameter(LAZY_CONNECT_KEY, false) ? new LazyConnectExchangeClient(url, requestHandler) : Exchangers.connect(url, requestHandler);
} catch (RemotingException e) {
throw new RpcException((("Fail to create remoting client for service(" + url) + "): ") + e.getMessage(), e);
}
} | 3.26 |
dubbo_DubboProtocol_buildReferenceCountExchangeClient_rdh | /**
* Build a single client
*
* @param url
* @return */
private ReferenceCountExchangeClient buildReferenceCountExchangeClient(URL url) {
ExchangeClient exchangeClient = initClient(url);
ReferenceCountExchangeClient client = new ReferenceCountExchangeClient(exchangeClient, DubboCodec.NAME);
// read configs
int shutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(url.getScopeModel());client.setShutdownWaitTime(shutdownTimeout);
return client;
} | 3.26 |
dubbo_DubboProtocol_getDubboProtocol_rdh | /**
*
* @deprecated Use {@link DubboProtocol#getDubboProtocol(ScopeModel)} instead
*/
@Deprecated
public static DubboProtocol getDubboProtocol() {
return ((DubboProtocol) (FrameworkModel.defaultModel().getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false)));
} | 3.26 |
dubbo_DubboProtocol_getSharedClient_rdh | /**
* Get shared connection
*
* @param url
* @param connectNum
* connectNum must be greater than or equal to 1
*/
@SuppressWarnings("unchecked")
private SharedClientsProvider getSharedClient(URL url, int connectNum) {
String key = url.getAddress();
// connectNum must be greater than or equal to 1
int expectedConnectNum = Math.max(connectNum, 1);
return referenceClientMap.compute(key, (originKey, originValue) -> {
if ((originValue != null) && originValue.increaseCount()) {
return originValue;
} else {
return new SharedClientsProvider(this, originKey, buildReferenceCountExchangeClientList(url, expectedConnectNum));
}
});
} | 3.26 |
dubbo_DubboProtocol_createInvocation_rdh | /**
* FIXME channel.getUrl() always binds to a fixed service, and this service is random.
* we can choose to use a common service to carry onConnect event if there's no easy way to get the specific
* service this connection is binding to.
*
* @param channel
* @param url
* @param methodKey
* @return */
private Invocation createInvocation(Channel channel,
URL url, String methodKey) {
String method
= url.getParameter(methodKey);
if ((method == null) || (method.length() == 0)) {
return null;
}
RpcInvocation invocation = new RpcInvocation(url.getServiceModel(), method, url.getParameter(INTERFACE_KEY), "", new Class<?>[0], new Object[0]);
invocation.setAttachment(PATH_KEY, url.getPath());
invocation.setAttachment(GROUP_KEY, url.getGroup());
invocation.setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY));
invocation.setAttachment(VERSION_KEY, url.getVersion());
if (url.getParameter(STUB_EVENT_KEY, false)) {
invocation.setAttachment(STUB_EVENT_KEY, Boolean.TRUE.toString());
}
return invocation;
} | 3.26 |
dubbo_DubboProtocol_getInvocationWithoutData_rdh | /**
* only log body in debugger mode for size & security consideration.
*
* @param invocation
* @return */
private Invocation getInvocationWithoutData(Invocation invocation) {
if (logger.isDebugEnabled())
{ return invocation;
}
if (invocation instanceof RpcInvocation) {
RpcInvocation rpcInvocation = ((RpcInvocation) (invocation));
rpcInvocation.setArguments(null);
return rpcInvocation;}
return invocation;
} | 3.26 |
dubbo_DefaultSerializeClassChecker_loadClass_rdh | /**
* Try load class
*
* @param className
* class name
* @throws IllegalArgumentException
* if class is blocked
*/
public Class<?> loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
Class<?>
aClass = loadClass0(classLoader, className);
if ((!aClass.isPrimitive()) && (!Serializable.class.isAssignableFrom(aClass))) {
String msg = (("[Serialization Security] Serialized class " + className) + " has not implement Serializable interface. ") + "Current mode is strict check, will disallow to deserialize it by default. ";
if (serializeSecurityManager.getWarnedClasses().add(className)) {
logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg);
}
if (checkSerializable) {throw new IllegalArgumentException(msg);
}
}
return aClass;
} | 3.26 |
dubbo_ArrayUtils_isNotEmpty_rdh | /**
* <p>Checks if the array is not null or empty. <p/>
*
* @param array
* th array to check
* @return {@code true} if the array is not null or empty.
*/
public static boolean isNotEmpty(final Object[] array) {
return !isEmpty(array);
} | 3.26 |
dubbo_ArrayUtils_of_rdh | /**
* Convert from variable arguments to array
*
* @param values
* variable arguments
* @param <T>
* The class
* @return array
* @since 2.7.9
*/
public static <T> T[] of(T... values) {
return values;
} | 3.26 |
dubbo_ArrayUtils_isEmpty_rdh | /**
* <p>Checks if the array is null or empty. <p/>
*
* @param array
* th array to check
* @return {@code true} if the array is null or empty.
*/
public static boolean isEmpty(final Object[] array) {
return (array == null) ||
(array.length == 0);
} | 3.26 |
dubbo_GsonUtils_setSupportGson_rdh | /**
*
* @deprecated for uts only
*/
@Deprecated
protected static void setSupportGson(Boolean supportGson) {
GsonUtils.supportGson = supportGson;
} | 3.26 |
dubbo_DeadlineFuture_newFuture_rdh | /**
* init a DeadlineFuture 1.init a DeadlineFuture 2.timeout check
*
* @param timeout
* timeout in Mills
* @return a new DeadlineFuture
*/
public static DeadlineFuture newFuture(String serviceName, String methodName, String address, int timeout, ExecutorService executor) {
final DeadlineFuture future = new
DeadlineFuture(serviceName, methodName, address, timeout);
future.m0(executor);
return future;
} | 3.26 |
dubbo_AbstractMetadataReport_getMetadataReportRetry_rdh | /**
*
* @deprecated only for unit test
*/
@Deprecated
protected MetadataReportRetry getMetadataReportRetry() {
return metadataReportRetry;
} | 3.26 |
dubbo_AbstractMetadataReport_retry_rdh | /**
*
* @return if need to continue
*/
public boolean retry() {
return doHandleMetadataCollection(failedReports);
} | 3.26 |
dubbo_AbstractMetadataReport_calculateStartTime_rdh | /**
* between 2:00 am to 6:00 am, the time is random.
*
* @return */
long
calculateStartTime() {
Calendar calendar = Calendar.getInstance();
long nowMill = calendar.getTimeInMillis();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long subtract = (calendar.getTimeInMillis() + ONE_DAY_IN_MILLISECONDS) - nowMill;
return (subtract + (FOUR_HOURS_IN_MILLISECONDS / 2))
+ ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS);
} | 3.26 |
dubbo_AbstractMetadataReport_getRetryExecutor_rdh | /**
*
* @deprecated only for test
*/
@Deprecated
ScheduledExecutorService getRetryExecutor() {
return retryExecutor;
} | 3.26 |
dubbo_AbstractMetadataReport_publishAll_rdh | /**
* not private. just for unittest.
*/
void publishAll() {
logger.info("start to publish all metadata.");
this.doHandleMetadataCollection(allMetadataReports);
} | 3.26 |
dubbo_AbstractMetadataReport_getReportCacheExecutor_rdh | /**
*
* @deprecated only for unit test
*/
@Deprecated
protected ExecutorService getReportCacheExecutor() {
return reportCacheExecutor;
} | 3.26 |
dubbo_AbortPolicyWithReport_dispatchThreadPoolExhaustedEvent_rdh | /**
* dispatch ThreadPoolExhaustedEvent
*
* @param msg
*/
public void dispatchThreadPoolExhaustedEvent(String msg) {
f0.forEach(listener -> listener.onEvent(new ThreadPoolExhaustedEvent(msg)));
} | 3.26 |
dubbo_BitList_clear_rdh | /**
* Caution: This operation will clear originList for removing references purpose.
* This may change the default behaviour when adding new element later.
*/
@Override
public void
clear() {
rootSet.clear();
// to remove references
originList = Collections.emptyList();
if (CollectionUtils.isNotEmpty(tailList)) {
tailList =
null;
}
} | 3.26 |
dubbo_BitList_and_rdh | /**
* And operation between two bitList. Return a new cloned list.
* TailList in source bitList will be totally saved even if it is not appeared in the target bitList.
*
* @param target
* target bitList
* @return this bitList only contains those elements contain in both two list and source bitList's tailList
*/
public BitList<E> and(BitList<E> target) {
rootSet.and(target.rootSet);
if (target.getTailList() != null) {
target.getTailList().forEach(this::addToTailList);
}
return this;
} | 3.26 |
dubbo_BitList_getOriginList_rdh | // Provided by BitList only
public List<E> getOriginList() {
return originList;} | 3.26 |
dubbo_AbstractHttpClientFactory_beforeCreated_rdh | // ////////////////////////////////////// implements end ///////////////////////////////////////////////
// ////////////////////////////////////// inner methods ///////////////////////////////////////////////
protected void beforeCreated(URL url) {
} | 3.26 |
dubbo_AbstractHttpClientFactory_createRestClient_rdh | // ////////////////////////////////////// implements start ///////////////////////////////////////////////
@Override
public RestClient createRestClient(URL url) throws RpcException {
beforeCreated(url);
// create a raw client
RestClient restClient =
doCreateRestClient(url);
// postprocessor
afterCreated(restClient);
return restClient;
} | 3.26 |
dubbo_MethodConfig_checkDefault_rdh | /**
* Set default field values of MethodConfig.
*
* @see org.apache.dubbo.config.annotation.Method
*/
@Override
protected void checkDefault() {
super.checkDefault();
// set default field values
// org.apache.dubbo.config.annotation.Method.isReturn() default true;
if (isReturn() == null) {
setReturn(true);
}
// org.apache.dubbo.config.annotation.Method.sent() default true;
if (getSent() == null) {
setSent(true);
}
} | 3.26 |
dubbo_MethodConfig_getPrefixes_rdh | /**
* Get method prefixes
*
* @return */
@Override
@Parameter(excluded = true, attribute = false)
public List<String> getPrefixes() {
// parent prefix + method name
if (parentPrefix != null) { List<String> prefixes = new ArrayList<>();
prefixes.add((parentPrefix + ".") + this.getName());
return prefixes;
} else {
throw
new IllegalStateException("The parent prefix of MethodConfig is null");
}
} | 3.26 |
dubbo_MethodConfig_constructMethodConfig_rdh | /**
* TODO remove constructMethodConfig
*
* @param methods
* @return */
@Deprecated
public static List<MethodConfig> constructMethodConfig(Method[] methods) {
if ((methods != null) && (methods.length != 0)) {
List<MethodConfig> methodConfigs = new ArrayList<>(methods.length);
for (int i = 0; i < methods.length; i++) {
MethodConfig methodConfig = new MethodConfig(methods[i]);
methodConfigs.add(methodConfig);
}
return methodConfigs;
}
return Collections.emptyList();
} | 3.26 |
dubbo_AbstractServiceDiscovery_update_rdh | /**
* Update assumes that DefaultServiceInstance and its attributes will never get updated once created.
* Checking hasExportedServices() before registration guarantees that at least one service is ready for creating the
* instance.
*/
@Override
public synchronized void update() throws RuntimeException {if (isDestroy) {
return;
}
if (this.serviceInstance == null) {
register();
}
if (!isValidInstance(this.serviceInstance)) {
return;
}
ServiceInstance oldServiceInstance =
this.serviceInstance;
DefaultServiceInstance newServiceInstance = new DefaultServiceInstance(((DefaultServiceInstance) (oldServiceInstance)));
boolean revisionUpdated = calOrUpdateInstanceRevision(newServiceInstance);
if (revisionUpdated) {
logger.info(String.format("Metadata of instance changed, updating instance with revision %s.", newServiceInstance.getServiceMetadata().getRevision()));
doUpdate(oldServiceInstance, newServiceInstance);
this.serviceInstance = newServiceInstance;
}
} | 3.26 |
dubbo_AbstractServiceDiscovery_doUpdate_rdh | /**
* Update Service Instance. Unregister and then register by default.
* Can be override if registry support update instance directly.
* <br/>
* NOTICE: Remind to update {@link AbstractServiceDiscovery#serviceInstance}'s reference if updated
* and report metadata by {@link AbstractServiceDiscovery#reportMetadata(MetadataInfo)}
*
* @param oldServiceInstance
* origin service instance
* @param newServiceInstance
* new service instance
*/
protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) {
this.doUnregister(oldServiceInstance);
this.serviceInstance = newServiceInstance;
if (!EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance))) { reportMetadata(newServiceInstance.getServiceMetadata());
this.doRegister(newServiceInstance);}
} | 3.26 |
dubbo_ClassHelper_forName_rdh | /**
* Replacement for <code>Class.forName()</code> that also returns Class
* instances for primitives (like "int") and array class names (like
* "String[]").
*
* @param name
* the name of the Class
* @param classLoader
* the class loader to use (may be <code>null</code>,
* which indicates the default class loader)
* @return Class instance for the supplied name
* @throws ClassNotFoundException
* if the class was not found
* @throws LinkageError
* if the class file could not be loaded
* @see Class#forName(String, boolean, ClassLoader)
*/
public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
return ClassUtils.forName(name, classLoader);
}
/**
* Resolve the given class name as primitive class, if appropriate,
* according to the JVM's naming rules for primitive classes.
* <p>
* Also supports the JVM's internal class names for primitive arrays. Does
* <i>not</i> support the "[]" suffix notation for primitive arrays; this is
* only supported by {@link #forName} | 3.26 |
dubbo_ClassHelper_isTypeMatch_rdh | /**
* We only check boolean value at this moment.
*
* @param type
* @param value
* @return */
public static boolean isTypeMatch(Class<?> type, String value)
{
return ClassUtils.isTypeMatch(type, value);} | 3.26 |
dubbo_ClassHelper_isSetter_rdh | /**
*
* @see org.apache.dubbo.common.utils.MethodUtils#isSetter(Method)
* @deprecated Replace to <code>MethodUtils#isSetter(Method)</code>
*/
public static boolean isSetter(Method method) {
return MethodUtils.isSetter(method);
} | 3.26 |
dubbo_ClassHelper_m0_rdh | /**
*
* @see org.apache.dubbo.common.utils.ClassUtils
* @deprecated Replace to <code>ClassUtils</code>
*/
| 3.26 |
dubbo_ClassHelper_isGetter_rdh | /**
*
* @see org.apache.dubbo.common.utils.MethodUtils#isGetter(Method) (Method)
* @deprecated Replace to <code>MethodUtils#isGetter(Method)</code>
*/
public static boolean isGetter(Method method) {
return MethodUtils.isGetter(method);
} | 3.26 |
dubbo_ClassHelper_getClassLoader_rdh | /**
* get class loader
*
* @param clazz
* @return class loader
*/
public static ClassLoader getClassLoader(Class<?> clazz) {
return ClassUtils.getClassLoader(clazz);
} | 3.26 |
dubbo_PropertySourcesUtils_getPropertyNames_rdh | /**
* Get the property names as the array from the specified {@link PropertySource} instance.
*
* @param propertySource
* {@link PropertySource} instance
* @return non-null
*/
public static String[] getPropertyNames(PropertySource propertySource) {
String[] propertyNames = (propertySource instanceof EnumerablePropertySource) ? ((EnumerablePropertySource) (propertySource)).getPropertyNames()
: null;
if (propertyNames == null) {
propertyNames = ObjectUtils.EMPTY_STRING_ARRAY;
}
return propertyNames;
} | 3.26 |
dubbo_PropertySourcesUtils_normalizePrefix_rdh | /**
* Normalize the prefix
*
* @param prefix
* the prefix
* @return the prefix
*/
public static String normalizePrefix(String prefix) {
return prefix.endsWith(".") ? prefix : prefix + ".";
} | 3.26 |
dubbo_PropertySourcesUtils_getSubProperties_rdh | /**
* Get prefixed {@link Properties}
*
* @param propertySources
* {@link PropertySources}
* @param propertyResolver
* {@link PropertyResolver} to resolve the placeholder if present
* @param prefix
* the prefix of property name
* @return Map
* @see Properties
*/
public static Map<String, Object> getSubProperties(PropertySources propertySources, PropertyResolver propertyResolver, String prefix) {
Map<String, Object> subProperties = new LinkedHashMap<String, Object>();
String normalizedPrefix = normalizePrefix(prefix);
Iterator<PropertySource<?>> iterator = propertySources.iterator();
while (iterator.hasNext()) {
PropertySource<?> source = iterator.next();
for (String name : getPropertyNames(source)) {
if ((!subProperties.containsKey(name)) && name.startsWith(normalizedPrefix)) {
String subName = name.substring(normalizedPrefix.length());
if (!subProperties.containsKey(subName)) {
// take first one
Object value = source.getProperty(name);
if (value instanceof String) {
// Resolve placeholder
value = propertyResolver.resolvePlaceholders(((String) (value)));
}
subProperties.put(subName, value);
}
}
}
}
return unmodifiableMap(subProperties);
} | 3.26 |
dubbo_MetricsGlobalRegistry_getCompositeRegistry_rdh | /**
* Use CompositeMeterRegistry according to the following priority
* 1. If useGlobalRegistry is configured, use the micrometer global CompositeMeterRegistry
* 2. If there is a spring actuator, use spring's CompositeMeterRegistry
* 3. Dubbo's own CompositeMeterRegistry is used by default
*/
public static CompositeMeterRegistry getCompositeRegistry(ApplicationModel applicationModel) { Optional<MetricsConfig> configOptional = applicationModel.getApplicationConfigManager().getMetrics();
if ((configOptional.isPresent() && (configOptional.get().getUseGlobalRegistry() != null)) && configOptional.get().getUseGlobalRegistry()) {
return Metrics.globalRegistry;} else {return compositeRegistry;
}
} | 3.26 |
dubbo_URLStrParser_m0_rdh | /**
*
* @param encodedURLStr
* : after {@link URL#encode(String)} string
* encodedURLStr after decode format: protocol://username:password@host:port/path?k1=v1&k2=v2
* [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2]
*/
public static URL m0(String encodedURLStr) {
Map<String, String> parameters = null;
int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F");// '?'
if
(pathEndIdx >= 0) {
parameters = parseEncodedParams(encodedURLStr, pathEndIdx + 3);
} else {
pathEndIdx = encodedURLStr.length();
}
// decodedBody format: [protocol://][username:password@][host:port]/[path]
String decodedBody = decodeComponent(encodedURLStr, 0, pathEndIdx, false, DECODE_TEMP_BUF.get());
return parseURLBody(encodedURLStr, decodedBody, parameters);
} | 3.26 |
dubbo_URLStrParser_parseDecodedStr_rdh | /**
*
* @param decodedURLStr
* : after {@link URL#decode} string
* decodedURLStr format: protocol://username:password@host:port/path?k1=v1&k2=v2
* [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2]
*/
public static URL parseDecodedStr(String decodedURLStr) {
Map<String, String> parameters = null;
int pathEndIdx = decodedURLStr.indexOf('?');
if (pathEndIdx >= 0) {
parameters = parseDecodedParams(decodedURLStr, pathEndIdx + 1);
} else {
pathEndIdx = decodedURLStr.length();
}
String
decodedBody = decodedURLStr.substring(0, pathEndIdx);
return parseURLBody(decodedURLStr, decodedBody, parameters);
} | 3.26 |
dubbo_NopDynamicConfiguration_publishConfig_rdh | /**
*
* @since 2.7.5
*/
@Override
public boolean publishConfig(String key, String group, String
content) {
return true;
} | 3.26 |
dubbo_DubboAbstractTDigest_m0_rdh | /**
* Compute the weighted average between <code>x1</code> with a weight of
* <code>w1</code> and <code>x2</code> with a weight of <code>w2</code>.
* This expects <code>x1</code> to be less than or equal to <code>x2</code>
* and is guaranteed to return a number in <code>[x1, x2]</code>. An
* explicit check is required since this isn't guaranteed with floating-point
* numbers.
*/
private static double m0(double x1, double w1, double x2, double w2) {
assert x1 <= x2;
final double x = ((x1 * w1) + (x2 * w2)) / (w1
+ w2);
return Math.max(x1, Math.min(x, x2));
} | 3.26 |
dubbo_DubboAbstractTDigest_add_rdh | /**
* Adds a sample to a histogram.
*
* @param x
* The value to add.
*/
@Override
public void add(double x) {
add(x, 1);
} | 3.26 |
dubbo_DubboAbstractTDigest_weightedAverage_rdh | /**
* Same as {@link #weightedAverageSorted(double, double, double, double)} but flips
* the order of the variables if <code>x2</code> is greater than
* <code>x1</code>.
*/
static double weightedAverage(double x1, double w1, double x2, double w2) {
if (x1 <= x2) {
return m0(x1, w1, x2, w2);
} else {
return m0(x2, w2, x1, w1);
}
} | 3.26 |
dubbo_ParamParserManager_consumerParamParse_rdh | /**
* consumer Design Description:
* <p>
* Object[] args=new Object[0];
* List<Object> argsList=new ArrayList<>;</>
* <p>
* setValueByIndex(int index,Object value);
* <p>
* args=toArray(new Object[0]);
*/
public static void consumerParamParse(ConsumerParseContext parseContext) {
List<ArgInfo> argInfos = parseContext.getArgInfos();
for (int i = 0; i < argInfos.size(); i++) {
for (BaseConsumerParamParser v5 : consumerParamParsers) {
ArgInfo argInfoByIndex = parseContext.getArgInfoByIndex(i);
if (!v5.paramTypeMatch(argInfoByIndex)) {
continue;
}
v5.parse(parseContext, argInfoByIndex);
}
}
// TODO add param require or default
} | 3.26 |
dubbo_ParamParserManager_providerParamParse_rdh | /**
* provider Design Description:
* <p>
* Object[] args=new Object[0];
* List<Object> argsList=new ArrayList<>;</>
* <p>
* setValueByIndex(int index,Object value);
* <p>
* args=toArray(new Object[0]);
*/
public static Object[] providerParamParse(ProviderParseContext parseContext) {List<ArgInfo> args = parseContext.getArgInfos();
for (int i = 0; i < args.size(); i++)
{
for (ParamParser paramParser : providerParamParsers) {
paramParser.parse(parseContext, args.get(i));
}
}
// TODO add param require or default & body arg size pre judge
return parseContext.getArgs().toArray(new Object[0]);
} | 3.26 |
dubbo_DubboCertManager_generatePemKey_rdh | /**
* Generate content in pem encoded
*
* @param type
* content type
* @param content
* content
* @return encoded data
* @throws IOException
* ioException
*/
private String generatePemKey(String type, byte[] content) throws IOException {
PemObject v26 = new PemObject(type, content);
StringWriter str = new StringWriter();
JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(str);
jcaPEMWriter.writeObject(v26);
jcaPEMWriter.close();
str.close();
return str.toString();
} | 3.26 |
dubbo_DubboCertManager_generatePrivatePemKey_rdh | /**
* Generate private key in pem encoded
*
* @param keyPair
* key pair
* @return private key
* @throws IOException
* ioException
*/
private String generatePrivatePemKey(KeyPair keyPair) throws
IOException {String key = generatePemKey("RSA PRIVATE KEY", keyPair.getPrivateKey().getEncoded());
if
(logger.isDebugEnabled()) {
logger.debug("Generated Private Key. \n" + key);
}
return key;
} | 3.26 |
dubbo_DubboCertManager_signWithRsa_rdh | /**
* Generate key pair with RSA
*
* @return key pair
*/
protected static KeyPair signWithRsa() {
KeyPair keyPair = null;try {
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
kpGenerator.initialize(4096);
KeyPair keypair = kpGenerator.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey privateKey = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate());
keyPair = new KeyPair(publicKey, privateKey, signer);
} catch (NoSuchAlgorithmException | OperatorCreationException e) {
logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", e);
}
return keyPair;} | 3.26 |
dubbo_DubboCertManager_signWithEcdsa_rdh | /**
* Generate key pair with ECDSA
*
* @return key pair
*/ protected
static KeyPair signWithEcdsa() {
KeyPair keyPair = null;
try {
ECGenParameterSpec ecSpec =
new ECGenParameterSpec("secp256r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
g.initialize(ecSpec, new SecureRandom());
KeyPair keypair = g.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey v23 = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(v23);
keyPair = new KeyPair(publicKey, v23, signer);
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) {
logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Key with secp256r1 algorithm failed. Please check if your system support. " + "Will attempt to generate with RSA2048.", e);
}
return keyPair;
} | 3.26 |
dubbo_DubboCertManager_connect0_rdh | /**
* Try to connect to remote certificate authorization
*
* @param certConfig
* certificate authorization address
*/
protected void connect0(CertConfig certConfig)
{
String caCertPath = certConfig.getCaCertPath();
String remoteAddress = certConfig.getRemoteAddress();
logger.info((("Try to connect to Dubbo Cert Authority server: " + remoteAddress) + ", caCertPath: ") + remoteAddress);
try {
if (StringUtils.isNotEmpty(caCertPath)) {
channel = NettyChannelBuilder.forTarget(remoteAddress).sslContext(GrpcSslContexts.forClient().trustManager(new File(caCertPath)).build()).build();
} else {
logger.warn(CONFIG_SSL_CONNECT_INSECURE, "", "", "No caCertPath is provided, will use insecure connection.");
channel = NettyChannelBuilder.forTarget(remoteAddress).sslContext(GrpcSslContexts.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()).build();
}} catch (Exception e) {
logger.error(LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load SSL cert file.", e);
throw
new RuntimeException(e);
}
} | 3.26 |
dubbo_DubboCertManager_scheduleRefresh_rdh | /**
* Create task to refresh cert pair for current Dubbo instance
*/
protected void scheduleRefresh() {
FrameworkExecutorRepository repository = frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class);
refreshFuture = repository.getSharedScheduledExecutor().scheduleAtFixedRate(this::generateCert, certConfig.getRefreshInterval(), certConfig.getRefreshInterval(), TimeUnit.MILLISECONDS);
} | 3.26 |
dubbo_DubboCertManager_generateCsr_rdh | /**
* Generate CSR (Certificate Sign Request)
*
* @param keyPair
* key pair to request
* @return csr
* @throws IOException
* ioException
*/private String generateCsr(KeyPair keyPair) throws IOException {
PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder(new X500Name("O=" + "cluster.domain"), keyPair.getPublicKey()).build(keyPair.m0());
String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded());
if (logger.isDebugEnabled()) {
logger.debug("CSR Request to Dubbo Certificate Authorization. \n" + csr);
}
return csr;
} | 3.26 |
dubbo_DubboCertManager_refreshCert_rdh | /**
* Request remote certificate authorization to generate cert pair for current Dubbo instance
*
* @return cert pair
* @throws IOException
* ioException
*/
protected CertPair refreshCert() throws IOException {
KeyPair keyPair = signWithEcdsa();
if (keyPair == null) {
keyPair = signWithRsa();
}
if (keyPair == null) {
logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Key failed. Please check if your system support.");
return null;
}
String csr = generateCsr(keyPair);
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub = DubboCertificateServiceGrpc.newBlockingStub(channel);
stub = setHeaderIfNeed(stub);
String privateKeyPem = generatePrivatePemKey(keyPair);
DubboCertificateResponse certificateResponse = stub.createCertificate(generateRequest(csr));
if ((certificateResponse == null) || (!certificateResponse.getSuccess())) {
logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", ("Failed to generate cert from Dubbo Certificate Authority. " + "Message: ") + (certificateResponse == null ? "null" : certificateResponse.getMessage()));
return null;
}
logger.info("Successfully generate cert from Dubbo Certificate Authority. Cert expire time: " + certificateResponse.getExpireTime());
return new CertPair(privateKeyPem, certificateResponse.getCertPem(), String.join("\n", certificateResponse.getTrustCertsList()), certificateResponse.getExpireTime());
} | 3.26 |
dubbo_XdsRouter_getXdsRouteRuleMap_rdh | /**
* for ut only
*/
@Deprecated
ConcurrentHashMap<String, List<XdsRouteRule>> getXdsRouteRuleMap() {
return xdsRouteRuleMap;
} | 3.26 |
dubbo_AbstractMetricsKeyListener_isSupport_rdh | /**
* The MetricsKey type determines whether events are supported
*/
@Override
public boolean isSupport(MetricsEvent event) {return super.isSupport(event) && event.isAssignableFrom(metricsKey);
} | 3.26 |
dubbo_RegistryDirectory_destroyAllInvokers_rdh | /**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {
Map<URL, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;// local reference
if (!CollectionUtils.isEmptyMap(localUrlInvokerMap)) {
for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {
try {
invoker.destroy();
} catch (Throwable t) {
// 1-15 - Failed to destroy service
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", (("Failed to destroy service " + serviceKey) + " to provider ") + invoker.getUrl(), t);
}
}
localUrlInvokerMap.clear();
}
this.urlInvokerMap = null;
this.cachedInvokerUrls = null;
destroyInvokers();
} | 3.26 |
dubbo_RegistryDirectory_m2_rdh | /**
* Haomin: added for test purpose
*/
public Map<URL, Invoker<T>> m2() {
return urlInvokerMap;
} | 3.26 |
dubbo_RegistryDirectory_toInvokers_rdh | /**
* Turn urls into invokers, and if url has been referred, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap
* it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<URL, Invoker<T>> toInvokers(Map<URL, Invoker<T>> oldUrlInvokerMap, List<URL> urls)
{
Map<URL, Invoker<T>> newUrlInvokerMap = new ConcurrentHashMap<>(urls == null ? 1 : ((int) ((urls.size() / 0.75F) + 1)));
if ((urls == null) || urls.isEmpty()) {
return newUrlInvokerMap;
}
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
for (URL providerUrl : urls) {
if
(!checkProtocolValid(queryProtocols, providerUrl)) {
continue;
}
URL v31 = mergeUrl(providerUrl);
// Cache key is url that does not merge with consumer side parameters,
// regardless of how the consumer combines parameters,
// if the server url changes, then refer again
Invoker<T>
invoker = (oldUrlInvokerMap == null) ? null : oldUrlInvokerMap.remove(v31);
if (invoker == null) {
// Not in the cache, refer again
try {
boolean v33 = true;if (v31.hasParameter(DISABLED_KEY)) {
v33 = !v31.getParameter(DISABLED_KEY, false);
} else {
v33 = v31.getParameter(ENABLED_KEY, true);
}if (v33) {
invoker = protocol.refer(serviceType, v31);
}
} catch (Throwable t) {// Thrown by AbstractProtocol.optimizeSerialization()
if ((t instanceof RpcException) && t.getMessage().contains("serialization optimizer")) {
// 4-2 - serialization optimizer class initialization failed.
logger.error(PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER, "typo in optimizer class", "", (((("Failed to refer invoker for interface:" + serviceType) + ",url:(") + v31) + ")") + t.getMessage(), t);
} else {
// 4-3 - Failed to refer invoker by other reason.
logger.error(PROTOCOL_FAILED_REFER_INVOKER, "", "", (((("Failed to refer invoker for interface:" + serviceType) + ",url:(") + v31) + ")") + t.getMessage(),
t);
}
}
if (invoker != null) {
// Put new invoker in cache
newUrlInvokerMap.put(v31, invoker);
}
} else {
newUrlInvokerMap.put(v31, invoker);
}
}
return newUrlInvokerMap;
} | 3.26 |
dubbo_RegistryDirectory_mergeUrl_rdh | /**
* Merge url parameters. the order is: override > -D >Consumer > Provider
*
* @param providerUrl
* @return */
private URL mergeUrl(URL providerUrl) {
if (providerUrl instanceof ServiceAddressURL) {
providerUrl = overrideWithConfigurator(providerUrl);
} else {
providerUrl = moduleModel.getApplicationModel().getBeanFactory().getBean(ClusterUtils.class).mergeUrl(providerUrl, queryMap);// Merge the consumer side parameters
providerUrl = overrideWithConfigurator(providerUrl);
providerUrl = providerUrl.addParameter(Constants.CHECK_KEY, String.valueOf(false));// Do not check whether the connection is successful or not, always create Invoker!
}
// FIXME, kept for mock
if (providerUrl.hasParameter(MOCK_KEY) || (providerUrl.getAnyMethodParameter(MOCK_KEY) != null)) {
providerUrl = providerUrl.removeParameter(MOCK_KEY);
}
if (((providerUrl.getPath() == null) || (providerUrl.getPath().length() == 0)) && DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) {
// Compatible version 1.0
// fix by tony.chenl DUBBO-44
String path = directoryUrl.getServiceInterface();
if (path
!=
null) {
int i = path.indexOf('/');
if (i >= 0) {
path = path.substring(i + 1);
}
i =
path.lastIndexOf(':');
if (i >= 0) {
path = path.substring(0, i);
}
providerUrl = providerUrl.setPath(path);
}
}
return providerUrl;
} | 3.26 |
dubbo_ServiceBuilder_build_rdh | // @Override
// public ServiceBuilder<U> mock(String mock) {
// throw new IllegalArgumentException("mock doesn't support on provider side");
// }
// @Override
// public ServiceBuilder<U> mock(Boolean mock) {
// throw new IllegalArgumentException("mock doesn't support on provider side");
// }
public ServiceConfig<U> build() {
ServiceConfig<U> serviceConfig = new ServiceConfig<>();
super.build(serviceConfig);
serviceConfig.setInterface(interfaceName);
serviceConfig.setInterface(interfaceClass);
serviceConfig.setRef(ref);
serviceConfig.setPath(path);
serviceConfig.setMethods(f0);
serviceConfig.setProvider(provider);
serviceConfig.setProviderIds(providerIds);serviceConfig.setGeneric(generic);
return serviceConfig;
} | 3.26 |
dubbo_DubboNamespaceHandler_parse_rdh | /**
* Override {@link NamespaceHandlerSupport#parse(Element, ParserContext)} method
*
* @param element
* {@link Element}
* @param parserContext
* {@link ParserContext}
* @return * @since 2.7.5
*/
@Override
public BeanDefinition parse(Element element, ParserContext
parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
registerAnnotationConfigProcessors(registry);
// initialize dubbo beans
DubboSpringInitializer.initialize(parserContext.getRegistry());
BeanDefinition beanDefinition = super.parse(element, parserContext);
setSource(beanDefinition);
return beanDefinition;
} | 3.26 |
dubbo_DubboNamespaceHandler_init_rdh | /**
* DubboNamespaceHandler
*
* @export */public class DubboNamespaceHandler extends NamespaceHandlerSupport implements ConfigurableSourceBeanMetadataElement {
@Override
public void init() {
registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class));
registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class));
registerBeanDefinitionParser("registry",
new DubboBeanDefinitionParser(RegistryConfig.class));
registerBeanDefinitionParser("config-center", new DubboBeanDefinitionParser(ConfigCenterBean.class));
registerBeanDefinitionParser("metadata-report", new DubboBeanDefinitionParser(MetadataReportConfig.class));
registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class));registerBeanDefinitionParser("metrics", new DubboBeanDefinitionParser(MetricsConfig.class));
registerBeanDefinitionParser("tracing", new DubboBeanDefinitionParser(TracingConfig.class));
registerBeanDefinitionParser("ssl", new DubboBeanDefinitionParser(SslConfig.class));
registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class));registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class));
registerBeanDefinitionParser("protocol", new
DubboBeanDefinitionParser(ProtocolConfig.class));
registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class));
registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class));
registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser());
} | 3.26 |
dubbo_DubboNamespaceHandler_registerAnnotationConfigProcessors_rdh | /**
* Register the processors for the Spring Annotation-Driven features
*
* @param registry
* {@link BeanDefinitionRegistry}
* @see AnnotationConfigUtils
* @since 2.7.5
*/
private void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(registry);
} | 3.26 |
dubbo_TypeDefinitionBuilder_build_rdh | /**
* Build the instance of {@link TypeDefinition} from the specified {@link TypeMirror type}
*
* @param processingEnv
* {@link ProcessingEnvironment}
* @param type
* {@link TypeMirror type}
* @return non-null
*/
static TypeDefinition build(ProcessingEnvironment processingEnv, TypeMirror type,
Map<String, TypeDefinition> typeCache) {
// Build by all instances of TypeDefinitionBuilder that were loaded By Java SPI
TypeDefinition typeDefinition = // load(TypeDefinitionBuilder.class, TypeDefinitionBuilder.class.getClassLoader())
ApplicationModel.defaultModel().getExtensionLoader(TypeBuilder.class).getSupportedExtensionInstances().stream().filter(builder -> builder.accept(processingEnv, type)).findFirst().map(builder -> {
return builder.build(processingEnv, type, typeCache);
// typeDefinition.setTypeBuilderName(builder.getClass().getName());
}).orElse(null);
if (typeDefinition != null)
{
typeCache.put(typeDefinition.getType(), typeDefinition);
}
return typeDefinition;
} | 3.26 |
dubbo_DefaultFuture_newFuture_rdh | /**
* init a DefaultFuture
* 1.init a DefaultFuture
* 2.timeout check
*
* @param channel
* channel
* @param request
* the request
* @param timeout
* timeout
* @return a new DefaultFuture
*/
public static DefaultFuture newFuture(Channel channel, Request request, int timeout, ExecutorService executor) {
final DefaultFuture future = new DefaultFuture(channel, request, timeout);
future.m0(executor);
// timeout check
timeoutCheck(future);
return future;
} | 3.26 |
dubbo_DefaultFuture_closeChannel_rdh | /**
* close a channel when a channel is inactive
* directly return the unfinished requests.
*
* @param channel
* channel to close
*/
public static void closeChannel(Channel channel, long timeout) {
long deadline = (timeout > 0) ? System.currentTimeMillis() + timeout : 0;
for (Map.Entry<Long, Channel> entry : f0.entrySet()) {
if (channel.equals(entry.getValue())) {
DefaultFuture future = getFuture(entry.getKey());
if ((future != null) && (!future.isDone())) {
long restTime = deadline - System.currentTimeMillis();
if (restTime > 0)
{
try {
future.get(restTime, TimeUnit.MILLISECONDS);
} catch (TimeoutException ignore) {
logger.warn(PROTOCOL_TIMEOUT_SERVER, "", "", (((("Trying to close channel " + channel) + ", but response is not received in ") + timeout) + "ms, and the request id is ") + future.id);} catch (Throwable ignore) {
}
}
if (!future.isDone()) {
respInactive(channel, future);
}
}
}
}
} | 3.26 |
dubbo_TaskQueue_retryOffer_rdh | /**
* retry offer task
*
* @param o
* task
* @return offer success or not
* @throws RejectedExecutionException
* if executor is terminated.
*/
public boolean retryOffer(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
if (executor.isShutdown()) {
throw new RejectedExecutionException("Executor is shutdown!");
}
return super.offer(o, timeout, unit);
} | 3.26 |
dubbo_DubboSpringInitContext_setKeepRunningOnSpringClosed_rdh | /**
* Keep Dubbo running when spring is stopped
*
* @param keepRunningOnSpringClosed
*/
public void setKeepRunningOnSpringClosed(boolean keepRunningOnSpringClosed) {
this.setModuleAttribute(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED, keepRunningOnSpringClosed);
} | 3.26 |
dubbo_ServiceDiscoveryRegistryDirectory_destroyAllInvokers_rdh | /**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {Map<ProtocolServiceKeyWithAddress, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;// local reference
if (localUrlInvokerMap
!= null) {
for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {try {
invoker.destroy();
} catch (Throwable t) {
logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "",
"", (("Failed to destroy service " + serviceKey) + " to provider ") + invoker.getUrl(), t);
}
}
localUrlInvokerMap.clear();
}
this.urlInvokerMap = null;
this.destroyInvokers();
} | 3.26 |
dubbo_ServiceDiscoveryRegistryDirectory_destroyUnusedInvokers_rdh | /**
* Check whether the invoker in the cache needs to be destroyed
* If set attribute of url: refer.autodestroy=false, the invokers will only increase without decreasing,there may be a refer leak
*
* @param oldUrlInvokerMap
* @param newUrlInvokerMap
*/
private void destroyUnusedInvokers(Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap, Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap) {if ((newUrlInvokerMap == null) || (newUrlInvokerMap.size() == 0)) {
destroyAllInvokers();
return;
}
if ((oldUrlInvokerMap == null) || (oldUrlInvokerMap.size() == 0)) {
return;
}
for (Map.Entry<ProtocolServiceKeyWithAddress, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) {
Invoker<T> v44 =
entry.getValue();
if (v44 != null)
{
try {
v44.destroy();
if (logger.isDebugEnabled())
{
logger.debug(("destroy invoker[" + v44.getUrl()) + "] success. ");
}
} catch (Exception e) {
logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", (("destroy invoker[" +
v44.getUrl()) + "]failed.") + e.getMessage(), e);
}
}
}
logger.info(oldUrlInvokerMap.size() + " deprecated invokers deleted.");
} | 3.26 |
dubbo_ServiceDiscoveryRegistryDirectory_toInvokers_rdh | /**
* Turn urls into invokers, and if url has been refer, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap
* it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<ProtocolServiceKeyWithAddress, Invoker<T>> toInvokers(Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap, List<URL> urls) {
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap = new ConcurrentHashMap<>(urls == null ? 1 : ((int) ((urls.size() / 0.75F) + 1)));
if ((urls == null) || urls.isEmpty()) {
return newUrlInvokerMap;
}
for (URL url : urls) {
InstanceAddressURL instanceAddressURL = ((InstanceAddressURL) (url));
if (EMPTY_PROTOCOL.equals(instanceAddressURL.getProtocol())) {
continue;
}
if (!getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).hasExtension(instanceAddressURL.getProtocol())) {
// 4-1 - Unsupported protocol
logger.error(PROTOCOL_UNSUPPORTED, "protocol extension does not installed", "", "Unsupported protocol.", new IllegalStateException((((((((("Unsupported protocol " + instanceAddressURL.getProtocol()) + " in notified url: ") + instanceAddressURL) + " from registry ") + getUrl().getAddress()) + " to consumer ") + NetUtils.getLocalHost()) + ", supported protocol: ") + getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions()));
continue;
}
instanceAddressURL.setProviderFirstParams(providerFirstParams);
// Override provider urls if needed
if (enableConfigurationListen) {
instanceAddressURL = overrideWithConfigurator(instanceAddressURL);
}
// filter all the service available (version wildcard, group wildcard, protocol wildcard)
int
port = instanceAddressURL.getPort();
List<ProtocolServiceKey> matchedProtocolServiceKeys = instanceAddressURL.getMetadataInfo().getMatchedServiceInfos(consumerProtocolServiceKey).stream().filter(serviceInfo -> (serviceInfo.getPort() <= 0) || (serviceInfo.getPort() == port)).map(MetadataInfo.ServiceInfo::getProtocolServiceKey).collect(Collectors.toList());
// see org.apache.dubbo.common.ProtocolServiceKey.isSameWith
// check if needed to override the consumer url
boolean shouldWrap = (matchedProtocolServiceKeys.size() != 1) || (!consumerProtocolServiceKey.isSameWith(matchedProtocolServiceKeys.get(0)));
for (ProtocolServiceKey v26 : matchedProtocolServiceKeys) {
ProtocolServiceKeyWithAddress protocolServiceKeyWithAddress = new ProtocolServiceKeyWithAddress(v26, instanceAddressURL.getAddress());
Invoker<T> invoker = (oldUrlInvokerMap == null) ? null : oldUrlInvokerMap.get(protocolServiceKeyWithAddress);
if ((invoker == null) || urlChanged(invoker, instanceAddressURL, v26)) {
// Not in the cache, refer again
try {
boolean enabled;
if (instanceAddressURL.hasParameter(DISABLED_KEY)) {
enabled = !instanceAddressURL.getParameter(DISABLED_KEY, false);
} else {
enabled = instanceAddressURL.getParameter(ENABLED_KEY, true);
}
if (enabled) {
if (shouldWrap) {
URL newConsumerUrl = ConcurrentHashMapUtils.computeIfAbsent(customizedConsumerUrlMap, v26, k -> consumerUrl.setProtocol(k.getProtocol()).addParameter(CommonConstants.GROUP_KEY, k.getGroup()).addParameter(CommonConstants.VERSION_KEY, k.getVersion()));
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
invoker = new InstanceWrappedInvoker<>(protocol.refer(serviceType, instanceAddressURL), newConsumerUrl, v26);
} else {
invoker = protocol.refer(serviceType, instanceAddressURL);
}
}
} catch (Throwable t) {
logger.error(PROTOCOL_FAILED_REFER_INVOKER, "", "", (((("Failed to refer invoker for interface:" + serviceType) + ",url:(") + instanceAddressURL) + ")") + t.getMessage(), t);
}
if (invoker != null) {
// Put new invoker in cache
newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker);
}} else {
newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker);oldUrlInvokerMap.remove(protocolServiceKeyWithAddress, invoker);
}
}
}
return newUrlInvokerMap;
} | 3.26 |
dubbo_ReferenceAnnotationBeanPostProcessor_isAnnotatedReferenceBean_rdh | /**
* check whether is @DubboReference at java-config @bean method
*/
private boolean isAnnotatedReferenceBean(BeanDefinition beanDefinition) {
if (beanDefinition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annotatedBeanDefinition = ((AnnotatedBeanDefinition) (beanDefinition));String beanClassName = SpringCompatUtils.getFactoryMethodReturnType(annotatedBeanDefinition);
if ((beanClassName != null) && ReferenceBean.class.getName().equals(beanClassName)) {
return true;
}
}
return false;} | 3.26 |
dubbo_ReferenceAnnotationBeanPostProcessor_getInjectedFieldReferenceBeanMap_rdh | /**
* Get {@link ReferenceBean} {@link Map} in injected field.
*
* @return non-null {@link Map}
* @since 2.5.11
*/
public Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> getInjectedFieldReferenceBeanMap() {
Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> map = new HashMap<>();
for (Map.Entry<InjectionMetadata.InjectedElement, String> entry : injectedFieldReferenceBeanCache.entrySet()) {
map.put(entry.getKey(), referenceBeanManager.getById(entry.getValue()));
}
return Collections.unmodifiableMap(map);
} | 3.26 |
dubbo_ReferenceAnnotationBeanPostProcessor_m0_rdh | /**
* Get {@link ReferenceBean} {@link Map} in injected method.
*
* @return non-null {@link Map}
* @since 2.5.11
*/
public Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> m0() {
Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> map = new HashMap<>();for (Map.Entry<InjectionMetadata.InjectedElement, String> v54 : injectedMethodReferenceBeanCache.entrySet()) {
map.put(v54.getKey(), referenceBeanManager.getById(v54.getValue()));
}
return Collections.unmodifiableMap(map);
} | 3.26 |
dubbo_ReferenceAnnotationBeanPostProcessor_postProcessProperties_rdh | /**
* Alternatives to the {@link #postProcessPropertyValues(PropertyValues, PropertyDescriptor[], Object, String)}.
*
* @see #postProcessPropertyValues
*/
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
try {
AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, bean.getClass(), pvs);
prepareInjection(metadata);
metadata.inject(bean, beanName, pvs);
} catch (BeansException ex) {throw ex;
} catch (Throwable ex) {
throw new BeanCreationException(beanName, ("Injection of @" + getAnnotationType().getSimpleName()) + " dependencies is failed", ex);
}
return pvs;
} | 3.26 |
dubbo_ReferenceAnnotationBeanPostProcessor_processReferenceAnnotatedBeanDefinition_rdh | /**
* process @DubboReference at java-config @bean method
* <pre class="code">
* @Configuration
* public class ConsumerConfig {
*
* @Bean
* @DubboReference(group="demo", version="1.2.3")
* public ReferenceBean<DemoService> demoService() {
* return new ReferenceBean();
* }
*
* }
* </pre>
*
* @param beanName
* @param beanDefinition
*/
private void processReferenceAnnotatedBeanDefinition(String beanName, AnnotatedBeanDefinition
beanDefinition) {
MethodMetadata factoryMethodMetadata = SpringCompatUtils.getFactoryMethodMetadata(beanDefinition);
// Extract beanClass from generic return type of java-config bean method: ReferenceBean<DemoService>
// see
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBeanFromMethod
Class beanClass = getBeanFactory().getType(beanName);
if (beanClass == Object.class) {
beanClass = SpringCompatUtils.getGenericTypeOfReturnType(factoryMethodMetadata);
}
if (beanClass == Object.class) {
// bean class is invalid, ignore it
return;
}
if (beanClass == null) {
String beanMethodSignature = ((factoryMethodMetadata.getDeclaringClassName() + "#") + factoryMethodMetadata.getMethodName()) + "()";
throw new BeanCreationException((("The ReferenceBean is missing necessary generic type, which returned by the @Bean method of Java-config class. " + "The generic type of the returned ReferenceBean must be specified as the referenced interface type, ") + "such as ReferenceBean<DemoService>. Please check bean method: ") + beanMethodSignature);
}
// get dubbo reference annotation attributes
Map<String, Object> annotationAttributes = null;
// try all dubbo reference annotation types
for (Class<? extends Annotation> annotationType : getAnnotationTypes()) {
if (factoryMethodMetadata.isAnnotated(annotationType.getName())) {
// Since Spring 5.2
// return factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap();
// Compatible with Spring 4.x
annotationAttributes = factoryMethodMetadata.getAnnotationAttributes(annotationType.getName());
annotationAttributes = filterDefaultValues(annotationType, annotationAttributes);
break;
}
}
if (annotationAttributes != null) {
// @DubboReference on @Bean method
LinkedHashMap<String, Object> attributes = new LinkedHashMap<>(annotationAttributes);
// reset id attribute
attributes.put(ReferenceAttributes.ID, beanName);
// convert annotation props
ReferenceBeanSupport.convertReferenceProps(attributes, beanClass);
// get interface
String interfaceName = ((String) (attributes.get(ReferenceAttributes.INTERFACE)));
// check beanClass and reference interface class
if ((!StringUtils.isEquals(interfaceName, beanClass.getName())) && (beanClass != GenericService.class)) {
String beanMethodSignature = ((factoryMethodMetadata.getDeclaringClassName() + "#") + factoryMethodMetadata.getMethodName()) + "()";
throw new BeanCreationException((((((((("The 'interfaceClass' or 'interfaceName' attribute value of @DubboReference annotation " + "is inconsistent with the generic type of the ReferenceBean returned by the bean method. ") + "The interface class of @DubboReference is: ") + interfaceName) + ", but return ReferenceBean<") + beanClass.getName()) + ">. ") + "Please remove the 'interfaceClass' and 'interfaceName' attributes from @DubboReference annotation. ") + "Please check bean method: ") + beanMethodSignature);
}
Class interfaceClass = beanClass;
// set attribute instead of property values
beanDefinition.setAttribute(Constants.REFERENCE_PROPS, attributes);
beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, interfaceClass);
beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_NAME, interfaceName);
} else {
// raw reference bean
// the ReferenceBean is not yet initialized
beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, beanClass);
if (beanClass != GenericService.class) {
beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_NAME, beanClass.getName());
}
}
// set id
beanDefinition.getPropertyValues().add(ReferenceAttributes.ID, beanName);
} | 3.26 |
dubbo_ReferenceAnnotationBeanPostProcessor_postProcessPropertyValues_rdh | /**
* Alternatives to the {@link #postProcessProperties(PropertyValues, Object, String)}, that removed as of Spring
* Framework 6.0.0, and in favor of {@link #postProcessProperties(PropertyValues, Object, String)}.
* <p>In order to be compatible with the lower version of Spring, it is still retained.
*
* @see #postProcessProperties
*/
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return postProcessProperties(pvs, bean, beanName);
} | 3.26 |