name
stringlengths 12
178
| code_snippet
stringlengths 8
36.5k
| score
float64 3.26
3.68
|
---|---|---|
dubbo_ServicePackagesHolder_isSubPackage_rdh | /**
* Whether test package is sub package of parent package
*
* @param testPkg
* @param parent
* @return */
private boolean isSubPackage(String testPkg, String parent) {// child pkg startsWith parent pkg
return testPkg.startsWith(parent);
} | 3.26 |
dubbo_ThrowableAction_execute_rdh | /**
* Executes {@link ThrowableAction}
*
* @param action
* {@link ThrowableAction}
* @throws RuntimeException
* wrap {@link Exception} to {@link RuntimeException}
*/
static void execute(ThrowableAction action) throws RuntimeException {
try {
action.execute();
} catch (Throwable e) {
throw new RuntimeException(e);
}
} | 3.26 |
dubbo_QosProtocolWrapper_stopServer_rdh | /* package */
void stopServer() {
if (hasStarted.compareAndSet(true, false)) {
Server server = frameworkModel.getBeanFactory().getBean(Server.class);
if (server.isStarted()) {
server.stop();
}
}
} | 3.26 |
dubbo_Pane_isTimeInWindow_rdh | /**
* Check whether given timestamp is in current pane.
*
* @param timeMillis
* timestamp in milliseconds.
* @return true if the given time is in current pane, otherwise false
*/
public boolean
isTimeInWindow(long timeMillis) {// [)
return (startInMs
<= timeMillis) && (timeMillis
< endInMs);
} | 3.26 |
dubbo_Pane_setStartInMs_rdh | /**
* Set the new start timestamp to the pane, for reset the instance.
*
* @param newStartInMs
* the new start timestamp.
*/
public void setStartInMs(long newStartInMs) {
this.startInMs = newStartInMs;
this.endInMs = this.startInMs + this.intervalInMs;
} | 3.26 |
dubbo_Pane_setValue_rdh | /**
* Set new value to the pane, for reset the instance.
*
* @param newData
* the new value.
*/
public void setValue(T newData) {
this.value = newData;
} | 3.26 |
dubbo_EnvironmentUtils_filterDubboProperties_rdh | /**
* Filters Dubbo Properties from {@link ConfigurableEnvironment}
*
* @param environment
* {@link ConfigurableEnvironment}
* @return Read-only SortedMap
*/public static SortedMap<String, String> filterDubboProperties(ConfigurableEnvironment environment) {
SortedMap<String, String> dubboProperties = new TreeMap<>();
Map<String, Object> properties = extractProperties(environment);
for
(Map.Entry<String, Object> entry : properties.entrySet()) {
String propertyName = entry.getKey();
if (propertyName.startsWith(DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR) && (entry.getValue() != null)) {
dubboProperties.put(propertyName, environment.resolvePlaceholders(entry.getValue().toString()));
}}
return Collections.unmodifiableSortedMap(dubboProperties);
} | 3.26 |
dubbo_EnvironmentUtils_extractProperties_rdh | /**
* Extras The properties from {@link ConfigurableEnvironment}
*
* @param environment
* {@link ConfigurableEnvironment}
* @return Read-only Map
*/
public static Map<String, Object> extractProperties(ConfigurableEnvironment environment) {
return Collections.unmodifiableMap(doExtraProperties(environment));
} | 3.26 |
dubbo_RpcUtils_m0_rdh | // check parameterTypesDesc to fix CVE-2020-1948
public static boolean m0(String parameterTypesDesc, String method) {
return
($INVOKE.equals(method) || $INVOKE_ASYNC.equals(method)) && GENERIC_PARAMETER_DESC.equals(parameterTypesDesc);
} | 3.26 |
dubbo_RpcUtils_attachInvocationIdIfAsync_rdh | /**
* Idempotent operation: invocation id will be added in async operation by default
*
* @param url
* @param inv
*/
public static void attachInvocationIdIfAsync(URL url, Invocation inv) {
if ((isAttachInvocationId(url, inv) && (getInvocationId(inv) == null)) && (inv instanceof RpcInvocation)) {
inv.setAttachment(ID_KEY, String.valueOf(INVOKE_ID.getAndIncrement()));
}
} | 3.26 |
dubbo_RpcUtils_isEcho_rdh | // check parameterTypesDesc to fix CVE-2020-1948
public static boolean isEcho(String parameterTypesDesc, String method) {
return $ECHO.equals(method) && $ECHO_PARAMETER_DESC.equals(parameterTypesDesc);
} | 3.26 |
dubbo_AnnotatedMethodParameterProcessor_buildDefaultValue_rdh | /**
* Build the default value
*
* @param parameterIndex
* the index of parameter
* @return the placeholder
*/
static String buildDefaultValue(int parameterIndex) {
return ("{" + parameterIndex) + "}";
} | 3.26 |
dubbo_SslContexts_findSslProvider_rdh | /**
* Returns OpenSSL if available, otherwise returns the JDK provider.
*/
private static SslProvider findSslProvider() {if (OpenSsl.isAvailable()) {
logger.debug("Using OPENSSL provider.");
return SslProvider.OPENSSL;
}
if (checkJdkProvider()) {
logger.debug("Using JDK provider.");
return SslProvider.JDK;
}throw new IllegalStateException("Could not find any valid TLS provider, please check your dependency or deployment environment, " + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed.");
} | 3.26 |
dubbo_MetadataInfo_calAndGetRevision_rdh | /**
* Calculation of this instance's status like revision and modification of the same instance must be synchronized among different threads.
* <p>
* Usage of this method is strictly restricted to certain points such as when during registration. Always try to use {@link this#getRevision()} instead.
*/
public synchronized String calAndGetRevision() {
if ((revision != null) && (!f0)) {
return revision;
}
f0 = false;
if (CollectionUtils.isEmptyMap(services)) {
this.revision = EMPTY_REVISION;
} else {
StringBuilder sb = new StringBuilder();
sb.append(app);
for (Map.Entry<String, ServiceInfo> entry : new TreeMap<>(services).entrySet()) {
sb.append(entry.getValue().toDescString());
}
String tempRevision = RevisionResolver.calRevision(sb.toString());
if (!StringUtils.isEquals(this.revision, tempRevision)) {
if (logger.isInfoEnabled()) {
logger.info(String.format("metadata revision changed: %s -> %s, app: %s, services: %d", this.revision, tempRevision, this.app, this.services.size()));
}this.revision = tempRevision;
this.rawMetadataInfo = JsonUtils.toJson(this);
}
}
return revision;
} | 3.26 |
dubbo_MetadataInfo_getNoProtocolServiceInfo_rdh | /**
* Get service infos of an interface with specified group, version.
* There may have several service infos of different protocols, this method will simply pick the first one.
*
* @param serviceKeyWithoutProtocol
* key is of format '{group}/{interface name}:{version}'
* @return the first service info related to serviceKey
*/
public ServiceInfo getNoProtocolServiceInfo(String serviceKeyWithoutProtocol) {
if (CollectionUtils.isEmptyMap(subscribedServices)) {
return null;
}
Set<ServiceInfo> subServices = subscribedServices.get(serviceKeyWithoutProtocol);
if (CollectionUtils.isNotEmpty(subServices)) {
return subServices.iterator().next();
}
return null;
} | 3.26 |
dubbo_MetadataInfo_getServiceInfo_rdh | /**
* Get service info of an interface with specified group, version and protocol
*
* @param protocolServiceKey
* key is of format '{group}/{interface name}:{version}:{protocol}'
* @return the specific service info related to protocolServiceKey
*/
public ServiceInfo getServiceInfo(String protocolServiceKey) {
return services.get(protocolServiceKey);
} | 3.26 |
dubbo_MetadataInfo_init_rdh | /**
* Initialize necessary caches right after deserialization on the consumer side
*/
protected void
init()
{
buildMatchKey();
buildServiceKey(name, group, version);
// init method params
this.methodParams = URLParam.initMethodParameters(params);
// Actually, consumer params is empty after deserialized on the consumer side, so no need to initialize.
// Check how InstanceAddressURL operates on consumer url for more detail.
// this.consumerMethodParams = URLParam.initMethodParameters(consumerParams);
// no need to init numbers for it's only for cache purpose
} | 3.26 |
dubbo_NacosNamingServiceUtils_createNamingService_rdh | /**
* Create an instance of {@link NamingService} from specified {@link URL connection url}
*
* @param connectionURL
* {@link URL connection url}
* @return {@link NamingService}
* @since 2.7.5
*/
public static NacosNamingServiceWrapper createNamingService(URL connectionURL) {
boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true);
int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 10);
NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(connectionURL, check,
retryTimes, sleepMsBetweenRetries);
return new NacosNamingServiceWrapper(nacosConnectionManager, retryTimes, sleepMsBetweenRetries);
} | 3.26 |
dubbo_NacosNamingServiceUtils_getGroup_rdh | /**
* The group of {@link NamingService} to register
*
* @param connectionURL
* {@link URL connection url}
* @return non-null, "default" as default
* @since 2.7.5
*/
public static String getGroup(URL connectionURL) {
// Compatible with nacos grouping via group.
String group = connectionURL.getParameter(GROUP_KEY, DEFAULT_GROUP);
return connectionURL.getParameter(NACOS_GROUP_KEY, group);
} | 3.26 |
dubbo_NacosNamingServiceUtils_toInstance_rdh | /**
* Convert the {@link ServiceInstance} to {@link Instance}
*
* @param serviceInstance
* {@link ServiceInstance}
* @return non-null
* @since 2.7.5
*/
public static Instance toInstance(ServiceInstance serviceInstance) {
Instance instance = new Instance();
instance.setServiceName(serviceInstance.getServiceName());
instance.setIp(serviceInstance.getHost());
instance.setPort(serviceInstance.getPort());
instance.setMetadata(serviceInstance.getSortedMetadata());
instance.setEnabled(serviceInstance.isEnabled());
instance.setHealthy(serviceInstance.isHealthy());
return instance;
}
/**
* Convert the {@link Instance} to {@link ServiceInstance}
*
* @param instance
* {@link Instance} | 3.26 |
dubbo_NacosDynamicConfiguration_createTargetListener_rdh | /**
* Ignores the group parameter.
*
* @param key
* property key the native listener will listen on
* @param group
* to distinguish different set of properties
* @return */
private NacosConfigListener createTargetListener(String
key, String group) {
NacosConfigListener configListener = new NacosConfigListener();
configListener.fillContext(key, group);
return configListener;
} | 3.26 |
dubbo_NacosDynamicConfiguration_innerReceive_rdh | /**
* receive
*
* @param dataId
* data ID
* @param group
* group
* @param configInfo
* content
*/
@Override
public void innerReceive(String dataId, String group, String configInfo) {
String oldValue = cacheData.get(dataId);
ConfigChangedEvent event = new ConfigChangedEvent(dataId, group, configInfo, m0(configInfo, oldValue));
if (configInfo == null) {
cacheData.remove(dataId);
} else {
cacheData.put(dataId, configInfo);
}
listeners.forEach(listener -> listener.process(event));
MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(applicationModel, event.getKey(), event.getGroup(), ConfigCenterEvent.NACOS_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE));
} | 3.26 |
dubbo_TagStateRouter_filterUsingStaticTag_rdh | /**
* If there's no dynamic tag rule being set, use static tag in URL.
* <p>
* A typical scenario is a Consumer using version 2.7.x calls Providers using version 2.6.x or lower,
* the Consumer should always respect the tag in provider URL regardless of whether a dynamic tag rule has been set to it or not.
* <p>
* TODO, to guarantee consistent behavior of interoperability between 2.6- and 2.7+, this method should has the same logic with the TagRouter in 2.6.x.
*
* @param invokers
* @param url
* @param invocation
* @param <T>
* @return */
private <T> BitList<Invoker<T>> filterUsingStaticTag(BitList<Invoker<T>> invokers, URL url, Invocation invocation) {
BitList<Invoker<T>> result;
// Dynamic param
String tag =
(StringUtils.isEmpty(invocation.getAttachment(TAG_KEY))) ? url.getParameter(TAG_KEY) : invocation.getAttachment(TAG_KEY);
// Tag request
if (!StringUtils.isEmpty(tag)) {
result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
if (CollectionUtils.isEmpty(result)
&& (!isForceUseTag(invocation))) {
result = filterInvoker(invokers, invoker
-> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
} else {
result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
return result;
} | 3.26 |
dubbo_StringUtils_isNumber_rdh | /**
* is positive integer or zero string.
*
* @param str
* a string
* @return is positive integer or zero
*/
public static boolean isNumber(String str) {
return isNotEmpty(str) && NUM_PATTERN.matcher(str).matches();
} | 3.26 |
dubbo_StringUtils_parseInteger_rdh | /**
* parse str to Integer(if str is not number or n < 0, then return 0)
*
* @param str
* a number str
* @return positive integer or zero
*/
public static int parseInteger(String str) {
return isNumber(str) ? Integer.parseInt(str) : 0;
} | 3.26 |
dubbo_StringUtils_m1_rdh | /**
* Splits String around matches of the given character.
* <p>
* Note: Compare with {@link StringUtils#split(String, char)}, this method reduce memory copy.
*/
public static List<String> m1(String str, char ch) {
if (isEmpty(str)) {
return Collections.emptyList();
}
return splitToList0(str, ch);
}
/**
* Split the specified value to be a {@link Set}
*
* @param value
* the content to be split
* @param separatorChar
* a char to separate
* @return non-null read-only {@link Set} | 3.26 |
dubbo_StringUtils_isAnyEmpty_rdh | /**
* <p>Checks if the strings contain at least on empty or null element. <p/>
*
* <pre>
* StringUtils.isAnyEmpty(null) = true
* StringUtils.isAnyEmpty("") = true
* StringUtils.isAnyEmpty(" ") = false
* StringUtils.isAnyEmpty("abc") = false
* StringUtils.isAnyEmpty("abc", "def") = false
* StringUtils.isAnyEmpty("abc", null) = true
* StringUtils.isAnyEmpty("abc", "") = true
* StringUtils.isAnyEmpty("abc", " ") = false
* </pre>
*
* @param ss
* the strings to check
* @return {@code true} if at least one in the strings is empty or null
*/
public static boolean isAnyEmpty(final String... ss) {
return !isNoneEmpty(ss);
} | 3.26 |
dubbo_StringUtils_isNoneEmpty_rdh | /**
* <p>Checks if the strings contain empty or null elements. <p/>
*
* <pre>
* StringUtils.isNoneEmpty(null) = false
* StringUtils.isNoneEmpty("") = false
* StringUtils.isNoneEmpty(" ") = true
* StringUtils.isNoneEmpty("abc") = true
* StringUtils.isNoneEmpty("abc", "def") = true
* StringUtils.isNoneEmpty("abc", null) = false
* StringUtils.isNoneEmpty("abc", "") = false
* StringUtils.isNoneEmpty("abc", " ") = true
* </pre>
*
* @param ss
* the strings to check
* @return {@code true} if all strings are not empty or null
*/
public static boolean isNoneEmpty(final String... ss) {
if (ArrayUtils.isEmpty(ss)) { return false;
}
for (final String s : ss) {
if (isEmpty(s)) {
return false;
}
}
return true;
} | 3.26 |
dubbo_StringUtils_parseParameters_rdh | /**
* Decode parameters string to map
*
* @param rawParameters
* format like '[{a:b},{c:d}]'
* @return */
public static Map<String, String> parseParameters(String rawParameters) {
if (StringUtils.isBlank(rawParameters)) {
return Collections.emptyMap();
}
Matcher matcher = PARAMETERS_PATTERN.matcher(rawParameters);
if (!matcher.matches()) {
return Collections.emptyMap();
}
String pairs = matcher.group(1);
String[] pairArr = pairs.split("\\s*,\\s*");
Map<String, String> parameters = new HashMap<>();
for (String pair : pairArr) {
Matcher pairMatcher = PAIR_PARAMETERS_PATTERN.matcher(pair);
if (pairMatcher.matches()) {
parameters.put(pairMatcher.group(1), pairMatcher.group(2));
}
}
return parameters;
} | 3.26 |
dubbo_StringUtils_toCommaDelimitedString_rdh | /**
* Create the common-delimited {@link String} by one or more {@link String} members
*
* @param one
* one {@link String}
* @param others
* others {@link String}
* @return <code>null</code> if <code>one</code> or <code>others</code> is <code>null</code>
* @since 2.7.8
*/
public static String toCommaDelimitedString(String one, String... others) {
String another = arrayToDelimitedString(others, COMMA_SEPARATOR);
return isEmpty(another) ? one : (one + COMMA_SEPARATOR) + another;} | 3.26 |
dubbo_StringUtils_parseQueryString_rdh | /**
* parse query string to Parameters.
*
* @param qs
* query string.
* @return Parameters instance.
*/
public static Map<String, String> parseQueryString(String qs) {
if
(isEmpty(qs)) {
return new HashMap<String, String>();
}
return parseKeyValuePair(qs, "\\&");
} | 3.26 |
dubbo_StringUtils_parseLong_rdh | /**
* parse str to Long(if str is not number or n < 0, then return 0)
*
* @param str
* a number str
* @return positive long or zero
*/
public static long parseLong(String str) {
return isNumber(str) ? Long.parseLong(str) : 0;
} | 3.26 |
dubbo_StringUtils_repeat_rdh | /**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.repeat('e', 0) = ""
* StringUtils.repeat('e', 3) = "eee"
* StringUtils.repeat('e', -2) = ""
* </pre>
*
* <p>Note: this method doesn't not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of {@code char}s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param ch
* character to repeat
* @param repeat
* number of times to repeat char, negative treated as zero
* @return String with repeated character
* @see #repeat(String, int)
*/
public static String repeat(final char ch, final int repeat) {
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
} | 3.26 |
dubbo_StringUtils_isNotBlank_rdh | /**
* is not blank string.
*
* @param cs
* source string.
* @return is not blank.
*/
public static boolean isNotBlank(CharSequence cs) {
return !isBlank(cs);
} | 3.26 |
dubbo_StringUtils_parseKeyValuePair_rdh | /**
* parse key-value pair.
*
* @param str
* string.
* @param itemSeparator
* item separator.
* @return key-value map;
*/
private static Map<String, String> parseKeyValuePair(String str, String itemSeparator) {
String[] tmp = str.split(itemSeparator);
Map<String, String> map = new HashMap<String, String>(tmp.length);
for (int i = 0; i < tmp.length; i++) {
Matcher matcher = KVP_PATTERN.matcher(tmp[i]);
if (!matcher.matches()) {
continue;
}
map.put(matcher.group(1), matcher.group(2));
}
return map;
} | 3.26 |
dubbo_StringUtils_isEmpty_rdh | /**
* is empty string.
*
* @param str
* source string.
* @return is empty.
*/
public static boolean isEmpty(String str) {
return (str == null) || str.isEmpty();
} | 3.26 |
dubbo_StringUtils_m4_rdh | /**
* Test str whether starts with the prefix ignore case.
*
* @param str
* @param prefix
* @return */
public static boolean m4(String
str, String prefix) {
if (((str == null) || (prefix == null)) || (str.length() < prefix.length())) {
return false;
}
// return str.substring(0, prefix.length()).equalsIgnoreCase(prefix);
return str.regionMatches(true, 0, prefix, 0, prefix.length());} | 3.26 |
dubbo_StringUtils_encodeParameters_rdh | /**
* Encode parameters map to string, like '[{a:b},{c:d}]'
*
* @param params
* @return */
public static String encodeParameters(Map<String,
String> params) {
if ((params
== null) || params.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append('[');
params.forEach((key, value) -> {
// {key:value},
if (hasText(value)) {
sb.append('{').append(key).append(':').append(value).append("},");
}
});
// delete last separator ','
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
}sb.append(']');
return sb.toString();
} | 3.26 |
dubbo_StringUtils_m0_rdh | /**
* if s1 is null and s2 is null, then return true
*
* @param s1
* str1
* @param s2
* str2
* @return equals
*/
public static boolean m0(String s1, String s2) {
if ((s1 == null) && (s2 == null)) {
return true;
}
if ((s1 == null) || (s2 == null)) {
return false;
}
return s1.equals(s2);
} | 3.26 |
dubbo_StringUtils_split_rdh | /**
* split.
*
* @param ch
* char.
* @return string array.
*/
public static String[] split(String str, char ch) {
if (isEmpty(str)) {
return EMPTY_STRING_ARRAY;
}
return splitToList0(str, ch).toArray(EMPTY_STRING_ARRAY);
} | 3.26 |
dubbo_StringUtils_join_rdh | /**
* join string like javascript.
*
* @param array
* String array.
* @param split
* split
* @return String.
*/
public static String join(String[] array, String split) {
if
(ArrayUtils.isEmpty(array)) {
return EMPTY_STRING;
}
StringBuilder sb = new StringBuilder();
for (int
i = 0; i < array.length; i++) {
if (i > 0) {
sb.append(split);
}
sb.append(array[i]);
}
return sb.toString();
} | 3.26 |
dubbo_StringUtils_hasText_rdh | /**
* Check the cs String whether contains non whitespace characters.
*
* @param cs
* @return */
public static boolean hasText(CharSequence cs) {
return !isBlank(cs);
} | 3.26 |
dubbo_StringUtils_toString_rdh | /**
*
* @param msg
* @param e
* @return string
*/
public static String toString(String msg, Throwable e) {
UnsafeStringWriter w = new UnsafeStringWriter();
w.write(msg + "\n");
PrintWriter p = new PrintWriter(w);
try {
e.printStackTrace(p);
return
w.toString();
} finally {
p.close();
}
} | 3.26 |
dubbo_StringUtils_isJavaIdentifier_rdh | /**
* Returns true if s is a legal Java identifier.<p>
* <a href="http://www.exampledepot.com/egs/java.lang/IsJavaId.html">more info.</a>
*/
public static boolean isJavaIdentifier(String s) {
if (isEmpty(s) || (!Character.isJavaIdentifierStart(s.charAt(0)))) {
return false;
}
for (int i = 1; i < s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return true;
} | 3.26 |
dubbo_StringUtils_translate_rdh | /**
* translate.
*
* @param src
* source string.
* @param from
* src char table.
* @param to
* target char table.
* @return String.
*/
public static String translate(String src, String from, String to) {
if (isEmpty(src)) {
return src;
}
StringBuilder sb = null;
int ix;
char c;
for (int i
=
0, len = src.length(); i < len; i++) {
c = src.charAt(i);
ix = from.indexOf(c);
if (ix == (-1))
{
if (sb != null) {
sb.append(c);
}
} else {
if (sb == null) {
sb = new StringBuilder(len);
sb.append(src, 0, i);
}
if (ix < to.length()) {
sb.append(to.charAt(ix));
}
}
}
return sb == null ? src : sb.toString();
} | 3.26 |
dubbo_StringUtils_convertToSplitName_rdh | /**
* Convert camelCase or snake_case/SNAKE_CASE to kebab-case
*
* @param str
* @param split
* @return */
public static String convertToSplitName(String str, String split) {
if (isSnakeCase(str)) {
return m2(str, split);
} else {
return camelToSplitName(str, split);
}
} | 3.26 |
dubbo_StringUtils_m2_rdh | /**
* Convert snake_case or SNAKE_CASE to kebab-case.
* <p>
* NOTE: Return itself if it's not a snake case.
*
* @param snakeName
* @param split
* @return */
public static String m2(String snakeName, String split) {
String lowerCase = snakeName.toLowerCase();
if (isSnakeCase(snakeName)) {
return replace(lowerCase, "_", split);
}
return snakeName;
} | 3.26 |
dubbo_StringUtils_isNotEmpty_rdh | /**
* is not empty string.
*
* @param str
* source string.
* @return is not empty.
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
} | 3.26 |
dubbo_StringUtils_stripEnd_rdh | /**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str
* the String to remove characters from, may be null
* @param stripChars
* the set of characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripEnd(final String str, final String stripChars) { int end;
if ((str == null) || ((end = str.length()) == 0)) {
return str;
}
if (stripChars == null) {
while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while
((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND)) {
end--;
}
}
return str.substring(0, end);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @param text
* text to search and replace in, may be null
* @param searchString
* the String to search for, may be null
* @param replacement
* the String to replace it with, may be null
* @return the text with any replacements processed,
{@code null} | 3.26 |
dubbo_StringUtils_decodeHexByte_rdh | /**
* Decode a 2-digit hex byte from within a string.
*/
public static byte decodeHexByte(CharSequence s, int pos) {
int hi = decodeHexNibble(s.charAt(pos));int lo = decodeHexNibble(s.charAt(pos + 1));if ((hi == (-1)) || (lo == (-1))) {
throw new IllegalArgumentException(String.format("invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s));
}
return ((byte) ((hi << 4) + lo));
} | 3.26 |
dubbo_StringUtils_splitToSet_rdh | /**
* Split the specified value to be a {@link Set}
*
* @param value
* the content to be split
* @param separatorChar
* a char to separate
* @param trimElements
* require to trim the elements or not
* @return non-null read-only {@link Set}
* @since 2.7.8
*/public static Set<String> splitToSet(String value, char separatorChar, boolean
trimElements) {
List<String> values = m1(value, separatorChar);
int size = values.size();
if (size < 1) {
// empty condition
return emptySet();
}
if (!trimElements) {
// Do not require to trim the elements
return new LinkedHashSet(values);
}
return unmodifiableSet(values.stream().map(String::trim).collect(LinkedHashSet::new, Set::add, Set::addAll));
} | 3.26 |
dubbo_ServiceBeanExportedEvent_getServiceBean_rdh | /**
* Get {@link ServiceBean} instance
*
* @return non-null
*/public ServiceBean getServiceBean() {
return ((ServiceBean) (super.getSource()));
} | 3.26 |
dubbo_ServiceInstancesChangedListener_hasEmptyMetadata_rdh | /**
* Calculate the number of revisions that failed to find metadata info.
*
* @param revisionToInstances
* instance list classified by revisions
* @return the number of revisions that failed at fetching MetadataInfo
*/protected int hasEmptyMetadata(Map<String, List<ServiceInstance>> revisionToInstances) {
if (revisionToInstances == null) {
return 0;}
StringBuilder builder = new StringBuilder();
int emptyMetadataNum = 0;
for (Map.Entry<String, List<ServiceInstance>> entry : revisionToInstances.entrySet()) {
DefaultServiceInstance serviceInstance = ((DefaultServiceInstance) (entry.getValue().get(0)));
if ((serviceInstance == null) || (serviceInstance.getServiceMetadata() == MetadataInfo.EMPTY)) {
emptyMetadataNum++;
}
builder.append(entry.getKey());
builder.append(' ');
}
if (emptyMetadataNum > 0) {
builder.insert(0, ((emptyMetadataNum + "/") + revisionToInstances.size()) + " revisions failed to get metadata from remote: ");
logger.error(INTERNAL_ERROR, "unknown error in registry module", "",
builder.toString());
} else {
builder.insert(0, revisionToInstances.size() + " unique working revisions: ");
logger.info(builder.toString());
}
return emptyMetadataNum;
} | 3.26 |
dubbo_ServiceInstancesChangedListener_doOnEvent_rdh | /**
*
* @param event
*/
private synchronized void doOnEvent(ServiceInstancesChangedEvent event) {
if ((destroyed.get() || (!accept(event))) || isRetryAndExpired(event)) {
return;
}
refreshInstance(event);
if
(logger.isDebugEnabled()) {
logger.debug(event.getServiceInstances().toString());
}
Map<String, List<ServiceInstance>> revisionToInstances = new HashMap<>();
Map<ServiceInfo, Set<String>> localServiceToRevisions = new HashMap<>();
// grouping all instances of this app(service name) by revision
for (Map.Entry<String, List<ServiceInstance>> entry : allInstances.entrySet()) {
List<ServiceInstance> instances = entry.getValue();
for (ServiceInstance instance : instances) {
String revision = getExportedServicesRevision(instance);
if ((revision == null) || EMPTY_REVISION.equals(revision)) {
if (logger.isDebugEnabled()) {
logger.debug("Find instance without valid service metadata: " + instance.getAddress());
}
continue;
}
List<ServiceInstance> subInstances = revisionToInstances.computeIfAbsent(revision, r ->
new LinkedList<>());
subInstances.add(instance);
}
}
// get MetadataInfo with revision
for (Map.Entry<String, List<ServiceInstance>> entry : revisionToInstances.entrySet()) {
String revision = entry.getKey();
List<ServiceInstance> subInstances
= entry.getValue();
MetadataInfo metadata = subInstances.stream().map(ServiceInstance::getServiceMetadata).filter(Objects::nonNull).filter(m -> revision.equals(m.getRevision())).findFirst().orElseGet(() -> serviceDiscovery.getRemoteMetadata(revision, subInstances));
parseMetadata(revision, metadata, localServiceToRevisions);
// update metadata into each instance, in case new instance created.
for (ServiceInstance tmpInstance : subInstances) {
MetadataInfo originMetadata = tmpInstance.getServiceMetadata();
if ((originMetadata == null) || (!Objects.equals(originMetadata.getRevision(), metadata.getRevision()))) {
tmpInstance.setServiceMetadata(metadata);
}
}
}
int emptyNum = hasEmptyMetadata(revisionToInstances);
if (emptyNum != 0) {
// retry every 10 seconds
hasEmptyMetadata = true;
if (retryPermission.tryAcquire()) {
if ((retryFuture != null) && (!retryFuture.isDone())) {
// cancel last retryFuture because only one retryFuture will be canceled at destroy().
retryFuture.cancel(true);
}
try {
retryFuture = scheduler.schedule(new AddressRefreshRetryTask(retryPermission, event.getServiceName()), 10000L, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.error(INTERNAL_ERROR, "unknown error in registry module", "", "Error submitting async retry task.");
}
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Address refresh try task submitted");
}
// return if all metadata is empty, this notification will not take effect.
if (emptyNum == revisionToInstances.size()) {
// 1-17 - Address refresh failed.
logger.error(REGISTRY_FAILED_REFRESH_ADDRESS, "metadata Server failure", "", "Address refresh failed because of Metadata Server failure, wait for retry or new address refresh event.");
return;
}
}
hasEmptyMetadata = false;
Map<String, Map<Integer, Map<Set<String>, Object>>> protocolRevisionsToUrls = new HashMap<>();
Map<String, List<ProtocolServiceKeyWithUrls>> newServiceUrls = new HashMap<>();
for (Map.Entry<ServiceInfo, Set<String>> entry : localServiceToRevisions.entrySet()) {ServiceInfo serviceInfo = entry.getKey();
Set<String> revisions = entry.getValue();
Map<Integer, Map<Set<String>,
Object>> portToRevisions = protocolRevisionsToUrls.computeIfAbsent(serviceInfo.getProtocol(), k -> new HashMap<>());
Map<Set<String>, Object> revisionsToUrls =
portToRevisions.computeIfAbsent(serviceInfo.getPort(), k -> new HashMap<>());
Object urls = revisionsToUrls.computeIfAbsent(revisions, k -> getServiceUrlsCache(revisionToInstances, revisions, serviceInfo.getProtocol(), serviceInfo.getPort()));
List<ProtocolServiceKeyWithUrls> list = newServiceUrls.computeIfAbsent(serviceInfo.getPath(), k -> new LinkedList<>());
list.add(new ProtocolServiceKeyWithUrls(serviceInfo.getProtocolServiceKey(), ((List<URL>) (urls))));
}
this.serviceUrls = newServiceUrls;
this.notifyAddressChanged();
} | 3.26 |
dubbo_ServiceInstancesChangedListener_notifyAddressChanged_rdh | /**
* race condition is protected by onEvent/doOnEvent
*/
protected void
notifyAddressChanged() {
MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> {
Map<String, Integer> lastNumMap = new HashMap<>();
// 1 different services
listeners.forEach((serviceKey, listenerSet) -> {
// 2 multiple subscription listener of the same service
for (NotifyListenerWithKey listenerWithKey : listenerSet) {
NotifyListener notifyListener = listenerWithKey.getNotifyListener();
List<URL> urls = toUrlsWithEmpty(getAddresses(listenerWithKey.getProtocolServiceKey(), notifyListener.getConsumerUrl()));
logger.info((("Notify service " + listenerWithKey.getProtocolServiceKey()) + " with urls ") + urls.size());
notifyListener.notify(urls);
lastNumMap.put(serviceKey, urls.size());
}
});
return lastNumMap;
});} | 3.26 |
dubbo_ServiceInstancesChangedListener_onEvent_rdh | /**
* On {@link ServiceInstancesChangedEvent the service instances change event}
*
* @param event
* {@link ServiceInstancesChangedEvent}
*/
public void onEvent(ServiceInstancesChangedEvent event) {
if ((destroyed.get() || (!accept(event))) || isRetryAndExpired(event)) {
return;
}
doOnEvent(event);
} | 3.26 |
dubbo_ServiceInstancesChangedListener_m0_rdh | /**
* Since this listener is shared among interfaces, destroy this listener only when all interface listener are unsubscribed
*/
public void m0() {
if (destroyed.compareAndSet(false, true)) {logger.info("Destroying instance listener of " + this.getServiceNames());
serviceDiscovery.removeServiceInstancesChangedListener(this);
synchronized(this) {allInstances.clear();
serviceUrls.clear();
listeners.clear();
if ((retryFuture != null) && (!retryFuture.isDone()))
{
retryFuture.cancel(true); }
}
}
} | 3.26 |
dubbo_ServiceInstancesChangedListener_accept_rdh | /**
*
* @param event
* {@link ServiceInstancesChangedEvent event}
* @return If service name matches, return <code>true</code>, or <code>false</code>
*/
private boolean accept(ServiceInstancesChangedEvent event) {
return serviceNames.contains(event.getServiceName());
} | 3.26 |
dubbo_PortUnificationExchanger_getServers_rdh | // for test
public static ConcurrentMap<String, RemotingServer> getServers() {
return servers;
} | 3.26 |
dubbo_InjvmExporterListener_exported_rdh | /**
* Overrides the exported method to add the given exporter to the exporters ConcurrentHashMap,
* <p>
* and to notify all registered ExporterChangeListeners of the export event.
*
* @param exporter
* The Exporter instance that has been exported.
* @throws RpcException
* If there is an error during the export process.
*/@Override
public void exported(Exporter<?> exporter) throws RpcException {
String serviceKey = exporter.getInvoker().getUrl().getServiceKey();
exporters.putIfAbsent(serviceKey, exporter);
Set<ExporterChangeListener> listeners = exporterChangeListeners.get(serviceKey);
if (!CollectionUtils.isEmpty(listeners)) {
for (ExporterChangeListener listener : listeners) {
listener.onExporterChangeExport(exporter);
}}
super.exported(exporter);
} | 3.26 |
dubbo_InjvmExporterListener_removeExporterChangeListener_rdh | /**
* Removes an ExporterChangeListener for a specific service.
*
* @param listener
* The ExporterChangeListener to remove.
* @param listenerKey
* The service key for the service to remove the listener from.
*/
public synchronized void removeExporterChangeListener(ExporterChangeListener listener, String listenerKey) {
Set<ExporterChangeListener> listeners = exporterChangeListeners.get(listenerKey);if (CollectionUtils.isEmpty(listeners))
{
return;
}
listeners.remove(listener);
if (CollectionUtils.isEmpty(listeners)) {
exporterChangeListeners.remove(listenerKey);
}
} | 3.26 |
dubbo_InjvmExporterListener_addExporterChangeListener_rdh | /**
* Adds an ExporterChangeListener for a specific service, and notifies the listener of the current Exporter instance
* <p>
* if it exists.
*
* @param listener
* The ExporterChangeListener to add.
* @param serviceKey
* The service key for the service to listen for changes on.
*/
public synchronized void addExporterChangeListener(ExporterChangeListener listener, String serviceKey) {
exporterChangeListeners.putIfAbsent(serviceKey, new ConcurrentHashSet<>());
exporterChangeListeners.get(serviceKey).add(listener);
if (exporters.get(serviceKey) != null) {
Exporter<?> exporter = exporters.get(serviceKey);
listener.onExporterChangeExport(exporter);
}
} | 3.26 |
dubbo_InjvmExporterListener_unexported_rdh | /**
* Overrides the unexported method to remove the given exporter from the exporters ConcurrentHashMap,
* <p>
* and to notify all registered ExporterChangeListeners of the unexport event.
*
* @param exporter
* The Exporter instance that has been unexported.
* @throws RpcException
* If there is an error during the unexport process.
*/
@Override
public void unexported(Exporter<?> exporter) throws RpcException {
String
serviceKey = exporter.getInvoker().getUrl().getServiceKey();
exporters.remove(serviceKey, exporter);
Set<ExporterChangeListener> listeners = exporterChangeListeners.get(serviceKey);
if (!CollectionUtils.isEmpty(listeners)) {
for (ExporterChangeListener listener : listeners) {
listener.onExporterChangeUnExport(exporter);
}
}
super.unexported(exporter);
} | 3.26 |
dubbo_OrderedPropertiesConfiguration_setProperties_rdh | /**
* For ut only
*/
@Deprecated
public void setProperties(Properties properties) {
this.f0 = properties;
} | 3.26 |
dubbo_ReflectionServiceDescriptor_getMethod_rdh | /**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param paramTypes
* @return */
public MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes) {
List<MethodDescriptor> methodModels = methods.get(methodName);
if (CollectionUtils.isNotEmpty(methodModels)) {
for (MethodDescriptor descriptor : methodModels) {
if (Arrays.equals(paramTypes, descriptor.getParameterClasses())) {
return descriptor;
}
}
}
return null;
} | 3.26 |
dubbo_ScriptStateRouter_getRoutedInvokers_rdh | /**
* get routed invokers from result of script rule evaluation
*/
@SuppressWarnings("unchecked")
protected BitList<Invoker<T>> getRoutedInvokers(BitList<Invoker<T>> invokers, Object obj) {
BitList<Invoker<T>> result = invokers.clone();
if (obj instanceof Invoker[]) {
result.retainAll(Arrays.asList(((Invoker<T>[]) (obj))));
}
else if (obj instanceof Object[]) {
result.retainAll(Arrays.stream(((Object[]) (obj))).map(item -> ((Invoker<T>) (item))).collect(Collectors.toList()));
} else {
result.retainAll(((List<Invoker<T>>) (obj)));
}
return
result;
} | 3.26 |
dubbo_ScriptStateRouter_getRule_rdh | /**
* get rule from url parameters.
*/private String getRule(URL url) {
String vRule = url.getParameterAndDecoded(RULE_KEY);
if (StringUtils.isEmpty(vRule)) {
throw new IllegalStateException("route rule can not be empty.");}
return vRule;
} | 3.26 |
dubbo_ScriptStateRouter_m0_rdh | /**
* create ScriptEngine instance by type from url parameters, then cache it
*/
private ScriptEngine m0(URL url) {
String type = url.getParameter(TYPE_KEY, DEFAULT_SCRIPT_TYPE_KEY);
return ConcurrentHashMapUtils.computeIfAbsent(ENGINES, type, t -> {
ScriptEngine v5 = new ScriptEngineManager().getEngineByName(type);
if (v5 == null) {
throw new IllegalStateException("unsupported route engine type: " + type);
}
return v5;
});
} | 3.26 |
dubbo_HttpHeaderUtil_parseRequestHeader_rdh | /**
* parse rest request header attachment & header
*
* @param rpcInvocation
* @param requestFacade
*/
public static void parseRequestHeader(RpcInvocation rpcInvocation, RequestFacade requestFacade) {
Enumeration<String> headerNames = requestFacade.getHeaderNames();
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
if (!isRestAttachHeader(header)) {
// attribute
rpcInvocation.put(header, requestFacade.getHeader(header));
continue;
}
// attachment
rpcInvocation.setAttachment(subRestAttachRealHeaderPrefix(header.trim()), requestFacade.getHeader(header));
}
} | 3.26 |
dubbo_HttpHeaderUtil_subRestAttachRealHeaderPrefix_rdh | /**
* for substring attachment prefix
*
* @param header
* @return */
public static String subRestAttachRealHeaderPrefix(String header)
{
return header.substring(RestHeaderEnum.REST_HEADER_PREFIX.getHeader().length());
} | 3.26 |
dubbo_HttpHeaderUtil_isRestAttachHeader_rdh | /**
* for judge rest header or rest attachment
*
* @param header
* @return */
public static boolean isRestAttachHeader(String header) {
if (StringUtils.isEmpty(header) || (!header.startsWith(RestHeaderEnum.REST_HEADER_PREFIX.getHeader()))) {
return false;
}
return true;
} | 3.26 |
dubbo_HttpHeaderUtil_addResponseAttachments_rdh | /**
* add provider attachment to response
*
* @param nettyHttpResponse
*/
public static void addResponseAttachments(NettyHttpResponse nettyHttpResponse) {
Map<String, List<String>> attachments =
createAttachments(RpcContext.getServerContext().getObjectAttachments());
attachments.entrySet().stream().forEach(attachment -> {nettyHttpResponse.getOutputHeaders().put(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue());
});
} | 3.26 |
dubbo_HttpHeaderUtil_parseResponseHeader_rdh | /**
* parse rest response header to appResponse attribute & attachment
*
* @param appResponse
* @param restResult
*/
public static void parseResponseHeader(AppResponse appResponse,
RestResult restResult) {
Map<String, List<String>> headers = restResult.headers();
if ((headers == null) || headers.isEmpty()) {
return;
}
headers.entrySet().stream().forEach(entry -> {
String header = entry.getKey();
if (isRestAttachHeader(header)) {
// attachment
appResponse.setAttachment(subRestAttachRealHeaderPrefix(header), entry.getValue());
} else {
// attribute
appResponse.setAttribute(header, entry.getValue());}
});
} | 3.26 |
dubbo_HttpHeaderUtil_appendPrefixToAttachRealHeader_rdh | /**
* append prefix to rest header distinguish from normal header
*
* @param header
* @return */
public static String appendPrefixToAttachRealHeader(String header) {
return RestHeaderEnum.REST_HEADER_PREFIX.getHeader() + header;
} | 3.26 |
dubbo_HttpHeaderUtil_parseRequest_rdh | /**
* parse request
*
* @param rpcInvocation
* @param request
*/public static void parseRequest(RpcInvocation rpcInvocation, RequestFacade request) {
parseRequestHeader(rpcInvocation, request);
parseRequestAttribute(rpcInvocation, request);
} | 3.26 |
dubbo_HttpHeaderUtil_parseRequestAttribute_rdh | /**
* parse request attribute
*
* @param rpcInvocation
* @param request
*/
public static void parseRequestAttribute(RpcInvocation rpcInvocation, RequestFacade request) {
int localPort = request.getLocalPort();
String localAddr = request.getLocalAddr();
int remotePort = request.getRemotePort();String
remoteAddr = request.getRemoteAddr();
rpcInvocation.put(RestConstant.REMOTE_ADDR,
remoteAddr);
rpcInvocation.put(RestConstant.LOCAL_ADDR, localAddr);
rpcInvocation.put(RestConstant.REMOTE_PORT, remotePort);
rpcInvocation.put(RestConstant.LOCAL_PORT, localPort);
} | 3.26 |
dubbo_HttpHeaderUtil_addRequestAttachments_rdh | /**
* add consumer attachment to request
*
* @param requestTemplate
* @param attachmentMap
*/
public static void addRequestAttachments(RequestTemplate requestTemplate, Map<String, Object> attachmentMap) {
Map<String, List<String>> attachments = createAttachments(attachmentMap); attachments.entrySet().forEach(attachment -> {
requestTemplate.addHeaders(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue());
});
} | 3.26 |
dubbo_HttpHeaderUtil_createAttachments_rdh | /**
* convert attachment to Map<String, List<String>>
*
* @param attachmentMap
* @return */
public static Map<String, List<String>> createAttachments(Map<String, Object> attachmentMap) {
Map<String, List<String>> attachments = new HashMap<>();
int size = 0;
for (Map.Entry<String, Object> entry : attachmentMap.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
if (value != null) {
size += value.getBytes(StandardCharsets.UTF_8).length;
}
List<String> strings = attachments.get(key);
if (strings == null) {
strings = new ArrayList<>();attachments.put(key, strings);
}
strings.add(value);
}
return attachments;
} | 3.26 |
dubbo_GenericBeanPostProcessorAdapter_processAfterInitialization_rdh | /**
* Process {@link T Bean} with name without return value after initialization,
* <p>
* This method will be invoked by BeanPostProcessor#postProcessAfterInitialization(Object, String)
*
* @param bean
* Bean Object
* @param beanName
* Bean Name
* @throws BeansException
* in case of errors
*/
protected void processAfterInitialization(T bean, String beanName) throws BeansException {
} | 3.26 |
dubbo_GenericBeanPostProcessorAdapter_doPostProcessAfterInitialization_rdh | /**
* Adapter BeanPostProcessor#postProcessAfterInitialization(Object, String) method , sub-type
* could override this method.
*
* @param bean
* Bean Object
* @param beanName
* Bean Name
* @return Bean Object
* @see BeanPostProcessor#postProcessAfterInitialization(Object, String)
*/
protected T doPostProcessAfterInitialization(T bean, String beanName) throws BeansException {
processAfterInitialization(bean, beanName);
return bean;
} | 3.26 |
dubbo_GenericBeanPostProcessorAdapter_doPostProcessBeforeInitialization_rdh | /**
* Adapter BeanPostProcessor#postProcessBeforeInitialization(Object, String) method , sub-type
* could override this method.
*
* @param bean
* Bean Object
* @param beanName
* Bean Name
* @return Bean Object
* @see BeanPostProcessor#postProcessBeforeInitialization(Object, String)
*/
protected T doPostProcessBeforeInitialization(T bean, String beanName) throws BeansException { processBeforeInitialization(bean, beanName);
return bean;} | 3.26 |
dubbo_GenericBeanPostProcessorAdapter_processBeforeInitialization_rdh | /**
* Process {@link T Bean} with name without return value before initialization,
* <p>
* This method will be invoked by BeanPostProcessor#postProcessBeforeInitialization(Object, String)
*
* @param bean
* Bean Object
* @param beanName
* Bean Name
* @throws BeansException
* in case of errors
*/
protected void processBeforeInitialization(T bean,
String beanName) throws BeansException {
} | 3.26 |
dubbo_GenericBeanPostProcessorAdapter_getBeanType_rdh | /**
* Bean Type
*
* @return Bean Type
*/
public final Class<T> getBeanType() {
return beanType;
} | 3.26 |
dubbo_DubboConfigInitEvent_getApplicationContext_rdh | /**
* Get the {@code ApplicationContext} that the event was raised for.
*/
public final ApplicationContext getApplicationContext() {
return ((ApplicationContext) (getSource()));
} | 3.26 |
dubbo_AbstractConfig_refresh_rdh | /**
* Dubbo config property override
*/
public void refresh() {
if (needRefresh) {
try {
// check and init before do refresh
preProcessRefresh();
refreshWithPrefixes(getPrefixes(),
getConfigMode());
} catch (Exception e) {logger.error(COMMON_FAILED_OVERRIDE_FIELD, "", "", "Failed to override field value of config bean: " + this, e);
throw new IllegalStateException("Failed to override field value of config bean: " + this, e);
}
postProcessRefresh();
}
refreshed.set(true);
} | 3.26 |
dubbo_AbstractConfig_checkDefault_rdh | /**
* Check and set default value for some fields.
* <p>
* This method will be called at the end of {@link #refresh()}, as a post-initializer.
* </p>
* <p>NOTE: </p>
* <p>
* To distinguish between user-set property values and default property values,
* do not initialize default value at field declare statement. <b>If the field has a default value,
* it should be set in the checkDefault() method</b>, which will be called at the end of {@link #refresh()},
* so that it will not affect the behavior of attribute overrides.</p>
*
* @see AbstractConfig#getMetaData()
* @see AbstractConfig#appendAttributes(Map, Object)
*/protected void checkDefault() {
} | 3.26 |
dubbo_AbstractConfig_convert_rdh | /**
*
* @param parameters
* the raw parameters
* @param prefix
* the prefix
* @return the parameters whose raw key will replace "-" to "."
* @revised 2.7.8 "private" to be "protected"
*/
protected static Map<String, String> convert(Map<String, String> parameters, String prefix) {
if ((parameters == null) || parameters.isEmpty()) {
return new HashMap<>();
}
Map<String, String> result = new HashMap<>();
String pre = (StringUtils.isNotEmpty(prefix)) ? prefix + "." : "";
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
result.put(pre + key, value); // For compatibility, key like "registry-type" will have a duplicate key "registry.type"
if (Arrays.binarySearch(Constants.DOT_COMPATIBLE_KEYS, key) >= 0) {
result.put(pre + key.replace('-', '.'), value);
}
}
return result;
} | 3.26 |
dubbo_AbstractConfig_isValid_rdh | /**
* FIXME check @Parameter(required=true) and any conditions that need to match.
*/
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
return true;
} | 3.26 |
dubbo_AbstractConfig_postProcessAfterScopeModelChanged_rdh | /**
* Subclass should override this method to initialize its SPI extensions and change referenced config's scope model.
* <p>
* For example:
* <pre>
* protected void postProcessAfterScopeModelChanged() {
* super.postProcessAfterScopeModelChanged();
* // re-initialize spi extension
* this.protocol = this.getExtensionLoader(Protocol.class).getAdaptiveExtension();
* // change referenced config's scope model
* if (this.providerConfig != null && this.providerConfig.getScopeModel() != scopeModel) {
* this.providerConfig.setScopeModel(scopeModel);
* }
* }
* </pre>
*
* @param oldScopeModel
* @param newScopeModel
*/
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
// remove this config from old ConfigManager
// if (oldScopeModel != null && oldScopeModel instanceof ApplicationModel) {
// ((ApplicationModel)oldScopeModel).getApplicationConfigManager().removeConfig(this);
// }
} | 3.26 |
dubbo_AbstractConfig_getMetaData_rdh | /**
* <p>
* <b>The new instance of the AbstractConfig subclass should return empty metadata.</b>
* The purpose is to get the attributes set by the user instead of the default value when the {@link #refresh()} method handles attribute overrides.
* </p>
*
* <p><b>The default value of the field should be set in the {@link #checkDefault()} method</b>,
* which will be called at the end of {@link #refresh()}, so that it will not affect the behavior of attribute overrides.</p>
*
* <p></p>
* Should be called after Config was fully initialized.
* <p>
* Notice! This method should include all properties in the returning map, treat @Parameter differently compared to appendParameters?
* </p>
* // FIXME: this method should be completely replaced by appendParameters?
* // -- Url parameter may use key, but props override only use property name. So replace it with appendAttributes().
*
* @see AbstractConfig#checkDefault()
* @see AbstractConfig#appendParameters(Map, Object, String)
*/
@Transient
public Map<String, String> getMetaData() {
return getMetaData(null);
} | 3.26 |
dubbo_AbstractConfig_computeAttributedMethods_rdh | /**
* compute attributed getter methods, subclass can override this method to add/remove attributed methods
*
* @return */
protected List<Method> computeAttributedMethods() {
Class<? extends AbstractConfig> cls = this.getClass();
BeanInfo beanInfo = getBeanInfo(cls);
List<Method> methods = new ArrayList<>(beanInfo.getMethodDescriptors().length);
for (MethodDescriptor methodDescriptor : beanInfo.getMethodDescriptors()) {
Method method = methodDescriptor.getMethod();
if (MethodUtils.isGetter(method) || isParametersGetter(method)) {
// filter non attribute
Parameter parameter = method.getAnnotation(Parameter.class);
if ((parameter != null) && (!parameter.attribute())) {
continue;
}
String propertyName = m1(method.getName());
// filter non-writable property, exclude non property methods, fix #4225
if (!isWritableProperty(beanInfo, propertyName)) {
continue;
}
methods.add(method);
}
}
return methods;
} | 3.26 |
dubbo_AbstractConfig_appendAnnotation_rdh | /**
* Copy attributes from annotation
*
* @param annotationClass
* @param annotation
*/
protected void appendAnnotation(Class<?> annotationClass, Object annotation) {
Method[] methods = annotationClass.getMethods();
for (Method method : methods) {
if ((((((method.getDeclaringClass() != Object.class) && (method.getDeclaringClass() != Annotation.class)) && (method.getReturnType() != void.class)) && (method.getParameterTypes().length == 0)) && Modifier.isPublic(method.getModifiers())) && (!Modifier.isStatic(method.getModifiers()))) {
try {
String property = method.getName();
if ("interfaceClass".equals(property) || "interfaceName".equals(property)) {
property = "interface";
}
String setter = calculatePropertyToSetter(property);
Object value
= method.invoke(annotation);
if ((value != null) && (!value.equals(method.getDefaultValue()))) {
Class<?> parameterType = ReflectUtils.getBoxedClass(method.getReturnType());
if ("filter".equals(property) || "listener".equals(property)) {parameterType = String.class;
value = StringUtils.join(((String[]) (value)), ",");
}
else if ("parameters".equals(property)) {
parameterType = Map.class;
value = CollectionUtils.toStringMap(((String[]) (value)));
}
try {
Method setterMethod = getClass().getMethod(setter, parameterType);
setterMethod.invoke(this, value);
} catch (NoSuchMethodException e) {
// ignore
}
}
} catch (Throwable e) {
logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", e.getMessage(), e);
}
} }
} | 3.26 |
dubbo_DubboShutdownHook_unregister_rdh | /**
* Unregister the ShutdownHook
*/
public void unregister() {
if ((!ignoreListenShutdownHook) && registered.compareAndSet(true, false)) {
if (this.isAlive()) {
// DubboShutdownHook thread is running
return;
}
try {
Runtime.getRuntime().removeShutdownHook(this);} catch (IllegalStateException e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e);
}
catch (Exception e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e);
}
}
} | 3.26 |
dubbo_DubboShutdownHook_register_rdh | /**
* Register the ShutdownHook
*/
public void register() {
if ((!ignoreListenShutdownHook) && registered.compareAndSet(false, true)) {
try {
Runtime.getRuntime().addShutdownHook(this);
} catch (IllegalStateException
e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "register shutdown hook failed: " + e.getMessage(), e);
} catch (Exception e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "register shutdown hook failed: " + e.getMessage(), e);
}
}
} | 3.26 |
dubbo_Converter_getTargetType_rdh | /**
* Get the target type
*
* @return non-null
*/
default Class<T> getTargetType() {
return findActualTypeArgument(getClass(), Converter.class, 1);} | 3.26 |
dubbo_Converter_getSourceType_rdh | /**
* Get the source type
*
* @return non-null
*/
default Class<S> getSourceType() {return findActualTypeArgument(getClass(), Converter.class, 0);
} | 3.26 |
dubbo_Converter_accept_rdh | /**
* Accept the source type and target type or not
*
* @param sourceType
* the source type
* @param targetType
* the target type
* @return if accepted, return <code>true</code>, or <code>false</code>
*/
default boolean accept(Class<?> sourceType, Class<?> targetType) {
return isAssignableFrom(sourceType, getSourceType()) && isAssignableFrom(targetType, getTargetType());
} | 3.26 |
dubbo_ReflectUtils_isCompatible_rdh | /**
* is compatible.
*
* @param cs
* class array.
* @param os
* object array.
* @return compatible or not.
*/
public static boolean isCompatible(Class<?>[] cs, Object[] os) {
int len = cs.length;
if (len != os.length) {
return false;
}
if (len == 0) {
return true;
}
for (int i = 0; i
< len; i++) {
if (!isCompatible(cs[i], os[i])) {return false;
}
}
return true;
} | 3.26 |
dubbo_ReflectUtils_findMethodByMethodName_rdh | /**
*
* @param clazz
* Target class to find method
* @param methodName
* Method signature, e.g.: method1(int, String). It is allowed to provide method name only, e.g.: method2
* @return target method
* @throws NoSuchMethodException
* @throws ClassNotFoundException
* @throws IllegalStateException
* when multiple methods are found (overridden method when parameter info is not provided)
* @deprecated Recommend {@link MethodUtils#findMethod(Class, String, Class[])}
*/
@Deprecated
public static Method findMethodByMethodName(Class<?> clazz, String methodName) throws NoSuchMethodException, ClassNotFoundException {
return findMethodByMethodSignature(clazz, methodName, null);
} | 3.26 |
dubbo_ReflectUtils_resolveTypes_rdh | /**
* Resolve the types of the specified values
*
* @param values
* the values
* @return If can't be resolved, return {@link ReflectUtils#EMPTY_CLASS_ARRAY empty class array}
* @since 2.7.6
*/
public static Class[] resolveTypes(Object... values) {
if (isEmpty(values)) {
return EMPTY_CLASS_ARRAY;
}
int size = values.length;
Class[] types = new Class[size];for (int i = 0; i < size; i++) {
Object value = values[i];
types[i] = (value == null)
? null : value.getClass();
}
return types;
} | 3.26 |