id
int64
0
10.2k
text_id
stringlengths
17
67
repo_owner
stringclasses
232 values
repo_name
stringclasses
295 values
issue_url
stringlengths
39
89
pull_url
stringlengths
37
87
comment_url
stringlengths
37
94
links_count
int64
1
2
link_keyword
stringclasses
12 values
issue_title
stringlengths
7
197
issue_body
stringlengths
45
21.3k
base_sha
stringlengths
40
40
head_sha
stringlengths
40
40
diff_url
stringlengths
120
170
diff
stringlengths
478
132k
changed_files
stringlengths
47
2.6k
changed_files_exts
stringclasses
22 values
changed_files_count
int64
1
22
java_changed_files_count
int64
1
22
kt_changed_files_count
int64
0
0
py_changed_files_count
int64
0
0
code_changed_files_count
int64
1
22
repo_symbols_count
int64
32.6k
242M
repo_tokens_count
int64
6.59k
49.2M
repo_lines_count
int64
992
6.2M
repo_files_without_tests_count
int64
12
28.1k
changed_symbols_count
int64
0
36.1k
changed_tokens_count
int64
0
6.5k
changed_lines_count
int64
0
561
changed_files_without_tests_count
int64
1
17
issue_symbols_count
int64
45
21.3k
issue_words_count
int64
2
1.39k
issue_tokens_count
int64
13
4.47k
issue_lines_count
int64
1
325
issue_links_count
int64
0
19
issue_code_blocks_count
int64
0
31
pull_create_at
timestamp[s]
repo_stars
int64
10
44.3k
repo_language
stringclasses
8 values
repo_languages
stringclasses
296 values
repo_license
stringclasses
2 values
519
wso2/product-is/4636/3914
wso2
product-is
https://github.com/wso2/product-is/issues/3914
https://github.com/wso2/product-is/pull/4636
https://github.com/wso2/product-is/pull/4636
1
fix
OIdC Session Management RP-initiated logout : Backchannel logout tokens form param should change to "logout_token"
backchannel logout tokens have a form param "logoutToken", which, according to the spec, should be "logout_token". Ref: http://openid.net/specs/openid-connect-backchannel-1_0.html#BCRequest.
b97dce268a5c3d198a24dbcce29a553fae6db0d5
3c3dba0dea7cf1f015e02613bd9aac6532794aaa
https://github.com/wso2/product-is/compare/b97dce268a5c3d198a24dbcce29a553fae6db0d5...3c3dba0dea7cf1f015e02613bd9aac6532794aaa
diff --git a/modules/samples/oauth2/playground2/src/main/org/wso2/sample/identity/oauth2/OIDCBackchannelLogoutServlet.java b/modules/samples/oauth2/playground2/src/main/org/wso2/sample/identity/oauth2/OIDCBackchannelLogoutServlet.java index 9def5b6fa..902953f65 100644 --- a/modules/samples/oauth2/playground2/src/main/org/wso2/sample/identity/oauth2/OIDCBackchannelLogoutServlet.java +++ b/modules/samples/oauth2/playground2/src/main/org/wso2/sample/identity/oauth2/OIDCBackchannelLogoutServlet.java @@ -56,8 +56,8 @@ public class OIDCBackchannelLogoutServlet extends HttpServlet { String sid = null; try { - sid = (String) SignedJWT.parse(req.getParameter("logoutToken")).getJWTClaimsSet().getClaim("sid"); - log.info("Logout token: " + req.getParameter("logoutToken")); + sid = (String) SignedJWT.parse(req.getParameter("logout_token")).getJWTClaimsSet().getClaim("sid"); + log.info("Logout token: " + req.getParameter("logout_token")); } catch (ParseException e) { log.error("Error in generating Logout Token.", e); }
['modules/samples/oauth2/playground2/src/main/org/wso2/sample/identity/oauth2/OIDCBackchannelLogoutServlet.java']
{'.java': 1}
1
1
0
0
1
1,655,058
326,093
41,410
298
375
80
4
1
190
18
47
1
1
0
1970-01-01T00:25:52
627
Java
{'Java': 5237276, 'JavaScript': 1286957, 'CSS': 701967, 'HTML': 68342, 'Python': 56729, 'Handlebars': 56641, 'Shell': 51738, 'Batchfile': 33345, 'Jinja': 12917}
Apache License 2.0
9,175
huaweicloud/sermant/970/969
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/969
https://github.com/huaweicloud/Sermant/pull/970
https://github.com/huaweicloud/Sermant/pull/970
1
fixes
【fix】fix bug springboot registry plugin
### What happened? if url contains space , request will fail; We need use the encoded url replcae decoded url ### How can we reproduce it (as minimally and precisely as possible)? Use url which has space(%20) request ### Anything else we need to know? _No response_ ### Sermant version <details> 0.7.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
e079acbd008d426caabb0ef8eed4b46b4a8255de
0568661b7abc9911afd6aec3e4a95e80a8a0c7cb
https://github.com/huaweicloud/sermant/compare/e079acbd008d426caabb0ef8eed4b46b4a8255de...0568661b7abc9911afd6aec3e4a95e80a8a0c7cb
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 4b05f568..7dd73d7e 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -308,9 +308,9 @@ public class RequestInterceptorUtils { .append(HttpConstants.HTTP_URL_COLON) .append(serviceInstance.getPort()) .append(path); - if (uri.getQuery() != null && method.equals(HttpConstants.HTTP_GET)) { + if (uri.getRawQuery() != null && method.equals(HttpConstants.HTTP_GET)) { urlBuild.append(HttpConstants.HTTP_URL_UNKNOWN) - .append(uri.getQuery()); + .append(uri.getRawQuery()); } return urlBuild.toString(); }
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java']
{'.java': 1}
1
1
0
0
1
2,909,138
667,695
92,192
978
249
50
4
1
576
92
147
37
0
1
1970-01-01T00:27:49
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,176
huaweicloud/sermant/964/963
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/963
https://github.com/huaweicloud/Sermant/pull/964
https://github.com/huaweicloud/Sermant/pull/964
1
fixes
【fix】fix protocol of feign for spring-boot-registry
### What happened? feign maybe not effect ### How can we reproduce it (as minimally and precisely as possible)? N/A ### Anything else we need to know? _No response_ ### Sermant version <details> 0.7.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
fa2a96fe391294765180eae060a694bc71e5ae9f
86ddedacf126a020396c1195d8f591499ceb78a0
https://github.com/huaweicloud/sermant/compare/fa2a96fe391294765180eae060a694bc71e5ae9f...86ddedacf126a020396c1195d8f591499ceb78a0
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java index e86e3bc3..66d23623 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java @@ -48,14 +48,15 @@ public class FeignInvokeInterceptor extends MarkInterceptor { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); Request request = (Request) context.getArguments()[0]; Map<String, String> urlInfo = RequestInterceptorUtils.recoverUrl(request.url()); - if (!PlugEffectWhiteBlackUtils.isAllowRun(request.url(), urlInfo.get(HttpConstants.HTTP_URI_HOST))) { + if (!PlugEffectWhiteBlackUtils.isAllowRun(urlInfo.get(HttpConstants.HTTP_URI_HOST), + urlInfo.get(HttpConstants.HTTP_URI_SERVICE))) { return context; } RequestInterceptorUtils.printRequestLog("feign", urlInfo); Optional<Object> result = invokerService.invoke( buildInvokerFunc(context, request, urlInfo), ex -> ex, - urlInfo.get(HttpConstants.HTTP_URI_HOST)); + urlInfo.get(HttpConstants.HTTP_URI_SERVICE)); if (result.isPresent()) { Object obj = result.get(); if (obj instanceof Exception) { diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java index daca8098..dc1ae2da 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java @@ -68,7 +68,7 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { return context; } Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); - if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_SERVICE))) { return context; } RequestInterceptorUtils.printRequestLog("OkHttp3", hostAndPath); @@ -77,7 +77,7 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { invokerService.invoke( buildInvokerFunc(uri, hostAndPath, request, rebuildRequest, context), buildExFunc(rebuildRequest), - hostAndPath.get(HttpConstants.HTTP_URI_HOST)) + hostAndPath.get(HttpConstants.HTTP_URI_SERVICE)) .ifPresent(o -> setResultOrThrow(context, o, uri.getPath())); return context; } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java index 6070583c..ebcee18e 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java @@ -70,7 +70,7 @@ public class OkHttpClientInterceptor extends MarkInterceptor { return context; } Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); - if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_SERVICE))) { return context; } RequestInterceptorUtils.printRequestLog("OkHttp", hostAndPath); @@ -79,7 +79,7 @@ public class OkHttpClientInterceptor extends MarkInterceptor { invokerService.invoke( buildInvokerFunc(uri, hostAndPath, request, rebuildRequest, context), buildExFunc(rebuildRequest), - hostAndPath.get(HttpConstants.HTTP_URI_HOST)) + hostAndPath.get(HttpConstants.HTTP_URI_SERVICE)) .ifPresent(o -> setResultOrThrow(context, o, uri.getPath())); return context; } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java index 73dcf258..c64b0f6b 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java @@ -54,14 +54,14 @@ public class RestTemplateInterceptor extends MarkInterceptor { return context; } Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); - if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_SERVICE))) { return context; } RequestInterceptorUtils.printRequestLog("restTemplate", hostAndPath); Optional<Object> result = invokerService.invoke( buildInvokerFunc(uri, hostAndPath, context, httpMethod), ex -> ex, - hostAndPath.get(HttpConstants.HTTP_URI_HOST)); + hostAndPath.get(HttpConstants.HTTP_URI_SERVICE)); if (result.isPresent()) { Object obj = result.get(); if (obj instanceof Exception) { diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java index d8d525dd..0a1752f1 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java @@ -117,7 +117,7 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { if (hostAndPath == null) { return context; } - final String serviceName = hostAndPath.get(HttpConstants.HTTP_URI_HOST); + final String serviceName = hostAndPath.get(HttpConstants.HTTP_URI_SERVICE); cleanCallback(); final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); final HttpAsyncContext asyncContext = HttpAsyncUtils.getOrCreateContext(); @@ -139,7 +139,7 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { if (originHostName == null || hostAndPath == null) { return false; } - return PlugEffectWhiteBlackUtils.isAllowRun(originHostName, hostAndPath.get(HttpConstants.HTTP_URI_HOST)); + return PlugEffectWhiteBlackUtils.isAllowRun(originHostName, hostAndPath.get(HttpConstants.HTTP_URI_SERVICE)); } private void acquireHostPath(HttpAsyncRequestProducer httpAsyncRequestProducer) throws Exception { diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java index ac970729..ce365260 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java @@ -75,14 +75,14 @@ public class HttpClient4xInterceptor extends MarkInterceptor { if (hostAndPath.isEmpty()) { return context; } - if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_SERVICE))) { return context; } RequestInterceptorUtils.printRequestLog("HttpClient", hostAndPath); invokerService.invoke( buildInvokerFunc(hostAndPath, httpRequest, context), buildExFunc(httpRequest, Thread.currentThread().getContextClassLoader()), - hostAndPath.get(HttpConstants.HTTP_URI_HOST)) + hostAndPath.get(HttpConstants.HTTP_URI_SERVICE)) .ifPresent(result -> this.setResultOrThrow(context, result, hostAndPath.get(HttpConstants.HTTP_URI_PATH))); return context; diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java index a4faf8ec..a19f0834 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java @@ -86,7 +86,7 @@ public class HttpUrlConnectionConnectInterceptor extends MarkInterceptor { } final String fullUrl = url.toString(); Map<String, String> urlInfo = RequestInterceptorUtils.recoverUrl(url); - if (!PlugEffectWhiteBlackUtils.isPlugEffect(urlInfo.get(HttpConstants.HTTP_URI_HOST))) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(urlInfo.get(HttpConstants.HTTP_URI_SERVICE))) { return context; } HttpConnectionUtils.save(new HttpConnectionContext(urlInfo, url)); @@ -94,7 +94,7 @@ public class HttpUrlConnectionConnectInterceptor extends MarkInterceptor { invokerService.invoke( buildInvokerFunc(context, url, urlInfo), ex -> ex, - urlInfo.get(HttpConstants.HTTP_URI_HOST)) + urlInfo.get(HttpConstants.HTTP_URI_SERVICE)) .ifPresent(obj -> { if (obj instanceof Exception) { LOGGER.log(Level.SEVERE, "request is error, uri is " + fullUrl, (Exception) obj); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionResponseStreamInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionResponseStreamInterceptor.java index 85e78dc7..2a629e81 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionResponseStreamInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionResponseStreamInterceptor.java @@ -90,7 +90,7 @@ public class HttpUrlConnectionResponseStreamInterceptor implements Interceptor { Optional<Object> result = invokerService.invoke( invokerContextObjectFunction, ex -> ex, - urlInfo.get(HttpConstants.HTTP_URI_HOST)); + urlInfo.get(HttpConstants.HTTP_URI_SERVICE)); if (result.isPresent()) { Object obj = result.get(); if (obj instanceof Exception) { @@ -117,11 +117,15 @@ public class HttpUrlConnectionResponseStreamInterceptor implements Interceptor { if (ex instanceof SocketTimeoutException) { // 此处仅SocketTimeoutException: Read timed out进行重试 final String message = ex.getMessage(); - return "Read timed out".equalsIgnoreCase(message) && this.lbConfig.isEnableSocketReadTimeoutRetry(); + return "Read timed out".equalsIgnoreCase(message) && isEnableRetry(); } return false; } + private boolean isEnableRetry() { + return this.lbConfig.isEnableSocketReadTimeoutRetry() && this.lbConfig.getMaxRetry() > 0; + } + private void resetStats(ExecuteContext context) { ReflectUtils.setFieldValue(context.getObject(), "rememberedException", null); ReflectUtils.setFieldValue(context.getObject(), "failedOnce", false); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/HttpConstants.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/HttpConstants.java index 25ddef6c..261d8a22 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/HttpConstants.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/HttpConstants.java @@ -33,7 +33,12 @@ public class HttpConstants { public static final String HTTP_GET = "GET"; /** - * 主机名 + * 从url解析的服务名 + */ + public static final String HTTP_URI_SERVICE = "serviceName"; + + /** + * 域名 */ public static final String HTTP_URI_HOST = "host"; diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 885d17c5..4b05f568 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -96,7 +96,7 @@ public class RequestInterceptorUtils { } final Map<String, String> result = new HashMap<>(URL_INFO_INIT_SIZE); result.put(HttpConstants.HTTP_URL_SCHEME, protocol); - result.put(HttpConstants.HTTP_URI_HOST, tokenizer.nextToken(delim)); + result.put(HttpConstants.HTTP_URI_SERVICE, tokenizer.nextToken(delim)); result.put(HttpConstants.HTTP_URI_PATH, formatPath(tokenizer.nextToken(HttpConstants.EMPTY_STR), url.getQuery())); return result; @@ -123,11 +123,11 @@ public class RequestInterceptorUtils { String scheme = rawScheme.substring(0, rawScheme.length() - 1); // domain 域名 - urlTokens.nextToken(baseSlash); + Map<String, String> result = new HashMap<>(URL_INFO_INIT_SIZE); + result.put(HttpConstants.HTTP_URI_HOST, urlTokens.nextToken(baseSlash)); final String serviceName = urlTokens.nextToken(baseSlash); final String path = urlTokens.nextToken(HttpConstants.EMPTY_STR); - Map<String, String> result = new HashMap<>(URL_INFO_INIT_SIZE); - result.put(HttpConstants.HTTP_URI_HOST, serviceName); + result.put(HttpConstants.HTTP_URI_SERVICE, serviceName); result.put(HttpConstants.HTTP_URL_SCHEME, scheme); result.put(HttpConstants.HTTP_URI_PATH, path); return result; @@ -175,7 +175,7 @@ public class RequestInterceptorUtils { if (!RECORDER.isEnable()) { return; } - String path = String.format(Locale.ENGLISH, "/%s%s", hostAndPath.get(HttpConstants.HTTP_URI_HOST), + String path = String.format(Locale.ENGLISH, "/%s%s", hostAndPath.get(HttpConstants.HTTP_URI_SERVICE), hostAndPath.get(HttpConstants.HTTP_URI_PATH)); LOGGER.log(Level.FINE, String.format(Locale.ENGLISH, "[%s] request [%s] has been intercepted!", source, path)); RECORDER.beforeRequest(); @@ -284,7 +284,7 @@ public class RequestInterceptorUtils { if (tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH) <= 0) { return result; } - result.put(HttpConstants.HTTP_URI_HOST, + result.put(HttpConstants.HTTP_URI_SERVICE, tempPath.substring(0, tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH))); result.put(HttpConstants.HTTP_URI_PATH, tempPath.substring(tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH)));
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionResponseStreamInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/HttpConstants.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java']
{'.java': 10}
10
10
0
0
10
2,874,679
660,108
90,995
969
3,898
780
56
10
474
74
126
36
0
1
1970-01-01T00:27:48
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,186
huaweicloud/sermant/838/837
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/837
https://github.com/huaweicloud/Sermant/pull/838
https://github.com/huaweicloud/Sermant/pull/838
1
fixes
【bug】fix the registry plugin bugs
### What happened? feign core 10.12无法正常工作,resttemplate 5.3.13/5.1.2.RELEASE无法正确处理异常 ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version 0.6.1 ### OS version n/a
2cf78adfe99402a2de2d5ca361bc9091f957d10b
c465388a830cbd0d44ce56a31b0c50a891be2b51
https://github.com/huaweicloud/sermant/compare/2cf78adfe99402a2de2d5ca361bc9091f957d10b...c465388a830cbd0d44ce56a31b0c50a891be2b51
diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/PluginManager.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/PluginManager.java index 423a720a..d9c5d91a 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/PluginManager.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/PluginManager.java @@ -113,7 +113,7 @@ public class PluginManager { private static void initPlugin(String pluginName, String pluginPackage, Instrumentation instrumentation) { final String pluginPath = pluginPackage + File.separatorChar + pluginName; if (!new File(pluginPath).exists()) { - LOGGER.warning(String.format(Locale.ROOT, + LOGGER.severe(String.format(Locale.ROOT, "Plugin directory %s does not exist, so skip initializing %s. ", pluginPath, pluginName)); return; } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java index 8a481081..498ff966 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java @@ -64,7 +64,7 @@ public class FeignInvokeInterceptor extends MarkInterceptor { return invokerContext -> { context.getArguments()[0] = Request.create(request.httpMethod(), RequestInterceptorUtils.buildUrl(urlInfo, invokerContext.getServiceInstance()), - request.headers(), request.requestBody()); + request.headers(), request.body(), request.charset()); return RequestInterceptorUtils.buildFunc(context, invokerContext).get(); }; } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java index 9497ad8a..080eeaca 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java @@ -22,21 +22,19 @@ import com.huawei.discovery.utils.HttpConstants; import com.huawei.discovery.utils.PlugEffectWhiteBlackUtils; import com.huawei.discovery.utils.RequestInterceptorUtils; +import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.client.ClientHttpResponse; -import java.io.IOException; -import java.io.InputStream; import java.net.URI; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; /** * 拦截获取服务列表 @@ -45,23 +43,31 @@ import java.util.function.Function; * @since 2022-09-27 */ public class RestTemplateInterceptor extends MarkInterceptor { + private static final Logger LOGGER = LoggerFactory.getLogger(); @Override protected ExecuteContext doBefore(ExecuteContext context) throws Exception { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); - URI uri = (URI)context.getArguments()[0]; - HttpMethod httpMethod = (HttpMethod)context.getArguments()[1]; + URI uri = (URI) context.getArguments()[0]; + HttpMethod httpMethod = (HttpMethod) context.getArguments()[1]; Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); if (!PlugEffectWhiteBlackUtils.isAllowRun(uri.getHost(), hostAndPath.get(HttpConstants.HTTP_URI_HOST), true)) { return context; } RequestInterceptorUtils.printRequestLog("restTemplate", hostAndPath); - invokerService.invoke( - buildInvokerFunc(uri, hostAndPath, context, httpMethod), - this::buildErrorResponse, - hostAndPath.get(HttpConstants.HTTP_URI_HOST)) - .ifPresent(context::skip); + Optional<Object> result = invokerService.invoke( + buildInvokerFunc(uri, hostAndPath, context, httpMethod), + this::buildErrorResponse, + hostAndPath.get(HttpConstants.HTTP_URI_HOST)); + if (result.isPresent()) { + Object obj = result.get(); + if (obj instanceof Exception) { + LOGGER.log(Level.SEVERE, "request is error, uri is " + uri, (Exception) obj); + return context; + } + context.skip(obj); + } return context; } @@ -89,7 +95,7 @@ public class RestTemplateInterceptor extends MarkInterceptor { ExecuteContext context, HttpMethod httpMethod) { return invokerContext -> { String url = RequestInterceptorUtils.buildUrlWithIp(uri, invokerContext.getServiceInstance(), - hostAndPath.get(HttpConstants.HTTP_URI_PATH), httpMethod.name()); + hostAndPath.get(HttpConstants.HTTP_URI_PATH), httpMethod.name()); context.getArguments()[0] = rebuildUri(url, uri); return RequestInterceptorUtils.buildFunc(context, invokerContext).get(); }; @@ -101,44 +107,8 @@ public class RestTemplateInterceptor extends MarkInterceptor { * @param ex * @return 响应 */ - private ClientHttpResponse buildErrorResponse(Exception ex) { - return new ClientHttpResponse() { - - @Override - public HttpHeaders getHeaders() { - return new HttpHeaders(); - } - - @Override - public InputStream getBody() throws IOException { - return new InputStream() { - @Override - public int read() throws IOException { - return 0; - } - }; - } - - @Override - public HttpStatus getStatusCode() throws IOException { - return HttpStatus.INTERNAL_SERVER_ERROR; - } - - @Override - public int getRawStatusCode() throws IOException { - return HttpStatus.INTERNAL_SERVER_ERROR.value(); - } - - @Override - public String getStatusText() throws IOException { - return ""; - } - - @Override - public void close() { - - } - }; + private Exception buildErrorResponse(Exception ex) { + return ex; } @Override diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/RestTemplateInterceptorTest.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/RestTemplateInterceptorTest.java index cd390e92..c6024f6b 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/RestTemplateInterceptorTest.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/RestTemplateInterceptorTest.java @@ -16,11 +16,13 @@ package com.huawei.discovery.interceptors; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URI; -import java.util.Map; -import java.util.Optional; +import com.huawei.discovery.config.PlugEffectWhiteBlackConstants; +import com.huawei.discovery.entity.PlugEffectStategyCache; +import com.huawei.discovery.service.InvokerService; + +import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; +import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; +import com.huaweicloud.sermant.core.utils.ReflectUtils; import org.junit.Assert; import org.junit.Test; @@ -28,15 +30,12 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.client.ClientHttpResponse; -import com.huawei.discovery.config.PlugEffectWhiteBlackConstants; -import com.huawei.discovery.entity.PlugEffectStategyCache; -import com.huawei.discovery.service.InvokerService; -import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; -import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; -import com.huaweicloud.sermant.core.utils.ReflectUtils; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Map; +import java.util.Optional; /** * RestTemplate调用测试 @@ -74,10 +73,10 @@ public class RestTemplateInterceptorTest extends BaseTest { interceptor = new RestTemplateInterceptor(); MockitoAnnotations.openMocks(this); pluginServiceManagerMockedStatic.when(() -> PluginServiceManager.getPluginService(InvokerService.class)) - .thenReturn(invokerService); + .thenReturn(invokerService); } - private URI createURI(String url){ + private URI createURI(String url) { return URI.create(url); } @@ -99,27 +98,27 @@ public class RestTemplateInterceptorTest extends BaseTest { //含域名,设置多个域名,未设置黑白名单 discoveryPluginConfig.setRealmName(realmNames); interceptor.doBefore(context); - URI uriNew = (URI)context.getArguments()[0]; + URI uriNew = (URI) context.getArguments()[0]; Assert.assertEquals(url, uriNew.toString()); discoveryPluginConfig.setRealmName(realmName); //含域名,设置全部通过策略 initStrategy(PlugEffectWhiteBlackConstants.STRATEGY_ALL, "zookeeper-provider-demo"); Mockito.when(invokerService.invoke(null, null, "zookeeper-provider-demo")) - .thenReturn(Optional.ofNullable(new Object())); + .thenReturn(Optional.ofNullable(new Object())); interceptor.doBefore(context); - uriNew = (URI)context.getArguments()[0]; + uriNew = (URI) context.getArguments()[0]; Assert.assertEquals(url, uriNew.toString()); } @Test public void rebuildUriTest() { Optional<Method> method = ReflectUtils.findMethod(RestTemplateInterceptor.class, "rebuildUri", - new Class[] {String.class, URI.class}); + new Class[]{String.class, URI.class}); URI uri = createURI(url); if (method.isPresent()) { Optional<Object> uriNew = ReflectUtils - .invokeMethod(interceptor, method.get(), new Object[] {convertUrl, uri}); + .invokeMethod(interceptor, method.get(), new Object[]{convertUrl, uri}); Assert.assertEquals(convertUrl, uriNew.get().toString()); } } @@ -127,12 +126,12 @@ public class RestTemplateInterceptorTest extends BaseTest { @Test public void buildErrorResponseTest() throws IOException { Optional<Method> method = ReflectUtils.findMethod(RestTemplateInterceptor.class, "buildErrorResponse", - new Class[] {Exception.class}); + new Class[]{Exception.class}); Exception ex = new Exception(); if (method.isPresent()) { Optional<Object> exception = ReflectUtils - .invokeMethod(interceptor, method.get(), new Object[] {ex}); - Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ((ClientHttpResponse)exception.get()).getStatusCode()); + .invokeMethod(interceptor, method.get(), new Object[]{ex}); + Assert.assertEquals(ex, exception.get()); } } }
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/PluginManager.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/RestTemplateInterceptorTest.java']
{'.java': 4}
4
4
0
0
4
3,129,595
717,319
98,560
1,112
3,040
503
76
3
277
37
89
19
0
0
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,185
huaweicloud/sermant/839/835
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/835
https://github.com/huaweicloud/Sermant/pull/839
https://github.com/huaweicloud/Sermant/pull/839
1
fixes
【bug】fix the registry plugin bugs
### What happened? can not work ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
5b4a28a42a6380a36dea764fc07bfffe45dc67da
4c76c97cfad4011049c478f85438d437b21353af
https://github.com/huaweicloud/sermant/compare/5b4a28a42a6380a36dea764fc07bfffe45dc67da...4c76c97cfad4011049c478f85438d437b21353af
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java index ce5ee597..454ca55e 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java @@ -40,6 +40,7 @@ import java.net.ConnectException; import java.net.NoRouteToHostException; import java.time.LocalDateTime; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; @@ -66,9 +67,8 @@ public class RetryServiceImpl implements InvokerService { ConnectException.class, NoRouteToHostException.class); - private final List<String> rawRetryEx = Arrays.asList( - "org.apache.http.conn.ConnectTimeoutException", - "org.apache.http.NoHttpResponseException"); + private final List<String> rawRetryEx = Collections.singletonList( + "org.apache.http.conn.ConnectTimeoutException"); private final Map<String, Retry> retryCache = new ConcurrentHashMap<>();
['sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java']
{'.java': 1}
1
1
0
0
1
3,128,862
717,238
98,530
1,112
342
60
6
1
463
73
123
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,184
huaweicloud/sermant/840/835
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/835
https://github.com/huaweicloud/Sermant/pull/840
https://github.com/huaweicloud/Sermant/pull/840
1
fixes
【bug】fix the registry plugin bugs
### What happened? can not work ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
9c4a080942067f774c7d02a2dc5c6e64717565f2
31e113661c432a76cbbe2dece28674bcf5df202c
https://github.com/huaweicloud/sermant/compare/9c4a080942067f774c7d02a2dc5c6e64717565f2...31e113661c432a76cbbe2dece28674bcf5df202c
diff --git a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huawei/sermant/premain/AgentPremain.java b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huawei/sermant/premain/AgentPremain.java index 1844d8f1..f29440dd 100644 --- a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huawei/sermant/premain/AgentPremain.java +++ b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huawei/sermant/premain/AgentPremain.java @@ -74,6 +74,8 @@ public class AgentPremain { // agent core入口 LOGGER.info("Loading sermant agent... "); AgentCoreEntrance.run(argsMap, instrumentation); + + LOGGER.info("Load sermant done. "); } catch (Exception e) { LOGGER.severe( String.format(Locale.ROOT, "Loading sermant agent failed, %s. ", e)); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java index 464d7b58..ed6ef173 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java @@ -16,7 +16,6 @@ package com.huawei.discovery.interceptors.httpclient; -import com.huawei.discovery.entity.SimpleRequestRecorder; import com.huawei.discovery.interceptors.MarkInterceptor; import com.huawei.discovery.retry.InvokerContext; import com.huawei.discovery.service.InvokerService; @@ -60,8 +59,6 @@ public class HttpClient4xInterceptor extends MarkInterceptor { private final AtomicBoolean isLoaded = new AtomicBoolean(); - private final SimpleRequestRecorder requestRecorder = new SimpleRequestRecorder(); - @Override public ExecuteContext doBefore(ExecuteContext context) { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); @@ -77,7 +74,6 @@ public class HttpClient4xInterceptor extends MarkInterceptor { return context; } RequestInterceptorUtils.printRequestLog("HttpClient", hostAndPath); - requestRecorder.beforeRequest(); invokerService.invoke( buildInvokerFunc(hostAndPath, uri, httpRequest, context), buildExFunc(httpRequest), diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/RetryConfig.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/RetryConfig.java index 40771082..335aa246 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/RetryConfig.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/RetryConfig.java @@ -127,10 +127,17 @@ public class RetryConfig { this.name = name; } - private Predicate<Throwable> buildThrowPredicate(List<Class<? extends Throwable>> retryEx, + /** + * 构建异常判断器 + * + * @param retryEx 类型判断 + * @param rawRetryEx 类全限定名判断 + * @return Predicate + */ + public static Predicate<Throwable> buildThrowPredicate(List<Class<? extends Throwable>> retryEx, List<String> rawRetryEx) { final Predicate<Throwable> assignableEx = ex -> { - if (ex == null) { + if (ex == null || retryEx == null) { return false; } for (Class<? extends Throwable> cur : retryEx) { @@ -144,10 +151,7 @@ public class RetryConfig { return false; }; final Predicate<Throwable> rawEx = ex -> { - if (ex == null) { - return false; - } - if (rawRetryEx == null) { + if (ex == null || rawRetryEx == null) { return false; } return rawRetryEx.stream().anyMatch(clazz -> isAssignableFrom(clazz, ex.getClass())); @@ -155,7 +159,7 @@ public class RetryConfig { return assignableEx.or(rawEx); } - private boolean isAssignableFrom(String clazz, Class<?> ex) { + private static boolean isAssignableFrom(String clazz, Class<?> ex) { if (clazz.equals(ex.getName())) { return true; } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index f26d6bb5..0ed24ac4 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -142,7 +142,7 @@ public class RequestInterceptorUtils { } catch (InvocationTargetException e) { invokerContext.setEx(e.getTargetException()); LOGGER.log(Level.FINE, String.format(Locale.ENGLISH, "invoke method [%s] failed", - context.getMethod().getName()), e); + context.getMethod().getName()), e.getTargetException()); } return Optional.empty(); }; diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/DiscoveryManager.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/DiscoveryManager.java index 92fe7357..985a0ed7 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/DiscoveryManager.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/DiscoveryManager.java @@ -219,6 +219,9 @@ public enum DiscoveryManager { private Loadbalancer getLoadbalancer(String serviceName) { checkStats(); return serviceLbCache.computeIfAbsent(serviceName, curService -> { + LOGGER.info(String.format(Locale.ENGLISH, + "Use the loadbalancer [%s], if the lb does not support, it will replace by RoundRobin", + lbConfig.getLbType())); final Class<? extends AbstractLoadbalancer> lbClazz = lbCache .getOrDefault(lbConfig.getLbType(), RoundRobinLoadbalancer.class); return createLb(lbClazz).orElse(null); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java index 454ca55e..5e868aa5 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java @@ -135,10 +135,10 @@ public class RetryServiceImpl implements InvokerService { throws Exception { final RetryContext<Recorder> context = retry.context(); final InvokerContext invokerContext = new InvokerContext(); - boolean isRetry = false; + boolean isInRetry = false; do { final long start = System.currentTimeMillis(); - final Optional<ServiceInstance> instance = choose(serviceName, isRetry, + final Optional<ServiceInstance> instance = choose(serviceName, isInRetry, invokerContext.getServiceInstance()); if (!instance.isPresent()) { throw new ProviderException("Can not found provider service named: " + serviceName); @@ -149,7 +149,7 @@ public class RetryServiceImpl implements InvokerService { long consumeTimeMs; try { final Object result = invokeFunc.apply(invokerContext); - isRetry = true; + isInRetry = true; consumeTimeMs = System.currentTimeMillis() - start; if (invokerContext.getEx() != null) { // 此处调用器, 若调用出现异常, 则以异常结果返回 @@ -163,7 +163,7 @@ public class RetryServiceImpl implements InvokerService { return Optional.ofNullable(result); } } catch (Exception ex) { - isRetry = true; + isInRetry = true; handleEx(ex, context, stats, System.currentTimeMillis() - start); } } while (true);
['sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/DiscoveryManager.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java', 'sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huawei/sermant/premain/AgentPremain.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/RetryConfig.java']
{'.java': 6}
6
6
0
0
6
3,128,849
717,234
98,530
1,112
1,685
341
37
6
463
73
123
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,183
huaweicloud/sermant/841/835
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/835
https://github.com/huaweicloud/Sermant/pull/841
https://github.com/huaweicloud/Sermant/pull/841
1
fixes
【bug】fix the registry plugin bugs
### What happened? can not work ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
7192b632d955dab24f9b5603fb571adf18a0f589
9813581cc4f726895c46736a4794d62c7ed6e97f
https://github.com/huaweicloud/sermant/compare/7192b632d955dab24f9b5603fb571adf18a0f589...9813581cc4f726895c46736a4794d62c7ed6e97f
diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java index 983044d0..900dae41 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java @@ -72,6 +72,11 @@ public class ExecuteContext { */ private Throwable throwable; + /** + * 抛出给宿主的异常 + */ + private Throwable throwableOut; + /** * 额外的静态属性 */ @@ -208,6 +213,10 @@ public class ExecuteContext { return throwable; } + public Throwable getThrowableOut() { + return throwableOut; + } + public Map<String, Object> getExtStaticFields() { return extStaticFields; } @@ -528,6 +537,17 @@ public class ExecuteContext { return this; } + /** + * 给宿主抛出异常 + * + * @param throwableOut 抛出给宿主的异常 + * @return 执行上下文 + */ + public ExecuteContext setThrowableOut(Throwable throwableOut) { + this.throwableOut = throwableOut; + return this; + } + @Override public String toString() { return "ExecuteContext{" diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java index 1e797cb2..f5e8453c 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java @@ -49,6 +49,7 @@ public class AdviceConstTemplate { * @param extStaticFields 额外静态属性集 * @param interceptorItr 拦截器迭代器 * @param context 执行上下文 + * @throws Throwable 抛给宿主的异常 */ @Advice.OnMethodEnter(suppress = Throwable.class) public static void onMethodEnter( @@ -60,7 +61,7 @@ public class AdviceConstTemplate { @Advice.FieldValue(value = "_EXT_STATIC_FIELDS_$SERMANT", readOnly = false, typing = Assigner.Typing.DYNAMIC) Map<String, Object> extStaticFields, @Advice.Local(value = "_INTERCEPTOR_ITR_$SERMANT_LOCAL") ListIterator<Interceptor> interceptorItr, - @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) { + @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) throws Throwable { interceptorItr = interceptorMap.get(methodKey).listIterator(); context = ExecuteContext.forConstructor(cls, constructor, arguments, extStaticFields); context = CommonConstAdviser.onMethodEnter(context, interceptorItr); @@ -76,6 +77,7 @@ public class AdviceConstTemplate { * @param extMemberFields 额外成员属性集 * @param interceptorItr 拦截器迭代器 * @param context 执行上下文 + * @throws Throwable 抛给宿主的异常 */ @Advice.OnMethodExit(suppress = Throwable.class) public static void onMethodExit( @@ -85,7 +87,7 @@ public class AdviceConstTemplate { @Advice.FieldValue(value = "_EXT_MEMBER_FIELDS_$SERMANT", readOnly = false, typing = Assigner.Typing.DYNAMIC) Map<String, Object> extMemberFields, @Advice.Local(value = "_INTERCEPTOR_ITR_$SERMANT_LOCAL") ListIterator<Interceptor> interceptorItr, - @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) { + @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) throws Throwable { context = CommonConstAdviser.onMethodExit(context.afterConstructor(obj, extMemberFields), interceptorItr); extStaticFields = context.getExtStaticFields(); extMemberFields = context.getExtMemberFields(); diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java index c113def5..47c41d8b 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java @@ -51,6 +51,7 @@ public class AdviceMemberTemplate { * @param interceptorItr 拦截器迭代器 * @param context 执行上下文 * @return 是否跳过主要方法 + * @throws Throwable 抛给宿主的异常 */ @Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class) public static boolean onMethodEnter( @@ -64,7 +65,7 @@ public class AdviceMemberTemplate { @Advice.FieldValue(value = "_EXT_MEMBER_FIELDS_$SERMANT", readOnly = false, typing = Assigner.Typing.DYNAMIC) Map<String, Object> extMemberFields, @Advice.Local(value = "_INTERCEPTOR_ITR_$SERMANT_LOCAL") ListIterator<Interceptor> interceptorItr, - @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) { + @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) throws Throwable { interceptorItr = interceptorMap.get(methodKey).listIterator(); context = ExecuteContext.forMemberMethod(obj, method, arguments, extStaticFields, extMemberFields); context = CommonMethodAdviser.onMethodEnter(context, interceptorItr); @@ -83,6 +84,7 @@ public class AdviceMemberTemplate { * @param extMemberFields 额外成员属性集 * @param interceptorItr 拦截器迭代器 * @param context 执行上下文 + * @throws Throwable 抛给宿主的异常 */ @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) public static void onMethodExit( @@ -93,7 +95,7 @@ public class AdviceMemberTemplate { @Advice.FieldValue(value = "_EXT_MEMBER_FIELDS_$SERMANT", readOnly = false, typing = Assigner.Typing.DYNAMIC) Map<String, Object> extMemberFields, @Advice.Local(value = "_INTERCEPTOR_ITR_$SERMANT_LOCAL") ListIterator<Interceptor> interceptorItr, - @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) { + @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) throws Throwable { context = context.isSkip() ? context : context.afterMethod(result, throwable); context = CommonMethodAdviser.onMethodExit(context, interceptorItr); result = context.getResult(); diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java index 840462fb..a9b630c6 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java @@ -50,6 +50,7 @@ public class AdviceStaticTemplate { * @param interceptorItr 拦截器迭代器 * @param context 执行上下文 * @return 是否跳过主要方法 + * @throws Throwable 抛给宿主的异常 */ @Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class) public static boolean onMethodEnter( @@ -61,7 +62,7 @@ public class AdviceStaticTemplate { @Advice.FieldValue(value = "_EXT_STATIC_FIELDS_$SERMANT", readOnly = false, typing = Assigner.Typing.DYNAMIC) Map<String, Object> extStaticFields, @Advice.Local(value = "_INTERCEPTOR_ITR_$SERMANT_LOCAL") ListIterator<Interceptor> interceptorItr, - @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) { + @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) throws Throwable { interceptorItr = interceptorMap.get(methodKey).listIterator(); context = ExecuteContext.forStaticMethod(cls, method, arguments, extStaticFields); context = CommonMethodAdviser.onMethodEnter(context, interceptorItr); @@ -78,6 +79,7 @@ public class AdviceStaticTemplate { * @param extStaticFields 额外静态属性集 * @param interceptorItr 拦截器迭代器 * @param context 执行上下文 + * @throws Throwable 抛给宿主的异常 */ @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) public static void onMethodExit( @@ -86,7 +88,7 @@ public class AdviceStaticTemplate { @Advice.FieldValue(value = "_EXT_STATIC_FIELDS_$SERMANT", readOnly = false, typing = Assigner.Typing.DYNAMIC) Map<String, Object> extStaticFields, @Advice.Local(value = "_INTERCEPTOR_ITR_$SERMANT_LOCAL") ListIterator<Interceptor> interceptorItr, - @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) { + @Advice.Local(value = "_EXECUTE_CONTEXT_$SERMANT_LOCAL") ExecuteContext context) throws Throwable { context = context.isSkip() ? context : context.afterMethod(result, throwable); context = CommonMethodAdviser.onMethodExit(context, interceptorItr); result = context.getResult(); diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonBaseAdviser.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonBaseAdviser.java index a2ca77db..06efe3ea 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonBaseAdviser.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonBaseAdviser.java @@ -39,9 +39,10 @@ public class CommonBaseAdviser { * @param interceptorItr 拦截器双向迭代器 * @param beforeHandler before的异常处理器 * @return 执行上下文 + * @throws Throwable 抛给宿主的异常 */ public static ExecuteContext onMethodEnter(ExecuteContext context, ListIterator<Interceptor> interceptorItr, - ExceptionHandler beforeHandler) { + ExceptionHandler beforeHandler) throws Throwable { ExecuteContext newContext = context; while (interceptorItr.hasNext()) { final Interceptor interceptor = interceptorItr.next(); @@ -56,6 +57,9 @@ public class CommonBaseAdviser { } catch (Throwable t) { beforeHandler.handle(context, interceptor, t); } + if (newContext.getThrowableOut() != null) { + throw newContext.getThrowableOut(); + } } return newContext; } @@ -68,9 +72,10 @@ public class CommonBaseAdviser { * @param onThrowHandler onThrow的异常处理器 * @param afterHandler after的的异常处理器 * @return 执行上下文 + * @throws Throwable 抛给宿主的异常 */ public static ExecuteContext onMethodExit(ExecuteContext context, ListIterator<Interceptor> interceptorItr, - ExceptionHandler onThrowHandler, ExceptionHandler afterHandler) { + ExceptionHandler onThrowHandler, ExceptionHandler afterHandler) throws Throwable { ExecuteContext newContext = context; while (interceptorItr.hasPrevious()) { final Interceptor interceptor = interceptorItr.previous(); @@ -83,6 +88,9 @@ public class CommonBaseAdviser { } catch (Throwable t) { onThrowHandler.handle(newContext, interceptor, t); } + if (newContext.getThrowableOut() != null) { + throw newContext.getThrowableOut(); + } } try { final ExecuteContext tempContext = interceptor.after(newContext); @@ -92,6 +100,9 @@ public class CommonBaseAdviser { } catch (Throwable t) { afterHandler.handle(newContext, interceptor, t); } + if (newContext.getThrowableOut() != null) { + throw newContext.getThrowableOut(); + } } return newContext; } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonConstAdviser.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonConstAdviser.java index fe80c975..2a8b7161 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonConstAdviser.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonConstAdviser.java @@ -61,8 +61,10 @@ public class CommonConstAdviser { * @param context 执行上下文 * @param interceptorItr 拦截器双向迭代器 * @return 执行上下文 + * @throws Throwable 抛给宿主的异常 */ - public static ExecuteContext onMethodEnter(ExecuteContext context, ListIterator<Interceptor> interceptorItr) { + public static ExecuteContext onMethodEnter(ExecuteContext context, ListIterator<Interceptor> interceptorItr) + throws Throwable { return CommonBaseAdviser.onMethodEnter(context, interceptorItr, new CommonBaseAdviser.ExceptionHandler() { @Override @@ -78,8 +80,10 @@ public class CommonConstAdviser { * @param context 执行上下文 * @param interceptorItr 拦截器双向迭代器 * @return 执行上下文 + * @throws Throwable 抛给宿主的异常 */ - public static ExecuteContext onMethodExit(ExecuteContext context, ListIterator<Interceptor> interceptorItr) { + public static ExecuteContext onMethodExit(ExecuteContext context, ListIterator<Interceptor> interceptorItr) + throws Throwable { return CommonBaseAdviser.onMethodExit(context, interceptorItr, null, new CommonBaseAdviser.ExceptionHandler() { @Override diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonMethodAdviser.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonMethodAdviser.java index d7909964..3724811d 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonMethodAdviser.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonMethodAdviser.java @@ -61,8 +61,10 @@ public class CommonMethodAdviser { * @param context 执行上下文 * @param interceptorItr 拦截器双向迭代器 * @return 执行上下文 + * @throws Throwable 抛给宿主的异常 */ - public static ExecuteContext onMethodEnter(ExecuteContext context, ListIterator<Interceptor> interceptorItr) { + public static ExecuteContext onMethodEnter(ExecuteContext context, ListIterator<Interceptor> interceptorItr) + throws Throwable { return CommonBaseAdviser.onMethodEnter(context, interceptorItr, new CommonBaseAdviser.ExceptionHandler() { @Override @@ -78,8 +80,10 @@ public class CommonMethodAdviser { * @param context 执行上下文 * @param interceptorItr 拦截器双向迭代器 * @return 执行上下文 + * @throws Throwable 抛给宿主的异常 */ - public static ExecuteContext onMethodExit(ExecuteContext context, ListIterator<Interceptor> interceptorItr) { + public static ExecuteContext onMethodExit(ExecuteContext context, ListIterator<Interceptor> interceptorItr) + throws Throwable { return CommonBaseAdviser.onMethodExit(context, interceptorItr, new CommonBaseAdviser.ExceptionHandler() { @Override diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java index 498ff966..e905e354 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java @@ -22,16 +22,17 @@ import com.huawei.discovery.utils.HttpConstants; import com.huawei.discovery.utils.PlugEffectWhiteBlackUtils; import com.huawei.discovery.utils.RequestInterceptorUtils; +import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; import feign.Request; -import feign.Response; - -import org.apache.http.HttpStatus; import java.util.Map; +import java.util.Optional; import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; /** * 拦截获取服务列表 @@ -40,22 +41,31 @@ import java.util.function.Function; * @since 2022-09-27 */ public class FeignInvokeInterceptor extends MarkInterceptor { + private static final Logger LOGGER = LoggerFactory.getLogger(); @Override protected ExecuteContext doBefore(ExecuteContext context) throws Exception { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); - Request request = (Request)context.getArguments()[0]; + Request request = (Request) context.getArguments()[0]; Map<String, String> urlInfo = RequestInterceptorUtils.recovertUrl(request.url()); if (!PlugEffectWhiteBlackUtils.isAllowRun(request.url(), urlInfo.get(HttpConstants.HTTP_URI_HOST), false)) { return context; } RequestInterceptorUtils.printRequestLog("feign", urlInfo); - invokerService.invoke( - buildInvokerFunc(context, request, urlInfo), - buildExFunc(request), - urlInfo.get(HttpConstants.HTTP_URI_HOST)) - .ifPresent(context::skip); + Optional<Object> result = invokerService.invoke( + buildInvokerFunc(context, request, urlInfo), + ex -> ex, + urlInfo.get(HttpConstants.HTTP_URI_HOST)); + if (result.isPresent()) { + Object obj = result.get(); + if (obj instanceof Exception) { + LOGGER.log(Level.SEVERE, "request is error, uri is " + request.url(), (Exception) obj); + context.setThrowableOut((Exception) obj); + return context; + } + context.skip(obj); + } return context; } @@ -69,24 +79,6 @@ public class FeignInvokeInterceptor extends MarkInterceptor { }; } - private Function<Exception, Object> buildExFunc(Request request) { - return ex -> buildErrorResponse(ex, request); - } - - /** - * 构建feign响应 - * - * @param ex - * @return 响应 - */ - private Response buildErrorResponse(Exception ex, Request request) { - Response.Builder builder = Response.builder(); - builder.status(HttpStatus.SC_INTERNAL_SERVER_ERROR); - builder.reason(ex.getMessage()); - builder.request(request); - return builder.build(); - } - @Override public ExecuteContext after(ExecuteContext context) throws Exception { return context; diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java index 080eeaca..62181676 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java @@ -58,12 +58,13 @@ public class RestTemplateInterceptor extends MarkInterceptor { RequestInterceptorUtils.printRequestLog("restTemplate", hostAndPath); Optional<Object> result = invokerService.invoke( buildInvokerFunc(uri, hostAndPath, context, httpMethod), - this::buildErrorResponse, + ex -> ex, hostAndPath.get(HttpConstants.HTTP_URI_HOST)); if (result.isPresent()) { Object obj = result.get(); if (obj instanceof Exception) { LOGGER.log(Level.SEVERE, "request is error, uri is " + uri, (Exception) obj); + context.setThrowableOut((Exception) obj); return context; } context.skip(obj); @@ -101,16 +102,6 @@ public class RestTemplateInterceptor extends MarkInterceptor { }; } - /** - * 构建restTemplete响应 - * - * @param ex - * @return 响应 - */ - private Exception buildErrorResponse(Exception ex) { - return ex; - } - @Override public ExecuteContext after(ExecuteContext context) throws Exception { return context;
['sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonMethodAdviser.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonBaseAdviser.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/CommonConstAdviser.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java']
{'.java': 9}
9
9
0
0
9
3,129,041
717,301
98,535
1,112
5,849
1,261
128
9
463
73
123
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,182
huaweicloud/sermant/843/835
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/835
https://github.com/huaweicloud/Sermant/pull/843
https://github.com/huaweicloud/Sermant/pull/843
1
fixes
【bug】fix the registry plugin bugs
### What happened? can not work ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
d746892d4bbe9990d765b98a101029b1ac4789ed
38432cfdc370f2ca5c78a07a02b0229ef0e20d9e
https://github.com/huaweicloud/sermant/compare/d746892d4bbe9990d765b98a101029b1ac4789ed...38432cfdc370f2ca5c78a07a02b0229ef0e20d9e
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttp3ClientDeclarer.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttp3ClientDeclarer.java index 2c06e3a6..d4444be9 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttp3ClientDeclarer.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttp3ClientDeclarer.java @@ -50,7 +50,8 @@ public class OkHttp3ClientDeclarer extends AbstractPluginDeclarer { @Override public InterceptDeclarer[] getInterceptDeclarers(ClassLoader classLoader) { return new InterceptDeclarer[] { - InterceptDeclarer.build(MethodMatcher.nameEquals("getResponseWithInterceptorChain"), INTERCEPT_CLASS) + InterceptDeclarer.build(MethodMatcher.nameContains("execute", "getResponseWithInterceptorChain"), + INTERCEPT_CLASS) }; } } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttpClientDeclarer.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttpClientDeclarer.java index c3d96662..f80a04e4 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttpClientDeclarer.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttpClientDeclarer.java @@ -50,7 +50,8 @@ public class OkHttpClientDeclarer extends AbstractPluginDeclarer { @Override public InterceptDeclarer[] getInterceptDeclarers(ClassLoader classLoader) { return new InterceptDeclarer[] { - InterceptDeclarer.build(MethodMatcher.nameEquals("getResponseWithInterceptorChain"), INTERCEPT_CLASS) + InterceptDeclarer.build(MethodMatcher.nameContains("execute", "getResponseWithInterceptorChain"), + INTERCEPT_CLASS) }; } } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java index 8fb1c39c..ffc674be 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java @@ -28,7 +28,7 @@ import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; import com.huaweicloud.sermant.core.utils.ReflectUtils; -import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; @@ -36,11 +36,14 @@ import okhttp3.Response.Builder; import org.apache.http.HttpStatus; +import java.io.IOException; +import java.lang.reflect.Method; import java.net.URI; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import java.util.logging.Level; import java.util.logging.Logger; /** @@ -71,14 +74,30 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { RequestInterceptorUtils.printRequestLog("OkHttp3", hostAndPath); AtomicReference<Request> rebuildRequest = new AtomicReference<>(); rebuildRequest.set(request); - invokerService.invoke( + final Optional<Object> invoke = invokerService.invoke( buildInvokerFunc(uri, hostAndPath, request, rebuildRequest, context), buildExFunc(rebuildRequest), - hostAndPath.get(HttpConstants.HTTP_URI_HOST)) - .ifPresent(context::skip); + hostAndPath.get(HttpConstants.HTTP_URI_HOST)); + if (!invoke.isPresent() && isNoneReturnMethod(context.getMethod())) { + context.skip(null); + } + invoke.ifPresent(o -> setResultOrThrow(context, o, uri.getPath())); return context; } + private void setResultOrThrow(ExecuteContext context, Object result, String url) { + if (result instanceof IOException) { + LOGGER.log(Level.SEVERE, "Ok http client request error, uri is " + url, (Exception) result); + context.setThrowableOut((Exception) result); + return; + } + context.skip(result); + } + + private boolean isNoneReturnMethod(Method method) { + return method.getReturnType() == void.class || method.getReturnType() == Void.class; + } + private Optional<Request> getRequest(ExecuteContext context) { final Optional<Object> originalRequest = ReflectUtils.getFieldValue(context.getObject(), FIELD_NAME); if (originalRequest.isPresent() && originalRequest.get() instanceof Request) { @@ -97,37 +116,43 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { final String method = request.method(); Request newRequest = covertRequest(uri, hostAndPath, request, method, invokerContext.getServiceInstance()); rebuildRequest.set(newRequest); - try { - context.setRawMemberFieldValue(FIELD_NAME, newRequest); - } catch (NoSuchFieldException e) { - LOGGER.warning("setRawMemberFieldValue originalRequest failed"); - return context; - } catch (IllegalAccessException e) { - LOGGER.warning("setRawMemberFieldValue originalRequest failed"); - return context; - } - return RequestInterceptorUtils.buildFunc(context, invokerContext).get(); + final Object target = copyNewCall(context, newRequest); + return RequestInterceptorUtils.buildFunc(target, context.getMethod(), context.getArguments(), + invokerContext).get(); }; } + private Object copyNewCall(ExecuteContext executeContext, Request newRequest) { + final Optional<Object> client = ReflectUtils.getFieldValue(executeContext.getObject(), "client"); + if (!client.isPresent()) { + return executeContext.getObject(); + } + final OkHttpClient okHttpClient = (OkHttpClient) client.get(); + return okHttpClient.newCall(newRequest); + } + private Request covertRequest(URI uri, Map<String, String> hostAndPath, Request request, String method, ServiceInstance serviceInstance) { String url = RequestInterceptorUtils.buildUrlWithIp(uri, serviceInstance, hostAndPath.get(HttpConstants.HTTP_URI_PATH), method); - HttpUrl newUrl = HttpUrl.parse(url); - return request - .newBuilder() - .url(newUrl) + return new Request.Builder() + .headers(request.headers()) + .method(request.method(), request.body()) + .url(url) + .tag(request.tag()) .build(); } /** * 构建okHttp3响应 * - * @param ex + * @param ex 指定异常 * @return 响应 */ - private Response buildErrorResponse(Exception ex, Request request) { + private Object buildErrorResponse(Exception ex, Request request) { + if (ex instanceof IOException) { + return ex; + } Builder builder = new Builder(); builder.code(HttpStatus.SC_INTERNAL_SERVER_ERROR); builder.message(ex.getMessage()); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java index 8266bcf5..1485a5fd 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java @@ -29,6 +29,7 @@ import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; import com.huaweicloud.sermant.core.utils.ReflectUtils; import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Protocol; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; @@ -36,11 +37,14 @@ import com.squareup.okhttp.Response.Builder; import org.apache.http.HttpStatus; +import java.io.IOException; +import java.lang.reflect.Method; import java.net.URI; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import java.util.logging.Level; import java.util.logging.Logger; /** @@ -50,7 +54,6 @@ import java.util.logging.Logger; * @since 2022-09-14 */ public class OkHttpClientInterceptor extends MarkInterceptor { - private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String FIELD_NAME = "originalRequest"; @@ -72,14 +75,30 @@ public class OkHttpClientInterceptor extends MarkInterceptor { RequestInterceptorUtils.printRequestLog("OkHttp", hostAndPath); AtomicReference<Request> rebuildRequest = new AtomicReference<>(); rebuildRequest.set(request); - invokerService.invoke( + final Optional<Object> invoke = invokerService.invoke( buildInvokerFunc(uri, hostAndPath, request, rebuildRequest, context), buildExFunc(rebuildRequest), - hostAndPath.get(HttpConstants.HTTP_URI_HOST)) - .ifPresent(context::skip); + hostAndPath.get(HttpConstants.HTTP_URI_HOST)); + if (!invoke.isPresent() && isNoneReturnMethod(context.getMethod())) { + context.skip(null); + } + invoke.ifPresent(o -> setResultOrThrow(context, o, uri.getPath())); return context; } + private void setResultOrThrow(ExecuteContext context, Object result, String url) { + if (result instanceof IOException) { + LOGGER.log(Level.SEVERE, "Ok http client request error, uri is " + url, (Exception) result); + context.setThrowableOut((Exception) result); + return; + } + context.skip(result); + } + + private boolean isNoneReturnMethod(Method method) { + return method.getReturnType() == void.class || method.getReturnType() == Void.class; + } + private Optional<Request> getRequest(ExecuteContext context) { final Optional<Object> originalRequest = ReflectUtils.getFieldValue(context.getObject(), FIELD_NAME); if (originalRequest.isPresent() && originalRequest.get() instanceof Request) { @@ -98,19 +117,21 @@ public class OkHttpClientInterceptor extends MarkInterceptor { final String method = request.method(); Request newRequest = covertRequest(uri, hostAndPath, request, method, invokerContext.getServiceInstance()); rebuildRequest.set(newRequest); - try { - context.setRawMemberFieldValue(FIELD_NAME, newRequest); - } catch (NoSuchFieldException e) { - LOGGER.warning("setRawMemberFieldValue originalRequest failed"); - return context; - } catch (IllegalAccessException e) { - LOGGER.warning("setRawMemberFieldValue originalRequest failed"); - return context; - } - return RequestInterceptorUtils.buildFunc(context, invokerContext).get(); + final Object newCall = copyNewCall(context, newRequest); + return RequestInterceptorUtils.buildFunc(newCall, context.getMethod(), context.getArguments(), + invokerContext).get(); }; } + private Object copyNewCall(ExecuteContext executeContext, Request newRequest) { + final Optional<Object> client = ReflectUtils.getFieldValue(executeContext.getObject(), "client"); + if (!client.isPresent()) { + return executeContext.getObject(); + } + final OkHttpClient okHttpClient = (OkHttpClient) client.get(); + return okHttpClient.newCall(newRequest); + } + private Request covertRequest(URI uri, Map<String, String> hostAndPath, Request request, String method, ServiceInstance serviceInstance) { String url = RequestInterceptorUtils.buildUrlWithIp(uri, serviceInstance, @@ -125,10 +146,13 @@ public class OkHttpClientInterceptor extends MarkInterceptor { /** * 构建okHttp响应 * - * @param ex + * @param ex 指定异常 * @return 响应 */ - private Response buildErrorResponse(Exception ex, Request request) { + private Object buildErrorResponse(Exception ex, Request request) { + if (ex instanceof IOException) { + return ex; + } Builder builder = new Builder(); builder.code(HttpStatus.SC_INTERNAL_SERVER_ERROR); builder.message(ex.getMessage()); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java index ed6ef173..b9fe9751 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java @@ -36,12 +36,14 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIUtils; +import java.io.IOException; import java.net.URI; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; +import java.util.logging.Level; import java.util.logging.Logger; /** @@ -78,10 +80,19 @@ public class HttpClient4xInterceptor extends MarkInterceptor { buildInvokerFunc(hostAndPath, uri, httpRequest, context), buildExFunc(httpRequest), hostAndPath.get(HttpConstants.HTTP_URI_HOST)) - .ifPresent(context::skip); + .ifPresent(result -> this.setResultOrThrow(context, result, uri.getPath())); return context; } + private void setResultOrThrow(ExecuteContext context, Object result, String url) { + if (result instanceof IOException) { + LOGGER.log(Level.SEVERE, "Http client request failed, uri is " + url, (Exception) result); + context.setThrowableOut((Exception) result); + return; + } + context.skip(result); + } + private Function<InvokerContext, Object> buildInvokerFunc(Map<String, String> hostAndPath, URI uri, HttpRequest httpRequest, ExecuteContext context) { final String method = httpRequest.getRequestLine().getMethod(); @@ -110,6 +121,9 @@ public class HttpClient4xInterceptor extends MarkInterceptor { private Function<Exception, Object> buildExFunc(HttpRequest httpRequest) { final ClassLoader appClassloader = Thread.currentThread().getContextClassLoader(); return ex -> { + if (ex instanceof IOException) { + return ex; + } final ClassLoader pluginClassloader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(appClassloader); try { diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 63471709..36e11129 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -133,21 +133,34 @@ public class RequestInterceptorUtils { * @return 调用器 */ public static Supplier<Object> buildFunc(ExecuteContext context, InvokerContext invokerContext) { + return buildFunc(context.getObject(), context.getMethod(), context.getArguments(), invokerContext); + } + + /** + * 构建invoke回调方法函数 + * + * @param target 目标 + * @param arguments 参数 + * @param method 方法 + * @param invokerContext 调用上下文 + * @return 调用器 + */ + public static Supplier<Object> buildFunc(Object target, Method method, Object[] arguments, + InvokerContext invokerContext) { return () -> { try { - final Method method = context.getMethod(); AccessController.doPrivileged((PrivilegedAction<Object>) () -> { method.setAccessible(true); return method; }); - return method.invoke(context.getObject(), context.getArguments()); + return method.invoke(target, arguments); } catch (IllegalAccessException e) { LOGGER.log(Level.SEVERE, String.format(Locale.ENGLISH, "Can not invoke method [%s]", - context.getMethod().getName()), e); + method.getName()), e); } catch (InvocationTargetException e) { invokerContext.setEx(e.getTargetException()); LOGGER.log(Level.FINE, String.format(Locale.ENGLISH, "invoke method [%s] failed", - context.getMethod().getName()), e); + method.getName()), e.getTargetException()); } return Optional.empty(); }; diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptorTest.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptorTest.java index d436dde0..2e4edea0 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptorTest.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptorTest.java @@ -104,7 +104,9 @@ public class OkHttp3ClientInterceptorTest extends BaseTest { public void testRestTemplateInterceptor() throws Exception { OkHttpClient client = new OkHttpClient(); Request request = createRequest(url); - ExecuteContext context = ExecuteContext.forMemberMethod(client.newCall(request), null, arguments, null, null); + ExecuteContext context = ExecuteContext.forMemberMethod(client.newCall(request), + String.class.getDeclaredMethod("trim"), arguments, null, + null); discoveryPluginConfig.setRealmName(realmName); initStrategy(PlugEffectWhiteBlackConstants.STRATEGY_ALL, "zookeeper-provider-demo"); interceptor.doBefore(context); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttpClientInterceptorTest.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttpClientInterceptorTest.java index a14b928b..6c1bf20c 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttpClientInterceptorTest.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttpClientInterceptorTest.java @@ -99,7 +99,9 @@ public class OkHttpClientInterceptorTest extends BaseTest { public void testRestTemplateInterceptor() throws Exception { OkHttpClient client = new OkHttpClient(); Request request = createRequest(url); - ExecuteContext context = ExecuteContext.forMemberMethod(client.newCall(request), null, arguments, null, null); + ExecuteContext context = ExecuteContext.forMemberMethod(client.newCall(request), + String.class.getDeclaredMethod("trim"), arguments, null, + null); discoveryPluginConfig.setRealmName(realmName); initStrategy(PlugEffectWhiteBlackConstants.STRATEGY_ALL, "zookeeper-provider-demo"); interceptor.doBefore(context);
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptorTest.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttp3ClientDeclarer.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/interceptors/OkHttpClientInterceptorTest.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/declarers/OkHttpClientDeclarer.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java']
{'.java': 8}
8
8
0
0
8
3,130,392
717,663
98,568
1,112
7,549
1,369
164
6
463
73
123
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,181
huaweicloud/sermant/844/835
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/835
https://github.com/huaweicloud/Sermant/pull/844
https://github.com/huaweicloud/Sermant/pull/844
1
fixes
【bug】fix the registry plugin bugs
### What happened? can not work ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
8987157956e7a1afa021d92e83502f342d262b44
41ce77de4e084593196d307cf594143bfb687ef5
https://github.com/huaweicloud/sermant/compare/8987157956e7a1afa021d92e83502f342d262b44...41ce77de4e084593196d307cf594143bfb687ef5
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 0ed24ac4..63471709 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -31,6 +31,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -62,23 +63,27 @@ public class RequestInterceptorUtils { */ public static Map<String, String> recovertUrl(String url) { if (StringUtils.isEmpty(url)) { - return new HashMap<>(); + return Collections.emptyMap(); } - Map<String, String> result = new HashMap<>(); - String scheme = url.substring(0, url.indexOf(HttpConstants.HTTP_URL_DOUBLIE_SLASH)); String temp = url.substring(url.indexOf(HttpConstants.HTTP_URL_DOUBLIE_SLASH) - + HttpConstants.HTTP_URL_DOUBLIE_SLASH.length()); + + HttpConstants.HTTP_URL_DOUBLIE_SLASH.length()); int slashLen = 1; // 剔除域名之后的path temp = temp.substring(temp.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH) + slashLen); // 服务名 - String host = temp.substring(0, temp.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH)); + int index = temp.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH); + if (index == -1) { + return Collections.emptyMap(); + } + String host = temp.substring(0, index); // 请求路径 String path = temp.substring(temp.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH)); + Map<String, String> result = new HashMap<>(); result.put(HttpConstants.HTTP_URI_HOST, host); + String scheme = url.substring(0, url.indexOf(HttpConstants.HTTP_URL_DOUBLIE_SLASH)); result.put(HttpConstants.HTTP_URL_SCHEME, scheme); result.put(HttpConstants.HTTP_URI_PATH, path); return result; @@ -92,7 +97,7 @@ public class RequestInterceptorUtils { */ public static void printRequestLog(String source, Map<String, String> hostAndPath) { String path = String.format(Locale.ENGLISH, "/%s%s", hostAndPath.get(HttpConstants.HTTP_URI_HOST), - hostAndPath.get(HttpConstants.HTTP_URI_PATH)); + hostAndPath.get(HttpConstants.HTTP_URI_PATH)); LOGGER.log(Level.FINE, String.format(Locale.ENGLISH, "[%s] request [%s] has been intercepted!", source, path)); RECORDER.beforeRequest(); } @@ -138,11 +143,11 @@ public class RequestInterceptorUtils { return method.invoke(context.getObject(), context.getArguments()); } catch (IllegalAccessException e) { LOGGER.log(Level.SEVERE, String.format(Locale.ENGLISH, "Can not invoke method [%s]", - context.getMethod().getName()), e); + context.getMethod().getName()), e); } catch (InvocationTargetException e) { invokerContext.setEx(e.getTargetException()); LOGGER.log(Level.FINE, String.format(Locale.ENGLISH, "invoke method [%s] failed", - context.getMethod().getName()), e.getTargetException()); + context.getMethod().getName()), e); } return Optional.empty(); }; @@ -158,11 +163,11 @@ public class RequestInterceptorUtils { public static String buildUrl(Map<String, String> urlIfo, ServiceInstance serviceInstance) { StringBuilder urlBuild = new StringBuilder(); urlBuild.append(urlIfo.get(HttpConstants.HTTP_URL_SCHEME)) - .append(HttpConstants.HTTP_URL_DOUBLIE_SLASH) - .append(serviceInstance.getIp()) - .append(HttpConstants.HTTP_URL_COLON) - .append(serviceInstance.getPort()) - .append(urlIfo.get(HttpConstants.HTTP_URI_PATH)); + .append(HttpConstants.HTTP_URL_DOUBLIE_SLASH) + .append(serviceInstance.getIp()) + .append(HttpConstants.HTTP_URL_COLON) + .append(serviceInstance.getPort()) + .append(urlIfo.get(HttpConstants.HTTP_URI_PATH)); return urlBuild.toString(); } @@ -186,9 +191,9 @@ public class RequestInterceptorUtils { return result; } result.put(HttpConstants.HTTP_URI_HOST, - tempPath.substring(0, tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH))); + tempPath.substring(0, tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH))); result.put(HttpConstants.HTTP_URI_PATH, - tempPath.substring(tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH))); + tempPath.substring(tempPath.indexOf(HttpConstants.HTTP_URL_SINGLE_SLASH))); return result; } @@ -204,14 +209,14 @@ public class RequestInterceptorUtils { public static String buildUrlWithIp(URI uri, ServiceInstance serviceInstance, String path, String method) { StringBuilder urlBuild = new StringBuilder(); urlBuild.append(uri.getScheme()) - .append(HttpConstants.HTTP_URL_DOUBLIE_SLASH) - .append(serviceInstance.getIp()) - .append(HttpConstants.HTTP_URL_COLON) - .append(serviceInstance.getPort()) - .append(path); + .append(HttpConstants.HTTP_URL_DOUBLIE_SLASH) + .append(serviceInstance.getIp()) + .append(HttpConstants.HTTP_URL_COLON) + .append(serviceInstance.getPort()) + .append(path); if (method.equals(HttpConstants.HTTP_GET)) { urlBuild.append(HttpConstants.HTTP_URL_UNKNOWN) - .append(uri.getQuery()); + .append(uri.getQuery()); } return urlBuild.toString(); }
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java']
{'.java': 1}
1
1
0
0
1
3,130,337
717,636
98,563
1,112
2,713
491
47
1
463
73
123
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,180
huaweicloud/sermant/848/847
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/847
https://github.com/huaweicloud/Sermant/pull/848
https://github.com/huaweicloud/Sermant/pull/848
1
fixes
【fix】remove the logic for catch throwabel of bytebudy
### What happened? remove the logic for catch throwabel of bytebudy ### How can we reproduce it (as minimally and precisely as possible)? 100% ### Anything else we need to know? _No response_ ### Sermant version <details> 0.7 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
086b4bed4a685bb807ffae45fadf37fd040fb78a
e55faf698126cc6717a87b46b41cfed35c7f86b0
https://github.com/huaweicloud/sermant/compare/086b4bed4a685bb807ffae45fadf37fd040fb78a...e55faf698126cc6717a87b46b41cfed35c7f86b0
diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java index f5e8453c..51bda3a9 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java @@ -51,7 +51,7 @@ public class AdviceConstTemplate { * @param context 执行上下文 * @throws Throwable 抛给宿主的异常 */ - @Advice.OnMethodEnter(suppress = Throwable.class) + @Advice.OnMethodEnter public static void onMethodEnter( @Advice.Origin Class<?> cls, @Advice.Origin Constructor<?> constructor, @@ -79,7 +79,7 @@ public class AdviceConstTemplate { * @param context 执行上下文 * @throws Throwable 抛给宿主的异常 */ - @Advice.OnMethodExit(suppress = Throwable.class) + @Advice.OnMethodExit public static void onMethodExit( @Advice.This(typing = Assigner.Typing.DYNAMIC) Object obj, @Advice.FieldValue(value = "_EXT_STATIC_FIELDS_$SERMANT", diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java index 47c41d8b..21ee1a26 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java @@ -53,7 +53,7 @@ public class AdviceMemberTemplate { * @return 是否跳过主要方法 * @throws Throwable 抛给宿主的异常 */ - @Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class) + @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class) public static boolean onMethodEnter( @Advice.This(typing = Assigner.Typing.DYNAMIC) Object obj, @Advice.Origin Method method, @@ -86,7 +86,7 @@ public class AdviceMemberTemplate { * @param context 执行上下文 * @throws Throwable 抛给宿主的异常 */ - @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) + @Advice.OnMethodExit(onThrowable = Throwable.class) public static void onMethodExit( @Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object result, @Advice.Thrown Throwable throwable, diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java index a9b630c6..7484e419 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java @@ -52,7 +52,7 @@ public class AdviceStaticTemplate { * @return 是否跳过主要方法 * @throws Throwable 抛给宿主的异常 */ - @Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class) + @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class) public static boolean onMethodEnter( @Advice.Origin Class<?> cls, @Advice.Origin Method method, @@ -81,7 +81,7 @@ public class AdviceStaticTemplate { * @param context 执行上下文 * @throws Throwable 抛给宿主的异常 */ - @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) + @Advice.OnMethodExit(onThrowable = Throwable.class) public static void onMethodExit( @Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object result, @Advice.Thrown Throwable throwable, diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapConstTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapConstTemplate.java index 53374ae1..fa8096d7 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapConstTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapConstTemplate.java @@ -51,7 +51,7 @@ public class BootstrapConstTemplate { * @param context 执行上下文 * @throws Exception 执行异常 */ - @Advice.OnMethodEnter(suppress = Throwable.class) + @Advice.OnMethodEnter public static void onMethodEnter( @Advice.Origin Class<?> cls, @Advice.Origin Constructor<?> constructor, @@ -87,7 +87,7 @@ public class BootstrapConstTemplate { * @param context 执行上下文 * @throws Exception 执行异常 */ - @Advice.OnMethodExit(suppress = Throwable.class) + @Advice.OnMethodExit public static void onMethodExit( @Advice.This(typing = Assigner.Typing.DYNAMIC) Object obj, @Advice.Local(value = "_CONTEXT_CLS_$SERMANT_LOCAL") Class<?> contextCls, diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapMemberTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapMemberTemplate.java index d690d948..3bdd6496 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapMemberTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapMemberTemplate.java @@ -52,7 +52,7 @@ public class BootstrapMemberTemplate { * @return 是否跳过主要方法 * @throws Exception 执行异常 */ - @Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class) + @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class) public static boolean onMethodEnter( @Advice.This(typing = Assigner.Typing.DYNAMIC) Object obj, @Advice.Origin Method method, @@ -90,7 +90,7 @@ public class BootstrapMemberTemplate { * @param context 执行上下文 * @throws Exception 执行异常 */ - @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) + @Advice.OnMethodExit(onThrowable = Throwable.class) public static void onMethodExit( @Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object result, @Advice.Thrown Throwable throwable, diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapStaticTemplate.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapStaticTemplate.java index 1feb99a2..91f697a5 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapStaticTemplate.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapStaticTemplate.java @@ -52,7 +52,7 @@ public class BootstrapStaticTemplate { * @return 是否跳过主要方法 * @throws Exception 执行异常 */ - @Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class) + @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class) public static boolean onMethodEnter( @Advice.Origin Class<?> cls, @Advice.Origin Method method, @@ -90,7 +90,7 @@ public class BootstrapStaticTemplate { * @param context 执行上下文 * @throws Exception 执行异常 */ - @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) + @Advice.OnMethodExit(onThrowable = Throwable.class) public static void onMethodExit( @Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object result, @Advice.Thrown Throwable throwable,
['sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapConstTemplate.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceConstTemplate.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceMemberTemplate.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapStaticTemplate.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/BootstrapMemberTemplate.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/template/AdviceStaticTemplate.java']
{'.java': 6}
6
6
0
0
6
3,133,465
718,297
98,646
1,112
1,542
352
24
6
499
78
129
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,179
huaweicloud/sermant/853/852
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/852
https://github.com/huaweicloud/Sermant/pull/853
https://github.com/huaweicloud/Sermant/pull/853
1
fixes
【bug】配置项为list时,yaml会抛出解析错误的bug
### What happened? 配置项为list时,yaml会抛出解析错误的bug ### How can we reproduce it (as minimally and precisely as possible)? 配置项为list时,yaml会抛出解析错误的bug ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.1 </details> ### OS version n/a
8f306861e38ada86c329e017f232adcf82d205d8
0ca5a54a4ff30a72a434b20c993f256f75946154
https://github.com/huaweicloud/sermant/compare/8f306861e38ada86c329e017f232adcf82d205d8...0ca5a54a4ff30a72a434b20c993f256f75946154
diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigOrderIntegratedProcessor.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigOrderIntegratedProcessor.java index ab536eeb..f8aebe96 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigOrderIntegratedProcessor.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigOrderIntegratedProcessor.java @@ -138,11 +138,16 @@ public class ConfigOrderIntegratedProcessor implements ConfigProcessor { targetHolder.getHolder().getOrDefault(originEvent.getKey(), new HashMap<>(CAP_SIZE)); olderDataMap.clear(); if (originEvent.getEventType() != DynamicConfigEventType.DELETE) { - Optional<Map<String, Object>> dataMap = yamlConverter.convert(originEvent.getContent(), Map.class); - if (!dataMap.isPresent()) { + Optional<Object> convert = yamlConverter.convert(originEvent.getContent(), Object.class); + if (!convert.isPresent()) { return false; } - olderDataMap.putAll(dataMap.get()); + Object obj = convert.get(); + if (obj instanceof Map) { + olderDataMap.putAll((Map<String, Object>) obj); + } else { + olderDataMap.put(originEvent.getKey(), obj); + } } targetHolder.getHolder().put(originEvent.getKey(), olderDataMap); return true; diff --git a/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/RouterConfigHandler.java b/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/RouterConfigHandler.java index a87025ad..66ecd6cb 100644 --- a/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/RouterConfigHandler.java +++ b/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/RouterConfigHandler.java @@ -16,7 +16,6 @@ package com.huaweicloud.sermant.router.config.handler; -import com.huaweicloud.sermant.core.plugin.subscribe.processor.OrderConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEventType; import com.huaweicloud.sermant.router.common.constants.RouterConstant; @@ -81,24 +80,6 @@ public class RouterConfigHandler extends AbstractConfigHandler { } private Map<String, String> getRouteRuleMap(DynamicConfigEvent event) { - if (event instanceof OrderConfigEvent) { - Map<String, Object> allData = ((OrderConfigEvent) event).getAllData(); - String prefix = - RouterConstant.ROUTER_CONFIG_SERVICECOMB_KEY + "." + RouterConstant.ROUTER_CONFIG_ROUTE_RULE_KEY + "."; - Map<String, String> routeRuleMap = new HashMap<>(); - for (Entry<String, Object> entry : allData.entrySet()) { - if (!entry.getKey().startsWith(prefix)) { - continue; - } - Object value = entry.getValue(); - if (value instanceof String) { - routeRuleMap.put(entry.getKey().substring(prefix.length()), (String) value); - } else { - routeRuleMap.put(entry.getKey().substring(prefix.length()), yaml.dump(value)); - } - } - return routeRuleMap; - } String content = event.getContent(); Map<String, Map<String, Map<String, String>>> load = yaml.load(content); if (CollectionUtils.isEmpty(load)) { diff --git a/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/ServiceConfigHandler.java b/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/ServiceConfigHandler.java index 2171b11d..6520ce2c 100644 --- a/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/ServiceConfigHandler.java +++ b/sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/ServiceConfigHandler.java @@ -16,9 +16,9 @@ package com.huaweicloud.sermant.router.config.handler; -import com.huaweicloud.sermant.core.plugin.subscribe.processor.OrderConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEventType; +import com.huaweicloud.sermant.core.utils.StringUtils; import com.huaweicloud.sermant.router.common.constants.RouterConstant; import com.huaweicloud.sermant.router.common.utils.CollectionUtils; import com.huaweicloud.sermant.router.config.cache.ConfigCache; @@ -30,10 +30,8 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; /** * 路由配置处理器(服务维度) @@ -79,23 +77,11 @@ public class ServiceConfigHandler extends AbstractConfigHandler { } private List<Map<String, Object>> getRule(DynamicConfigEvent event, String serviceName) { - if (event instanceof OrderConfigEvent) { - Map<String, Object> allData = ((OrderConfigEvent) event).getAllData(); - Map<String, List<Map<String, Object>>> routeRuleMap = new HashMap<>(); - for (Entry<String, Object> entry : allData.entrySet()) { - String key = entry.getKey(); - if (!key.startsWith(RouterConstant.ROUTER_KEY_PREFIX + POINT)) { - continue; - } - Object value = entry.getValue(); - if (value instanceof String) { - routeRuleMap.put(entry.getKey(), yaml.loadAs((String) value, List.class)); - } else { - routeRuleMap.put(entry.getKey(), (List<Map<String, Object>>) value); - } - } - return routeRuleMap.get(RouterConstant.ROUTER_KEY_PREFIX + POINT + serviceName); + String content = event.getContent(); + if (StringUtils.isBlank(content)) { + return Collections.emptyList(); } - return yaml.loadAs(event.getContent(), List.class); + Map<String, List<Map<String, Object>>> map = yaml.load(content); + return map.get(RouterConstant.ROUTER_KEY_PREFIX + POINT + serviceName); } } \\ No newline at end of file diff --git a/sermant-plugins/sermant-service-registry/dubbo-registry-service/src/main/java/com/huawei/dubbo/registry/listener/GovernanceConfigListener.java b/sermant-plugins/sermant-service-registry/dubbo-registry-service/src/main/java/com/huawei/dubbo/registry/listener/GovernanceConfigListener.java index 0816b965..3d07b3af 100644 --- a/sermant-plugins/sermant-service-registry/dubbo-registry-service/src/main/java/com/huawei/dubbo/registry/listener/GovernanceConfigListener.java +++ b/sermant-plugins/sermant-service-registry/dubbo-registry-service/src/main/java/com/huawei/dubbo/registry/listener/GovernanceConfigListener.java @@ -20,11 +20,11 @@ import com.huawei.dubbo.registry.entity.GovernanceCache; import com.huawei.dubbo.registry.entity.GovernanceData; import com.huawei.dubbo.registry.service.RegistryService; -import com.huaweicloud.sermant.core.plugin.subscribe.processor.OrderConfigEvent; import com.huaweicloud.sermant.core.service.ServiceManager; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEventType; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigListener; +import com.huaweicloud.sermant.core.utils.StringUtils; import com.alibaba.fastjson.JSONObject; @@ -54,8 +54,8 @@ public class GovernanceConfigListener implements DynamicConfigListener { GovernanceData governanceData = null; if (event.getEventType() != DynamicConfigEventType.DELETE) { String content = event.getContent(); - if (event instanceof OrderConfigEvent) { - content = JSONObject.toJSONString(((OrderConfigEvent) event).getAllData()); + if (StringUtils.isBlank(content)) { + return; } governanceData = JSONObject.parseObject(content, GovernanceData.class); } diff --git a/sermant-plugins/sermant-service-registry/spring-cloud-registry-plugin/src/main/java/com/huawei/registry/config/RegistryConfigResolver.java b/sermant-plugins/sermant-service-registry/spring-cloud-registry-plugin/src/main/java/com/huawei/registry/config/RegistryConfigResolver.java index 01a2dc01..59d00710 100644 --- a/sermant-plugins/sermant-service-registry/spring-cloud-registry-plugin/src/main/java/com/huawei/registry/config/RegistryConfigResolver.java +++ b/sermant-plugins/sermant-service-registry/spring-cloud-registry-plugin/src/main/java/com/huawei/registry/config/RegistryConfigResolver.java @@ -19,7 +19,6 @@ package com.huawei.registry.config; import com.huaweicloud.sermant.core.operation.OperationManager; import com.huaweicloud.sermant.core.operation.converter.api.YamlConverter; -import com.huaweicloud.sermant.core.plugin.subscribe.processor.OrderConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEvent; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEventType; import com.huaweicloud.sermant.core.utils.MapUtils; @@ -50,14 +49,7 @@ public abstract class RegistryConfigResolver { if (!isTargetConfig(event)) { return; } - boolean isUpdated; - if (event instanceof OrderConfigEvent) { - final Map<String, Object> allData = ((OrderConfigEvent) event).getAllData(); - isUpdated = updateConfig(allData, event.getEventType()); - } else { - isUpdated = this.updateWithDefaultMode(event); - } - if (isUpdated) { + if (updateWithDefaultMode(event)) { afterUpdateConfig(); } }
['sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/ServiceConfigHandler.java', 'sermant-plugins/sermant-service-registry/dubbo-registry-service/src/main/java/com/huawei/dubbo/registry/listener/GovernanceConfigListener.java', 'sermant-plugins/sermant-router/router-config-service/src/main/java/com/huaweicloud/sermant/router/config/handler/RouterConfigHandler.java', 'sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigOrderIntegratedProcessor.java', 'sermant-plugins/sermant-service-registry/spring-cloud-registry-plugin/src/main/java/com/huawei/registry/config/RegistryConfigResolver.java']
{'.java': 5}
5
5
0
0
5
3,133,129
718,217
98,646
1,112
3,886
728
72
5
268
36
90
22
0
0
1970-01-01T00:27:46
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,178
huaweicloud/sermant/901/900
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/900
https://github.com/huaweicloud/Sermant/pull/901
https://github.com/huaweicloud/Sermant/pull/901
1
fixes
【fix】fix the statics logic for request count
### What happened? Redundant statistics for request count ### How can we reproduce it (as minimally and precisely as possible)? always ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.1 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
fe56e06cff5c62a5c70afbef622507df34d16914
7dddcbf6071b1d4b0270b9062ee42b6d52cd94b0
https://github.com/huaweicloud/sermant/compare/fe56e06cff5c62a5c70afbef622507df34d16914...7dddcbf6071b1d4b0270b9062ee42b6d52cd94b0
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java index 13274605..65c66a95 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java @@ -48,16 +48,17 @@ public class SimpleRequestRecorder implements Recorder { @Override public void beforeRequest() { + if (!discoveryPluginConfig.isEnableRequestCount()) { + return; + } final long allRequest = allRequestCount.incrementAndGet(); if (allRequest <= 0) { allRequestCount.set(0); LOGGER.info("SimpleRequestRecorder has over the max num of long, it has been reset to 0!"); } - if (discoveryPluginConfig.isEnableRequestCount()) { - LOGGER.info(String.format(Locale.ENGLISH, - "currentTime: %s request count handle by plugin is: %s", - HttpConstants.currentTime(), allRequest)); - } + LOGGER.info(String.format(Locale.ENGLISH, + "currentTime: %s request count handle by plugin is: %s", + HttpConstants.currentTime(), allRequest)); } @Override diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/entity/SimpleRequestRecorderTest.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/entity/SimpleRequestRecorderTest.java index b95e77ed..16431e19 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/entity/SimpleRequestRecorderTest.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/entity/SimpleRequestRecorderTest.java @@ -46,6 +46,7 @@ public class SimpleRequestRecorderTest { public void setUp() throws Exception { pluginConfigManagerMockedStatic = Mockito .mockStatic(PluginConfigManager.class); + discoveryPluginConfig.setEnableRequestCount(true); pluginConfigManagerMockedStatic.when(() -> PluginConfigManager.getPluginConfig(DiscoveryPluginConfig.class)) .thenReturn(discoveryPluginConfig); }
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/test/java/com/huawei/discovery/entity/SimpleRequestRecorderTest.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java']
{'.java': 2}
2
2
0
0
2
3,241,569
742,701
102,013
1,146
555
99
11
1
493
75
127
36
0
1
1970-01-01T00:27:47
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,177
huaweicloud/sermant/960/959
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/959
https://github.com/huaweicloud/Sermant/pull/960
https://github.com/huaweicloud/Sermant/pull/960
1
fixes
【fix】fix bug for springboot registry plugin
### What happened? if the url which for springboot registry plugin is invalid, it will throw ex ### How can we reproduce it (as minimally and precisely as possible)? use url request whose url is invalid, such as http://www.domain.com/test ### Anything else we need to know? _No response_ ### Sermant version <details> 0.7.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
32db176cc5b92438fc0a260209bf552b8c02c945
d3dad05e34a6b709ac30dba5b9e27eac87842268
https://github.com/huaweicloud/sermant/compare/32db176cc5b92438fc0a260209bf552b8c02c945...d3dad05e34a6b709ac30dba5b9e27eac87842268
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java index c48a5913..e86e3bc3 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java @@ -48,8 +48,7 @@ public class FeignInvokeInterceptor extends MarkInterceptor { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); Request request = (Request) context.getArguments()[0]; Map<String, String> urlInfo = RequestInterceptorUtils.recoverUrl(request.url()); - if (!PlugEffectWhiteBlackUtils.isAllowRun(request.url(), urlInfo.get(HttpConstants.HTTP_URI_HOST), - false)) { + if (!PlugEffectWhiteBlackUtils.isAllowRun(request.url(), urlInfo.get(HttpConstants.HTTP_URI_HOST))) { return context; } RequestInterceptorUtils.printRequestLog("feign", urlInfo); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java index 062f1f4a..daca8098 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java @@ -64,9 +64,11 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { } Request request = rawRequest.get(); URI uri = request.url().uri(); + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(uri.getHost())) { + return context; + } Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); - if (!PlugEffectWhiteBlackUtils.isAllowRun(uri.getHost(), hostAndPath.get(HttpConstants.HTTP_URI_HOST), - true)) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { return context; } RequestInterceptorUtils.printRequestLog("OkHttp3", hostAndPath); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java index 8e72882f..6070583c 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java @@ -66,9 +66,11 @@ public class OkHttpClientInterceptor extends MarkInterceptor { } Request request = rawRequest.get(); URI uri = request.uri(); + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(uri.getHost())) { + return context; + } Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); - if (!PlugEffectWhiteBlackUtils.isAllowRun(uri.getHost(), hostAndPath.get(HttpConstants.HTTP_URI_HOST), - true)) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { return context; } RequestInterceptorUtils.printRequestLog("OkHttp", hostAndPath); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java index 62181676..73dcf258 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java @@ -50,9 +50,11 @@ public class RestTemplateInterceptor extends MarkInterceptor { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); URI uri = (URI) context.getArguments()[0]; HttpMethod httpMethod = (HttpMethod) context.getArguments()[1]; + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(uri.getHost())) { + return context; + } Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); - if (!PlugEffectWhiteBlackUtils.isAllowRun(uri.getHost(), hostAndPath.get(HttpConstants.HTTP_URI_HOST), - true)) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { return context; } RequestInterceptorUtils.printRequestLog("restTemplate", hostAndPath); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java index c569196f..d8d525dd 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java @@ -80,7 +80,11 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { @Override public ExecuteContext before(ExecuteContext context) throws Exception { ready(); - acquireHostPath(context); + HttpAsyncRequestProducer httpAsyncRequestProducer = (HttpAsyncRequestProducer) context.getArguments()[0]; + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(httpAsyncRequestProducer.getTarget().getHostName())) { + return context; + } + acquireHostPath(httpAsyncRequestProducer); if (!isConfigEnable()) { // 配置不允许则直接返回 return context; @@ -99,6 +103,7 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { @Override public ExecuteContext after(ExecuteContext context) throws Exception { if (!isConfigEnable()) { + HttpAsyncUtils.remove(); return context; } final ClassLoader appClassloader = Thread.currentThread().getContextClassLoader(); @@ -134,12 +139,10 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { if (originHostName == null || hostAndPath == null) { return false; } - return PlugEffectWhiteBlackUtils - .isAllowRun(originHostName, hostAndPath.get(HttpConstants.HTTP_URI_HOST), true); + return PlugEffectWhiteBlackUtils.isAllowRun(originHostName, hostAndPath.get(HttpConstants.HTTP_URI_HOST)); } - private void acquireHostPath(ExecuteContext context) throws Exception { - HttpAsyncRequestProducer httpAsyncRequestProducer = (HttpAsyncRequestProducer) context.getArguments()[0]; + private void acquireHostPath(HttpAsyncRequestProducer httpAsyncRequestProducer) throws Exception { final HttpHost httpHost = httpAsyncRequestProducer.getTarget(); final HttpRequest httpRequest = httpAsyncRequestProducer.generateRequest(); final Optional<URI> optionalUri = RequestInterceptorUtils.formatUri(httpRequest.getRequestLine().getUri()); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java index f6b2c886..ac970729 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java @@ -67,12 +67,15 @@ public class HttpClient4xInterceptor extends MarkInterceptor { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); HttpHost httpHost = (HttpHost) context.getArguments()[0]; final HttpRequest httpRequest = (HttpRequest) context.getArguments()[1]; + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(httpHost.getHostName())) { + return context; + } final Map<String, String> hostAndPath = RequestInterceptorUtils.recoverUrl(httpRequest.getRequestLine() .getUri()); if (hostAndPath.isEmpty()) { return context; } - if (!isConfigEnable(hostAndPath, httpHost.getHostName())) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(hostAndPath.get(HttpConstants.HTTP_URI_HOST))) { return context; } RequestInterceptorUtils.printRequestLog("HttpClient", hostAndPath); @@ -154,10 +157,6 @@ public class HttpClient4xInterceptor extends MarkInterceptor { }; } - private boolean isConfigEnable(Map<String, String> hostAndPath, String hostName) { - return PlugEffectWhiteBlackUtils.isAllowRun(hostName, hostAndPath.get(HttpConstants.HTTP_URI_HOST), true); - } - @Override protected void ready() { if (isLoaded.compareAndSet(false, true)) { diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java index 7ef28948..a4faf8ec 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java @@ -81,10 +81,12 @@ public class HttpUrlConnectionConnectInterceptor extends MarkInterceptor { return context; } final URL url = rawUrl.get(); + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(url.getHost())) { + return context; + } final String fullUrl = url.toString(); Map<String, String> urlInfo = RequestInterceptorUtils.recoverUrl(url); - if (!PlugEffectWhiteBlackUtils.isAllowRun(url.getHost(), urlInfo.get(HttpConstants.HTTP_URI_HOST), - false)) { + if (!PlugEffectWhiteBlackUtils.isPlugEffect(urlInfo.get(HttpConstants.HTTP_URI_HOST))) { return context; } HttpConnectionUtils.save(new HttpConnectionContext(urlInfo, url)); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/PlugEffectWhiteBlackUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/PlugEffectWhiteBlackUtils.java index b6396969..21630568 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/PlugEffectWhiteBlackUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/PlugEffectWhiteBlackUtils.java @@ -135,14 +135,10 @@ public class PlugEffectWhiteBlackUtils { * * @param realmStr 拦截获取的域名 * @param serviceName 下游服务名 - * @param isByEqual 是否基于等于比较 * @return 是否允许执行 */ - public static boolean isAllowRun(String realmStr, String serviceName, boolean isByEqual) { - if (isByEqual && !PlugEffectWhiteBlackUtils.isHostEqualRealmName(realmStr)) { - return false; - } - if (!isByEqual && !PlugEffectWhiteBlackUtils.isUrlContainsRealmName(realmStr)) { + public static boolean isAllowRun(String realmStr, String serviceName) { + if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(realmStr)) { return false; } return PlugEffectWhiteBlackUtils.isPlugEffect(serviceName); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index acfa9abe..885d17c5 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -55,6 +55,17 @@ public class RequestInterceptorUtils { private static final int URL_INFO_INIT_SIZE = 8; + /** + * 解析url时,分隔的最小长度, 其path必须为/serviceName/api/xxx, 否则将不是目标请求 {@link RequestInterceptorUtils#recoverUrl(URL)} + */ + private static final int MIN_LEN_FOR_VALID_PATH = 2; + + /** + * 解析url时,分隔的最小长度, 其url必须为http:/www.domain.com/serviceName/api/xxx, 否则将不是目标请求 + * {@link RequestInterceptorUtils#recoverUrl(String)} + */ + private static final int MIN_LEN_FOR_VALID_URL = 4; + private RequestInterceptorUtils() { } @@ -75,14 +86,17 @@ public class RequestInterceptorUtils { if (url == null) { return Collections.emptyMap(); } - final Map<String, String> result = new HashMap<>(URL_INFO_INIT_SIZE); final String protocol = url.getProtocol(); // /serviceName/sayHello?name=1, 已切分为serviceName, sayHello?name=1 - final StringTokenizer tokenizer = new StringTokenizer(url.getPath()); + String delim = String.valueOf(HttpConstants.HTTP_URL_SINGLE_SLASH); + final StringTokenizer tokenizer = new StringTokenizer(url.getPath(), delim); + if (tokenizer.countTokens() < MIN_LEN_FOR_VALID_PATH) { + return Collections.emptyMap(); + } + final Map<String, String> result = new HashMap<>(URL_INFO_INIT_SIZE); result.put(HttpConstants.HTTP_URL_SCHEME, protocol); - result.put(HttpConstants.HTTP_URI_HOST, - tokenizer.nextToken(String.valueOf(HttpConstants.HTTP_URL_SINGLE_SLASH))); + result.put(HttpConstants.HTTP_URI_HOST, tokenizer.nextToken(delim)); result.put(HttpConstants.HTTP_URI_PATH, formatPath(tokenizer.nextToken(HttpConstants.EMPTY_STR), url.getQuery())); return result; @@ -98,8 +112,11 @@ public class RequestInterceptorUtils { if (StringUtils.isEmpty(url) || !isValidUrl(url)) { return Collections.emptyMap(); } - final StringTokenizer urlTokens = new StringTokenizer(url); String baseSlash = String.valueOf(HttpConstants.HTTP_URL_SINGLE_SLASH); + final StringTokenizer urlTokens = new StringTokenizer(url, baseSlash); + if (urlTokens.countTokens() < MIN_LEN_FOR_VALID_URL) { + return Collections.emptyMap(); + } // http(s):.subString(0, len - 1) final String rawScheme = urlTokens.nextToken(baseSlash);
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpClient4xInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpconnection/HttpUrlConnectionConnectInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/RestTemplateInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/FeignInvokeInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/PlugEffectWhiteBlackUtils.java']
{'.java': 9}
9
9
0
0
9
2,873,726
659,881
90,973
969
5,018
1,065
84
9
597
93
151
36
1
1
1970-01-01T00:27:48
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,187
huaweicloud/sermant/836/835
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/835
https://github.com/huaweicloud/Sermant/pull/836
https://github.com/huaweicloud/Sermant/pull/836
1
fixes
【bug】fix the registry plugin bugs
### What happened? can not work ### How can we reproduce it (as minimally and precisely as possible)? no ### Anything else we need to know? _No response_ ### Sermant version <details> 0.6.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
960821e519fb82f73c6484d18713c7d0bdcaec4e
e92160564783ad57a6192fe62b005cb4a847ca3c
https://github.com/huaweicloud/sermant/compare/960821e519fb82f73c6484d18713c7d0bdcaec4e...e92160564783ad57a6192fe62b005cb4a847ca3c
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConfig.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConfig.java index 72f1627e..de1eb957 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConfig.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConfig.java @@ -135,9 +135,9 @@ public class LbConfig implements PluginConfig { private boolean preferIpAddress = false; /** - * 统计并发数的时间窗口, 默认10分钟, 并发数仅在时间窗口内统计生效, 超出则清0 + * 实例状态统计时间窗口, 默认10分钟, 每一个时间窗口的开始, 统计都会清0 */ - private long activeRequestTimeoutWindowMs = LbConstants.DEFAULT_ACTIVE_REQUEST_COUNT_WINDOW_MS; + private long instanceStatTimeWindowMs = LbConstants.DEFAULT_INSTANCE_STATE_TIME_WINDOW_MS; public long getRefreshTimerInterval() { return refreshTimerInterval; @@ -187,8 +187,8 @@ public class LbConfig implements PluginConfig { this.zkServerVersion = version; } - public long getActiveRequestTimeoutWindowMs() { - return activeRequestTimeoutWindowMs; + public long getInstanceStatTimeWindowMs() { + return instanceStatTimeWindowMs; } public int getMaxRetryConfigCache() { @@ -199,8 +199,8 @@ public class LbConfig implements PluginConfig { this.maxRetryConfigCache = maxRetryConfigCache; } - public void setActiveRequestTimeoutWindowMs(long activeRequestTimeoutWindowMs) { - this.activeRequestTimeoutWindowMs = activeRequestTimeoutWindowMs; + public void setInstanceStatTimeWindowMs(long instanceStatTimeWindowMs) { + this.instanceStatTimeWindowMs = instanceStatTimeWindowMs; } public String getZkUriSpec() { diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConstants.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConstants.java index 64beed89..c7e8fa86 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConstants.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConstants.java @@ -64,9 +64,9 @@ public class LbConstants { public static final long DEFAULT_LB_STATS_REFRESH_INTERVAL_MS = 30000L; /** - * 统计并发数的时间窗口, 默认10分钟 + * 实例状态统计时间窗口, 默认10分钟, 每一个时间窗口的开始, 统计都会清0 */ - public static final long DEFAULT_ACTIVE_REQUEST_COUNT_WINDOW_MS = 600000L; + public static final long DEFAULT_INSTANCE_STATE_TIME_WINDOW_MS = 600000L; /** * 服务超时后最大重试次数 diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java index 2ff7d40f..13274605 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java @@ -55,7 +55,7 @@ public class SimpleRequestRecorder implements Recorder { } if (discoveryPluginConfig.isEnableRequestCount()) { LOGGER.info(String.format(Locale.ENGLISH, - "currentTime: %s httpClientInterceptor effect count: %s", + "currentTime: %s request count handle by plugin is: %s", HttpConstants.currentTime(), allRequest)); } } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java index 43759e24..8fb1c39c 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java @@ -26,6 +26,7 @@ import com.huawei.discovery.utils.RequestInterceptorUtils; import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; +import com.huaweicloud.sermant.core.utils.ReflectUtils; import okhttp3.HttpUrl; import okhttp3.Protocol; @@ -37,6 +38,7 @@ import org.apache.http.HttpStatus; import java.net.URI; import java.util.Map; +import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.logging.Logger; @@ -48,7 +50,6 @@ import java.util.logging.Logger; * @since 2022-09-14 */ public class OkHttp3ClientInterceptor extends MarkInterceptor { - private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String FIELD_NAME = "originalRequest"; @@ -56,10 +57,11 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { @Override protected ExecuteContext doBefore(ExecuteContext context) throws Exception { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); - if (context.getRawMemberFieldValue(FIELD_NAME) == null) { + final Optional<Request> rawRequest = getRequest(context); + if (!rawRequest.isPresent()) { return context; } - Request request = (Request)context.getRawMemberFieldValue(FIELD_NAME); + Request request = rawRequest.get(); URI uri = request.url().uri(); Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); if (!PlugEffectWhiteBlackUtils.isAllowRun(uri.getHost(), hostAndPath.get(HttpConstants.HTTP_URI_HOST), @@ -68,6 +70,7 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { } RequestInterceptorUtils.printRequestLog("OkHttp3", hostAndPath); AtomicReference<Request> rebuildRequest = new AtomicReference<>(); + rebuildRequest.set(request); invokerService.invoke( buildInvokerFunc(uri, hostAndPath, request, rebuildRequest, context), buildExFunc(rebuildRequest), @@ -76,6 +79,14 @@ public class OkHttp3ClientInterceptor extends MarkInterceptor { return context; } + private Optional<Request> getRequest(ExecuteContext context) { + final Optional<Object> originalRequest = ReflectUtils.getFieldValue(context.getObject(), FIELD_NAME); + if (originalRequest.isPresent() && originalRequest.get() instanceof Request) { + return Optional.of((Request) originalRequest.get()); + } + return Optional.empty(); + } + private Function<Exception, Object> buildExFunc(AtomicReference<Request> rebuildRequest) { return ex -> buildErrorResponse(ex, rebuildRequest.get()); } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java index 49e3e077..8266bcf5 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java @@ -26,6 +26,7 @@ import com.huawei.discovery.utils.RequestInterceptorUtils; import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext; import com.huaweicloud.sermant.core.plugin.service.PluginServiceManager; +import com.huaweicloud.sermant.core.utils.ReflectUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.Protocol; @@ -37,6 +38,7 @@ import org.apache.http.HttpStatus; import java.net.URI; import java.util.Map; +import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.logging.Logger; @@ -56,10 +58,11 @@ public class OkHttpClientInterceptor extends MarkInterceptor { @Override protected ExecuteContext doBefore(ExecuteContext context) throws Exception { final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); - if (context.getRawMemberFieldValue(FIELD_NAME) == null) { + final Optional<Request> rawRequest = getRequest(context); + if (!rawRequest.isPresent()) { return context; } - Request request = (Request)context.getRawMemberFieldValue(FIELD_NAME); + Request request = rawRequest.get(); URI uri = request.uri(); Map<String, String> hostAndPath = RequestInterceptorUtils.recoverHostAndPath(uri.getPath()); if (!PlugEffectWhiteBlackUtils.isAllowRun(uri.getHost(), hostAndPath.get(HttpConstants.HTTP_URI_HOST), @@ -68,6 +71,7 @@ public class OkHttpClientInterceptor extends MarkInterceptor { } RequestInterceptorUtils.printRequestLog("OkHttp", hostAndPath); AtomicReference<Request> rebuildRequest = new AtomicReference<>(); + rebuildRequest.set(request); invokerService.invoke( buildInvokerFunc(uri, hostAndPath, request, rebuildRequest, context), buildExFunc(rebuildRequest), @@ -76,6 +80,14 @@ public class OkHttpClientInterceptor extends MarkInterceptor { return context; } + private Optional<Request> getRequest(ExecuteContext context) { + final Optional<Object> originalRequest = ReflectUtils.getFieldValue(context.getObject(), FIELD_NAME); + if (originalRequest.isPresent() && originalRequest.get() instanceof Request) { + return Optional.of((Request) originalRequest.get()); + } + return Optional.empty(); + } + private Function<Exception, Object> buildExFunc(AtomicReference<Request> rebuildRequest) { return ex -> buildErrorResponse(ex, rebuildRequest.get()); } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java index e2cb4c8a..9b88cc21 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java @@ -18,9 +18,7 @@ package com.huawei.discovery.interceptors.httpclient; import com.huawei.discovery.entity.FutureDecorator; import com.huawei.discovery.entity.HttpAsyncContext; -import com.huawei.discovery.entity.Recorder; import com.huawei.discovery.entity.ServiceInstance; -import com.huawei.discovery.entity.SimpleRequestRecorder; import com.huawei.discovery.retry.InvokerContext; import com.huawei.discovery.service.InvokerService; import com.huawei.discovery.utils.HttpAsyncUtils; @@ -69,8 +67,6 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { private final AtomicBoolean isLoaded = new AtomicBoolean(); - private final Recorder recorder = new SimpleRequestRecorder(); - @Override public ExecuteContext before(ExecuteContext context) throws Exception { ready(); @@ -108,7 +104,6 @@ public class HttpAsyncClient4xInterceptor implements Interceptor { } RequestInterceptorUtils.printRequestLog("HttpAsyncClient", HttpAsyncUtils.getOrCreateContext() .getHostAndPath()); - recorder.beforeRequest(); final Object result = context.getResult(); if (!(result instanceof Future)) { return context; diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/DefaultRetryImpl.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/DefaultRetryImpl.java index 43d58198..f16c0b73 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/DefaultRetryImpl.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/DefaultRetryImpl.java @@ -18,8 +18,13 @@ package com.huawei.discovery.retry; import com.huawei.discovery.entity.Recorder; +import com.huaweicloud.sermant.core.common.LoggerFactory; + +import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; +import java.util.logging.Level; +import java.util.logging.Logger; /** * 默认重试器 @@ -28,6 +33,8 @@ import java.util.function.Predicate; * @since 2022-09-28 */ public class DefaultRetryImpl implements Retry { + private static final Logger LOGGER = LoggerFactory.getLogger(); + private final RetryConfig retryConfig; private final String name; @@ -106,7 +113,13 @@ public class DefaultRetryImpl implements Retry { } // 抛出异常 - throw new RetryException(ex); + if (invokeCount.get() > 0) { + LOGGER.log(Level.WARNING, String.format(Locale.ENGLISH, "Retry failed with %s times", + invokeCount.get()), ex); + } + final RetryException retryException = new RetryException(ex); + retryException.setStackTrace(ex.getStackTrace()); + throw retryException; } @Override diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 08c8be3c..f26d6bb5 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -16,7 +16,9 @@ package com.huawei.discovery.utils; +import com.huawei.discovery.entity.Recorder; import com.huawei.discovery.entity.ServiceInstance; +import com.huawei.discovery.entity.SimpleRequestRecorder; import com.huawei.discovery.retry.InvokerContext; import com.huaweicloud.sermant.core.common.LoggerFactory; @@ -44,9 +46,10 @@ import java.util.logging.Logger; * @since 2022-10-09 */ public class RequestInterceptorUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(); + private static final Recorder RECORDER = new SimpleRequestRecorder(); + private RequestInterceptorUtils() { } @@ -91,6 +94,7 @@ public class RequestInterceptorUtils { String path = String.format(Locale.ENGLISH, "/%s%s", hostAndPath.get(HttpConstants.HTTP_URI_HOST), hostAndPath.get(HttpConstants.HTTP_URI_PATH)); LOGGER.log(Level.FINE, String.format(Locale.ENGLISH, "[%s] request [%s] has been intercepted!", source, path)); + RECORDER.beforeRequest(); } /** diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/stats/InstanceStats.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/stats/InstanceStats.java index fe04669a..78528cb2 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/stats/InstanceStats.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/stats/InstanceStats.java @@ -53,24 +53,25 @@ public class InstanceStats implements Recorder { /** * 时间窗口 */ - private final long activeRequestTimeoutWindowMs; + private final long instanceStateTimeWindowMs; /** - * 上一次记录并发数的时间戳 + * 上一次时间窗口更新时间, 作为时间窗口的左边界 */ - private volatile long lastActiveRequestTimestamp; + private volatile long lastLeftWindowTime; /** - * 平均响应时间 + * 时间窗口内的平均响应时间 */ - private double responseAvgTime = 0d; + private volatile double responseAvgTime; /** * 构造器 */ public InstanceStats() { - this.activeRequestTimeoutWindowMs = - PluginConfigManager.getPluginConfig(LbConfig.class).getActiveRequestTimeoutWindowMs(); + this.instanceStateTimeWindowMs = + PluginConfigManager.getPluginConfig(LbConfig.class).getInstanceStatTimeWindowMs(); + lastLeftWindowTime = System.currentTimeMillis(); } /** @@ -80,7 +81,6 @@ public class InstanceStats implements Recorder { public void beforeRequest() { activeRequests.incrementAndGet(); allRequestCount.incrementAndGet(); - lastActiveRequestTimestamp = System.currentTimeMillis(); } /** @@ -102,13 +102,24 @@ public class InstanceStats implements Recorder { baseStats(consumeTimeMs); } + private void calculateResponseAvgTime() { + final long allConsumeTime = allRequestConsumeTime.get(); + final long currentTimeMillis = System.currentTimeMillis(); + if (currentTimeMillis - lastLeftWindowTime >= this.instanceStateTimeWindowMs) { + lastLeftWindowTime = currentTimeMillis; + allRequestCount.set(0); + allRequestConsumeTime.set(0); + } + this.responseAvgTime = allRequestCount.get() == 0 ? 0 : (allConsumeTime * 1d / allRequestCount.get()); + } + private void baseStats(long consumeTimeMs) { final long request = activeRequests.decrementAndGet(); if (request < 0) { activeRequests.set(0); } - final long responseTime = allRequestConsumeTime.addAndGet(consumeTimeMs); - responseAvgTime = allRequestCount.get() == 0 ? 0 : (responseTime * 1d / allRequestCount.get()); + allRequestConsumeTime.addAndGet(consumeTimeMs); + this.calculateResponseAvgTime(); } /** @@ -134,7 +145,8 @@ public class InstanceStats implements Recorder { public long getActiveRequests() { final long activeCount = activeRequests.get(); final long currentTimeMillis = System.currentTimeMillis(); - if (currentTimeMillis - lastActiveRequestTimestamp >= this.activeRequestTimeoutWindowMs) { + if (currentTimeMillis - lastLeftWindowTime >= this.instanceStateTimeWindowMs) { + lastLeftWindowTime = currentTimeMillis; this.activeRequests.set(0); return 0; } @@ -145,6 +157,11 @@ public class InstanceStats implements Recorder { return failRequestCount; } + /** + * 获取平均响应时间 + * + * @return responseAvgTime + */ public double getResponseAvgTime() { return responseAvgTime; } diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java index d2304a44..ce5ee597 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java @@ -40,7 +40,6 @@ import java.net.ConnectException; import java.net.NoRouteToHostException; import java.time.LocalDateTime; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; @@ -67,7 +66,9 @@ public class RetryServiceImpl implements InvokerService { ConnectException.class, NoRouteToHostException.class); - private final List<String> rawRetryEx = Collections.singletonList("org.apache.http.conn.ConnectTimeoutException"); + private final List<String> rawRetryEx = Arrays.asList( + "org.apache.http.conn.ConnectTimeoutException", + "org.apache.http.NoHttpResponseException"); private final Map<String, Retry> retryCache = new ConcurrentHashMap<>(); @@ -108,9 +109,6 @@ public class RetryServiceImpl implements InvokerService { try { return invokeWithEx(invokeFunc, serviceName, retry); } catch (RetryException ex) { - // 走异常处理流程 - LOGGER.log(Level.WARNING, String.format(Locale.ENGLISH, "Retry failed with %s times", - retry.config().getMaxRetry()), ex); return Optional.ofNullable(exFunc.apply(ex.getRealEx())); } catch (Exception ex) { // 重试最终失败抛出异常, 需对异常进行封装, 返回给上游, 或者作为当前调用返回调用方 diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/test/java/com/huawei/discovery/service/lb/stats/InstanceStatsTest.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/test/java/com/huawei/discovery/service/lb/stats/InstanceStatsTest.java index 5b8bb279..3fc46985 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/test/java/com/huawei/discovery/service/lb/stats/InstanceStatsTest.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/test/java/com/huawei/discovery/service/lb/stats/InstanceStatsTest.java @@ -68,7 +68,7 @@ public class InstanceStatsTest extends BaseTest { @Test public void testActiveRequest() throws InterruptedException { - lbConfig.setActiveRequestTimeoutWindowMs(1L); + lbConfig.setInstanceStatTimeWindowMs(1L); final InstanceStats stats = new InstanceStats(); stats.beforeRequest(); Thread.sleep(10);
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/httpclient/HttpAsyncClient4xInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/test/java/com/huawei/discovery/service/lb/stats/InstanceStatsTest.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/lb/stats/InstanceStats.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/entity/SimpleRequestRecorder.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttpClientInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/retry/DefaultRetryImpl.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/interceptors/OkHttp3ClientInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-service/src/main/java/com/huawei/discovery/service/retry/RetryServiceImpl.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConfig.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/config/LbConstants.java']
{'.java': 11}
11
11
0
0
11
3,127,660
716,923
98,510
1,112
6,337
1,373
124
10
463
73
123
36
0
1
1970-01-01T00:27:45
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,174
huaweicloud/sermant/1012/1010
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/1010
https://github.com/huaweicloud/Sermant/pull/1012
https://github.com/huaweicloud/Sermant/pull/1012
1
fixes
【fix】fix the bug that springboot registry plugin can not process the url query params when method is post
### What happened? when the method is post, and it's url has the url query params, plugin will not handler it. The result for it will lose the query params ### How can we reproduce it (as minimally and precisely as possible)? N/A ### Anything else we need to know? _No response_ ### Sermant version <details> 0.8.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
0bdf7d91bd519f175d413d40c986677096b9b6ae
1cf2ef962ea9ac5fb937b4487d603b761860e1ac
https://github.com/huaweicloud/sermant/compare/0bdf7d91bd519f175d413d40c986677096b9b6ae...1cf2ef962ea9ac5fb937b4487d603b761860e1ac
diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 7dd73d7e..3efa99ef 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -308,9 +308,8 @@ public class RequestInterceptorUtils { .append(HttpConstants.HTTP_URL_COLON) .append(serviceInstance.getPort()) .append(path); - if (uri.getRawQuery() != null && method.equals(HttpConstants.HTTP_GET)) { - urlBuild.append(HttpConstants.HTTP_URL_UNKNOWN) - .append(uri.getRawQuery()); + if (uri.getRawQuery() != null) { + urlBuild.append(HttpConstants.HTTP_URL_UNKNOWN).append(uri.getRawQuery()); } return urlBuild.toString(); }
['sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java']
{'.java': 1}
1
1
0
0
1
2,922,022
670,560
92,522
980
318
61
5
1
588
97
152
36
0
1
1970-01-01T00:27:50
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
9,173
huaweicloud/sermant/1013/1010
huaweicloud
sermant
https://github.com/huaweicloud/Sermant/issues/1010
https://github.com/huaweicloud/Sermant/pull/1013
https://github.com/huaweicloud/Sermant/pull/1013
1
fixes
【fix】fix the bug that springboot registry plugin can not process the url query params when method is post
### What happened? when the method is post, and it's url has the url query params, plugin will not handler it. The result for it will lose the query params ### How can we reproduce it (as minimally and precisely as possible)? N/A ### Anything else we need to know? _No response_ ### Sermant version <details> 0.8.0 </details> ### OS version <details> ```console # On Linux: $ cat /etc/os-release # paste output here $ uname -a # paste output here # On Windows: C:\\> wmic os get Caption, Version, BuildNumber, OSArchitecture # paste output here ``` </details>
b1dd072144a8bda8fd8a139041d9c0273b9d0656
6919115739eefd10ccae0252fbba47e040f7a05d
https://github.com/huaweicloud/sermant/compare/b1dd072144a8bda8fd8a139041d9c0273b9d0656...6919115739eefd10ccae0252fbba47e040f7a05d
diff --git a/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/declarer/UrlDeclarer.java b/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/declarer/UrlDeclarer.java index 20cb863a..6821721a 100644 --- a/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/declarer/UrlDeclarer.java +++ b/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/declarer/UrlDeclarer.java @@ -43,7 +43,8 @@ public class UrlDeclarer extends AbstractPluginDeclarer { @Override public InterceptDeclarer[] getInterceptDeclarers(ClassLoader classLoader) { return new InterceptDeclarer[]{ - InterceptDeclarer.build(MethodMatcher.nameEquals(METHOD_NAME), INTERCEPT_CLASS) + InterceptDeclarer.build(MethodMatcher.nameEquals(METHOD_NAME) + .and(MethodMatcher.paramTypesEqual("java.lang.String", "java.lang.String")), INTERCEPT_CLASS) }; } } diff --git a/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/interceptor/UrlInterceptor.java b/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/interceptor/UrlInterceptor.java index 327662ab..7b059949 100644 --- a/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/interceptor/UrlInterceptor.java +++ b/sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/interceptor/UrlInterceptor.java @@ -67,10 +67,11 @@ public class UrlInterceptor extends AbstractInterceptor { @Override public ExecuteContext before(ExecuteContext context) { - LbContext.INSTANCE.setCurLoadbalancerType(LbContext.LOADBALANCER_DUBBO); Object[] arguments = context.getArguments(); if (arguments != null && arguments.length > 1 && DubboUrlParamsConstants.DUBBO_LOAD_BALANCER_KEY.equals(arguments[1])) { + LbContext.INSTANCE.setCurLoadbalancerType(LbContext.LOADBALANCER_DUBBO); + // 如果为empty,继续执行原方法,即使用宿主的负载均衡策略 // 如果不为empty,则使用返回的type并跳过原方法 checkRules(); diff --git a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java index 7dd73d7e..3efa99ef 100644 --- a/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java +++ b/sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java @@ -308,9 +308,8 @@ public class RequestInterceptorUtils { .append(HttpConstants.HTTP_URL_COLON) .append(serviceInstance.getPort()) .append(path); - if (uri.getRawQuery() != null && method.equals(HttpConstants.HTTP_GET)) { - urlBuild.append(HttpConstants.HTTP_URL_UNKNOWN) - .append(uri.getRawQuery()); + if (uri.getRawQuery() != null) { + urlBuild.append(HttpConstants.HTTP_URL_UNKNOWN).append(uri.getRawQuery()); } return urlBuild.toString(); }
['sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/interceptor/UrlInterceptor.java', 'sermant-plugins/sermant-springboot-registry/springboot-registry-plugin/src/main/java/com/huawei/discovery/utils/RequestInterceptorUtils.java', 'sermant-plugins/sermant-loadbalancer/dubbo-loadbalancer-plugin/src/main/java/com/huaweicloud/loadbalancer/declarer/UrlDeclarer.java']
{'.java': 3}
3
3
0
0
3
2,942,984
675,320
93,198
987
769
161
11
3
588
97
152
36
0
1
1970-01-01T00:27:50
625
Java
{'Java': 5367471, 'Roff': 51750, 'Vue': 35403, 'Groovy': 9659, 'Shell': 6979, 'Python': 6856, 'TypeScript': 3199, 'FreeMarker': 3170, 'CSS': 2150, 'SCSS': 1577, 'Batchfile': 873, 'HTML': 344, 'JavaScript': 317, 'Dockerfile': 217}
Apache License 2.0
8,811
hxsecurity/dongtai-agent-java/158/153
hxsecurity
dongtai-agent-java
https://github.com/HXSecurity/DongTai-agent-java/issues/153
https://github.com/HXSecurity/DongTai-agent-java/pull/158
https://github.com/HXSecurity/DongTai-agent-java/pull/158#issuecomment-983420821
1
closes
When using resttemplate to customize the header, some fields will not be loaded, such as the host header.
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/HXSecurity/DongTai/blob/main/.github/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/HXSecurity/DongTai/issues) for an issue that matches the one I want to file, without success. - [X] I am not looking for support or already pursued the available [support channels](https://github.com/HXSecurity/DongTai/issues/new/choose) without success. ### Version 1.1.2 ### Installation Type Official Docker Compose ### Service Name DongTai-agent-java ### Describe the details of the bug and the steps to reproduce it When using resttemplate to customize the header, some fields will not be loaded, such as the host header.In sun.net.www.protocol.http.httpurlconnection, allowrestrictedheaders is assigned in the static block and will be initialized only once. In the agent, httpurlconnection is loaded before the program, which leads to this problem. 使用RestTemplate自定义头的时候有些字段会加载不进来,比如说host头。因为在sun.net.www.protocol.http.HttpURLConnection中allowRestrictedHeaders是放在static块中赋值,只会初始化一次。而在agent中先于程序加载了HttpURLConnection,所以导致这个问题。 ### Additional Information _No response_ ### Logs _No response_
c11628f9d235e6e972d24f2657fab5ba3305e85f
4e143208c5377fc88d31e40892ded345be30d0c7
https://github.com/hxsecurity/dongtai-agent-java/compare/c11628f9d235e6e972d24f2657fab5ba3305e85f...4e143208c5377fc88d31e40892ded345be30d0c7
diff --git a/iast-agent/src/main/java/com/secnium/iast/agent/AgentLauncher.java b/iast-agent/src/main/java/com/secnium/iast/agent/AgentLauncher.java index 26ef6647..6f380206 100755 --- a/iast-agent/src/main/java/com/secnium/iast/agent/AgentLauncher.java +++ b/iast-agent/src/main/java/com/secnium/iast/agent/AgentLauncher.java @@ -24,6 +24,7 @@ public class AgentLauncher { * @param inst inst */ public static void premain(String args, Instrumentation inst) { + System.setProperty("sun.net.http.allowRestrictedHeaders","true"); LAUNCH_MODE = LAUNCH_MODE_AGENT; try { Agent.appendToolsPath();
['iast-agent/src/main/java/com/secnium/iast/agent/AgentLauncher.java']
{'.java': 1}
1
1
0
0
1
569,114
124,230
17,871
229
74
13
1
1
1,248
138
322
30
3
0
1970-01-01T00:27:18
621
Java
{'Java': 1172876, 'Shell': 3769}
Apache License 2.0
8,812
hxsecurity/dongtai-agent-java/447/374
hxsecurity
dongtai-agent-java
https://github.com/HXSecurity/DongTai-agent-java/issues/374
https://github.com/HXSecurity/DongTai-agent-java/pull/447
https://github.com/HXSecurity/DongTai-agent-java/pull/447#issuecomment-1457515691
1
fixed
[Bug]: install成功后,原服务无法正常工作
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/HXSecurity/DongTai/blob/main/.github/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/HXSecurity/DongTai/issues) for an issue that matches the one I want to file, without success. - [X] I am not looking for support or already pursued the available [support channels](https://github.com/HXSecurity/DongTai/issues/new/choose) without success. ### Version 1.4.0 ### Installation Type Official Docker Compose ### Service Name DongTai-agent-java ### Describe the details of the bug and the steps to reproduce it - docker run -d -p 8082:8080 --name springrce -it vulfocus/spring-core-rce-2022-03-29 这个镜像 - 用热部署的方法插入之后,服务器显示 500错误 `Request processing failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/beans/factory/ListableBeanFactory` **(正常情况页面显示是OK)** ### Additional Information _No response_ ### Logs ```shell 02-Apr-2022 02:26:49.126 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath 02-Apr-2022 02:26:50.801 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext 02-Apr-2022 02:40:41.273 INFO [http-nio-8080-exec-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring DispatcherServlet 'dispatcherServlet' 02-Apr-2022 02:40:41.444 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.ApplicationDispatcher.invoke Servlet.service() for servlet [dispatcherServlet] threw exception java.lang.NoClassDefFoundError: org/springframework/beans/factory/ListableBeanFactory at java.base/java.lang.Class.getDeclaredMethods0(Native Method) at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3139) at java.base/java.lang.Class.getDeclaredMethod(Class.java:2430) at io.dongtai.iast.core.bytecode.enhance.plugin.spring.SpringApplicationImpl.loadApplicationContext(SpringApplicationImpl.java:41) at io.dongtai.iast.core.bytecode.enhance.plugin.spring.SpringApplicationImpl.getWebApplicationContext(SpringApplicationImpl.java:26) at io.dongtai.iast.core.handler.hookpoint.SpyDispatcherImpl.collectMethodPool(SpyDispatcherImpl.java:344) at org.springframework.web.servlet.FrameworkServlet.getWebApplicationContext(FrameworkServlet.java:806) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:462) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:388) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) at org.springframework.boot.web.servlet.support.ErrorPageFilter.forwardToErrorPage(ErrorPageFilter.java:191) at org.springframework.boot.web.servlet.support.ErrorPageFilter.handleException(ErrorPageFilter.java:176) at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:143) at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:64) at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:101) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:881) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:844) 02-Apr-2022 02:40:41.452 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/beans/factory/ListableBeanFactory] with root cause java.lang.NoClassDefFoundError: org/springframework/beans/factory/ListableBeanFactory at java.base/java.lang.Class.getDeclaredMethods0(Native Method) at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3139) at java.base/java.lang.Class.getDeclaredMethod(Class.java:2430) at io.dongtai.iast.core.bytecode.enhance.plugin.spring.SpringApplicationImpl.loadApplicationContext(SpringApplicationImpl.java:41) at io.dongtai.iast.core.bytecode.enhance.plugin.spring.SpringApplicationImpl.getWebApplicationContext(SpringApplicationImpl.java:26) at io.dongtai.iast.core.handler.hookpoint.SpyDispatcherImpl.collectMethodPool(SpyDispatcherImpl.java:344) at org.springframework.web.servlet.FrameworkServlet.getWebApplicationContext(FrameworkServlet.java:806) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:462) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:388) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) at org.springframework.boot.web.servlet.support.ErrorPageFilter.forwardToErrorPage(ErrorPageFilter.java:191) at org.springframework.boot.web.servlet.support.ErrorPageFilter.handleException(ErrorPageFilter.java:176) at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:143) at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:64) at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:101) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:881) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:844) ```
9b326f53b76bd46229045cf5a4e5adca658ed38b
af37a3604be994928dcfdd98ec687bcc86bf89a8
https://github.com/hxsecurity/dongtai-agent-java/compare/9b326f53b76bd46229045cf5a4e5adca658ed38b...af37a3604be994928dcfdd98ec687bcc86bf89a8
diff --git a/dongtai-core/src/main/java/io/dongtai/iast/core/bytecode/enhance/plugin/spring/SpringApplicationImpl.java b/dongtai-core/src/main/java/io/dongtai/iast/core/bytecode/enhance/plugin/spring/SpringApplicationImpl.java index 682d9329..d1a91db6 100644 --- a/dongtai-core/src/main/java/io/dongtai/iast/core/bytecode/enhance/plugin/spring/SpringApplicationImpl.java +++ b/dongtai-core/src/main/java/io/dongtai/iast/core/bytecode/enhance/plugin/spring/SpringApplicationImpl.java @@ -37,6 +37,12 @@ public class SpringApplicationImpl { getAPI = proxyClass.getDeclaredMethod("getAPI", Object.class); } catch (NoSuchMethodException e) { DongTaiLog.error("SpringApplicationImpl.loadApplicationContext failed", e); + } catch (NoClassDefFoundError e) { + // spring mvc has no class org/springframework/beans/factory/ListableBeanFactory + if (!e.getMessage().equals(" org/springframework/beans/factory/ListableBeanFactory".substring(1))) { + DongTaiLog.warn("SpringApplicationImpl.loadApplicationContext failed", e); + } + isSend = true; } finally { iastClassLoader = null; }
['dongtai-core/src/main/java/io/dongtai/iast/core/bytecode/enhance/plugin/spring/SpringApplicationImpl.java']
{'.java': 1}
1
1
0
0
1
799,051
173,938
23,432
294
410
82
6
1
13,947
435
3,071
163
3
1
1970-01-01T00:27:52
621
Java
{'Java': 1172876, 'Shell': 3769}
Apache License 2.0
8,813
hxsecurity/dongtai-agent-java/534/533
hxsecurity
dongtai-agent-java
https://github.com/HXSecurity/DongTai-agent-java/issues/533
https://github.com/HXSecurity/DongTai-agent-java/pull/534
https://github.com/HXSecurity/DongTai-agent-java/pull/534#issuecomment-1586758946
1
fix
[Bug]: fastjson已经是1.2.83版本了,洞态显示请求头有反序列化漏洞
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/HXSecurity/DongTai/blob/main/.github/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/HXSecurity/DongTai/issues) for an issue that matches the one I want to file, without success. - [X] I am not looking for support or already pursued the available [support channels](https://github.com/HXSecurity/DongTai/issues/new/choose) without success. ### Version 1.11.0 ### Installation Type Official SaaS Service ### Service Name DongTai-agent-java ### Describe the details of the bug and the steps to reproduce it ![image](https://github.com/HXSecurity/DongTai/assets/28825226/0184d78d-e070-4be4-b069-aaf2065c9d3a) 污点流程图 ![image](https://github.com/HXSecurity/DongTai/assets/28825226/d8638f70-9be5-43d2-9c37-f85caf9e9603) 危险方法显示是fastjson ![image](https://github.com/HXSecurity/DongTai/assets/28825226/79cf4cfb-3544-4352-97c9-84ed54554b28) 但是fastjson目前已经是最新版本 1.2.83 ,这是否是误报?不是误报的话又该怎么验证 ### Additional Information _No response_ ### Logs _No response_
1142b3229194466dd0a69d2144e5d539ecb48b12
d327a1db4478cd5643a18a5c11d6f49267d3e80d
https://github.com/hxsecurity/dongtai-agent-java/compare/1142b3229194466dd0a69d2144e5d539ecb48b12...d327a1db4478cd5643a18a5c11d6f49267d3e80d
diff --git a/dongtai-agent/src/main/java/io/dongtai/iast/agent/middlewarerecognition/dubbo/DubboService.java b/dongtai-agent/src/main/java/io/dongtai/iast/agent/middlewarerecognition/dubbo/DubboService.java index 0007b4e1..c46f4ee3 100644 --- a/dongtai-agent/src/main/java/io/dongtai/iast/agent/middlewarerecognition/dubbo/DubboService.java +++ b/dongtai-agent/src/main/java/io/dongtai/iast/agent/middlewarerecognition/dubbo/DubboService.java @@ -13,7 +13,7 @@ public class DubboService implements IServer { } catch (Throwable ignored) { } try { - loader.loadClass("com.alibaba.dubbo.monitor.support.MonitorFilter"); + loader.loadClass(" com.alibaba.dubbo.monitor.support.MonitorFilter".substring(1)); return true; } catch (Throwable ignored) { } diff --git a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/vulscan/dynamic/FastjsonCheck.java b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/vulscan/dynamic/FastjsonCheck.java index 73da47fe..31229db6 100644 --- a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/vulscan/dynamic/FastjsonCheck.java +++ b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/vulscan/dynamic/FastjsonCheck.java @@ -12,9 +12,9 @@ import java.util.List; public class FastjsonCheck implements SinkSafeChecker { public static List<String> FASTJSON_SINK_METHODS = Arrays.asList( - "com.alibaba.fastjson.JSON.parseObject(java.lang.String)", - "com.alibaba.fastjson.JSON.parse(java.lang.String,int)", - "com.alibaba.fastjson.JSON.parse(java.lang.String)" + " com.alibaba.fastjson.JSON.parseObject(java.lang.String)".substring(1), + " com.alibaba.fastjson.JSON.parse(java.lang.String,int)".substring(1), + " com.alibaba.fastjson.JSON.parse(java.lang.String)".substring(1) ); private String policySignature; @@ -36,9 +36,9 @@ public class FastjsonCheck implements SinkSafeChecker { try { Class<?> cls; if (JSON_CLASS_LOADER == null) { - cls = Class.forName("com.alibaba.fastjson.JSON"); + cls = Class.forName(" com.alibaba.fastjson.JSON".substring(1)); } else { - cls = Class.forName("com.alibaba.fastjson.JSON", false, JSON_CLASS_LOADER); + cls = Class.forName(" com.alibaba.fastjson.JSON".substring(1), false, JSON_CLASS_LOADER); } Field f = cls.getDeclaredField("VERSION"); Class<?> t = f.getType(); @@ -61,9 +61,9 @@ public class FastjsonCheck implements SinkSafeChecker { // https://github.com/alibaba/fastjson/wiki/fastjson_safemode Class<?> cfgClass; if (PARSE_CONFIG_CLASS_LOADER == null) { - cfgClass = Class.forName("com.alibaba.fastjson.parser.ParserConfig"); + cfgClass = Class.forName(" com.alibaba.fastjson.parser.ParserConfig".substring(1)); } else { - cfgClass = Class.forName("com.alibaba.fastjson.parser.ParserConfig", false, PARSE_CONFIG_CLASS_LOADER); + cfgClass = Class.forName(" com.alibaba.fastjson.parser.ParserConfig".substring(1), false, PARSE_CONFIG_CLASS_LOADER); } Object cfg = cfgClass.getMethod("getGlobalInstance").invoke(null); Object isSafeMode = cfg.getClass().getMethod("isSafeMode").invoke(cfg);
['dongtai-agent/src/main/java/io/dongtai/iast/agent/middlewarerecognition/dubbo/DubboService.java', 'dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/vulscan/dynamic/FastjsonCheck.java']
{'.java': 2}
2
2
0
0
2
867,401
186,520
25,295
301
1,424
266
16
2
1,115
99
362
34
6
0
1970-01-01T00:28:06
621
Java
{'Java': 1172876, 'Shell': 3769}
Apache License 2.0
8,814
hxsecurity/dongtai-agent-java/542/538
hxsecurity
dongtai-agent-java
https://github.com/HXSecurity/DongTai-agent-java/issues/538
https://github.com/HXSecurity/DongTai-agent-java/pull/542
https://github.com/HXSecurity/DongTai-agent-java/pull/542
1
fix
[Bug]: POST出现服务器端请求伪造漏洞,位置:HEADER
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/HXSecurity/DongTai/blob/main/.github/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/HXSecurity/DongTai/issues) for an issue that matches the one I want to file, without success. - [X] I am not looking for support or already pursued the available [support channels](https://github.com/HXSecurity/DongTai/issues/new/choose) without success. ### Version 1.12.0 ### Installation Type Official Kubernetes ### Service Name DongTai-Web ### Describe the details of the bug and the steps to reproduce it ![image](https://github.com/HXSecurity/DongTai/assets/28825226/b9918e2a-0816-4b39-9b9b-452509b8c1c4) 根据调用链显示x-forwarded-for参数存在ssrf的注入点,我将洞态上的请求复制到burp上重新发从,发现将x-forwarded-for这个参数删除之后仍然可以得到响应结果,这个是不是误报? ![image](https://github.com/HXSecurity/DongTai/assets/28825226/3d4e2780-8d32-417b-b7d4-7c72681e94d8) ![image](https://github.com/HXSecurity/DongTai/assets/28825226/f53fe931-acb6-48b2-84f2-38a075361fd6) ### Additional Information _No response_ ### Logs _No response_
87dd311b4a33c283b66ff9345dbd1152146578ed
e987bfee2fd367ab6c246acbb81050a4dc08203d
https://github.com/hxsecurity/dongtai-agent-java/compare/87dd311b4a33c283b66ff9345dbd1152146578ed...e987bfee2fd367ab6c246acbb81050a4dc08203d
diff --git a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommand.java b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommand.java index a269fb53..f131b262 100644 --- a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommand.java +++ b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommand.java @@ -13,6 +13,7 @@ public enum TaintCommand { REMOVE, REPLACE, CONCAT, + OVERWRITE, TRIM, TRIM_RIGHT, TRIM_LEFT, diff --git a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommandRunner.java b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommandRunner.java index 97b5dd20..ae5c85e5 100644 --- a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommandRunner.java +++ b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommandRunner.java @@ -133,6 +133,8 @@ public class TaintCommandRunner { case CONCAT: this.builder.concat(tr, target, oldTaintRanges, source, srcTaintRanges, params); break; + case OVERWRITE: + this.builder.overwrite(tr, oldTaintRanges, source, srcTaintRanges, p1, this.paramsCount); case TRIM: case TRIM_LEFT: case TRIM_RIGHT: diff --git a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintRangesBuilder.java b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintRangesBuilder.java index 6a6be60e..f78d114f 100644 --- a/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintRangesBuilder.java +++ b/dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintRangesBuilder.java @@ -144,6 +144,16 @@ public class TaintRangesBuilder { taintRanges.merge(); } + public void overwrite(TaintRanges taintRanges, TaintRanges oldTagRanges, Object source, TaintRanges srcTagRanges, int p1, int argC) { + if (argC == 1) { + int length = getLength(source); + srcTagRanges.shift(p1); + oldTagRanges.clear(p1, length + p1); + taintRanges.addAll(oldTagRanges); + taintRanges.addAll(srcTagRanges); + } + } + public void trim(TaintCommand command, TaintRanges taintRanges, Object source, TaintRanges srcTaintRanges, int argC) { if (argC > 0) { return;
['dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommandRunner.java', 'dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintCommand.java', 'dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/models/taint/range/TaintRangesBuilder.java']
{'.java': 3}
3
3
0
0
3
950,980
207,467
28,410
336
568
133
13
3
1,140
94
384
34
6
0
1970-01-01T00:28:08
621
Java
{'Java': 1172876, 'Shell': 3769}
Apache License 2.0
8,816
hxsecurity/dongtai-agent-java/201/202
hxsecurity
dongtai-agent-java
https://github.com/HXSecurity/DongTai-agent-java/issues/202
https://github.com/HXSecurity/DongTai-agent-java/pull/201
https://github.com/HXSecurity/DongTai-agent-java/pull/201
1
closes
Agent动态attach后卸载存在bug
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/HXSecurity/DongTai/blob/main/.github/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/HXSecurity/DongTai/issues) for an issue that matches the one I want to file, without success. - [X] I am not looking for support or already pursued the available [support channels](https://github.com/HXSecurity/DongTai/issues/new/choose) without success. ### Version 1.1.4 ### Installation Type Other (specify below) ### Service Name DongTai-agent-java ### Describe the details of the bug and the steps to reproduce it 1.不涉及 2.不涉及 3.执行卸载时AttachLauncher 传入的是“token=uninstall” ,而agentmain中判断传入字符是否等于“uninstall”。前后不一致导致发起热卸载操作失败 ### Additional Information _No response_ ### Logs _No response_
72d05912ae91060b2a50489abd32120f53f8d045
c13466d162ffb4430a4319c8822f7ed1d45bfbf5
https://github.com/hxsecurity/dongtai-agent-java/compare/72d05912ae91060b2a50489abd32120f53f8d045...c13466d162ffb4430a4319c8822f7ed1d45bfbf5
diff --git a/iast-agent/src/main/java/com/secnium/iast/agent/AttachLauncher.java b/iast-agent/src/main/java/com/secnium/iast/agent/AttachLauncher.java index ab373c86..fe861bc1 100644 --- a/iast-agent/src/main/java/com/secnium/iast/agent/AttachLauncher.java +++ b/iast-agent/src/main/java/com/secnium/iast/agent/AttachLauncher.java @@ -34,7 +34,7 @@ public class AttachLauncher { } } - vmObj.loadAgent(AGENT_PATH, "token=" + args); + vmObj.loadAgent(AGENT_PATH, args); LogUtils.info("attach to process " + pid + " success."); } finally { if (null != vmObj) {
['iast-agent/src/main/java/com/secnium/iast/agent/AttachLauncher.java']
{'.java': 1}
1
1
0
0
1
582,267
126,584
18,287
230
106
26
2
1
845
96
251
31
3
0
1970-01-01T00:27:20
621
Java
{'Java': 1172876, 'Shell': 3769}
Apache License 2.0
8,815
hxsecurity/dongtai-agent-java/406/403
hxsecurity
dongtai-agent-java
https://github.com/HXSecurity/DongTai-agent-java/issues/403
https://github.com/HXSecurity/DongTai-agent-java/pull/406
https://github.com/HXSecurity/DongTai-agent-java/pull/406
1
close
[Bug]: agent在wndows下运行时,无法注册,报错
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/HXSecurity/DongTai/blob/main/.github/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/HXSecurity/DongTai/issues) for an issue that matches the one I want to file, without success. - [X] I am not looking for support or already pursued the available [support channels](https://github.com/HXSecurity/DongTai/issues/new/choose) without success. ### Version latest ### Installation Type Official Kubernetes ### Service Name DongTai-Web ### Describe the details of the bug and the steps to reproduce it 下载agent后在windows下运行(运行命令` java -javaagent:dongtai-agent.jar -jar xxx.jar`),报错注册失败: 2022-11-03 09:00:11 [io.dongtai.iast.agent] [ERROR] Register msg: {"status": 202, "msg": "\\u63a2\\u9488\\u6ce8\\u518c\\u5931\\u8d25"} ### Additional Information 查看服务端日志,疑似编码问题。 相关日志: ERROR 2022-11-03 10:28:09,614 [agent_register.post:298] 探针注册失败,原因:'utf-8' codec can't decode byte 0xbb in position 480: invalid start byte Traceback (most recent call last): File "/opt/dongtai/./dongtai_protocol/views/agent_register.py", line 272, in post self.register_server( File "/opt/dongtai/./dongtai_protocol/views/agent_register.py", line 122, in register_server env = base64.b64decode(server_env).decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 480: invalid start byte [pid: 25|app: 0|req: 1/5] 10.42.178.223 () {42 vars in 643 bytes} [Thu Nov 3 10:28:08 2022] POST /api/v1/agent/register => generated 62 ### Logs ```shell ERROR 2022-11-03 10:28:09,614 [agent_register.post:298] 探针注册失败,原因:'utf-8' codec can't decode byte 0xbb in position 480: invalid start byte Traceback (most recent call last): File "/opt/dongtai/./dongtai_protocol/views/agent_register.py", line 272, in post self.register_server( File "/opt/dongtai/./dongtai_protocol/views/agent_register.py", line 122, in register_server env = base64.b64decode(server_env).decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 480: invalid start byte [pid: 25|app: 0|req: 1/5] 10.42.178.223 () {42 vars in 643 bytes} [Thu Nov 3 10:28:08 2022] POST /api/v1/agent/register => generated 62 ```
fb3940975dd33fa7b84645fe37f02d9dad352d61
60941c8700ab5e729826553b5c2d7b940eb88736
https://github.com/hxsecurity/dongtai-agent-java/compare/fb3940975dd33fa7b84645fe37f02d9dad352d61...60941c8700ab5e729826553b5c2d7b940eb88736
diff --git a/dongtai-agent/src/main/java/io/dongtai/iast/agent/report/AgentRegisterReport.java b/dongtai-agent/src/main/java/io/dongtai/iast/agent/report/AgentRegisterReport.java index ce285d2b..6b887954 100644 --- a/dongtai-agent/src/main/java/io/dongtai/iast/agent/report/AgentRegisterReport.java +++ b/dongtai-agent/src/main/java/io/dongtai/iast/agent/report/AgentRegisterReport.java @@ -13,6 +13,7 @@ import org.json.JSONArray; import org.json.JSONObject; import java.net.*; +import java.nio.charset.Charset; import java.util.Enumeration; /** @@ -48,8 +49,9 @@ public class AgentRegisterReport { object.put("hostname", AgentRegisterReport.getInternalHostName()); object.put("language", AgentConstant.LANGUAGE); object.put("network", readIpInfo()); - object.put("serverEnv", - Base64Encoder.encodeBase64String(System.getProperties().toString().getBytes()).replaceAll("\\n", "")); + object.put("serverEnv", Base64Encoder + .encodeBase64String(System.getProperties().toString().getBytes(Charset.forName("UTF-8"))) + .replaceAll("\\n", "")); object.put("containerName", null == server ? "" : server.getName()); object.put("containerVersion", null == server ? "" : server.getVersion()); object.put("serverPath", ServerDetect.getWebServerPath()); @@ -195,12 +197,12 @@ public class AgentRegisterReport { JSONObject jsonObject = new JSONObject(); String displayName = networkInterface.getDisplayName(); String hostAddress = inetAddress.getHostAddress(); - jsonObject.put("name",displayName); - jsonObject.put("ip",hostAddress); - if (displayName.startsWith("en")){ - jsonObject.put("isAddress","1"); - }else { - jsonObject.put("isAddress","0"); + jsonObject.put("name", displayName); + jsonObject.put("ip", hostAddress); + if (displayName.startsWith("en")) { + jsonObject.put("isAddress", "1"); + } else { + jsonObject.put("isAddress", "0"); } network.put(jsonObject); } @@ -211,7 +213,7 @@ public class AgentRegisterReport { } } - public void register(){ + public void register() { try { if (server == null) { System.out.println("[io.dongtai.iast.agent] Can't Recognize Web Service");
['dongtai-agent/src/main/java/io/dongtai/iast/agent/report/AgentRegisterReport.java']
{'.java': 1}
1
1
0
0
1
924,350
203,464
27,425
343
1,071
184
20
1
2,293
247
750
49
3
1
1970-01-01T00:27:47
621
Java
{'Java': 1172876, 'Shell': 3769}
Apache License 2.0
9,004
androidx/media/141/131
androidx
media
https://github.com/androidx/media/issues/131
https://github.com/androidx/media/pull/141
https://github.com/androidx/media/pull/141
1
fixes
API <=26: MediaNotification will add a Badge to the App Icon
New APIs will never show a badge for a MediaStyle notification. It seems that for older API versions it needs to be deactivated manually. ### Media3 Version 1.0.0-beta02
26c8478de667180cb8137a20ae88df285c0bb046
22efef2dea3789c19a5660c57a0b5e31b96dace2
https://github.com/androidx/media/compare/26c8478de667180cb8137a20ae88df285c0bb046...22efef2dea3789c19a5660c57a0b5e31b96dace2
diff --git a/libraries/session/src/main/java/androidx/media3/session/DefaultMediaNotificationProvider.java b/libraries/session/src/main/java/androidx/media3/session/DefaultMediaNotificationProvider.java index 4b588cfda7..23bbb9f85d 100644 --- a/libraries/session/src/main/java/androidx/media3/session/DefaultMediaNotificationProvider.java +++ b/libraries/session/src/main/java/androidx/media3/session/DefaultMediaNotificationProvider.java @@ -508,6 +508,9 @@ public class DefaultMediaNotificationProvider implements MediaNotification.Provi channelId, context.getString(channelNameResourceId), NotificationManager.IMPORTANCE_LOW); + if (Util.SDK_INT == 26 || Util.SDK_INT == 27) { + channel.setShowBadge(false); + } notificationManager.createNotificationChannel(channel); }
['libraries/session/src/main/java/androidx/media3/session/DefaultMediaNotificationProvider.java']
{'.java': 1}
1
1
0
0
1
11,161,935
2,478,514
298,867
1,020
95
27
3
1
179
28
41
7
0
0
1970-01-01T00:27:39
609
Java
{'Java': 20334016, 'C++': 112467, 'GLSL': 48492, 'AIDL': 28951, 'Makefile': 11496, 'Shell': 8440, 'CMake': 3728}
Apache License 2.0
431
exercism/java/1646/1645
exercism
java
https://github.com/exercism/java/issues/1645
https://github.com/exercism/java/pull/1646
https://github.com/exercism/java/pull/1646
1
fixes
DnD Character Track build issues
Hey everyone, I am currently going through the Java track and I just downloaded the exercise. This exercise gives me a lot of errors but that is without me implementing anything. It looks like the solution .java file has a lot of **missing methods** and that is uncommon for the track. Here is the error log. ``` > Executing task: gradle test < > Task :compileTestJava FAILED C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:118: error: cannot find symbol assertTrue(character.getDexterity() > 2 && character.getDexterity() < 19); ^ symbol: method getDexterity() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:118: error: cannot find symbol assertTrue(character.getDexterity() > 2 && character.getDexterity() < 19); ^ symbol: method getDexterity() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:119: error: cannot find symbol assertTrue(character.getConstitution() > 2 && character.getConstitution() < 19); ^ symbol: method getConstitution() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:119: error: cannot find symbol assertTrue(character.getConstitution() > 2 && character.getConstitution() < 19); ^ symbol: method getConstitution() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:120: error: cannot find symbol assertTrue(character.getIntelligence() > 2 && character.getIntelligence() < 19); ^ symbol: method getIntelligence() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:120: error: cannot find symbol assertTrue(character.getIntelligence() > 2 && character.getIntelligence() < 19); ^ symbol: method getIntelligence() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:121: error: cannot find symbol assertTrue(character.getWisdom() > 2 && character.getWisdom() < 19); ^ symbol: method getWisdom() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:121: error: cannot find symbol assertTrue(character.getWisdom() > 2 && character.getWisdom() < 19); ^ symbol: method getWisdom() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:122: error: cannot find symbol assertTrue(character.getCharisma() > 2 && character.getCharisma() < 19); ^ symbol: method getCharisma() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:122: error: cannot find symbol assertTrue(character.getCharisma() > 2 && character.getCharisma() < 19); ^ symbol: method getCharisma() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:123: error: cannot find symbol assertEquals(character.getHitpoints(), ^ symbol: method getHitpoints() location: variable character of type DnDCharacter C:\\Users\\Mayur\\Exercism\\java\\dnd-character\\src\\test\\java\\DnDCharacterTest.java:124: error: cannot find symbol 10 + character.modifier(character.getConstitution())); ^ symbol: method getConstitution() location: variable character of type DnDCharacter 12 errors FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':compileTestJava'. > Compilation failed; see the compiler error output for details. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 1s 2 actionable tasks: 1 executed, 1 up-to-date The terminal process terminated with exit code: 1 ```
83e8cb9a5c4d10e9df7642a615a55e3ecd8bdaea
8e7e277fb9560be7604e69058831a96ffeb3dbc4
https://github.com/exercism/java/compare/83e8cb9a5c4d10e9df7642a615a55e3ecd8bdaea...8e7e277fb9560be7604e69058831a96ffeb3dbc4
diff --git a/exercises/dnd-character/src/main/java/DnDCharacter.java b/exercises/dnd-character/src/main/java/DnDCharacter.java index 1bc48c69..470d3327 100644 --- a/exercises/dnd-character/src/main/java/DnDCharacter.java +++ b/exercises/dnd-character/src/main/java/DnDCharacter.java @@ -8,4 +8,32 @@ class DnDCharacter { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); } + int getStrength() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + + int getDexterity() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + + int getConstitution() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + + int getIntelligence() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + + int getWisdom() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + + int getCharisma() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + + int getHitpoints() { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } + }
['exercises/dnd-character/src/main/java/DnDCharacter.java']
{'.java': 1}
1
1
0
0
1
222,451
47,239
7,953
206
1,015
159
28
1
4,931
403
1,137
89
1
1
1970-01-01T00:25:54
589
Java
{'Java': 1063911, 'Shell': 29846}
MIT License
434
exercism/java/422/416
exercism
java
https://github.com/exercism/java/issues/416
https://github.com/exercism/java/pull/422
https://github.com/exercism/java/pull/422
1
closes
book-store: Example implementation is incorrect
The description of the exercise describes a a scenario that is also a [test case](https://github.com/exercism/xjava/blob/master/exercises/book-store/src/test/java/BookstoreTest.java#L70-L74) where two groups of 4 are cheaper than two groups of 5 and 3. The example implementation always starts with the biggest possible group and does not try all other combinations to really find the cheapest price. The problem why the tests don't find this is the incorrect use of the delta parameter in the assert method. ```java List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,3,4,5)); Bookstore bookstore = new Bookstore(books); assertEquals(51.20,bookstore.calculateTotalCost(),2); ``` While `calculateTotalCost()` actually returns the wrong price of `51.6` because of the `delta=2` even `53.2` or `49.2` would be considered equal. > delta - the maximum delta between expected and actual for which both numbers are still considered equal. Maybe `delta` should better be something like `0.001` so people really implement the correct algorithm.
165511f4d6d8bceb1e7ac9c16f0e2a9b10d2758b
0e0d28882bd889642f99b68550d93ad684e6bed5
https://github.com/exercism/java/compare/165511f4d6d8bceb1e7ac9c16f0e2a9b10d2758b...0e0d28882bd889642f99b68550d93ad684e6bed5
diff --git a/exercises/book-store/src/example/java/Bookstore.java b/exercises/book-store/src/example/java/Bookstore.java index 54908ed6..48b27e7f 100644 --- a/exercises/book-store/src/example/java/Bookstore.java +++ b/exercises/book-store/src/example/java/Bookstore.java @@ -1,61 +1,57 @@ -import java.awt.print.Printable; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -public class Bookstore{ +class Bookstore { - private static int BOOK_PRICE = 8, MAX_GROUP_SIZE = 5; - private List<Integer> books; - private static double[] DISCOUNT_TIERS = {0,5,10,20,25}; + private static final int BOOK_PRICE = 8, MAX_GROUP_SIZE = 5; - public Bookstore (List<Integer> books){ - this.books = books; - } - + private static double[] DISCOUNT_TIERS = {0, 5, 10, 20, 25}; + private List<Integer> books; + Bookstore(List<Integer> books) { + this.books = books; + } - public double calculateTotalCost(){ - return calculateTotalCost(this.books,0); - } + double calculateTotalCost() { + return calculateTotalCost(this.books, 0); + } - private double calculateTotalCost (List<Integer> books,double priceSoFar ){ - double minPrice = Double.MAX_VALUE; + private double calculateTotalCost(List<Integer> books, double priceSoFar) { + if (books.size() == 0) { + return priceSoFar; + } + List<Integer> availableBookNumbers = books.stream() + .distinct() + .collect(Collectors.toList()); - if(books.size() == 0){ - return priceSoFar; - } + double minPrice = Double.MAX_VALUE; - List<Integer> groups = (ArrayList<Integer>) books.stream().distinct().collect(Collectors.toList()); + for (int i = 0; i < availableBookNumbers.size(); i++) { + List<Integer> newGroupBooks = new ArrayList<>(availableBookNumbers.subList(0, i + 1)); + List<Integer> remainingBooks = new ArrayList<>(books); - - double price = 0; + for (final Integer newGroupBook : newGroupBooks) { + //noinspection UseBulkOperation - we want to remove _one_ of each book number, not _all_ of each book number. + remainingBooks.remove(newGroupBook); + } - for(int i = 0;i<groups.size();i++){ - books.remove(groups.get(i)); - } - - try { - price = calculateTotalCost(books,priceSoFar + costPerGroup(groups.size())); - } catch (Exception e) { - e.printStackTrace(); - } - - minPrice = Math.min(minPrice, price); - return minPrice; + double price = calculateTotalCost(remainingBooks, priceSoFar + costOfGroupSize(newGroupBooks.size())); + minPrice = Math.min(minPrice, price); + } - } + return minPrice; + } - private double costPerGroup(int groupSize) throws Exception{ - if (groupSize < 1 || groupSize > MAX_GROUP_SIZE){ - throw new Exception("Invalid group size : " + groupSize ); - } - return BOOK_PRICE * groupSize * (100 - DISCOUNT_TIERS[groupSize-1])/100; - } + private double costOfGroupSize(int groupSize) { + if (groupSize < 1 || groupSize > MAX_GROUP_SIZE) { + throw new IllegalStateException("Invalid group size : " + groupSize); + } + return BOOK_PRICE * groupSize * (100 - DISCOUNT_TIERS[groupSize - 1]) / 100; + } } diff --git a/exercises/book-store/src/test/java/BookstoreTest.java b/exercises/book-store/src/test/java/BookstoreTest.java index 8552d393..89389648 100644 --- a/exercises/book-store/src/test/java/BookstoreTest.java +++ b/exercises/book-store/src/test/java/BookstoreTest.java @@ -1,5 +1,6 @@ import static org.junit.Assert.assertEquals; +import java.util.Collections; import java.util.List; import java.util.ArrayList; import java.util.Arrays; @@ -7,112 +8,112 @@ import java.util.Arrays; import org.junit.Ignore; import org.junit.Test; -public class BookstoreTest{ - - @Test - public void onlyASingleBook(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1)); - Bookstore bookstore = new Bookstore(books); - assertEquals(8,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void twoOfSameBook(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,1)); - Bookstore bookstore = new Bookstore(books); - assertEquals(16,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void emptyBasket(){ - List<Integer> books = new ArrayList<>(); - Bookstore bookstore = new Bookstore(books); - assertEquals(0,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void twoDifferentBooks(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,2)); - Bookstore bookstore = new Bookstore(books); - assertEquals(15.20,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void threeDifferentBooks(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,2,3)); - Bookstore bookstore = new Bookstore(books); - assertEquals(21.6,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void fourDifferentBooks(){ - ArrayList<Integer> books = new ArrayList<>(Arrays.asList(1,2,3,4)); - Bookstore bookstore = new Bookstore(books); - assertEquals(25.6,bookstore.calculateTotalCost(),2); - - } - - @Ignore - @Test - public void fiveDifferentBooks(){ - ArrayList<Integer> books = new ArrayList<>(Arrays.asList(1,2,3,4,5)); - Bookstore bookstore = new Bookstore(books); - assertEquals(30,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void twoGroupsOfFourIsCheaperThanGroupOfFivePlusGroupOfThree(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,3,4,5)); - Bookstore bookstore = new Bookstore(books); - assertEquals(51.20,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void groupOfFourPlusGroupOfTwoIsCheaperThanTwoGroupsOfThree(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,4)); - Bookstore bookstore = new Bookstore(books); - assertEquals(40.8,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void twoEachOfFirst4BooksAnd1CopyEachOfRest(){ - Integer[] p = {1,1,2,2,3,3,4,4,5}; - List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,3,4,4,5)); - Bookstore bookstore = new Bookstore(books); - assertEquals(55.60,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void twoCopiesOfEachBook(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,3,4,4,5,5)); - Bookstore bookstore = new Bookstore(books); - assertEquals(60.00,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void threeCopiesOfFirstBookAnd2EachOfRemaining(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,3,4,4,5,5,1)); - Bookstore bookstore = new Bookstore(books); - assertEquals(68.00,bookstore.calculateTotalCost(),2); - } - - @Ignore - @Test - public void threeEachOFirst2BooksAnd2EachOfRemainingBooks(){ - List<Integer> books = new ArrayList<>(Arrays.asList(1,1,2,2,3,3,4,4,5,5,1,2)); - Bookstore bookstore = new Bookstore(books); - assertEquals(75.20,bookstore.calculateTotalCost(),2); - } +public class BookstoreTest { + + // This is sufficient accuracy since we're handling currency values, which should be equal to within 2 decimal places. + private static final double EQUALITY_TOLERANCE = 0.001; + + @Test + public void onlyASingleBook() { + List<Integer> books = new ArrayList<>(Collections.singletonList(1)); + Bookstore bookstore = new Bookstore(books); + assertEquals(8, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void twoOfSameBook() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1)); + Bookstore bookstore = new Bookstore(books); + assertEquals(16, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void emptyBasket() { + List<Integer> books = new ArrayList<>(); + Bookstore bookstore = new Bookstore(books); + assertEquals(0, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void twoDifferentBooks() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 2)); + Bookstore bookstore = new Bookstore(books); + assertEquals(15.20, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void threeDifferentBooks() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 2, 3)); + Bookstore bookstore = new Bookstore(books); + assertEquals(21.6, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void fourDifferentBooks() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); + Bookstore bookstore = new Bookstore(books); + assertEquals(25.6, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void fiveDifferentBooks() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + Bookstore bookstore = new Bookstore(books); + assertEquals(30, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void twoGroupsOfFourIsCheaperThanGroupOfFivePlusGroupOfThree() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 5)); + Bookstore bookstore = new Bookstore(books); + assertEquals(51.20, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void groupOfFourPlusGroupOfTwoIsCheaperThanTwoGroupsOfThree() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 4)); + Bookstore bookstore = new Bookstore(books); + assertEquals(40.8, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void twoEachOfFirst4BooksAnd1CopyEachOfRest() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5)); + Bookstore bookstore = new Bookstore(books); + assertEquals(55.60, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void twoCopiesOfEachBook() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5)); + Bookstore bookstore = new Bookstore(books); + assertEquals(60.00, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void threeCopiesOfFirstBookAnd2EachOfRemaining() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1)); + Bookstore bookstore = new Bookstore(books); + assertEquals(68.00, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } + + @Ignore + @Test + public void threeEachOFirst2BooksAnd2EachOfRemainingBooks() { + List<Integer> books = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2)); + Bookstore bookstore = new Bookstore(books); + assertEquals(75.20, bookstore.calculateTotalCost(), EQUALITY_TOLERANCE); + } } -
['exercises/book-store/src/example/java/Bookstore.java', 'exercises/book-store/src/test/java/BookstoreTest.java']
{'.java': 2}
2
2
0
0
2
97,207
20,997
3,674
118
2,819
702
76
1
1,064
139
250
14
1
1
1970-01-01T00:24:52
589
Java
{'Java': 1063911, 'Shell': 29846}
MIT License
432
exercism/java/780/778
exercism
java
https://github.com/exercism/java/issues/778
https://github.com/exercism/java/pull/780
https://github.com/exercism/java/pull/780
1
fixes
saddle-points: unhelpful error message
When running the saddle-points tests you don't get a very descriptive error message (unless I'm doing something wrong). The error message I get is something along the lines of: `expected:<MatrixCoordinate@1f> but was:<MatrixCoordinate@0` Which isn't much help in finding out what you've done wrong. To improve this we could iterate over the sets and compare each point with a more detailed error message e.g. `"Expected row to be " + expected.getRow() + " and it was " + actual.getRow() + ". Expected column to be " + expected.getCol() + " and it was " + actual.getCol() + ".";` What do you think @exercism/java?
37e3c794bd78a0a707c84e07b2901193066fdd35
49db0afcf0a0e63626c9fcaf39a3ff1fcbce5534
https://github.com/exercism/java/compare/37e3c794bd78a0a707c84e07b2901193066fdd35...49db0afcf0a0e63626c9fcaf39a3ff1fcbce5534
diff --git a/exercises/saddle-points/.meta/src/reference/java/MatrixCoordinate.java b/exercises/saddle-points/.meta/src/reference/java/MatrixCoordinate.java index 140bf2ce..1180e2ca 100644 --- a/exercises/saddle-points/.meta/src/reference/java/MatrixCoordinate.java +++ b/exercises/saddle-points/.meta/src/reference/java/MatrixCoordinate.java @@ -1,31 +1,33 @@ -final class MatrixCoordinate { - - private final int row; - - private final int col; - - MatrixCoordinate(final int row, final int col) { - this.row = row; - this.col = col; - } - - // Generated equals and hashcode. - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final MatrixCoordinate that = (MatrixCoordinate) o; - - return row == that.row && col == that.col; - } - - @Override - public int hashCode() { - int result = row; - result = 31 * result + col; - return result; - } - +class MatrixCoordinate { + private final int row; + private final int col; + + MatrixCoordinate(final int row, final int col) { + this.row = row; + this.col = col; + } + + @Override + public String toString() { + return "Row: " + row + ", Column: " + col; + } + + // Generated equals and hashcode. + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final MatrixCoordinate that = (MatrixCoordinate) o; + + return row == that.row && col == that.col; + } + + @Override + public int hashCode() { + int result = row; + result = 31 * result + col; + return result; + } } diff --git a/exercises/saddle-points/src/main/java/MatrixCoordinate.java b/exercises/saddle-points/src/main/java/MatrixCoordinate.java index 6c35e9ab..1180e2ca 100644 --- a/exercises/saddle-points/src/main/java/MatrixCoordinate.java +++ b/exercises/saddle-points/src/main/java/MatrixCoordinate.java @@ -1,31 +1,33 @@ class MatrixCoordinate { + private final int row; + private final int col; - private final int row; + MatrixCoordinate(final int row, final int col) { + this.row = row; + this.col = col; + } - private final int col; + @Override + public String toString() { + return "Row: " + row + ", Column: " + col; + } - MatrixCoordinate(final int row, final int col) { - this.row = row; - this.col = col; - } + // Generated equals and hashcode. - // Generated equals and hashcode. + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + final MatrixCoordinate that = (MatrixCoordinate) o; - final MatrixCoordinate that = (MatrixCoordinate) o; - - return row == that.row && col == that.col; - } - - @Override - public int hashCode() { - int result = row; - result = 31 * result + col; - return result; - } + return row == that.row && col == that.col; + } + @Override + public int hashCode() { + int result = row; + result = 31 * result + col; + return result; + } }
['exercises/saddle-points/.meta/src/reference/java/MatrixCoordinate.java', 'exercises/saddle-points/src/main/java/MatrixCoordinate.java']
{'.java': 2}
2
2
0
0
2
142,580
30,626
5,241
142
2,708
637
108
2
645
102
150
12
0
0
1970-01-01T00:25:06
589
Java
{'Java': 1063911, 'Shell': 29846}
MIT License
277
asciidoctor/asciidoctorj/283/275
asciidoctor
asciidoctorj
https://github.com/asciidoctor/asciidoctorj/issues/275
https://github.com/asciidoctor/asciidoctorj/pull/283
https://github.com/asciidoctor/asciidoctorj/pull/283
1
fixes
Asciidoctorj gives error if input file is an absolute path
Hi, I have error if I pass the input file as an absolute path, but using relative path everything is ok. Asciidoctorj version (installed via GVM): ``` enrico@lap:~/union/feasibility-docs/developers-manual$ asciidoctorj --version Asciidoctor 1.5.2 [http://asciidoctor.org] ``` The failing command: ``` enrico@lap:~/union/feasibility-docs/developers-manual$ asciidoctorj --backend html5 \\ --destination-dir /home/enrico/union/feasibility-docs/developers-manual/build \\ --out-file index.html --doctype book --attribute project-version=0.1 \\ /home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc asciidoctor: FAILED: input file(s) '[/home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc]' missing or cannot be read Exception in thread "main" java.lang.IllegalArgumentException: asciidoctor: FAILED: input file(s) '[/home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc]' missing or cannot be read at org.asciidoctor.cli.AsciidoctorInvoker.invoke(AsciidoctorInvoker.java:51) at org.asciidoctor.cli.AsciidoctorInvoker.main(AsciidoctorInvoker.java:184) ``` The input file exists: ``` enrico@lap:~/union/feasibility-docs/developers-manual$ ll /home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc -rw-rw-r-- 1 enrico enrico 288 gen 27 16:39 /home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc ``` The successful command (change only the input file path, from absolute to relative): ``` enrico@lap:~/union/feasibility-docs/developers-manual$ asciidoctorj --backend html5 \\ --destination-dir /home/enrico/union/feasibility-docs/developers-manual/build \\ --out-file index.html --doctype book --attribute project-version=0.1 \\ src/asciidoc/index.adoc ``` Is this expected? Anyway, thanks a lot for this awesome tool! Enrico
47f568070d1dcac5a4da0733ea1c8b2fd6823fa7
b25541fcc7ff1ac3a385664f112374d1aa1f70e2
https://github.com/asciidoctor/asciidoctorj/compare/47f568070d1dcac5a4da0733ea1c8b2fd6823fa7...b25541fcc7ff1ac3a385664f112374d1aa1f70e2
diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java b/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java index 907b3ff7..a87fd80a 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java @@ -24,11 +24,63 @@ public class GlobDirectoryWalker implements DirectoryWalker { private final List<File> matches = new ArrayList<File>(); private final String globExpression; - public GlobDirectoryWalker(String rootDir, String globExpression) { - rootDirectory = new File(rootDir); - checkInput(rootDirectory); - this.canonicalRootDir = getCanonicalPath(rootDirectory); - this.globExpression = globExpression; + public GlobDirectoryWalker(String globExpression) { + + if (isAbsoluteGlobExpression(globExpression)) { + + // If the given path is an absolute path we want to split it into an absolute part containing + // directories without wildcards and a glob part with wildcards and file names + int indexOfUnglobbedPart = findIndexOfUnglobbedPart(globExpression); + this.rootDirectory = new File(globExpression.substring(0, indexOfUnglobbedPart)); + this.globExpression = globExpression.substring(indexOfUnglobbedPart + 1); + checkInput(rootDirectory); + this.canonicalRootDir = getCanonicalPath(rootDirectory); + + } else { + // It's a relative expression, current working dir is sufficient as root directory + rootDirectory = new File("."); + checkInput(rootDirectory); + this.canonicalRootDir = getCanonicalPath(rootDirectory); + this.globExpression = globExpression; + + } + } + + // An absolute path will consist of an absolute, unglobbed part and a globbed part. + // The globbed part starts at the first path element that contains a '*' or it is + // the part following the last separator + private int findIndexOfUnglobbedPart(String globExpression) { + int result = 0; + for (int i = 0; i < globExpression.length(); i++) { + switch (globExpression.charAt(i)) { + case '/': + case '\\\\': + result = i; + break; + case '*': + return result; + default: + } + } + // There is apparently no wildcard in the path, let the directory part be the path + // and the glob part only the filename + return result; + } + + // Determines if the given glob expression is an absolute path + // That is the expression starts with a separator or with [A-Za-z]:[/\\] on Windows + private boolean isAbsoluteGlobExpression(String globExpression) { + if (globExpression.startsWith(File.separator)) { + return true; + } + if (isWindows()) { + return globExpression.matches("^[A-Za-z]:[\\\\\\\\/].*$"); + } + return false; + } + + private boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("win"); } @Override diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java b/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java index 0da5fd57..c068a3cd 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java @@ -171,8 +171,7 @@ public class AsciidoctorInvoker { List<File> filesToBeRendered = new ArrayList<File>(); for (String globExpression : parameters) { - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(".", - globExpression); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(globExpression); filesToBeRendered.addAll(globDirectoryWalker.scan()); } diff --git a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java index 01aeba5d..140b5563 100644 --- a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java +++ b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java @@ -21,7 +21,7 @@ public class WhenGlobExpressionIsUsedForScanning { public void all_files_with_given_extension_of_current_directory_should_be_returned() { File pathToWalk = classpath.getResource("src"); - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath(), "documents/*.adoc"); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath() + File.separator + "documents/*.adoc"); List<File> asciidocFiles = globDirectoryWalker.scan(); assertThat( @@ -35,7 +35,7 @@ public class WhenGlobExpressionIsUsedForScanning { public void all_files_with_given_extension_should_be_returned_recursively() { File pathToWalk = classpath.getResource("src"); - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath(), "**/*.adoc"); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath() + File.separator + "**/*.adoc"); List<File> asciidocFiles = globDirectoryWalker.scan(); assertThat( @@ -49,7 +49,7 @@ public class WhenGlobExpressionIsUsedForScanning { public void no_should_be_returned_if_glob_expression_does_not_match() { File pathToWalk = classpath.getResource("src"); - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath(), "**/*.a"); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath() + File.separator + "**/*.a"); List<File> asciidocFiles = globDirectoryWalker.scan(); assertThat(asciidocFiles, is(empty())); diff --git a/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java b/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java index 97578201..d1c13c80 100644 --- a/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java +++ b/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java @@ -231,7 +231,19 @@ public class WhenAsciidoctorIsCalledUsingCli { } - private ByteArrayOutputStream redirectStdout() { + @Test + public void with_absolute_path_file_should_be_rendered() { + + File inputFile = classpath.getResource("rendersample.asciidoc"); + String inputPath = inputFile.getAbsolutePath(); + new AsciidoctorInvoker().invoke(inputPath); + File expectedFile = new File(inputPath.replaceFirst("\\\\.asciidoc$", ".html")); + + assertThat(expectedFile.exists(), is(true)); + expectedFile.delete(); + } + + private ByteArrayOutputStream redirectStdout() { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); return output;
['asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java', 'asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java', 'asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java', 'asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java']
{'.java': 4}
4
4
0
0
4
263,175
55,199
8,228
85
2,909
565
65
2
1,846
145
526
46
1
4
1970-01-01T00:23:46
588
Java
{'Java': 973088, 'Groovy': 143210, 'Ruby': 78105, 'Shell': 6743, 'CSS': 3759, 'PowerShell': 1831, 'CoffeeScript': 414, 'Makefile': 321, 'Slim': 25, 'Haml': 16}
Apache License 2.0
275
asciidoctor/asciidoctorj/435/434
asciidoctor
asciidoctorj
https://github.com/asciidoctor/asciidoctorj/issues/434
https://github.com/asciidoctor/asciidoctorj/pull/435
https://github.com/asciidoctor/asciidoctorj/pull/435
1
fixes
asciidoctor.loadFile(file, options) doesn't generate complete document.
loadFile doesn't generate complete document, only first paragraph will be processed. Reading from string (line based reading of a file done before) does work. The project is maven based and is using version 1.5.4 of asciidoctorj. // Example of reading via loadFile Map<String,Object> attributes = new HashMap<String, Object>(); attributes.put("stylesdir", "adocs/css"); attributes.put("stylesheet", "asciidoctor.css"); Map<String, Object> options = new HashMap<String, Object>(); options.put("attributes", attributes); options.put("in_place", true); options.put("header", true); options.put("footer", true); options.put("safe", 0); Document document = asciidoctor.loadFile(file, options); // Example for asciidoctor.load: Map<String,Object> attributes = new HashMap<String, Object>(); attributes.put("stylesdir", "adocs/css"); attributes.put("stylesheet", "asciidoctor.css"); Map<String, Object> options = new HashMap<String, Object>(); options.put("attributes", attributes); options.put("in_place", true); options.put("header", true); options.put("footer", true); options.put("safe", 0); String lines = ""; String tmpString = ""; if (file.canRead()) { System.out.println("File: " + file + " is readable"); try { FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); while( (tmpString = bufferedReader.readLine()) != null ) { lines = lines + "\\n" + tmpString; } bufferedReader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Document document = asciidoctor.load(lines, options); System.out.println("content: " + document.convert());
7a8fe72a4bc58ac066be2295bb0d20d4dbd2d050
594bc08ae4ba503e95243e39fde8e224a13552b8
https://github.com/asciidoctor/asciidoctorj/compare/7a8fe72a4bc58ac066be2295bb0d20d4dbd2d050...594bc08ae4ba503e95243e39fde8e224a13552b8
diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/internal/JRubyAsciidoctor.java b/asciidoctorj-core/src/main/java/org/asciidoctor/internal/JRubyAsciidoctor.java index 722041e0..64d8c0fd 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/internal/JRubyAsciidoctor.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/internal/JRubyAsciidoctor.java @@ -598,7 +598,7 @@ public class JRubyAsciidoctor implements Asciidoctor { @Override public Document loadFile(File file, Map<String, Object> options) { RubyHash rubyHash = RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options); - return new Document(this.asciidoctorModule.load(file.getAbsolutePath(), rubyHash), this.rubyRuntime); + return new Document(this.asciidoctorModule.load_file(file.getAbsolutePath(), rubyHash), this.rubyRuntime); } } diff --git a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java index f8d61791..c9fe3609 100644 --- a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java +++ b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java @@ -1,9 +1,11 @@ package org.asciidoctor; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsMapContaining.hasKey; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.io.File; @@ -205,4 +207,18 @@ public class WhenAsciiDocIsRenderedToDocument { assertThat(content, is(IOUtils.readFull(new FileReader(inputFile)))); } + @Test + public void should_load_a_document_from_File() throws FileNotFoundException { + Map<String, Object> options = OptionsBuilder.options().safe(SafeMode.SAFE) + .attributes(AttributesBuilder.attributes().dataUri(false)) + .compact(true).asMap(); + File inputFile = classpath.getResource("rendersample.asciidoc"); + Document document = asciidoctor.loadFile(inputFile, options); + assertEquals(1, document.blocks().size()); + assertThat(document.blocks().get(0), instanceOf(Section.class)); + Section section = (Section) document.blocks().get(0); + assertEquals(1, section.getBlocks().size()); + assertEquals("<strong>Section A</strong> paragraph.", section.getBlocks().get(0).getContent()); + } + }
['asciidoctorj-core/src/main/java/org/asciidoctor/internal/JRubyAsciidoctor.java', 'asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java']
{'.java': 2}
2
2
0
0
2
227,674
48,663
7,430
74
226
45
2
1
1,779
186
404
53
0
0
1970-01-01T00:24:16
588
Java
{'Java': 973088, 'Groovy': 143210, 'Ruby': 78105, 'Shell': 6743, 'CSS': 3759, 'PowerShell': 1831, 'CoffeeScript': 414, 'Makefile': 321, 'Slim': 25, 'Haml': 16}
Apache License 2.0
273
asciidoctor/asciidoctorj/594/593
asciidoctor
asciidoctorj
https://github.com/asciidoctor/asciidoctorj/issues/593
https://github.com/asciidoctor/asciidoctorj/pull/594
https://github.com/asciidoctor/asciidoctorj/pull/594
2
fixes
(RuntimeError) can't modify frozen NilClass on getParent()
When `getParent()` is called on the root `ContentNode` (where `null` is expected), a ruby `RuntimeError` is thrown. Code to reproduce it: public static void main(String[] args) { String s = "== A small Example\\n" + "\\n" + "Lorem ipsum dolor sit amet:\\n"; org.asciidoctor.Asciidoctor asciidoctor = org.asciidoctor.Asciidoctor.Factory.create(); org.asciidoctor.ast.Document document = asciidoctor.load(s, new java.util.HashMap<String, Object>()); org.asciidoctor.ast.ContentNode parent = document.getParent(); // Runtime error here! System.out.println(parent); } Using `org.asciidoctor: asciidoctorj:1.6.0-alpha.6` as dependency. Error is: > Exception in thread "main" org.jruby.exceptions.RaiseException: (RuntimeError) can't modify frozen NilClass --- The code works with `org.asciidoctor:asciidoctorj:1.5.6` (the code needs to be modified, because the API changed): public static void main(String[] args) { String s = "== A small Example\\n" + "\\n" + "Lorem ipsum dolor sit amet:\\n"; org.asciidoctor.Asciidoctor asciidoctor = org.asciidoctor.Asciidoctor.Factory.create(); org.asciidoctor.ast.Document document = asciidoctor.load(s, new java.util.HashMap<String, Object>()); org.asciidoctor.ast.AbstractNode parent = document.getParent(); System.out.println(parent); } This works: `parent` is `null` as expected.
5b8018792c787f59df8ee099d5f8393f68e7591b
a4a41460ada7e095980ecc767de68b21a89672b8
https://github.com/asciidoctor/asciidoctorj/compare/5b8018792c787f59df8ee099d5f8393f68e7591b...a4a41460ada7e095980ecc767de68b21a89672b8
diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/ast/NodeConverter.java b/asciidoctorj-core/src/main/java/org/asciidoctor/ast/NodeConverter.java index 9dbb8ed0..bdd04a6a 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/ast/NodeConverter.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/ast/NodeConverter.java @@ -126,15 +126,16 @@ public final class NodeConverter { if (object instanceof IRubyObject || object instanceof RubyObjectHolderProxy) { IRubyObject rubyObject = asRubyObject(object); + if (rubyObject.isNil()) { + return null; + } NodeCache nodeCache = NodeCache.get(rubyObject); ContentNode cachedNode = nodeCache.getASTNode(); if (cachedNode != null) { return cachedNode; } - Ruby runtime = rubyObject.getRuntime(); - - ContentNode ret = null; + ContentNode ret; switch (NodeType.getNodeType(rubyObject)) { case BLOCK_CLASS: diff --git a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java index 1ac0b756..4f848e38 100644 --- a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java +++ b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java @@ -1,25 +1,9 @@ package org.asciidoctor; -import static org.hamcrest.Matchers.either; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.collection.IsMapContaining.hasKey; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.asciidoctor.arquillian.api.Unshared; -import org.asciidoctor.ast.StructuralNode; import org.asciidoctor.ast.Document; import org.asciidoctor.ast.Section; +import org.asciidoctor.ast.StructuralNode; import org.asciidoctor.internal.IOUtils; import org.asciidoctor.util.ClasspathResources; import org.jboss.arquillian.junit.Arquillian; @@ -27,6 +11,22 @@ import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; import org.junit.runner.RunWith; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.Matchers.either; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.hamcrest.collection.IsMapContaining.hasKey; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; + @RunWith(Arquillian.class) public class WhenAsciiDocIsRenderedToDocument { @@ -341,4 +341,15 @@ public class WhenAsciiDocIsRenderedToDocument { assertThat(section.getContentModel(), is("compound")); assertThat(section.getBlocks().get(0).getContentModel(), is("simple")); } + + @Test + public void should_be_able_to_get_parent_from_document() { + String s = "== A small Example\\n" + + "\\n" + + "Lorem ipsum dolor sit amet:\\n"; + + Document document = asciidoctor.load(s, new HashMap<String, Object>()); + assertNull(document.getParent()); + } + }
['asciidoctorj-core/src/main/java/org/asciidoctor/ast/NodeConverter.java', 'asciidoctorj-core/src/test/java/org/asciidoctor/WhenAsciiDocIsRenderedToDocument.java']
{'.java': 2}
2
2
0
0
2
458,017
97,187
14,065
134
205
35
7
1
1,518
142
367
37
0
0
1970-01-01T00:25:11
588
Java
{'Java': 973088, 'Groovy': 143210, 'Ruby': 78105, 'Shell': 6743, 'CSS': 3759, 'PowerShell': 1831, 'CoffeeScript': 414, 'Makefile': 321, 'Slim': 25, 'Haml': 16}
Apache License 2.0
272
asciidoctor/asciidoctorj/759/749
asciidoctor
asciidoctorj
https://github.com/asciidoctor/asciidoctorj/issues/749
https://github.com/asciidoctor/asciidoctorj/pull/759
https://github.com/asciidoctor/asciidoctorj/pull/759
1
fixes
RubyExtensionRegistry references Impl
While refactoring the RubyExtensionRegistry to interfaces the implementation of this interface slipped through and appears as the return type: https://github.com/asciidoctor/asciidoctorj/blob/15fd95849ad7f236a34a3e7a38321093ea741283/asciidoctorj-core/src/main/java/org/asciidoctor/extension/RubyExtensionRegistry.java#L8 Instead all methods should return just RubyExtensionRegistry. This cannot be fixed on 1.6.0 as this would result in a binary incompatibility.
fa6a40feffca444fa321b53a8ca125de93ffb83d
2d32f1ddc76f4555416fc5578063797d66c8424d
https://github.com/asciidoctor/asciidoctorj/compare/fa6a40feffca444fa321b53a8ca125de93ffb83d...2d32f1ddc76f4555416fc5578063797d66c8424d
diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/extension/RubyExtensionRegistry.java b/asciidoctorj-core/src/main/java/org/asciidoctor/extension/RubyExtensionRegistry.java index d575a139..b6ada669 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/extension/RubyExtensionRegistry.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/extension/RubyExtensionRegistry.java @@ -1,33 +1,32 @@ package org.asciidoctor.extension; -import org.asciidoctor.internal.RubyExtensionRegistryImpl; - import java.io.InputStream; public interface RubyExtensionRegistry { - RubyExtensionRegistryImpl requireLibrary(String requiredLibrary); - RubyExtensionRegistryImpl loadClass(InputStream rubyClassStream); + RubyExtensionRegistry requireLibrary(String requiredLibrary); + + RubyExtensionRegistry loadClass(InputStream rubyClassStream); - RubyExtensionRegistryImpl preprocessor(String preprocessor); + RubyExtensionRegistry preprocessor(String preprocessor); - RubyExtensionRegistryImpl postprocessor(String postprocessor); + RubyExtensionRegistry postprocessor(String postprocessor); - RubyExtensionRegistryImpl docinfoProcessor(String docinfoProcessor); + RubyExtensionRegistry docinfoProcessor(String docinfoProcessor); - RubyExtensionRegistryImpl includeProcessor(String includeProcessor); + RubyExtensionRegistry includeProcessor(String includeProcessor); - RubyExtensionRegistryImpl treeprocessor(String treeProcessor); + RubyExtensionRegistry treeprocessor(String treeProcessor); - RubyExtensionRegistryImpl block(String blockName, String blockProcessor); + RubyExtensionRegistry block(String blockName, String blockProcessor); - RubyExtensionRegistryImpl block(String blockProcessor); + RubyExtensionRegistry block(String blockProcessor); - RubyExtensionRegistryImpl blockMacro(String blockName, String blockMacroProcessor); + RubyExtensionRegistry blockMacro(String blockName, String blockMacroProcessor); - RubyExtensionRegistryImpl blockMacro(String blockMacroProcessor); + RubyExtensionRegistry blockMacro(String blockMacroProcessor); - RubyExtensionRegistryImpl inlineMacro(String blockName, String inlineMacroProcessor); + RubyExtensionRegistry inlineMacro(String blockName, String inlineMacroProcessor); - RubyExtensionRegistryImpl inlineMacro(String inlineMacroProcessor); + RubyExtensionRegistry inlineMacro(String inlineMacroProcessor); }
['asciidoctorj-core/src/main/java/org/asciidoctor/extension/RubyExtensionRegistry.java']
{'.java': 1}
1
1
0
0
1
484,597
102,946
14,797
145
1,923
324
29
1
469
41
120
6
1
0
1970-01-01T00:25:48
588
Java
{'Java': 973088, 'Groovy': 143210, 'Ruby': 78105, 'Shell': 6743, 'CSS': 3759, 'PowerShell': 1831, 'CoffeeScript': 414, 'Makefile': 321, 'Slim': 25, 'Haml': 16}
Apache License 2.0
278
asciidoctor/asciidoctorj/282/275
asciidoctor
asciidoctorj
https://github.com/asciidoctor/asciidoctorj/issues/275
https://github.com/asciidoctor/asciidoctorj/pull/282
https://github.com/asciidoctor/asciidoctorj/pull/282
1
fixes
Asciidoctorj gives error if input file is an absolute path
Hi, I have error if I pass the input file as an absolute path, but using relative path everything is ok. Asciidoctorj version (installed via GVM): ``` enrico@lap:~/union/feasibility-docs/developers-manual$ asciidoctorj --version Asciidoctor 1.5.2 [http://asciidoctor.org] ``` The failing command: ``` enrico@lap:~/union/feasibility-docs/developers-manual$ asciidoctorj --backend html5 \\ --destination-dir /home/enrico/union/feasibility-docs/developers-manual/build \\ --out-file index.html --doctype book --attribute project-version=0.1 \\ /home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc asciidoctor: FAILED: input file(s) '[/home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc]' missing or cannot be read Exception in thread "main" java.lang.IllegalArgumentException: asciidoctor: FAILED: input file(s) '[/home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc]' missing or cannot be read at org.asciidoctor.cli.AsciidoctorInvoker.invoke(AsciidoctorInvoker.java:51) at org.asciidoctor.cli.AsciidoctorInvoker.main(AsciidoctorInvoker.java:184) ``` The input file exists: ``` enrico@lap:~/union/feasibility-docs/developers-manual$ ll /home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc -rw-rw-r-- 1 enrico enrico 288 gen 27 16:39 /home/enrico/union/feasibility-docs/developers-manual/src/asciidoc/index.adoc ``` The successful command (change only the input file path, from absolute to relative): ``` enrico@lap:~/union/feasibility-docs/developers-manual$ asciidoctorj --backend html5 \\ --destination-dir /home/enrico/union/feasibility-docs/developers-manual/build \\ --out-file index.html --doctype book --attribute project-version=0.1 \\ src/asciidoc/index.adoc ``` Is this expected? Anyway, thanks a lot for this awesome tool! Enrico
2bdd6ea28ad1ae12c634192ff8875b69db9bdacb
c775e46d3a9b786a993eb4e0954f5e20704ad0c5
https://github.com/asciidoctor/asciidoctorj/compare/2bdd6ea28ad1ae12c634192ff8875b69db9bdacb...c775e46d3a9b786a993eb4e0954f5e20704ad0c5
diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java b/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java index 907b3ff7..a87fd80a 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java @@ -24,11 +24,63 @@ public class GlobDirectoryWalker implements DirectoryWalker { private final List<File> matches = new ArrayList<File>(); private final String globExpression; - public GlobDirectoryWalker(String rootDir, String globExpression) { - rootDirectory = new File(rootDir); - checkInput(rootDirectory); - this.canonicalRootDir = getCanonicalPath(rootDirectory); - this.globExpression = globExpression; + public GlobDirectoryWalker(String globExpression) { + + if (isAbsoluteGlobExpression(globExpression)) { + + // If the given path is an absolute path we want to split it into an absolute part containing + // directories without wildcards and a glob part with wildcards and file names + int indexOfUnglobbedPart = findIndexOfUnglobbedPart(globExpression); + this.rootDirectory = new File(globExpression.substring(0, indexOfUnglobbedPart)); + this.globExpression = globExpression.substring(indexOfUnglobbedPart + 1); + checkInput(rootDirectory); + this.canonicalRootDir = getCanonicalPath(rootDirectory); + + } else { + // It's a relative expression, current working dir is sufficient as root directory + rootDirectory = new File("."); + checkInput(rootDirectory); + this.canonicalRootDir = getCanonicalPath(rootDirectory); + this.globExpression = globExpression; + + } + } + + // An absolute path will consist of an absolute, unglobbed part and a globbed part. + // The globbed part starts at the first path element that contains a '*' or it is + // the part following the last separator + private int findIndexOfUnglobbedPart(String globExpression) { + int result = 0; + for (int i = 0; i < globExpression.length(); i++) { + switch (globExpression.charAt(i)) { + case '/': + case '\\\\': + result = i; + break; + case '*': + return result; + default: + } + } + // There is apparently no wildcard in the path, let the directory part be the path + // and the glob part only the filename + return result; + } + + // Determines if the given glob expression is an absolute path + // That is the expression starts with a separator or with [A-Za-z]:[/\\] on Windows + private boolean isAbsoluteGlobExpression(String globExpression) { + if (globExpression.startsWith(File.separator)) { + return true; + } + if (isWindows()) { + return globExpression.matches("^[A-Za-z]:[\\\\\\\\/].*$"); + } + return false; + } + + private boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("win"); } @Override diff --git a/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java b/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java index 0da5fd57..c068a3cd 100644 --- a/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java +++ b/asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java @@ -171,8 +171,7 @@ public class AsciidoctorInvoker { List<File> filesToBeRendered = new ArrayList<File>(); for (String globExpression : parameters) { - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(".", - globExpression); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(globExpression); filesToBeRendered.addAll(globDirectoryWalker.scan()); } diff --git a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java index 01aeba5d..140b5563 100644 --- a/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java +++ b/asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java @@ -21,7 +21,7 @@ public class WhenGlobExpressionIsUsedForScanning { public void all_files_with_given_extension_of_current_directory_should_be_returned() { File pathToWalk = classpath.getResource("src"); - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath(), "documents/*.adoc"); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath() + File.separator + "documents/*.adoc"); List<File> asciidocFiles = globDirectoryWalker.scan(); assertThat( @@ -35,7 +35,7 @@ public class WhenGlobExpressionIsUsedForScanning { public void all_files_with_given_extension_should_be_returned_recursively() { File pathToWalk = classpath.getResource("src"); - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath(), "**/*.adoc"); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath() + File.separator + "**/*.adoc"); List<File> asciidocFiles = globDirectoryWalker.scan(); assertThat( @@ -49,7 +49,7 @@ public class WhenGlobExpressionIsUsedForScanning { public void no_should_be_returned_if_glob_expression_does_not_match() { File pathToWalk = classpath.getResource("src"); - DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath(), "**/*.a"); + DirectoryWalker globDirectoryWalker = new GlobDirectoryWalker(pathToWalk.getPath() + File.separator + "**/*.a"); List<File> asciidocFiles = globDirectoryWalker.scan(); assertThat(asciidocFiles, is(empty())); diff --git a/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java b/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java index 97578201..d1c13c80 100644 --- a/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java +++ b/asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java @@ -231,7 +231,19 @@ public class WhenAsciidoctorIsCalledUsingCli { } - private ByteArrayOutputStream redirectStdout() { + @Test + public void with_absolute_path_file_should_be_rendered() { + + File inputFile = classpath.getResource("rendersample.asciidoc"); + String inputPath = inputFile.getAbsolutePath(); + new AsciidoctorInvoker().invoke(inputPath); + File expectedFile = new File(inputPath.replaceFirst("\\\\.asciidoc$", ".html")); + + assertThat(expectedFile.exists(), is(true)); + expectedFile.delete(); + } + + private ByteArrayOutputStream redirectStdout() { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); return output;
['asciidoctorj-core/src/test/java/org/asciidoctor/WhenGlobExpressionIsUsedForScanning.java', 'asciidoctorj-core/src/main/java/org/asciidoctor/GlobDirectoryWalker.java', 'asciidoctorj-core/src/test/java/org/asciidoctor/cli/WhenAsciidoctorIsCalledUsingCli.java', 'asciidoctorj-core/src/main/java/org/asciidoctor/cli/AsciidoctorInvoker.java']
{'.java': 4}
4
4
0
0
4
222,477
47,141
7,325
74
2,909
565
65
2
1,846
145
526
46
1
4
1970-01-01T00:23:46
588
Java
{'Java': 973088, 'Groovy': 143210, 'Ruby': 78105, 'Shell': 6743, 'CSS': 3759, 'PowerShell': 1831, 'CoffeeScript': 414, 'Makefile': 321, 'Slim': 25, 'Haml': 16}
Apache License 2.0
1,288
kyoripowered/adventure/859/414
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/414
https://github.com/KyoriPowered/adventure/pull/859
https://github.com/KyoriPowered/adventure/pull/859
1
fixes
Unable to handle Empty Hover Event Value/Contents Array
Weirdly enough, vanilla Minecraft actually accepts a json string like this as a valid chat component. ```json {"text": "hello", "hoverEvent":{"action":"show_text","value":[]}} ``` AND ```json {"text": "hello", "hoverEvent":{"action":"show_text","contents":[]}} ``` Which in game, the whole hoverEvent would just be ignored. But with Adventure, it'll not know what to do/throw an error. ``` [02:25:32 INFO]: com.google.gson.JsonParseException: Don't know how to turn [] into a Component [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.notSureHowToDeserialize(ComponentSerializerImpl.java:262) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.deserialize0(ComponentSerializerImpl.java:92) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.deserialize(ComponentSerializerImpl.java:75) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.deserialize(ComponentSerializerImpl.java:55) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:887) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:952) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.internal.bind.TreeTypeAdapter$GsonContextImpl.deserialize(TreeTypeAdapter.java:162) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.StyleSerializer.deserialize(StyleSerializer.java:155) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.StyleSerializer.deserialize(StyleSerializer.java:98) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.StyleSerializer.deserialize(StyleSerializer.java:53) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:887) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:952) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.internal.bind.TreeTypeAdapter$GsonContextImpl.deserialize(TreeTypeAdapter.java:162) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.deserialize0(ComponentSerializerImpl.java:161) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.deserialize(ComponentSerializerImpl.java:75) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.deserialize(ComponentSerializerImpl.java:55) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:887) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:852) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:801) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at com.google.gson.Gson.fromJson(Gson.java:773) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.GsonComponentSerializerImpl.deserialize(GsonComponentSerializerImpl.java:101) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] [02:25:32 INFO]: at net.kyori.adventure.text.serializer.gson.GsonComponentSerializerImpl.deserialize(GsonComponentSerializerImpl.java:44) ~[Paper-Server-reobf.jar:git-Paper-"416ec98"] ``` An extra piece of information, ```json [] ``` is not a valid component as expected, so accepting (and then ignoring) empty arrays is just a special case for Components in hoverEvents, not everywhere.
42ea3df1942644a3a3b70c467c0035de63eb511c
1438b88eec775bd981702cead14df1dee0ae0644
https://github.com/kyoripowered/adventure/compare/42ea3df1942644a3a3b70c467c0035de63eb511c...1438b88eec775bd981702cead14df1dee0ae0644
diff --git a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java index 4f74b016..5f692cb6 100644 --- a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java +++ b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java @@ -147,7 +147,9 @@ final class StyleSerializer extends TypeAdapter<Style> { if (hoverEventObject.has(HOVER_EVENT_CONTENTS)) { final @Nullable JsonElement rawValue = hoverEventObject.get(HOVER_EVENT_CONTENTS); final Class<?> actionType = action.type(); - if (SerializerFactory.COMPONENT_TYPE.isAssignableFrom(actionType)) { + if (isNullOrEmpty(rawValue)) { + value = null; + } else if (SerializerFactory.COMPONENT_TYPE.isAssignableFrom(actionType)) { value = this.gson.fromJson(rawValue, SerializerFactory.COMPONENT_TYPE); } else if (SerializerFactory.SHOW_ITEM_TYPE.isAssignableFrom(actionType)) { value = this.gson.fromJson(rawValue, SerializerFactory.SHOW_ITEM_TYPE); @@ -157,8 +159,13 @@ final class StyleSerializer extends TypeAdapter<Style> { value = null; } } else if (hoverEventObject.has(HOVER_EVENT_VALUE)) { - final Component rawValue = this.gson.fromJson(hoverEventObject.get(HOVER_EVENT_VALUE), SerializerFactory.COMPONENT_TYPE); - value = this.legacyHoverEventContents(action, rawValue); + final JsonElement element = hoverEventObject.get(HOVER_EVENT_VALUE); + if (isNullOrEmpty(element)) { + value = null; + } else { + final Component rawValue = this.gson.fromJson(element, SerializerFactory.COMPONENT_TYPE); + value = this.legacyHoverEventContents(action, rawValue); + } } else { value = null; } @@ -177,6 +184,10 @@ final class StyleSerializer extends TypeAdapter<Style> { return style.build(); } + private static boolean isNullOrEmpty(final @Nullable JsonElement element) { + return element == null || element.isJsonNull() || (element.isJsonArray() && element.getAsJsonArray().size() == 0) || (element.isJsonObject() && element.getAsJsonObject().size() == 0); + } + private boolean readBoolean(final JsonReader in) throws IOException { final JsonToken peek = in.peek(); if (peek == JsonToken.BOOLEAN) { diff --git a/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java b/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java index 7cad7c7c..db6f1416 100644 --- a/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java +++ b/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java @@ -90,6 +90,14 @@ class GsonComponentSerializerTest { assertEquals("Don't know how to turn null into a Component", ex.getMessage()); } + // https://github.com/KyoriPowered/adventure/issues/414 + @Test + void testSkipInvalidHoverEvent() { + final String input = "{\\"text\\": \\"hello\\", \\"hoverEvent\\":{\\"action\\":\\"show_text\\",\\"value\\":[]}}"; + final Component expected = Component.text("hello"); + assertEquals(expected, GsonComponentSerializer.gson().deserialize(input)); + } + private static String name(final NamedTextColor color) { return NamedTextColor.NAMES.key(color); }
['text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java', 'text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java']
{'.java': 2}
2
2
0
0
2
1,730,035
398,207
49,738
371
1,117
210
17
1
4,650
220
1,298
43
0
4
1970-01-01T00:27:53
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,290
kyoripowered/adventure/475/473
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/473
https://github.com/KyoriPowered/adventure/pull/475
https://github.com/KyoriPowered/adventure/pull/475
1
fix
Expected BOOLEAN but was STRING at path $.underlined
Copied from Discord, but of course if you need more information I'm happy to provide. Hello! Geyser just updated from 4.8.0 to 4.9.2 and we've got what appears to be a brand new error! yey ``` [09:47:22] [defaultEventLoopGroup-3-10/WARN] [Geyser-BungeeCord]: Downstream packet error! java.lang.IllegalStateException: Expected BOOLEAN but was STRING at path $.bold [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BOOLEAN but was STRING at path $.bold [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:944) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:1003) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:975) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at org.geysermc.platform.bungeecord.shaded.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.read(ComponentSerializerImpl.java:214) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at org.geysermc.platform.bungeecord.shaded.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.read(ComponentSerializerImpl.java:56) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.TypeAdapter$1.read(TypeAdapter.java:199) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:932) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at org.geysermc.platform.bungeecord.shaded.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.read(ComponentSerializerImpl.java:173) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at org.geysermc.platform.bungeecord.shaded.kyori.adventure.text.serializer.gson.ComponentSerializerImpl.read(ComponentSerializerImpl.java:56) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.TypeAdapter$1.read(TypeAdapter.java:199) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:932) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:897) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:846) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.google.gson.Gson.fromJson(Gson.java:817) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at org.geysermc.platform.bungeecord.shaded.kyori.adventure.text.serializer.gson.GsonComponentSerializerImpl.deserialize(GsonComponentSerializerImpl.java:84) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at org.geysermc.platform.bungeecord.shaded.kyori.adventure.text.serializer.gson.GsonComponentSerializerImpl.deserialize(GsonComponentSerializerImpl.java:37) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.github.steveice10.mc.protocol.packet.ingame.server.ServerPlayerListEntryPacket.read(ServerPlayerListEntryPacket.java:93) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at com.github.steveice10.packetlib.tcp.TcpPacketCodec.decode(TcpPacketCodec.java:59) [09:47:22] [defaultEventLoopGroup-3-10/ERROR]: at io.netty.handler.codec.ByteToMessageCodec$1.decode(ByteToMessageCodec.java:42) ``` I *believe* this is an example suspect string: `{"text":"","extra":[{"text":"lobby","color":"yellow","underlined":"true"},{"text":" (1):","color":"white","italic":"true"}]}` though I get `Expected BOOLEAN but was STRING at path $.underlined` with that.
f5253d09c699e65418f4722ef8a9f46c1c9cf36b
034768aca57e9f8b271f5c55532183b3219e43a7
https://github.com/kyoripowered/adventure/compare/f5253d09c699e65418f4722ef8a9f46c1c9cf36b...034768aca57e9f8b271f5c55532183b3219e43a7
diff --git a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java index 7293b0f4..cf0d317f 100644 --- a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java +++ b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java @@ -111,7 +111,7 @@ final class StyleSerializer extends TypeAdapter<Style> { style.decoration(color.decoration, TextDecoration.State.TRUE); } } else if (TextDecoration.NAMES.keys().contains(fieldName)) { - style.decoration(TextDecoration.NAMES.value(fieldName), in.nextBoolean()); + style.decoration(TextDecoration.NAMES.value(fieldName), this.readBoolean(in)); } else if (fieldName.equals(INSERTION)) { style.insertion(in.nextString()); } else if (fieldName.equals(CLICK_EVENT)) { @@ -177,6 +177,17 @@ final class StyleSerializer extends TypeAdapter<Style> { return style.build(); } + private boolean readBoolean(final JsonReader in) throws IOException { + final JsonToken peek = in.peek(); + if (peek == JsonToken.BOOLEAN) { + return in.nextBoolean(); + } else if (peek == JsonToken.STRING || peek == JsonToken.NUMBER) { + return Boolean.parseBoolean(in.nextString()); + } else { + throw new JsonParseException("Token of type " + peek + " cannot be interpreted as a boolean"); + } + } + private Object legacyHoverEventContents(final HoverEvent.Action<?> action, final Component rawValue) { if (action == HoverEvent.Action.SHOW_TEXT) { return rawValue; // Passthrough -- no serialization needed diff --git a/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/StyleTest.java b/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/StyleTest.java index 9d8147ce..ac9db8fd 100644 --- a/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/StyleTest.java +++ b/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/StyleTest.java @@ -24,6 +24,8 @@ package net.kyori.adventure.text.serializer.gson; import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; @@ -39,7 +41,9 @@ import net.kyori.adventure.text.format.TextDecoration; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("CodeBlock2Expr") @@ -87,6 +91,27 @@ class StyleTest extends GsonTest<Style> { @Test void testDecoration() { this.test(Style.style(TextDecoration.BOLD), object(json -> json.addProperty(name(TextDecoration.BOLD), true))); + + Style s0 = GsonComponentSerializer.gson().serializer().fromJson(object(object -> { + object.addProperty(name(TextDecoration.BOLD), "true"); + }), Style.class); + assertTrue(s0.hasDecoration(TextDecoration.BOLD)); + + s0 = GsonComponentSerializer.gson().serializer().fromJson(object(object -> { + object.addProperty(name(TextDecoration.BOLD), "false"); + }), Style.class); + assertFalse(s0.hasDecoration(TextDecoration.BOLD)); + + s0 = GsonComponentSerializer.gson().serializer().fromJson(object(object -> { + object.addProperty(name(TextDecoration.BOLD), 1); + }), Style.class); + assertFalse(s0.hasDecoration(TextDecoration.BOLD)); + + assertThrows(JsonParseException.class, () -> { + GsonComponentSerializer.gson().serializer().fromJson(object(object -> { + object.add(name(TextDecoration.BOLD), JsonNull.INSTANCE); + }), Style.class); + }); } @Test
['text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/StyleSerializer.java', 'text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/StyleTest.java']
{'.java': 2}
2
2
0
0
2
1,181,082
272,861
34,031
254
608
127
13
1
3,957
175
1,113
32
0
1
1970-01-01T00:27:13
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,291
kyoripowered/adventure/439/427
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/427
https://github.com/KyoriPowered/adventure/pull/439
https://github.com/KyoriPowered/adventure/pull/439
1
fixes
Enforce nullability checks on component appending
At the moment, the nullability of components is not enforced when appending components, meaning that the children of a component may contain null elements.
eb867ffbbd1e751ced298235abe51ff52d1dcdfe
02449c28502bfcdec20db17481836612fc6477b5
https://github.com/kyoripowered/adventure/compare/eb867ffbbd1e751ced298235abe51ff52d1dcdfe...02449c28502bfcdec20db17481836612fc6477b5
diff --git a/api/src/main/java/net/kyori/adventure/text/AbstractComponentBuilder.java b/api/src/main/java/net/kyori/adventure/text/AbstractComponentBuilder.java index a58d0840..4fecb02e 100644 --- a/api/src/main/java/net/kyori/adventure/text/AbstractComponentBuilder.java +++ b/api/src/main/java/net/kyori/adventure/text/AbstractComponentBuilder.java @@ -39,6 +39,8 @@ import net.kyori.adventure.text.format.TextDecoration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import static java.util.Objects.requireNonNull; + /** * An abstract implementation of a component builder. * @@ -74,13 +76,14 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex public @NotNull B append(final @NotNull Component component) { if (component == Component.empty()) return (B) this; this.prepareChildren(); - this.children.add(component); + this.children.add(requireNonNull(component, "component")); return (B) this; } @Override @SuppressWarnings("unchecked") public @NotNull B append(final @NotNull Component@NotNull... components) { + requireNonNull(components, "components"); boolean prepared = false; for (int i = 0, length = components.length; i < length; i++) { final Component component = components[i]; @@ -89,7 +92,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex this.prepareChildren(); prepared = true; } - this.children.add(component); + this.children.add(requireNonNull(component, "components[?]")); } } return (B) this; @@ -98,6 +101,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex @Override @SuppressWarnings("unchecked") public @NotNull B append(final @NotNull ComponentLike@NotNull... components) { + requireNonNull(components, "components"); boolean prepared = false; for (int i = 0, length = components.length; i < length; i++) { final Component component = components[i].asComponent(); @@ -106,7 +110,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex this.prepareChildren(); prepared = true; } - this.children.add(component); + this.children.add(requireNonNull(component, "components[?]")); } } return (B) this; @@ -115,6 +119,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex @Override @SuppressWarnings("unchecked") public @NotNull B append(final @NotNull Iterable<? extends ComponentLike> components) { + requireNonNull(components, "components"); boolean prepared = false; for (final ComponentLike like : components) { final Component component = like.asComponent(); @@ -123,7 +128,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex this.prepareChildren(); prepared = true; } - this.children.add(component); + this.children.add(requireNonNull(component, "components[?]")); } } return (B) this; @@ -167,7 +172,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex if (!(child instanceof BuildableComponent<?, ?>)) { continue; } - final BuildableComponent<?, ?> mappedChild = function.apply((BuildableComponent<?, ?>) child); + final BuildableComponent<?, ?> mappedChild = requireNonNull(function.apply((BuildableComponent<?, ?>) child), "mappedChild"); if (child == mappedChild) { continue; } @@ -188,7 +193,7 @@ abstract class AbstractComponentBuilder<C extends BuildableComponent<C, B>, B ex if (!(child instanceof BuildableComponent<?, ?>)) { continue; } - final BuildableComponent<?, ?> mappedChild = function.apply((BuildableComponent<?, ?>) child); + final BuildableComponent<?, ?> mappedChild = requireNonNull(function.apply((BuildableComponent<?, ?>) child), "mappedChild"); if (mappedChild.children().isEmpty()) { if (child == mappedChild) { continue; diff --git a/api/src/main/java/net/kyori/adventure/text/ScopedComponent.java b/api/src/main/java/net/kyori/adventure/text/ScopedComponent.java index fabb7940..8356c35e 100644 --- a/api/src/main/java/net/kyori/adventure/text/ScopedComponent.java +++ b/api/src/main/java/net/kyori/adventure/text/ScopedComponent.java @@ -35,6 +35,8 @@ import net.kyori.adventure.util.MonkeyBars; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import static java.util.Objects.requireNonNull; + /** * Some magic to change return types. * @@ -77,7 +79,7 @@ public interface ScopedComponent<C extends Component> extends Component { default @NotNull C append(final @NotNull Component component) { if (component == Component.empty()) return (C) this; final List<Component> oldChildren = this.children(); - return this.children(MonkeyBars.addOne(oldChildren, component)); + return this.children(MonkeyBars.addOne(oldChildren, requireNonNull(component, "component"))); } @Override
['api/src/main/java/net/kyori/adventure/text/ScopedComponent.java', 'api/src/main/java/net/kyori/adventure/text/AbstractComponentBuilder.java']
{'.java': 2}
2
2
0
0
2
1,180,100
272,466
34,015
254
1,312
243
21
2
155
24
28
1
0
0
1970-01-01T00:27:10
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,293
kyoripowered/adventure/364/363
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/363
https://github.com/KyoriPowered/adventure/pull/364
https://github.com/KyoriPowered/adventure/pull/364
1
fixes
Component contains check doesn't check identical but separately created components
The following test will fail despite seeming like it should work. ```java final Component c0 = Component.text("best!"); final Component c1 = Component.text() .append(Component.text("Nero ")) .append(Component.text(" are the ").append(c0)) .build(); assertTrue(c1.contains(Component.text("best!"))); ``` As far as I'm concerned there are a few possible solutions to this: 1. Modify the Javadoc to note that this is how the check works. 2. Swap the identity check for a true equality check. 3. Create a new method, `Component#contains(Component, boolean)` which can be used to define the type of check that is made and make the old method overload this one. I kinda prefer options 1 or 3 because doing a true equality check every time here is going to be an awful lot of recursion which would suck.
9596f1ea0085cf0e987423637138d2358c683d8f
6e269d83f8daab0e0cc2b2cca2a0acc5d15204c8
https://github.com/kyoripowered/adventure/compare/9596f1ea0085cf0e987423637138d2358c683d8f...6e269d83f8daab0e0cc2b2cca2a0acc5d15204c8
diff --git a/api/src/main/java/net/kyori/adventure/text/Component.java b/api/src/main/java/net/kyori/adventure/text/Component.java index 8c85c3c8..b7ae6efa 100644 --- a/api/src/main/java/net/kyori/adventure/text/Component.java +++ b/api/src/main/java/net/kyori/adventure/text/Component.java @@ -28,7 +28,9 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.UnaryOperator; @@ -93,6 +95,19 @@ import org.jetbrains.annotations.Unmodifiable; */ @ApiStatus.NonExtendable public interface Component extends ComponentBuilderApplicable, ComponentLike, Examinable, HoverEventSource<Component> { + /** + * A predicate that checks equality of two {@code Component}s using {@link Objects#equals(Object, Object)}. + * + * @since 4.8.0 + */ + BiPredicate<? super Component, ? super Component> EQUALS = Objects::equals; + /** + * A predicate that checks equality of two {@code Component}s using identity equality. + * + * @since 4.8.0 + */ + BiPredicate<? super Component, ? super Component> EQUALS_IDENTITY = (a, b) -> a == b; + /** * Gets an empty component. * @@ -1270,15 +1285,31 @@ public interface Component extends ComponentBuilderApplicable, ComponentLike, Ex /** * Checks if this component contains a component. * + * <p>This method uses <b>identity</b> comparison when checking for contains. Use {@link #contains(Component, BiPredicate)} with {@link #EQUALS} if you + * wish to use full equality comparison.</p> + * * @param that the other component * @return {@code true} if this component contains the provided * component, {@code false} otherwise * @since 4.0.0 */ default boolean contains(final @NonNull Component that) { - if(this == that) return true; + return this.contains(that, EQUALS_IDENTITY); + } + + /** + * Checks if this component contains a component. + * + * @param that the other component + * @param equals the equality tester + * @return {@code true} if this component contains the provided + * component, {@code false} otherwise + * @since 4.8.0 + */ + default boolean contains(final @NonNull Component that, final @NonNull BiPredicate<? super Component, ? super Component> equals) { + if(equals.test(this, that)) return true; for(final Component child : this.children()) { - if(child.contains(that)) return true; + if(child.contains(that, equals)) return true; } final @Nullable HoverEvent<?> hoverEvent = this.hoverEvent(); if(hoverEvent != null) { @@ -1286,7 +1317,7 @@ public interface Component extends ComponentBuilderApplicable, ComponentLike, Ex final Component hover = (Component) hoverEvent.value(); if(that == hover) return true; for(final Component child : hover.children()) { - if(child.contains(that)) return true; + if(child.contains(that, equals)) return true; } } } diff --git a/api/src/test/java/net/kyori/adventure/text/TextComponentTest.java b/api/src/test/java/net/kyori/adventure/text/TextComponentTest.java index 5abe6724..1421731c 100644 --- a/api/src/test/java/net/kyori/adventure/text/TextComponentTest.java +++ b/api/src/test/java/net/kyori/adventure/text/TextComponentTest.java @@ -142,6 +142,18 @@ class TextComponentTest extends AbstractComponentTest<TextComponent, TextCompone assertTrue(component.contains(child)); } + // https://github.com/KyoriPowered/adventure/issues/363 + @Test + void testContainsEquality() { + final Component c0 = Component.text("best!"); + final Component c1 = Component.text() + .append(Component.text("Nero ")) + .append(Component.text(" are the ").append(c0)) + .build(); + + assertTrue(c1.contains(Component.text("best!"), Component.EQUALS)); + } + @Test void testContent() { final TextComponent c0 = Component.text("foo");
['api/src/main/java/net/kyori/adventure/text/Component.java', 'api/src/test/java/net/kyori/adventure/text/TextComponentTest.java']
{'.java': 2}
2
2
0
0
2
1,002,261
232,019
29,195
201
1,482
359
37
1
823
123
183
18
0
1
1970-01-01T00:27:00
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,292
kyoripowered/adventure/421/387
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/387
https://github.com/KyoriPowered/adventure/pull/421
https://github.com/KyoriPowered/adventure/pull/421
1
fixes
Loss of style when replacing full match text
When replacing text with a complete match of the text of a component with another component (`ComponentLike`) without a style (primitive text without any style), the outer style is lost, although it should be inherited. If you do a partial match, such as adding spaces at the end or beginning of the original component, the style is inherited correctly. I found the code that is responsible for this. However, I don’t know how to fix it correctly. https://github.com/KyoriPowered/adventure/blob/e23407ac6c0d4122cc4646d2f9e9fa1328a0423a/api/src/main/java/net/kyori/adventure/text/TextReplacementConfig.java#L193-L197 https://github.com/KyoriPowered/adventure/blob/e23407ac6c0d4122cc4646d2f9e9fa1328a0423a/api/src/main/java/net/kyori/adventure/text/TextReplacementRenderer.java#L75-L76
201a0ba7bfbc9bd409a39c63524ee6a0e202238a
b2dfd4ec1d56a8fdf3bfd1fc00cdd94c96035b9c
https://github.com/kyoripowered/adventure/compare/201a0ba7bfbc9bd409a39c63524ee6a0e202238a...b2dfd4ec1d56a8fdf3bfd1fc00cdd94c96035b9c
diff --git a/api/src/main/java/net/kyori/adventure/text/TextReplacementRenderer.java b/api/src/main/java/net/kyori/adventure/text/TextReplacementRenderer.java index 4b2f28b9..483330ce 100644 --- a/api/src/main/java/net/kyori/adventure/text/TextReplacementRenderer.java +++ b/api/src/main/java/net/kyori/adventure/text/TextReplacementRenderer.java @@ -30,6 +30,7 @@ import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.renderer.ComponentRenderer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -76,6 +77,10 @@ final class TextReplacementRenderer implements ComponentRenderer<TextReplacement .style(component.style())); modified = replacement == null ? Component.empty() : replacement.asComponent(); + + // merge style of the match into this component to prevent unexpected loss of style + modified = modified.style(modified.style().merge(component.style(), Style.Merge.Strategy.IF_ABSENT_ON_TARGET)); + if (children == null) { // Prepare children children = new ArrayList<>(oldChildrenSize + modified.children().size()); children.addAll(modified.children()); diff --git a/api/src/test/java/net/kyori/adventure/text/TextReplacementRendererTest.java b/api/src/test/java/net/kyori/adventure/text/TextReplacementRendererTest.java index c2c546e7..f39cc94e 100644 --- a/api/src/test/java/net/kyori/adventure/text/TextReplacementRendererTest.java +++ b/api/src/test/java/net/kyori/adventure/text/TextReplacementRendererTest.java @@ -246,4 +246,16 @@ class TextReplacementRendererTest { .build(); assertEquals(expected, replaced); } + + // https://github.com/KyoriPowered/adventure/issues/387 + @Test + void testFullMatchReplaceWithStyle() { + final Component base = Component.text("hello", NamedTextColor.RED); + + final Component replaced = base.replaceText(c -> c.matchLiteral("hello") + .replacement(Component.text("world").decorate(TextDecoration.BOLD))); + + final Component expected = Component.text("world", NamedTextColor.RED, TextDecoration.BOLD); + assertEquals(expected, replaced); + } }
['api/src/main/java/net/kyori/adventure/text/TextReplacementRenderer.java', 'api/src/test/java/net/kyori/adventure/text/TextReplacementRendererTest.java']
{'.java': 2}
2
2
0
0
2
1,113,670
257,347
32,220
241
272
52
5
1
788
79
208
5
2
0
1970-01-01T00:27:08
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,287
kyoripowered/adventure/954/953
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/953
https://github.com/KyoriPowered/adventure/pull/954
https://github.com/KyoriPowered/adventure/pull/954
1
closes
`ComponentFlattener.basic()` converts `ScoreComponent` with null `value` to null
A specific action bar received by Geyser cannot be serialized using the legacy serializer. The offending component was logged to console by the reporting user: ``` {"extra":[{"extra":[{"font":"nameplates:default","text":"끎끓끒끑끗"},{"color":"red","extra":[{"font":"nameplates:default","text":"끎끓끒끑끐끏끗"},{"color":"#00A5FF","extra":[{"font":"nameplates:default","text":"끎끔끑끏끗"},{"color":"#D31FEB","extra":[{"font":"nameplates:default","text":"끎끓끒끐끗"},{"color":"green","extra":[{"font":"nameplates:default","text":""},{"color":"#FFFEFD","extra":[{"font":"nameplates:ascent_-5","text":"100"},{"text":" "},{"font":"nameplates:default","text":"뀅"}],"text":""}],"text":"44°C "}],"text":"20.0 ✦ "}],"text":"1.0 ❈ "}],"text":"20 ❤ "}],"text":""}],"score":{"name":"nameplates","objective":"actionbar"}} ``` --- I was able to reproduce the issue and have posted it a test project [here](https://github.com/Konicai/actionbar-test/blob/main/src/test/java/me/konicai/test/ActionBarTest.java): ```java @Test public void testThing() { String input = "{\\"extra\\":[{\\"extra\\":[{\\"font\\":\\"nameplates:default\\",\\"text\\":\\"끎\\uF801끓\\uF801끒\\uF801끑\\uF801끗\\uF809\\uF808\\uF803\\"},{\\"color\\":\\"red\\",\\"extra\\":[{\\"font\\":\\"nameplates:default\\",\\"text\\":\\"끎\\uF801끓\\uF801끒\\uF801끑\\uF801끐\\uF801끏\\uF801끗\\uF809\\uF808\\uF806\\"},{\\"color\\":\\"#00A5FF\\",\\"extra\\":[{\\"font\\":\\"nameplates:default\\",\\"text\\":\\"끎\\uF801끔\\uF801끑\\uF801끏\\uF801끗\\uF80A\\uF804\\"},{\\"color\\":\\"#D31FEB\\",\\"extra\\":[{\\"font\\":\\"nameplates:default\\",\\"text\\":\\"끎\\uF801끓\\uF801끒\\uF801끐\\uF801끗\\uF809\\uF808\\uF801\\"},{\\"color\\":\\"green\\",\\"extra\\":[{\\"font\\":\\"nameplates:default\\",\\"text\\":\\"\\uF819\\uF818\\uF813\\"},{\\"color\\":\\"#FFFEFD\\",\\"extra\\":[{\\"font\\":\\"nameplates:ascent_-5\\",\\"text\\":\\"100\\"},{\\"text\\":\\" \\"},{\\"font\\":\\"nameplates:default\\",\\"text\\":\\"뀅\\"}],\\"text\\":\\"\\"}],\\"text\\":\\"44°C \\uF80A\\uF809\\uF804\\"}],\\"text\\":\\"20.0 ✦ \\"}],\\"text\\":\\"1.0 ❈ \\"}],\\"text\\":\\"20 ❤ \\"}],\\"text\\":\\"\\uF828\\uF824\\"}],\\"score\\":{\\"name\\":\\"nameplates\\",\\"objective\\":\\"actionbar\\"}}"; Component message = GsonComponentSerializer.gson().deserialize(input); System.out.println(PlainTextComponentSerializer.plainText().serialize(message)); LegacyComponentSerializer.legacySection().serialize(message); } ``` The following error occurs while trying to serialize the component to legacy text: ``` Cannot invoke "String.isEmpty()" because "text" is null java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "text" is null at net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializerImpl$Cereal.component(LegacyComponentSerializerImpl.java:326) at net.kyori.adventure.text.flattener.ComponentFlattenerImpl.lambda$flattener$3(ComponentFlattenerImpl.java:117) at net.kyori.adventure.text.flattener.ComponentFlattenerImpl.flatten0(ComponentFlattenerImpl.java:95) at net.kyori.adventure.text.flattener.ComponentFlattenerImpl.flatten(ComponentFlattenerImpl.java:78) at net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializerImpl.serialize(LegacyComponentSerializerImpl.java:271) at me.konicai.test.ActionBarTest.testThing(ActionBarTest.java:18) ``` The plain text serializer works fine and creates the following output (null at the front seems smelly): ``` null끎끓끒끑끗20 ❤ 끎끓끒끑끐끏끗1.0 ❈ 끎끔끑끏끗20.0 ✦ 끎끓끒끐끗44°C 100 뀅 ``` --- This occurs with `4.14.0`, which the test project is running (unlike Geyser). The affected code in Geyser begins [here](https://github.com/GeyserMC/Geyser/blob/18e7db8c30821edf38410d91e13d1a3690eff066/core/src/main/java/org/geysermc/geyser/translator/protocol/java/title/JavaSetActionBarTextTranslator.java#L44).
f8fa6ffec951743d90994855509bdf852e994c36
999ae5611e2e49cccf46ed68806ac56a600a7c19
https://github.com/kyoripowered/adventure/compare/f8fa6ffec951743d90994855509bdf852e994c36...999ae5611e2e49cccf46ed68806ac56a600a7c19
diff --git a/api/src/main/java/net/kyori/adventure/text/flattener/ComponentFlattenerImpl.java b/api/src/main/java/net/kyori/adventure/text/flattener/ComponentFlattenerImpl.java index 78dce1c1..51c1987b 100644 --- a/api/src/main/java/net/kyori/adventure/text/flattener/ComponentFlattenerImpl.java +++ b/api/src/main/java/net/kyori/adventure/text/flattener/ComponentFlattenerImpl.java @@ -47,7 +47,11 @@ final class ComponentFlattenerImpl implements ComponentFlattener { @SuppressWarnings("deprecation") static final ComponentFlattener BASIC = new BuilderImpl() .mapper(KeybindComponent.class, component -> component.keybind()) // IntelliJ is wrong here, this is fine - .mapper(ScoreComponent.class, ScoreComponent::value) // Removed in Vanilla 1.16, but we keep it for backwards compat + .mapper(ScoreComponent.class, component -> { + // Removed in Vanilla 1.16, but we keep it for backwards compat + final @Nullable String value = component.value(); + return value != null ? value : ""; + }) .mapper(SelectorComponent.class, SelectorComponent::pattern) .mapper(TextComponent.class, TextComponent::content) .mapper(TranslatableComponent.class, component -> {
['api/src/main/java/net/kyori/adventure/text/flattener/ComponentFlattenerImpl.java']
{'.java': 1}
1
1
0
0
1
1,896,024
435,511
54,027
410
349
80
6
1
3,775
168
1,393
36
2
4
1970-01-01T00:28:10
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,294
kyoripowered/adventure/213/212
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/212
https://github.com/KyoriPowered/adventure/pull/213
https://github.com/KyoriPowered/adventure/pull/213
1
fixes
@NonNull not being followed when using GsonComponentSerializer
When converting `"null"` using the GsonComponentSerializer the `deserialize` method returns null even though the method is marked `@NonNull`. I think it would be best to throw a JsonSyntaxException or something similar in this case. Version: 7acd956 Code: ```java System.out.println(GsonComponentSerializer.gson().deserialize("null")) System.out.println(GsonComponentSerializer.gson().deserialize("null") == null) ``` Output: ``` null true ```
f627af74783aa7b0372c9a090d68f0d4b00ce274
9fc26d18a88eb43a04c5a240e7aa99ff6cbfdf2e
https://github.com/kyoripowered/adventure/compare/f627af74783aa7b0372c9a090d68f0d4b00ce274...9fc26d18a88eb43a04c5a240e7aa99ff6cbfdf2e
diff --git a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/ComponentSerializerImpl.java b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/ComponentSerializerImpl.java index 2fa1686c..56f905bf 100644 --- a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/ComponentSerializerImpl.java +++ b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/ComponentSerializerImpl.java @@ -235,7 +235,7 @@ final class ComponentSerializerImpl implements JsonDeserializer<Component>, Json return object; } - private static JsonParseException notSureHowToDeserialize(final JsonElement element) { + static JsonParseException notSureHowToDeserialize(final Object element) { return new JsonParseException("Don't know how to turn " + element + " into a Component"); } diff --git a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerImpl.java b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerImpl.java index 0b214e22..89197320 100644 --- a/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerImpl.java +++ b/text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerImpl.java @@ -80,7 +80,9 @@ final class GsonComponentSerializerImpl implements GsonComponentSerializer { @Override public @NonNull Component deserialize(final @NonNull String string) { - return this.serializer().fromJson(string, Component.class); + final Component component = this.serializer().fromJson(string, Component.class); + if(component == null) throw ComponentSerializerImpl.notSureHowToDeserialize(string); + return component; } @Override diff --git a/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java b/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java index 6671aa4e..5db99099 100644 --- a/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java +++ b/text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java @@ -35,8 +35,15 @@ import static net.kyori.adventure.text.serializer.gson.GsonTest.array; import static net.kyori.adventure.text.serializer.gson.GsonTest.object; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class GsonComponentSerializerTest { + @Test + void testDeserializeNull() { + final JsonParseException jpe = assertThrows(JsonParseException.class, () -> GsonComponentSerializer.gson().deserialize("null")); + assertTrue(jpe.getMessage().contains("turn null into a Component")); + } + @Test void testDeserializePrimitive() { assertEquals(Component.text("potato"), GsonComponentSerializer.gson().serializer().fromJson(new JsonPrimitive("potato"), Component.class));
['text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/ComponentSerializerImpl.java', 'text-serializer-gson/src/main/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerImpl.java', 'text-serializer-gson/src/test/java/net/kyori/adventure/text/serializer/gson/GsonComponentSerializerTest.java']
{'.java': 3}
3
3
0
0
3
864,797
199,231
25,448
180
429
76
6
2
461
48
99
16
0
2
1970-01-01T00:26:46
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
1,295
kyoripowered/adventure/12/11
kyoripowered
adventure
https://github.com/KyoriPowered/adventure/issues/11
https://github.com/KyoriPowered/adventure/pull/12
https://github.com/KyoriPowered/adventure/pull/12
1
fixes
Legacy color code parsing
When more than one color code is specified consecutively, the one which appears first is used, rather than the last. For example, `&a&9foo` is parsed to `foo` with color `green` as opposed to `foo` with color `blue`. Test case: ```java @Test public void testFromColor() { final TextComponent component = TextComponent.builder("") .append(TextComponent.of("foo").color(TextColor.BLUE)) .build(); assertEquals(component, ComponentSerializers.LEGACY.deserialize("&a&9foo", '&')); } ``` ``` java.lang.AssertionError: Expected :TextComponent{content=, children=[TextComponent{content=foo, children=[], color=blue, obfuscated=null, bold=null, strikethrough=null, underlined=null, italic=null, clickEvent=null, hoverEvent=null, insertion=null}], color=null, obfuscated=null, bold=null, strikethrough=null, underlined=null, italic=null, clickEvent=null, hoverEvent=null, insertion=null} Actual :TextComponent{content=, children=[TextComponent{content=foo, children=[], color=green, obfuscated=null, bold=null, strikethrough=null, underlined=null, italic=null, clickEvent=null, hoverEvent=null, insertion=null}], color=null, obfuscated=null, bold=null, strikethrough=null, underlined=null, italic=null, clickEvent=null, hoverEvent=null, insertion=null} ``` I've tried playing around with `LegacyComponentSerializer` to work out a fix. I assume this is happening because the string is being parsed in reverse, meaning the first color code in the string is being read after the color code later in the string - hence overriding the last.
24e44d683f825f9cc6fecbe2c8f5b684e5494b34
0ef8fcc8a7d1ee78aefd6aec2f3b479b3721c3b7
https://github.com/kyoripowered/adventure/compare/24e44d683f825f9cc6fecbe2c8f5b684e5494b34...0ef8fcc8a7d1ee78aefd6aec2f3b479b3721c3b7
diff --git a/src/main/java/net/kyori/text/AbstractBuildableComponent.java b/src/main/java/net/kyori/text/AbstractBuildableComponent.java index 949ebfe1..904274a7 100644 --- a/src/main/java/net/kyori/text/AbstractBuildableComponent.java +++ b/src/main/java/net/kyori/text/AbstractBuildableComponent.java @@ -215,6 +215,15 @@ public abstract class AbstractBuildableComponent<C extends BuildableComponent<C, return (B) this; } + @NonNull + @Override + public B colorIfAbsent(@Nullable final TextColor color) { + if(this.color == null) { + this.color = color; + } + return (B) this; + } + @NonNull @Override public B decoration(@NonNull final TextDecoration decoration, @NonNull final TextDecoration.State state) { diff --git a/src/main/java/net/kyori/text/BuildableComponent.java b/src/main/java/net/kyori/text/BuildableComponent.java index 4cb74fec..168fcabb 100644 --- a/src/main/java/net/kyori/text/BuildableComponent.java +++ b/src/main/java/net/kyori/text/BuildableComponent.java @@ -125,6 +125,15 @@ public interface BuildableComponent<C extends BuildableComponent<C, B>, B extend @NonNull B color(@Nullable final TextColor color); + /** + * Sets the color of this component if there isn't one set already. + * + * @param color the color + * @return this builder + */ + @NonNull + B colorIfAbsent(@Nullable final TextColor color); + /** * Sets the state of a decoration on this component. * diff --git a/src/main/java/net/kyori/text/serializer/LegacyComponentSerializerImpl.java b/src/main/java/net/kyori/text/serializer/LegacyComponentSerializerImpl.java index cf776c30..85df3668 100644 --- a/src/main/java/net/kyori/text/serializer/LegacyComponentSerializerImpl.java +++ b/src/main/java/net/kyori/text/serializer/LegacyComponentSerializerImpl.java @@ -109,7 +109,7 @@ class LegacyComponentSerializerImpl implements LegacyComponentSerializer { private static boolean applyFormat(@NonNull final TextComponent.Builder builder, @NonNull final TextFormat format) { if(format instanceof TextColor) { - builder.color((TextColor) format); + builder.colorIfAbsent((TextColor) format); return true; } else if(format instanceof TextDecoration) { builder.decoration((TextDecoration) format, TextDecoration.State.TRUE); diff --git a/src/test/java/net/kyori/text/serializer/ComponentSerializerTest.java b/src/test/java/net/kyori/text/serializer/ComponentSerializerTest.java index d46696ef..5a80917c 100644 --- a/src/test/java/net/kyori/text/serializer/ComponentSerializerTest.java +++ b/src/test/java/net/kyori/text/serializer/ComponentSerializerTest.java @@ -47,6 +47,15 @@ public class ComponentSerializerTest { assertEquals(component, ComponentSerializers.LEGACY.deserialize("&a&lfoo&9bar", '&')); } + @Test + public void testFromColorOverride() { + final TextComponent component = TextComponent.builder("") + .append(TextComponent.of("foo").color(TextColor.BLUE)) + .build(); + + assertEquals(component, ComponentSerializers.LEGACY.deserialize("&a&9foo", '&')); + } + @Test public void testToLegacy() { final TextComponent c1 = TextComponent.builder("hi")
['src/test/java/net/kyori/text/serializer/ComponentSerializerTest.java', 'src/main/java/net/kyori/text/BuildableComponent.java', 'src/main/java/net/kyori/text/serializer/LegacyComponentSerializerImpl.java', 'src/main/java/net/kyori/text/AbstractBuildableComponent.java']
{'.java': 4}
4
4
0
0
4
141,179
31,360
3,901
19
514
119
20
3
1,568
152
368
23
0
2
1970-01-01T00:25:13
581
Java
{'Java': 2437627, 'Kotlin': 34310}
MIT License
665
scalecube/scalecube-services/550/549
scalecube
scalecube-services
https://github.com/scalecube/scalecube-services/issues/549
https://github.com/scalecube/scalecube-services/pull/550
https://github.com/scalecube/scalecube-services/pull/550
1
fix
Client-sdk doesn't parse type with nested generics
For example `java.util.List<io.scalecube.FetchResponse>>` throws exception
76c8de6019e5480a1436d12b37acf163f70eea47
7c443017c41e6746ced8381747b5386db0ce0e38
https://github.com/scalecube/scalecube-services/compare/76c8de6019e5480a1436d12b37acf163f70eea47...7c443017c41e6746ced8381747b5386db0ce0e38
diff --git a/services-api/src/main/java/io/scalecube/services/methods/MethodInfo.java b/services-api/src/main/java/io/scalecube/services/methods/MethodInfo.java index 0fcdb9fb..2d6c4463 100644 --- a/services-api/src/main/java/io/scalecube/services/methods/MethodInfo.java +++ b/services-api/src/main/java/io/scalecube/services/methods/MethodInfo.java @@ -3,13 +3,14 @@ package io.scalecube.services.methods; import io.scalecube.services.CommunicationMode; import io.scalecube.services.api.Qualifier; import io.scalecube.services.api.ServiceMessage; +import java.lang.reflect.Type; public final class MethodInfo { private final String serviceName; private final String methodName; private final String qualifier; - private final Class<?> parameterizedReturnType; + private final Type parameterizedReturnType; private final CommunicationMode communicationMode; private final int parameterCount; private final Class<?> requestType; @@ -27,7 +28,7 @@ public final class MethodInfo { public MethodInfo( String serviceName, String methodName, - Class<?> parameterizedReturnType, + Type parameterizedReturnType, CommunicationMode communicationMode, int parameterCount, Class<?> requestType) { @@ -53,7 +54,7 @@ public final class MethodInfo { return qualifier; } - public Class<?> parameterizedReturnType() { + public Type parameterizedReturnType() { return parameterizedReturnType; } diff --git a/services-api/src/main/java/io/scalecube/services/transport/api/DataCodec.java b/services-api/src/main/java/io/scalecube/services/transport/api/DataCodec.java index 1d62b68c..7b9bd9ab 100644 --- a/services-api/src/main/java/io/scalecube/services/transport/api/DataCodec.java +++ b/services-api/src/main/java/io/scalecube/services/transport/api/DataCodec.java @@ -4,6 +4,7 @@ import io.scalecube.services.ServiceLoaderUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.Type; import java.util.Collection; import java.util.Map; import java.util.function.Function; @@ -41,5 +42,5 @@ public interface DataCodec { void encode(OutputStream stream, Object value) throws IOException; - Object decode(InputStream stream, Class<?> type) throws IOException; + Object decode(InputStream stream, Type type) throws IOException; } diff --git a/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java b/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java index 9c261a50..9bb54845 100644 --- a/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java +++ b/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java @@ -8,6 +8,7 @@ import io.netty.buffer.Unpooled; import io.scalecube.services.api.ErrorData; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.exceptions.MessageCodecException; +import java.lang.reflect.Type; import java.util.function.BiFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -104,7 +105,7 @@ public final class ServiceMessageCodec { * (of type data type) * @throws MessageCodecException when decode fails */ - public static ServiceMessage decodeData(ServiceMessage message, Class<?> dataType) + public static ServiceMessage decodeData(ServiceMessage message, Type dataType) throws MessageCodecException { if (dataType == null || !message.hasData(ByteBuf.class) @@ -113,7 +114,7 @@ public final class ServiceMessageCodec { } Object data; - Class<?> targetType = message.isError() ? ErrorData.class : dataType; + Type targetType = message.isError() ? ErrorData.class : dataType; ByteBuf dataBuffer = message.data(); try (ByteBufInputStream inputStream = new ByteBufInputStream(dataBuffer, true)) { diff --git a/services-examples/src/main/java/io/scalecube/services/examples/GreetingService.java b/services-examples/src/main/java/io/scalecube/services/examples/GreetingService.java index de8856ba..93895fd1 100644 --- a/services-examples/src/main/java/io/scalecube/services/examples/GreetingService.java +++ b/services-examples/src/main/java/io/scalecube/services/examples/GreetingService.java @@ -2,6 +2,7 @@ package io.scalecube.services.examples; import io.scalecube.services.annotations.Service; import io.scalecube.services.annotations.ServiceMethod; +import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -28,6 +29,9 @@ public interface GreetingService { @ServiceMethod("pojo/one") Mono<GreetingResponse> pojoOne(GreetingRequest request); + @ServiceMethod("pojo/list") + Mono<List<GreetingResponse>> pojoList(GreetingRequest request); + @ServiceMethod("pojo/many") Flux<GreetingResponse> pojoMany(GreetingRequest request); diff --git a/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceCancelCallback.java b/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceCancelCallback.java index df94b777..50779793 100644 --- a/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceCancelCallback.java +++ b/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceCancelCallback.java @@ -1,5 +1,6 @@ package io.scalecube.services.examples; +import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -42,6 +43,11 @@ public class GreetingServiceCancelCallback implements GreetingService { return greetingService.pojoOne(request).doOnCancel(onCancel); } + @Override + public Mono<List<GreetingResponse>> pojoList(GreetingRequest request) { + return greetingService.pojoList(request).doOnCancel(onCancel); + } + @Override public Flux<GreetingResponse> pojoMany(GreetingRequest request) { return greetingService.pojoMany(request).doOnCancel(onCancel); diff --git a/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceImpl.java b/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceImpl.java index fefe0773..ab0a3f48 100644 --- a/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceImpl.java +++ b/services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceImpl.java @@ -1,6 +1,8 @@ package io.scalecube.services.examples; import java.time.Duration; +import java.util.Collections; +import java.util.List; import java.util.stream.LongStream; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -47,6 +49,12 @@ public class GreetingServiceImpl implements GreetingService { return Mono.defer(() -> one(request.getText()).map(GreetingResponse::new)); } + @Override + public Mono<List<GreetingResponse>> pojoList(GreetingRequest request) { + return Mono.defer( + () -> one(request.getText()).map(GreetingResponse::new).map(Collections::singletonList)); + } + @Override public Flux<GreetingResponse> pojoMany(GreetingRequest request) { return Flux.defer(() -> many(request.getText()).map(GreetingResponse::new)); diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientCodec.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientCodec.java index 6394a7fc..2849dc2d 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientCodec.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientCodec.java @@ -4,6 +4,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.scalecube.services.gateway.clientsdk.exceptions.MessageCodecException; import io.scalecube.services.transport.api.DataCodec; +import java.lang.reflect.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,14 +26,14 @@ public interface ClientCodec<T> { * @return client message object. * @throws MessageCodecException in case if data decoding fails. */ - default ClientMessage decodeData(ClientMessage message, Class<?> dataType) + default ClientMessage decodeData(ClientMessage message, Type dataType) throws MessageCodecException { if (!message.hasData(ByteBuf.class) || dataType == null) { return message; } Object data; - Class<?> targetType = message.isError() ? ErrorData.class : dataType; + Type targetType = message.isError() ? ErrorData.class : dataType; ByteBuf dataBuffer = message.data(); try (ByteBufInputStream inputStream = new ByteBufInputStream(dataBuffer, true)) { @@ -48,7 +49,7 @@ public interface ClientCodec<T> { /** * Returns codec which is used to decode data object of {@link ClientMessage}. * - * @see ClientCodec#decodeData(ClientMessage, Class) + * @see ClientCodec#decodeData(ClientMessage, Type) * @return data codec */ DataCodec getDataCodec(); diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/Reflect.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/Reflect.java index af30d76a..ddf06b4f 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/Reflect.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/Reflect.java @@ -70,15 +70,10 @@ class Reflect { * @param method to extract type from. * @return the generic type of the return value or object. */ - private static Class<?> parameterizedReturnType(Method method) { + private static Type parameterizedReturnType(Method method) { Type type = method.getGenericReturnType(); if (type instanceof ParameterizedType) { - try { - return Class.forName( - (((ParameterizedType) type).getActualTypeArguments()[0]).getTypeName()); - } catch (ClassNotFoundException e) { - return Object.class; - } + return ((ParameterizedType) type).getActualTypeArguments()[0]; } else { return Object.class; } diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/RemoteInvocationHandler.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/RemoteInvocationHandler.java index ff69d869..0a78f730 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/RemoteInvocationHandler.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/RemoteInvocationHandler.java @@ -4,6 +4,7 @@ import io.scalecube.services.gateway.clientsdk.exceptions.ClientErrorMapper; import io.scalecube.services.methods.MethodInfo; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.lang.reflect.Type; import java.util.Map; import reactor.core.Exceptions; @@ -42,7 +43,7 @@ public class RemoteInvocationHandler implements InvocationHandler { .data(methodInfo.parameterCount() != 0 ? args[0] : null) .build(); - Class<?> responseType = methodInfo.parameterizedReturnType(); + Type responseType = methodInfo.parameterizedReturnType(); switch (methodInfo.communicationMode()) { case REQUEST_RESPONSE: diff --git a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpGatewayTest.java b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpGatewayTest.java index 9e46c1fe..e8cdd0fa 100644 --- a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpGatewayTest.java +++ b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpGatewayTest.java @@ -54,6 +54,14 @@ class HttpGatewayTest { .verify(TIMEOUT); } + @Test + void shouldReturnListResponseWithPojoRequest() { + StepVerifier.create(service.pojoList(new GreetingRequest("hello"))) + .expectNextMatches(response -> "Echo:hello".equals(response.get(0).getText())) + .expectComplete() + .verify(TIMEOUT); + } + @Test void shouldReturnNoContentWhenResponseIsEmpty() { StepVerifier.create(service.emptyOne("hello")).expectComplete().verify(TIMEOUT); diff --git a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpLocalGatewayTest.java b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpLocalGatewayTest.java index caa83e17..c20fb32f 100644 --- a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpLocalGatewayTest.java +++ b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpLocalGatewayTest.java @@ -52,6 +52,14 @@ class HttpLocalGatewayTest { .verify(TIMEOUT); } + @Test + void shouldReturnListResponseWithPojoRequest() { + StepVerifier.create(service.pojoList(new GreetingRequest("hello"))) + .expectNextMatches(response -> "Echo:hello".equals(response.get(0).getText())) + .expectComplete() + .verify(TIMEOUT); + } + @Test void shouldReturnNoContentWhenResponseIsEmpty() { StepVerifier.create(service.emptyOne("hello")).expectComplete().verify(TIMEOUT); diff --git a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketGatewayTest.java b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketGatewayTest.java index 7ed709f2..d09da7e7 100644 --- a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketGatewayTest.java +++ b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketGatewayTest.java @@ -55,6 +55,14 @@ class RSocketGatewayTest { .verify(TIMEOUT); } + @Test + void shouldReturnListResponseWithPojoRequest() { + StepVerifier.create(service.pojoList(new GreetingRequest("hello"))) + .expectNextMatches(response -> "Echo:hello".equals(response.get(0).getText())) + .expectComplete() + .verify(TIMEOUT); + } + @Test void shouldReturnManyResponses() { int expectedResponseNum = 3; diff --git a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketLocalGatewayTest.java b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketLocalGatewayTest.java index e1205fe4..5cb09604 100644 --- a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketLocalGatewayTest.java +++ b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketLocalGatewayTest.java @@ -55,6 +55,14 @@ class RSocketLocalGatewayTest { .verify(TIMEOUT); } + @Test + void shouldReturnListResponseWithPojoRequest() { + StepVerifier.create(service.pojoList(new GreetingRequest("hello"))) + .expectNextMatches(response -> "Echo:hello".equals(response.get(0).getText())) + .expectComplete() + .verify(TIMEOUT); + } + @Test void shouldReturnManyResponses() { int expectedResponseNum = 3; diff --git a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketGatewayTest.java b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketGatewayTest.java index 2989056c..0b32d249 100644 --- a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketGatewayTest.java +++ b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketGatewayTest.java @@ -55,6 +55,14 @@ class WebsocketGatewayTest { .verify(TIMEOUT); } + @Test + void shouldReturnListResponseWithPojoRequest() { + StepVerifier.create(service.pojoList(new GreetingRequest("hello"))) + .expectNextMatches(response -> "Echo:hello".equals(response.get(0).getText())) + .expectComplete() + .verify(TIMEOUT); + } + @Test void shouldReturnManyResponsesWithSimpleRequest() { int expectedResponseNum = 3; diff --git a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketLocalGatewayTest.java b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketLocalGatewayTest.java index 39adede8..6004ecfb 100644 --- a/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketLocalGatewayTest.java +++ b/services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketLocalGatewayTest.java @@ -54,6 +54,14 @@ class WebsocketLocalGatewayTest { .verify(TIMEOUT); } + @Test + void shouldReturnListResponseWithPojoRequest() { + StepVerifier.create(service.pojoList(new GreetingRequest("hello"))) + .expectNextMatches(response -> "Echo:hello".equals(response.get(0).getText())) + .expectComplete() + .verify(TIMEOUT); + } + @Test void shouldReturnManyResponsesWithSimpleRequest() { int expectedResponseNum = 3; diff --git a/services-transport-jackson/src/main/java/io/scalecube/services/transport/jackson/JacksonCodec.java b/services-transport-jackson/src/main/java/io/scalecube/services/transport/jackson/JacksonCodec.java index ee8a3430..8c565e70 100644 --- a/services-transport-jackson/src/main/java/io/scalecube/services/transport/jackson/JacksonCodec.java +++ b/services-transport-jackson/src/main/java/io/scalecube/services/transport/jackson/JacksonCodec.java @@ -12,6 +12,7 @@ import io.scalecube.services.transport.api.HeadersCodec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -53,8 +54,8 @@ public final class JacksonCodec implements DataCodec, HeadersCodec { } @Override - public Object decode(InputStream stream, Class<?> type) throws IOException { - return mapper.readValue(stream, type); + public Object decode(InputStream stream, Type type) throws IOException { + return mapper.readValue(stream, mapper.getTypeFactory().constructType(type)); } private static ObjectMapper initMapper() { diff --git a/services-transport-protostuff/src/main/java/io/scalecube/services/transport/protostuff/ProtostuffCodec.java b/services-transport-protostuff/src/main/java/io/scalecube/services/transport/protostuff/ProtostuffCodec.java index ca8d26a7..c09d821e 100644 --- a/services-transport-protostuff/src/main/java/io/scalecube/services/transport/protostuff/ProtostuffCodec.java +++ b/services-transport-protostuff/src/main/java/io/scalecube/services/transport/protostuff/ProtostuffCodec.java @@ -5,11 +5,14 @@ import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.StringMapSchema; import io.protostuff.runtime.RuntimeSchema; +import io.scalecube.services.exceptions.MessageCodecException; import io.scalecube.services.transport.api.DataCodec; import io.scalecube.services.transport.api.HeadersCodec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; @@ -40,14 +43,24 @@ public final class ProtostuffCodec implements HeadersCodec, DataCodec { } @Override - public Object decode(InputStream stream, Class<?> type) throws IOException { - Schema schema = RuntimeSchema.getSchema(type); - Object result = schema.newMessage(); + public Object decode(InputStream stream, Type type) throws IOException { + try { + Class<?> clazz = null; + if (type instanceof Class<?>) { + clazz = (Class<?>) type; + } else if (type instanceof ParameterizedType) { + clazz = Class.forName(((ParameterizedType) type).getRawType().getTypeName()); + } + Schema schema = RuntimeSchema.getSchema(clazz); + Object result = schema.newMessage(); - try (RecyclableLinkedBuffer rlb = recyclableLinkedBuffer.get()) { - ProtobufIOUtil.mergeFrom(stream, result, schema, rlb.buffer()); + try (RecyclableLinkedBuffer rlb = recyclableLinkedBuffer.get()) { + ProtobufIOUtil.mergeFrom(stream, result, schema, rlb.buffer()); + } + return result; + } catch (ClassNotFoundException e) { + throw new MessageCodecException("Couldn't decode message", e); } - return result; } @Override diff --git a/services/src/main/java/io/scalecube/services/Reflect.java b/services/src/main/java/io/scalecube/services/Reflect.java index 4b53f2ab..358e772f 100644 --- a/services/src/main/java/io/scalecube/services/Reflect.java +++ b/services/src/main/java/io/scalecube/services/Reflect.java @@ -62,15 +62,10 @@ public final class Reflect { * @param method to extract type from. * @return the generic type of the return value or object. */ - public static Class<?> parameterizedReturnType(Method method) { + public static Type parameterizedReturnType(Method method) { Type type = method.getGenericReturnType(); if (type instanceof ParameterizedType) { - try { - return Class.forName( - (((ParameterizedType) type).getActualTypeArguments()[0]).getTypeName()); - } catch (ClassNotFoundException e) { - return Object.class; - } + return ((ParameterizedType) type).getActualTypeArguments()[0]; } else { return Object.class; } diff --git a/services/src/main/java/io/scalecube/services/ServiceCall.java b/services/src/main/java/io/scalecube/services/ServiceCall.java index fe1212cd..9ef8986e 100644 --- a/services/src/main/java/io/scalecube/services/ServiceCall.java +++ b/services/src/main/java/io/scalecube/services/ServiceCall.java @@ -19,6 +19,7 @@ import io.scalecube.services.transport.api.ReferenceCountUtil; import io.scalecube.services.transport.api.ServiceMessageCodec; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.lang.reflect.Type; import java.util.Map; import java.util.Optional; import java.util.concurrent.Callable; @@ -150,7 +151,7 @@ public class ServiceCall { * @param responseType type of response. * @return mono publisher completing with single response message or with error. */ - public Mono<ServiceMessage> requestOne(ServiceMessage request, Class<?> responseType) { + public Mono<ServiceMessage> requestOne(ServiceMessage request, Type responseType) { return Mono.defer( () -> { String qualifier = request.qualifier(); @@ -175,7 +176,7 @@ public class ServiceCall { * @return mono publisher completing with single response message or with error. */ public Mono<ServiceMessage> requestOne( - ServiceMessage request, Class<?> responseType, Address address) { + ServiceMessage request, Type responseType, Address address) { return Mono.defer( () -> { requireNonNull(address, "requestOne address parameter is required and must not be null"); @@ -205,7 +206,7 @@ public class ServiceCall { * @param responseType type of responses. * @return flux publisher of service responses. */ - public Flux<ServiceMessage> requestMany(ServiceMessage request, Class<?> responseType) { + public Flux<ServiceMessage> requestMany(ServiceMessage request, Type responseType) { return Flux.defer( () -> { String qualifier = request.qualifier(); @@ -232,7 +233,7 @@ public class ServiceCall { * @return flux publisher of service responses. */ public Flux<ServiceMessage> requestMany( - ServiceMessage request, Class<?> responseType, Address address) { + ServiceMessage request, Type responseType, Address address) { return Flux.defer( () -> { requireNonNull(address, "requestMany address parameter is required and must not be null"); @@ -263,7 +264,7 @@ public class ServiceCall { * @return flux publisher of service responses. */ public Flux<ServiceMessage> requestBidirectional( - Publisher<ServiceMessage> publisher, Class<?> responseType) { + Publisher<ServiceMessage> publisher, Type responseType) { return Flux.from(publisher) .switchOnFirst( (first, messages) -> { @@ -298,7 +299,7 @@ public class ServiceCall { * @return flux publisher of service responses. */ public Flux<ServiceMessage> requestBidirectional( - Publisher<ServiceMessage> publisher, Class<?> responseType, Address address) { + Publisher<ServiceMessage> publisher, Type responseType, Address address) { return Flux.defer( () -> { requireNonNull( @@ -331,7 +332,7 @@ public class ServiceCall { new Class[] {serviceInterface}, (proxy, method, params) -> { final MethodInfo methodInfo = genericReturnTypes.get(method); - final Class<?> returnType = methodInfo.parameterizedReturnType(); + final Type returnType = methodInfo.parameterizedReturnType(); final boolean isServiceMessage = methodInfo.isRequestTypeServiceMessage(); Optional<Object> check =
['services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpLocalGatewayTest.java', 'services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientCodec.java', 'services-api/src/main/java/io/scalecube/services/transport/api/DataCodec.java', 'services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketGatewayTest.java', 'services/src/main/java/io/scalecube/services/ServiceCall.java', 'services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java', 'services/src/main/java/io/scalecube/services/Reflect.java', 'services-examples/src/main/java/io/scalecube/services/examples/GreetingService.java', 'services-transport-protostuff/src/main/java/io/scalecube/services/transport/protostuff/ProtostuffCodec.java', 'services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceImpl.java', 'services-gateway-tests/src/test/java/io/scalecube/services/gateway/http/HttpGatewayTest.java', 'services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/Reflect.java', 'services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/RemoteInvocationHandler.java', 'services-transport-jackson/src/main/java/io/scalecube/services/transport/jackson/JacksonCodec.java', 'services-api/src/main/java/io/scalecube/services/methods/MethodInfo.java', 'services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketGatewayTest.java', 'services-gateway-tests/src/test/java/io/scalecube/services/gateway/websocket/WebsocketLocalGatewayTest.java', 'services-gateway-tests/src/test/java/io/scalecube/services/gateway/rsocket/RSocketLocalGatewayTest.java', 'services-examples/src/main/java/io/scalecube/services/examples/GreetingServiceCancelCallback.java']
{'.java': 19}
19
19
0
0
19
444,219
88,706
14,054
197
5,473
1,060
106
13
74
5
16
1
0
0
1970-01-01T00:25:56
581
Java
{'Java': 668288}
Apache License 2.0
666
scalecube/scalecube-services/515/513
scalecube
scalecube-services
https://github.com/scalecube/scalecube-services/issues/513
https://github.com/scalecube/scalecube-services/pull/515
https://github.com/scalecube/scalecube-services/pull/515
1
fix
Method not being called when making HTTP request to @ServiceMethod that have no input params
Method not being called when making HTTP request to @ServiceMethod that have no input params, response is empty and no error in log. Example: **Definition** `@ServiceMethod("getVersion") Mono<String> getVersion();` **Implementation** `@Override public Mono<String> getVersion() { return Mono.just("version 1"); }` **Request:** - POST - URL: localhost:8080/adminservice/getVersion - Headers: Content-Type:application/json - Body: <empty>
a9761776973df8d990658eeffca7d5025f58b209
fd7c32ebd462a793821c2c6b39551a17ecb8969d
https://github.com/scalecube/scalecube-services/compare/a9761776973df8d990658eeffca7d5025f58b209...fd7c32ebd462a793821c2c6b39551a17ecb8969d
diff --git a/services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java b/services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java index 57612923..498cc025 100644 --- a/services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java +++ b/services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java @@ -154,7 +154,7 @@ public final class ServiceMessage { /** * Verify that this message contains data. * - * @param dataClass the expected class of the dara + * @param dataClass the expected class of the data * @return true if the data is instance of the dataClass */ public boolean hasData(Class<?> dataClass) { diff --git a/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java b/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java index 0f51bfda..9c261a50 100644 --- a/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java +++ b/services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java @@ -106,7 +106,9 @@ public final class ServiceMessageCodec { */ public static ServiceMessage decodeData(ServiceMessage message, Class<?> dataType) throws MessageCodecException { - if (!message.hasData(ByteBuf.class) || dataType == null) { + if (dataType == null + || !message.hasData(ByteBuf.class) + || ((ByteBuf) message.data()).readableBytes() == 0) { return message; } diff --git a/services-gateway-http/src/main/java/io/scalecube/services/gateway/http/HttpGatewayAcceptor.java b/services-gateway-http/src/main/java/io/scalecube/services/gateway/http/HttpGatewayAcceptor.java index 7c1504c6..d1127030 100644 --- a/services-gateway-http/src/main/java/io/scalecube/services/gateway/http/HttpGatewayAcceptor.java +++ b/services-gateway-http/src/main/java/io/scalecube/services/gateway/http/HttpGatewayAcceptor.java @@ -14,7 +14,6 @@ import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ErrorData; -import io.scalecube.services.api.Qualifier; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.api.ServiceMessage.Builder; import io.scalecube.services.exceptions.DefaultErrorMapper; @@ -27,6 +26,7 @@ import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; +import reactor.netty.ByteBufMono; import reactor.netty.http.server.HttpServerRequest; import reactor.netty.http.server.HttpServerResponse; @@ -64,6 +64,7 @@ public class HttpGatewayAcceptor return httpRequest .receive() .aggregate() + .switchIfEmpty(Mono.defer(() -> ByteBufMono.just(Unpooled.EMPTY_BUFFER))) .map(ByteBuf::retain) .doOnNext(content -> metrics.markRequest()) .flatMap(content -> handleRequest(content, httpRequest, httpResponse))
['services-api/src/main/java/io/scalecube/services/transport/api/ServiceMessageCodec.java', 'services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java', 'services-gateway-http/src/main/java/io/scalecube/services/gateway/http/HttpGatewayAcceptor.java']
{'.java': 3}
3
3
0
0
3
438,186
87,825
13,970
195
465
113
9
3
490
50
110
25
0
0
1970-01-01T00:25:50
581
Java
{'Java': 668288}
Apache License 2.0
668
scalecube/scalecube-services/36/34
scalecube
scalecube-services
https://github.com/scalecube/scalecube-services/issues/34
https://github.com/scalecube/scalecube-services/pull/36
https://github.com/scalecube/scalecube-services/pull/36
1
fix
Data type can be lost if message is passed via proxy node (e.g. gossip)
Since message doesn't contain field dataType, but only in deserialized form at MessageSchema when message pass via some proxy which can't resolve dataType via class by name (e.g. gossip which pass to some node which doesn't have required data model) then data type will be lost on this node and won't be transferred on next hop.
fb9cebc26a35184b357f6cd5d3135edbb8e51821
19bd2da6d286ce8594f776f11ec9cfd2d1ec20d2
https://github.com/scalecube/scalecube-services/compare/fb9cebc26a35184b357f6cd5d3135edbb8e51821...19bd2da6d286ce8594f776f11ec9cfd2d1ec20d2
diff --git a/transport/src/main/java/io/servicefabric/transport/TransportHeaders.java b/transport/src/main/java/io/servicefabric/transport/TransportHeaders.java index 5bc3ef79..ef85fa9d 100644 --- a/transport/src/main/java/io/servicefabric/transport/TransportHeaders.java +++ b/transport/src/main/java/io/servicefabric/transport/TransportHeaders.java @@ -7,10 +7,23 @@ import rx.functions.Func1; */ public final class TransportHeaders { + /** + * This header is supposed to be used by application in case if same data type can be reused for different message + * meanings so it will allow to qualify the specific meaning of data. + */ public static final String QUALIFIER = "q"; + /** + * This header is supposed to be used by application in order to correlate request and response messages. + */ public static final String CORRELATION_ID = "cid"; + /** + * This is a system header which used by transport for serialization and deserialization purpose. It is not supposed + * to be used by application directly and it is subject to changes in future releases. + */ + public static final String DATA_TYPE = "_type"; + private TransportHeaders() { // Do not instantiate } diff --git a/transport/src/main/java/io/servicefabric/transport/protocol/MessageSchema.java b/transport/src/main/java/io/servicefabric/transport/protocol/MessageSchema.java index 249b16b9..299d3888 100644 --- a/transport/src/main/java/io/servicefabric/transport/protocol/MessageSchema.java +++ b/transport/src/main/java/io/servicefabric/transport/protocol/MessageSchema.java @@ -3,6 +3,7 @@ package io.servicefabric.transport.protocol; import static io.protostuff.LinkedBuffer.MIN_BUFFER_SIZE; import static io.servicefabric.transport.utils.RecyclableLinkedBuffer.DEFAULT_MAX_CAPACITY; +import io.servicefabric.transport.TransportHeaders; import io.servicefabric.transport.utils.RecyclableLinkedBuffer; import io.servicefabric.transport.utils.memoization.Computable; import io.servicefabric.transport.utils.memoization.ConcurrentMapMemoizer; @@ -34,15 +35,13 @@ final class MessageSchema implements Schema<Message> { private static final int HEADER_KEYS_FIELD_NUMBER = 1; private static final int HEADER_VALUES_FIELD_NUMBER = 2; - private static final int DATA_PAYLOAD_FIELD_NUMBER = 3; - private static final int DATA_TYPE_FIELD_NUMBER = 4; + private static final int DATA_FIELD_NUMBER = 3; private static final RecyclableLinkedBuffer recyclableLinkedBuffer = new RecyclableLinkedBuffer(MIN_BUFFER_SIZE, DEFAULT_MAX_CAPACITY); private static final Map<String, Integer> fieldMap = ImmutableMap.of("headerKeys", HEADER_KEYS_FIELD_NUMBER, - "headerValues", HEADER_VALUES_FIELD_NUMBER, "dataPayload", DATA_PAYLOAD_FIELD_NUMBER, "dataType", - DATA_TYPE_FIELD_NUMBER); + "headerValues", HEADER_VALUES_FIELD_NUMBER, "data", DATA_FIELD_NUMBER); private final ConcurrentMapMemoizer<String, Optional<Class>> classCache = new ConcurrentMapMemoizer<>( new Computable<String, Optional<Class>>() { @@ -64,10 +63,8 @@ final class MessageSchema implements Schema<Message> { return "headerKeys"; case HEADER_VALUES_FIELD_NUMBER: return "headerValues"; - case DATA_PAYLOAD_FIELD_NUMBER: - return "dataPayload"; - case DATA_TYPE_FIELD_NUMBER: - return "dataType"; + case DATA_FIELD_NUMBER: + return "data"; default: return null; } @@ -109,8 +106,7 @@ final class MessageSchema implements Schema<Message> { boolean iterate = true; List<String> headerKeys = new ArrayList<>(); List<String> headerValues = new ArrayList<>(); - byte[] dataPayload = null; - String dataType = null; + byte[] dataBytes = null; while (iterate) { int number = input.readFieldNumber(this); switch (number) { @@ -123,11 +119,8 @@ final class MessageSchema implements Schema<Message> { case HEADER_VALUES_FIELD_NUMBER: headerValues.add(input.readString()); break; - case DATA_PAYLOAD_FIELD_NUMBER: - dataPayload = input.readByteArray(); - break; - case DATA_TYPE_FIELD_NUMBER: - dataType = input.readString(); + case DATA_FIELD_NUMBER: + dataBytes = input.readByteArray(); break; default: input.handleUnknownField(number, this); @@ -135,38 +128,43 @@ final class MessageSchema implements Schema<Message> { } // Deserialize headers + Map<String, String> headers = new HashMap<>(headerKeys.size()); if (!headerKeys.isEmpty()) { - Map<String, String> headers = new HashMap<>(headerKeys.size()); ListIterator<String> headerValuesIterator = headerValues.listIterator(); for (String key : headerKeys) { String value = headerValuesIterator.next(); headers.put(key, value); } - message.setHeaders(headers); } // Deserialize data - if (dataPayload != null) { + Object data = null; + if (dataBytes != null) { + String dataType = headers.get(TransportHeaders.DATA_TYPE); if (dataType == null) { - message.setData(dataPayload); + data = dataBytes; } else { Optional<Class> optionalDataClass = classCache.get(dataType); if (optionalDataClass.isPresent()) { + headers.remove(TransportHeaders.DATA_TYPE); Class<?> dataClass = optionalDataClass.get(); Schema dataSchema = RuntimeSchema.getSchema(dataClass); - Object data = dataSchema.newMessage(); + data = dataSchema.newMessage(); try { - ProtostuffIOUtil.mergeFrom(dataPayload, data, dataSchema); + ProtostuffIOUtil.mergeFrom(dataBytes, data, dataSchema); } catch (Throwable e) { LOGGER.error("Failed to deserialize : {}", message); throw e; } - message.setData(data); } else { - message.setData(dataPayload); + data = dataBytes; } } } + + // Set message + message.setHeaders(headers); + message.setData(data); } @Override @@ -183,15 +181,20 @@ final class MessageSchema implements Schema<Message> { Object originalData = message.data(); if (originalData != null) { if (originalData instanceof byte[]) { - output.writeByteArray(DATA_PAYLOAD_FIELD_NUMBER, (byte[]) originalData, false); + // Write data byte array as is + output.writeByteArray(DATA_FIELD_NUMBER, (byte[]) originalData, false); } else { + // Write data class as an additional header Class<?> dataClass = originalData.getClass(); + output.writeString(HEADER_KEYS_FIELD_NUMBER, TransportHeaders.DATA_TYPE, true); + output.writeString(HEADER_VALUES_FIELD_NUMBER, dataClass.getName(), true); + + // Write data as serialized byte array Schema dataSchema = RuntimeSchema.getSchema(dataClass); try (RecyclableLinkedBuffer rlb = recyclableLinkedBuffer.get()) { byte[] array = ProtostuffIOUtil.toByteArray(originalData, dataSchema, rlb.buffer()); - output.writeByteArray(DATA_PAYLOAD_FIELD_NUMBER, array, false); + output.writeByteArray(DATA_FIELD_NUMBER, array, false); } - output.writeString(DATA_TYPE_FIELD_NUMBER, dataClass.getName(), false); } } }
['transport/src/main/java/io/servicefabric/transport/TransportHeaders.java', 'transport/src/main/java/io/servicefabric/transport/protocol/MessageSchema.java']
{'.java': 2}
2
2
0
0
2
195,153
41,441
6,064
74
3,166
626
68
2
329
56
68
2
0
0
1970-01-01T00:24:01
581
Java
{'Java': 668288}
Apache License 2.0
667
scalecube/scalecube-services/470/469
scalecube
scalecube-services
https://github.com/scalecube/scalecube-services/issues/469
https://github.com/scalecube/scalecube-services/pull/470
https://github.com/scalecube/scalecube-services/pull/470
1
fix
Client-sdk doesn't support redirecting
When we launch the following example: ```java class Scratch { public static void main(String[] args) throws Exception { Client client = onWebsocket( ClientSettings.builder() .host("develop-ws.aws.com") .port(80) /// 443 .loopResources(LoopResources.create("test")) .build()); client .forService(UserService.class) .find(new FindUserRequest("123")) .subscribe( System.out::println, Throwable::printStackTrace, () -> System.out.println("Complete")); Thread.currentThread().join(); } } ``` it throws: ```c io.netty.handler.codec.http.websocketx.WebSocketHandshakeException: Invalid handshake response getStatus: 301 Moved Permanently at io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker13.verify(WebSocketClientHandshaker13.java:191) at io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker.finishHandshake(WebSocketClientHandshaker.java:216) at reactor.netty.http.client.WebsocketClientOperations.onInboundNext(WebsocketClientOperations.java:109) at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:141) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:102) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438) at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:310) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:284) at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1434) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:965) at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:808) at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:410) at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:310) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884) at java.lang.Thread.run(Thread.java:748) ``` So can we use the client-sdk with redirecting?
d6a5d03afb226d8d132c7fbd77953ba81aec0dd2
8ceb77d7aa7410e8ba55632eacde67bdac29fe54
https://github.com/scalecube/scalecube-services/compare/d6a5d03afb226d8d132c7fbd77953ba81aec0dd2...8ceb77d7aa7410e8ba55632eacde67bdac29fe54
diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientSettings.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientSettings.java index a51df11c..e418c881 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientSettings.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientSettings.java @@ -2,6 +2,7 @@ package io.scalecube.services.gateway.clientsdk; import java.net.InetSocketAddress; import reactor.netty.resources.LoopResources; +import reactor.netty.tcp.SslProvider; public class ClientSettings { @@ -12,12 +13,16 @@ public class ClientSettings { private final int port; private final String contentType; private final LoopResources loopResources; + private final boolean followRedirect; + private final SslProvider sslProvider; private ClientSettings(Builder builder) { this.host = builder.host; this.port = builder.port; this.contentType = builder.contentType; this.loopResources = builder.loopResources; + this.followRedirect = builder.followRedirect; + this.sslProvider = builder.sslProvider; } public String host() { @@ -36,22 +41,29 @@ public class ClientSettings { return loopResources; } + public boolean followRedirect() { + return followRedirect; + } + + public SslProvider sslProvider() { + return sslProvider; + } + public static Builder builder() { return new Builder(); } @Override public String toString() { - return "ClientSettings{" - + "host='" - + host - + '\\'' - + ", port=" - + port - + ", contentType='" - + contentType - + '\\'' - + '}'; + final StringBuilder sb = new StringBuilder("ClientSettings{"); + sb.append("host='").append(host).append('\\''); + sb.append(", port=").append(port); + sb.append(", contentType='").append(contentType).append('\\''); + sb.append(", loopResources=").append(loopResources); + sb.append(", followRedirect=").append(followRedirect); + sb.append(", sslProvider=").append(sslProvider); + sb.append('}'); + return sb.toString(); } public static class Builder { @@ -59,6 +71,8 @@ public class ClientSettings { private int port; private String contentType = DEFAULT_CONTENT_TYPE; private LoopResources loopResources; + private boolean followRedirect = true; + private SslProvider sslProvider; private Builder() {} @@ -86,6 +100,38 @@ public class ClientSettings { return this; } + /** + * Specifies is auto-redirect enabled for HTTP 301/302 status codes. Enabled by default. + * + * @param followRedirect if <code>true</code> auto-redirect is enabled, otherwise disabled + * @return builder + */ + public Builder followRedirect(boolean followRedirect) { + this.followRedirect = followRedirect; + return this; + } + + /** + * Use default SSL client provider. + * + * @return builder + */ + public Builder secure() { + this.sslProvider = SslProvider.defaultClientProvider(); + return this; + } + + /** + * Use specified SSL provider. + * + * @param sslProvider SSL provider + * @return builder + */ + public Builder secure(SslProvider sslProvider) { + this.sslProvider = sslProvider; + return this; + } + public ClientSettings build() { return new ClientSettings(this); } diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/http/HttpClientTransport.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/http/HttpClientTransport.java index f0c2b489..3edaf942 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/http/HttpClientTransport.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/http/HttpClientTransport.java @@ -40,9 +40,14 @@ public final class HttpClientTransport implements ClientTransport { httpClient = HttpClient.create(connectionProvider) + .followRedirect(settings.followRedirect()) .tcpConfiguration( - tcpClient -> - tcpClient.runOn(loopResources).host(settings.host()).port(settings.port())); + tcpClient -> { + if (settings.sslProvider() != null) { + tcpClient = tcpClient.secure(settings.sslProvider()); + } + return tcpClient.runOn(loopResources).host(settings.host()).port(settings.port()); + }); } @Override diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/rsocket/RSocketClientTransport.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/rsocket/RSocketClientTransport.java index bcdd5245..7b5e5f41 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/rsocket/RSocketClientTransport.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/rsocket/RSocketClientTransport.java @@ -139,9 +139,14 @@ public final class RSocketClientTransport implements ClientTransport { HttpClient httpClient = HttpClient.newConnection() + .followRedirect(settings.followRedirect()) .tcpConfiguration( - tcpClient -> - tcpClient.runOn(loopResources).host(settings.host()).port(settings.port())); + tcpClient -> { + if (settings.sslProvider() != null) { + tcpClient = tcpClient.secure(settings.sslProvider()); + } + return tcpClient.runOn(loopResources).host(settings.host()).port(settings.port()); + }); return WebsocketClientTransport.create(httpClient, path); } diff --git a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/websocket/WebsocketClientTransport.java b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/websocket/WebsocketClientTransport.java index 5f5af7fa..471d8e21 100644 --- a/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/websocket/WebsocketClientTransport.java +++ b/services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/websocket/WebsocketClientTransport.java @@ -49,9 +49,14 @@ public final class WebsocketClientTransport implements ClientTransport { httpClient = HttpClient.newConnection() + .followRedirect(settings.followRedirect()) .tcpConfiguration( - tcpClient -> - tcpClient.runOn(loopResources).host(settings.host()).port(settings.port())); + tcpClient -> { + if (settings.sslProvider() != null) { + tcpClient = tcpClient.secure(settings.sslProvider()); + } + return tcpClient.runOn(loopResources).host(settings.host()).port(settings.port()); + }); } @Override
['services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/websocket/WebsocketClientTransport.java', 'services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/rsocket/RSocketClientTransport.java', 'services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/ClientSettings.java', 'services-gateway-clientsdk/src/main/java/io/scalecube/services/gateway/clientsdk/http/HttpClientTransport.java']
{'.java': 4}
4
4
0
0
4
427,576
85,865
13,611
183
3,402
646
93
4
3,647
117
699
60
0
2
1970-01-01T00:25:44
581
Java
{'Java': 668288}
Apache License 2.0
1,323
polyhedraldev/terra/158/140
polyhedraldev
terra
https://github.com/PolyhedralDev/Terra/issues/140
https://github.com/PolyhedralDev/Terra/pull/158
https://github.com/PolyhedralDev/Terra/pull/158
1
closes
Eyes of ender do not work
When generating a terra world (fabric), if you use eyes of ender to try to find a stronghold, they cannot find one. This is with a vanilla world on the terra default config and the only 3 mods installed are terra, terra fabric server, and fabric api.
dbc60b1d8254eefedf626c4e6fc229ffe3fd0bb6
77a4c95c4a4f1f2f13bcfab75bee6d50403222dd
https://github.com/polyhedraldev/terra/compare/dbc60b1d8254eefedf626c4e6fc229ffe3fd0bb6...77a4c95c4a4f1f2f13bcfab75bee6d50403222dd
diff --git a/platforms/fabric/src/main/java/com/dfsek/terra/fabric/generation/FabricChunkGeneratorWrapper.java b/platforms/fabric/src/main/java/com/dfsek/terra/fabric/generation/FabricChunkGeneratorWrapper.java index 2a78c36f8..efac7ee53 100644 --- a/platforms/fabric/src/main/java/com/dfsek/terra/fabric/generation/FabricChunkGeneratorWrapper.java +++ b/platforms/fabric/src/main/java/com/dfsek/terra/fabric/generation/FabricChunkGeneratorWrapper.java @@ -5,19 +5,25 @@ import com.dfsek.terra.api.platform.world.generator.ChunkData; import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper; import com.dfsek.terra.api.util.FastRandom; import com.dfsek.terra.api.world.generation.TerraChunkGenerator; +import com.dfsek.terra.api.world.locate.AsyncStructureFinder; import com.dfsek.terra.config.pack.ConfigPack; +import com.dfsek.terra.fabric.FabricAdapter; import com.dfsek.terra.fabric.TerraFabricPlugin; import com.dfsek.terra.world.TerraWorld; import com.dfsek.terra.world.generation.generators.DefaultChunkGenerator3D; import com.dfsek.terra.world.generation.math.samplers.Sampler; +import com.dfsek.terra.world.population.items.TerraStructure; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.jafama.FastMath; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; +import net.minecraft.server.world.ServerWorld; import net.minecraft.structure.StructureManager; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.registry.DynamicRegistryManager; +import net.minecraft.util.registry.Registry; import net.minecraft.world.BlockView; import net.minecraft.world.ChunkRegion; import net.minecraft.world.Heightmap; @@ -29,6 +35,12 @@ import net.minecraft.world.gen.StructureAccessor; import net.minecraft.world.gen.chunk.ChunkGenerator; import net.minecraft.world.gen.chunk.StructuresConfig; import net.minecraft.world.gen.chunk.VerticalBlockSample; +import net.minecraft.world.gen.feature.StructureFeature; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; public class FabricChunkGeneratorWrapper extends ChunkGenerator implements GeneratorWrapper { private final long seed; @@ -75,6 +87,28 @@ public class FabricChunkGeneratorWrapper extends ChunkGenerator implements Gener } + @Nullable + @Override + public BlockPos locateStructure(ServerWorld world, StructureFeature<?> feature, BlockPos center, int radius, boolean skipExistingChunks) { + String name = Objects.requireNonNull(Registry.STRUCTURE_FEATURE.getId(feature)).toString(); + TerraWorld terraWorld = TerraFabricPlugin.getInstance().getWorld((World) world); + TerraStructure located = pack.getStructure(pack.getTemplate().getLocatable().get(name)); + if(located != null) { + CompletableFuture<BlockPos> result = new CompletableFuture<>(); + AsyncStructureFinder finder = new AsyncStructureFinder(terraWorld.getBiomeProvider(), located, FabricAdapter.adapt(center).toLocation((World) world), 0, 500, location -> { + result.complete(FabricAdapter.adapt(location)); + }, TerraFabricPlugin.getInstance()); + finder.run(); // Do this synchronously. + try { + return result.get(); + } catch(InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + } + TerraFabricPlugin.getInstance().logger().warning("No overrides are defined for \\"" + name + "\\""); + return null; + } + @Override public void generateFeatures(ChunkRegion region, StructureAccessor accessor) { super.generateFeatures(region, accessor);
['platforms/fabric/src/main/java/com/dfsek/terra/fabric/generation/FabricChunkGeneratorWrapper.java']
{'.java': 1}
1
1
0
0
1
1,181,429
267,140
34,758
672
1,797
329
34
1
250
47
56
1
0
0
1970-01-01T00:27:00
558
Java
{'Java': 1687377, 'Kotlin': 54436}
MIT License
1,322
polyhedraldev/terra/379/378
polyhedraldev
terra
https://github.com/PolyhedralDev/Terra/issues/378
https://github.com/PolyhedralDev/Terra/pull/379
https://github.com/PolyhedralDev/Terra/pull/379
1
fixes
[Bug] Bukkit incorrectly names minecraft:end_crystal
Bukkit's Entity enum incorrectly calls `minecraft:end_crystal` `ENDER_CRYSTAL`
75a2dd7b6e443140815b05606841543b06be3238
eb9685c734e42b762a7fb3de89fa2c917a0e7255
https://github.com/polyhedraldev/terra/compare/75a2dd7b6e443140815b05606841543b06be3238...eb9685c734e42b762a7fb3de89fa2c917a0e7255
diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java index 33e2f6708..563a3b66e 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java @@ -52,7 +52,12 @@ public class BukkitWorldHandle implements WorldHandle { @Override public @NotNull EntityType getEntity(@NotNull String id) { if(!id.startsWith("minecraft:")) throw new IllegalArgumentException("Invalid entity identifier " + id); - return new BukkitEntityType(org.bukkit.entity.EntityType.valueOf(id.toUpperCase(Locale.ROOT).substring(10))); + String entityID = id.toUpperCase(Locale.ROOT).substring(10); + + return new BukkitEntityType(switch(entityID) { + case "END_CRYSTAL" -> org.bukkit.entity.EntityType.ENDER_CRYSTAL; + case "ENDER_CRYSTAL" -> throw new IllegalArgumentException("Invalid entity identifier " + id); // make sure this issue can't happen the other way around. + default -> org.bukkit.entity.EntityType.valueOf(entityID); + }); } - }
['platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/handles/BukkitWorldHandle.java']
{'.java': 1}
1
1
0
0
1
1,436,211
314,189
41,140
748
591
119
9
1
82
7
21
3
0
0
1970-01-01T00:27:47
558
Java
{'Java': 1687377, 'Kotlin': 54436}
MIT License
559
greenmail-mail-test/greenmail/78/77
greenmail-mail-test
greenmail
https://github.com/greenmail-mail-test/greenmail/issues/77
https://github.com/greenmail-mail-test/greenmail/pull/78
https://github.com/greenmail-mail-test/greenmail/pull/78
1
fixes
Greenmail SMTP server doesn't handle periods correctly
Per http://tools.ietf.org/html/rfc5321#section-4.5.2 : > ``` > When a line of mail text is received by the SMTP server, it checks > the line. If the line is composed of a single period, it is > treated as the end of mail indicator. If the first character is a > period and there are other characters on the line, the first > character is deleted. > ``` `com.icegreen.greenmail.mail.MovingMessage#readDotTerminatedContent` handles the the case of a line containing a single period, but does not handle the case where a line starts with a period and there are other characters. The end result is mail sent to Greenmail's SMTP server can contain extra periods when retrieved via IMAP or POP3.
11297e2fe73686ac57ed28c0e6a406b14bb2790b
93ef9c391a8c05552f1f69b30ad5d7666aae4ab0
https://github.com/greenmail-mail-test/greenmail/compare/11297e2fe73686ac57ed28c0e6a406b14bb2790b...93ef9c391a8c05552f1f69b30ad5d7666aae4ab0
diff --git a/greenmail-core/src/main/java/com/icegreen/greenmail/mail/MovingMessage.java b/greenmail-core/src/main/java/com/icegreen/greenmail/mail/MovingMessage.java index 03e6a64e..fbbfd15d 100644 --- a/greenmail-core/src/main/java/com/icegreen/greenmail/mail/MovingMessage.java +++ b/greenmail-core/src/main/java/com/icegreen/greenmail/mail/MovingMessage.java @@ -110,6 +110,8 @@ public class MovingMessage { dataWriter.close(); break; + } else if (line.startsWith(".")) { + dataWriter.println(line.substring(1)); } else { dataWriter.println(line); } diff --git a/greenmail-core/src/test/java/com/icegreen/greenmail/test/SmtpServerTest.java b/greenmail-core/src/test/java/com/icegreen/greenmail/test/SmtpServerTest.java index c56b6f79..8a4b89f5 100644 --- a/greenmail-core/src/test/java/com/icegreen/greenmail/test/SmtpServerTest.java +++ b/greenmail-core/src/test/java/com/icegreen/greenmail/test/SmtpServerTest.java @@ -128,4 +128,14 @@ public class SmtpServerTest { assertEquals(i, gif[i]); } } + + @Test + public void testSmtpServerLeadingPeriods() throws MessagingException { + String body = ". body with leading period"; + GreenMailUtil.sendTextEmailTest("to@localhost.com", "from@localhost.com", "subject", body); + MimeMessage[] emails = greenMail.getReceivedMessages(); + assertEquals(1, emails.length); + assertEquals("subject", emails[0].getSubject()); + assertEquals(body, GreenMailUtil.getBody(emails[0])); + } }
['greenmail-core/src/test/java/com/icegreen/greenmail/test/SmtpServerTest.java', 'greenmail-core/src/main/java/com/icegreen/greenmail/mail/MovingMessage.java']
{'.java': 2}
2
2
0
0
2
617,795
135,652
18,356
152
105
20
2
1
700
116
175
14
1
1
1970-01-01T00:23:53
546
Java
{'Java': 954809, 'HTML': 2354, 'Dockerfile': 1625, 'Shell': 161}
Apache License 2.0
1,012
slackapi/java-slack-sdk/412/410
slackapi
java-slack-sdk
https://github.com/slackapi/java-slack-sdk/issues/410
https://github.com/slackapi/java-slack-sdk/pull/412
https://github.com/slackapi/java-slack-sdk/pull/412
2
fix
Hint for a Modal Surface's Input block
### Issue Type Place an `x` in one of the `[ ]`. - [x] Bug - [ ] Enhancement / Feature request - [ ] Question - [ ] Documentation ### Description According to the [Slack Block kit Reference for Layout blocks](https://api.slack.com/reference/block-kit/blocks#input), the Input block available on the **Modals** surface allows to have the optional field **hint** as a **text object** with a type of **plain_text**; however **hint** is defined as a **String** in the **com.slack.api.model.block.InputBlock** class The issue is reproducible in: * Module Version: slack.api.model: 1.0.1 * JDK Version: openjdk version "1.8.0_242" * OS Version etc: Ubuntu 18.04.4 LTS The steps to reproduce are: 1. Define a new [Slack Modal View](https://github.com/slackapi/java-slack-sdk/blob/master/slack-api-model/src/main/java/com/slack/api/model/view/View.java) 2. Add an Input Block with a hint ``` import static com.slack.api.model.block.Blocks.*; import static com.slack.api.model.block.composition.BlockCompositions.*; import static com.slack.api.model.block.element.BlockElements.*; import static com.slack.api.model.view.Views.*; ... view(view -> view .callbackId("slack-view-sample") .type("modal") .notifyOnClose(true) .title(viewTitle(title -> title.type("plain_text").text("Slack View for InputBlock"))) .submit(viewSubmit(submit -> submit.type("plain_text").text("Submit"))) .close(viewClose(close -> close.type("plain_text").text("Cancel"))) .blocks(asBlocks( input(input -> input .blockId("input-block") .element(plainTextInput(pti -> pti.actionId("input-block-field").maxLength(255))) .label(plainText(pt -> pt.text("Input Block"))) .hint("Maximum 255 characters") ) )) ); ``` 3. Add the Slack Modal View to an *App* command and invoke the command in Slack The expected result is: - The Slack Modal shows an input block with a hint The actual results is: - An error is returned when trying to create the Slack Modal Surface `ViewsOpenResponse(ok=false, warning=null, error=invalid_arguments, needed=null, provided=null, view=null, responseMetadata=ErrorResponseMetadata(messages=[[ERROR] failed to match all allowed schemas [json-pointer:/view], [ERROR] must provide an object [json-pointer:/view/blocks/0/hint]]))` ### Requirements (place an `x` in each of the `[ ]`) * [x] I've read and understood the [Contributing guidelines](https://github.com/slackapi/java-slack-sdk/blob/master/.github/contributing.md) and have done my best effort to follow them. * [x] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). * [x] I've searched for any related issues and avoided creating a duplicate issue.
6b77581b87ff390513e6e0d7d8a3b36c9aefb0a9
5c9897e41cbc85369f0dfedb65b5c40ef39cad49
https://github.com/slackapi/java-slack-sdk/compare/6b77581b87ff390513e6e0d7d8a3b36c9aefb0a9...5c9897e41cbc85369f0dfedb65b5c40ef39cad49
diff --git a/slack-api-model/src/main/java/com/slack/api/model/block/InputBlock.java b/slack-api-model/src/main/java/com/slack/api/model/block/InputBlock.java index 8646214f..d6399802 100644 --- a/slack-api-model/src/main/java/com/slack/api/model/block/InputBlock.java +++ b/slack-api-model/src/main/java/com/slack/api/model/block/InputBlock.java @@ -36,7 +36,7 @@ public class InputBlock implements LayoutBlock { * It must be a a text object with a type of plain_text. * Maximum length for the text in this field is 2000 characters. */ - private String hint; + private PlainTextObject hint; /** * A boolean that indicates whether the input element may be empty when a user submits the modal. diff --git a/slack-api-model/src/test/java/test_locally/api/model/block/BlockKitTest.java b/slack-api-model/src/test/java/test_locally/api/model/block/BlockKitTest.java index 0460013d..2beadb74 100644 --- a/slack-api-model/src/test/java/test_locally/api/model/block/BlockKitTest.java +++ b/slack-api-model/src/test/java/test_locally/api/model/block/BlockKitTest.java @@ -28,6 +28,10 @@ public class BlockKitTest { " \\"type\\": \\"plain_text\\",\\n" + " \\"text\\": \\"Label of input\\"\\n" + " },\\n" + + " \\"hint\\": {\\n" + + " \\"type\\": \\"plain_text\\",\\n" + + " \\"text\\": \\"Hint of input\\"\\n" + + " },\\n" + " \\"element\\": {\\n" + " \\"type\\": \\"plain_text_input\\",\\n" + " \\"action_id\\": \\"plain_input\\",\\n" + @@ -42,6 +46,7 @@ public class BlockKitTest { InputBlock inputBlock = (InputBlock) message.getBlocks().get(0); assertThat(inputBlock.getLabel(), is(notNullValue())); assertThat(inputBlock.getElement(), is(notNullValue())); + assertThat(inputBlock.getHint(),is(notNullValue())); } @Test diff --git a/slack-api-model/src/test/java/test_locally/api/model/block/BlocksTest.java b/slack-api-model/src/test/java/test_locally/api/model/block/BlocksTest.java index e0a802c1..c1a098e1 100644 --- a/slack-api-model/src/test/java/test_locally/api/model/block/BlocksTest.java +++ b/slack-api-model/src/test/java/test_locally/api/model/block/BlocksTest.java @@ -242,6 +242,11 @@ public class BlocksTest { " \\"type\\": \\"plain_text\\",\\n" + " \\"text\\": \\"Choose the conversation to publish your result to:\\",\\n" + " \\"emoji\\": true\\n" + + " },\\n" + + " \\"hint\\": {\\n" + + " \\"type\\": \\"plain_text\\",\\n" + + " \\"text\\": \\"Choose the conversation to publish your result to:\\",\\n" + + " \\"emoji\\": true\\n" + " }\\n" + " }\\n" + "]}";
['slack-api-model/src/test/java/test_locally/api/model/block/BlocksTest.java', 'slack-api-model/src/test/java/test_locally/api/model/block/BlockKitTest.java', 'slack-api-model/src/main/java/com/slack/api/model/block/InputBlock.java']
{'.java': 3}
3
3
0
0
3
1,520,921
307,585
45,768
1,081
60
12
2
1
3,003
293
680
57
4
1
1970-01-01T00:26:25
525
Java
{'Java': 5424202, 'Kotlin': 308094, 'Shell': 6494, 'Batchfile': 3120, 'Dockerfile': 253}
MIT License
1,008
slackapi/java-slack-sdk/490/489
slackapi
java-slack-sdk
https://github.com/slackapi/java-slack-sdk/issues/489
https://github.com/slackapi/java-slack-sdk/pull/490
https://github.com/slackapi/java-slack-sdk/pull/490
1
fix
Event type extract does not match correctly if there are "type" properties in JSON subentries.
The current code for extracting event types seems to assume that the "type:" entry that contains the event type is the first type entry in the JSON that follows "event:". However, this is not always the case. E.g. in the following message `{"authed_users":["RETRACTED"],"event_id":"RETRACTED","api_app_id":"RETRACTED","team_id":"RETRACTED","event":{"client_msg_id":"b5ac4998-4526-4d0b-8bb0-7bd614c1b774","blocks":[{"elements":[{"elements":[{"text":"test","type":"text"}],"type":"rich_text_section"}],"type":"rich_text","block_id":"Ws3Y"}],"event_ts":"1592257234.003200","channel":"RETRACTED","text":"test","team":"RETRACTED","type":"message","channel_type":"channel","user":"RETRACTED","ts":"1592257234.003200"},"type":"event_callback","event_time":1592257234,"token":"RETRACTED"}` the `"type": "text"`value of the "blocks" field comes first. The event for that message is detected as "text" even though it would need to be "message" to arrive in the correct event handler. https://github.com/slackapi/java-slack-sdk/blob/a2e96f3582189cbd7e9b0bd5a4504bdba4262ce6/slack-app-backend/src/main/java/com/slack/api/app_backend/events/EventTypeExtractorImpl.java#L23
05f9c5809f1681f05b5702d13f913ecdd2b58f57
fe88a05f25ca93f2c2793003bede5792779f33de
https://github.com/slackapi/java-slack-sdk/compare/05f9c5809f1681f05b5702d13f913ecdd2b58f57...fe88a05f25ca93f2c2793003bede5792779f33de
diff --git a/slack-app-backend/src/main/java/com/slack/api/app_backend/events/EventTypeExtractorImpl.java b/slack-app-backend/src/main/java/com/slack/api/app_backend/events/EventTypeExtractorImpl.java index 10233ad8..d3d586f8 100644 --- a/slack-app-backend/src/main/java/com/slack/api/app_backend/events/EventTypeExtractorImpl.java +++ b/slack-app-backend/src/main/java/com/slack/api/app_backend/events/EventTypeExtractorImpl.java @@ -1,100 +1,39 @@ package com.slack.api.app_backend.events; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import lombok.extern.slf4j.Slf4j; + +@Slf4j public class EventTypeExtractorImpl implements EventTypeExtractor { @Override public String extractEventType(String json) { - StringBuilder sb = new StringBuilder(); - char[] chars = json.toCharArray(); - boolean isInsideEventData = false; - for (int idx = 0; idx < (chars.length - 7); idx++) { - if (!isInsideEventData && chars[idx] == '"' - && chars[idx + 1] == 'e' - && chars[idx + 2] == 'v' - && chars[idx + 3] == 'e' - && chars[idx + 4] == 'n' - && chars[idx + 5] == 't' - && chars[idx + 6] == '"' - && chars[idx + 7] == ':') { - idx = idx + 8; - isInsideEventData = true; - } - - if (isInsideEventData && chars[idx] == '"' - && chars[idx + 1] == 't' - && chars[idx + 2] == 'y' - && chars[idx + 3] == 'p' - && chars[idx + 4] == 'e' - && chars[idx + 5] == '"' - && chars[idx + 6] == ':') { - idx = idx + 7; - int doubleQuoteCount = 0; - boolean isPreviousCharEscape = false; - while (doubleQuoteCount < 2 && idx < chars.length) { - char c = chars[idx]; - if (c == '"' && !isPreviousCharEscape) { - doubleQuoteCount++; - } else { - if (doubleQuoteCount == 1) { - sb.append(c); - } - } - isPreviousCharEscape = c == '\\\\'; - idx++; - } - break; - } - } - return sb.toString(); + return extractFieldUnderEvent(json, "type"); } @Override public String extractEventSubtype(String json) { - StringBuilder sb = new StringBuilder(); - char[] chars = json.toCharArray(); - boolean isInsideEventData = false; - for (int idx = 0; idx < (chars.length - 7); idx++) { - if (!isInsideEventData && chars[idx] == '"' - && chars[idx + 1] == 'e' - && chars[idx + 2] == 'v' - && chars[idx + 3] == 'e' - && chars[idx + 4] == 'n' - && chars[idx + 5] == 't' - && chars[idx + 6] == '"' - && chars[idx + 7] == ':') { - idx = idx + 8; - isInsideEventData = true; - } + return extractFieldUnderEvent(json, "subtype"); + } - if (isInsideEventData && chars[idx] == '"' - && chars[idx + 1] == 's' - && chars[idx + 2] == 'u' - && chars[idx + 3] == 'b' - && chars[idx + 4] == 't' - && chars[idx + 5] == 'y' - && chars[idx + 6] == 'p' - && chars[idx + 7] == 'e' - && chars[idx + 8] == '"' - && chars[idx + 9] == ':') { - idx = idx + 10; - int doubleQuoteCount = 0; - boolean isPreviousCharEscape = false; - while (doubleQuoteCount < 2 && idx < chars.length) { - char c = chars[idx]; - if (c == '"' && !isPreviousCharEscape) { - doubleQuoteCount++; - } else { - if (doubleQuoteCount == 1) { - sb.append(c); - } + private static String extractFieldUnderEvent(String json, String fieldName) { + try { + JsonElement root = JsonParser.parseString(json); + if (root != null && root.isJsonObject() && root.getAsJsonObject().has("event")) { + JsonElement event = root.getAsJsonObject().get("event"); + if (event.isJsonObject() && event.getAsJsonObject().has(fieldName)) { + JsonElement eventType = event.getAsJsonObject().get(fieldName); + if (eventType.isJsonPrimitive()) { + return eventType.getAsString(); } - isPreviousCharEscape = c == '\\\\'; - idx++; } - break; } + } catch (JsonSyntaxException e) { + log.debug("Failed to parse {} as a JSON data", json, e); } - return sb.toString(); + return ""; } } diff --git a/slack-app-backend/src/test/java/test_locally/app_backend/events/EventTypeDetectorImplTest.java b/slack-app-backend/src/test/java/test_locally/app_backend/events/EventTypeDetectorImplTest.java index d7f36362..73f21d2e 100644 --- a/slack-app-backend/src/test/java/test_locally/app_backend/events/EventTypeDetectorImplTest.java +++ b/slack-app-backend/src/test/java/test_locally/app_backend/events/EventTypeDetectorImplTest.java @@ -11,6 +11,26 @@ public class EventTypeDetectorImplTest { private EventTypeExtractor eventTypeExtractor = new EventTypeExtractorImpl(); + @Test + public void notFound() { + { + String eventType = eventTypeExtractor.extractEventType("{}"); + assertThat(eventType, is("")); + } + { + String eventType = eventTypeExtractor.extractEventType("{\\"event\\": {}}"); + assertThat(eventType, is("")); + } + { + String eventType = eventTypeExtractor.extractEventSubtype("{}"); + assertThat(eventType, is("")); + } + { + String eventType = eventTypeExtractor.extractEventSubtype("{\\"event\\": {}}"); + assertThat(eventType, is("")); + } + } + @Test public void detect_goodbye() { String payload = "{\\n" + @@ -54,4 +74,49 @@ public class EventTypeDetectorImplTest { assertThat(eventType, is("message")); } + @Test + public void issue_489() { + String payload = "{\\n" + + " \\"authed_users\\": [\\n" + + " \\"RETRACTED\\"\\n" + + " ],\\n" + + " \\"event_id\\": \\"RETRACTED\\",\\n" + + " \\"api_app_id\\": \\"RETRACTED\\",\\n" + + " \\"team_id\\": \\"RETRACTED\\",\\n" + + " \\"event\\": {\\n" + + " \\"client_msg_id\\": \\"b5ac4998-4526-4d0b-8bb0-7bd614c1b774\\",\\n" + + " \\"blocks\\": [\\n" + + " {\\n" + + " \\"elements\\": [\\n" + + " {\\n" + + " \\"elements\\": [\\n" + + " {\\n" + + " \\"text\\": \\"test\\",\\n" + + " \\"type\\": \\"text\\"\\n" + + " }\\n" + + " ],\\n" + + " \\"type\\": \\"rich_text_section\\"\\n" + + " }\\n" + + " ],\\n" + + " \\"type\\": \\"rich_text\\",\\n" + + " \\"block_id\\": \\"Ws3Y\\"\\n" + + " }\\n" + + " ],\\n" + + " \\"event_ts\\": \\"1592257234.003200\\",\\n" + + " \\"channel\\": \\"RETRACTED\\",\\n" + + " \\"text\\": \\"test\\",\\n" + + " \\"team\\": \\"RETRACTED\\",\\n" + + " \\"type\\": \\"message\\",\\n" + + " \\"channel_type\\": \\"channel\\",\\n" + + " \\"user\\": \\"RETRACTED\\",\\n" + + " \\"ts\\": \\"1592257234.003200\\"\\n" + + " },\\n" + + " \\"type\\": \\"event_callback\\",\\n" + + " \\"event_time\\": 1592257234,\\n" + + " \\"token\\": \\"RETRACTED\\"\\n" + + "}"; + String eventType = eventTypeExtractor.extractEventType(payload); + assertThat(eventType, is("message")); + } + }
['slack-app-backend/src/main/java/com/slack/api/app_backend/events/EventTypeExtractorImpl.java', 'slack-app-backend/src/test/java/test_locally/app_backend/events/EventTypeDetectorImplTest.java']
{'.java': 2}
2
2
0
0
2
1,587,688
320,775
47,509
1,114
4,530
944
103
1
1,166
77
327
5
1
0
1970-01-01T00:26:32
525
Java
{'Java': 5424202, 'Kotlin': 308094, 'Shell': 6494, 'Batchfile': 3120, 'Dockerfile': 253}
MIT License
1,009
slackapi/java-slack-sdk/475/474
slackapi
java-slack-sdk
https://github.com/slackapi/java-slack-sdk/issues/474
https://github.com/slackapi/java-slack-sdk/pull/475
https://github.com/slackapi/java-slack-sdk/pull/475
1
fix
MethodsClientImpl oauthV2Access: redirect_uri should be optional
### Issue Type [ x ] Bug [ ] Enhancement / Feature request [ ] Question [ ] Documentation ### Description Hi @seratch ! I'm seeing this error when sending a null `redirect_uri` in `OauthV2AccessRequestBuilder`: ``` java.lang.IllegalArgumentException: Parameter specified as non-null is null: method okhttp3.FormBody$Builder.add, parameter value ``` It seems OKHTTP's form builder specifies that all param values must be non-null. I think simply wrapping [this line](https://github.com/slackapi/java-slack-sdk/blob/master/slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java#L1698) in `MethodsClientImpl` with a null check should suffice: ``` if (req.getRedirectUri() != null) { form.add("redirect_uri", req.getRedirectUri()); } ``` Filing this as a bug due to a mismatch between [Slack's Oauth V2 api documentation](https://api.slack.com/methods/oauth.v2.access), which specifies `redirect_uri` as optional. I should mention that I previously was using a hand-cooked Slack API client and Oauth worked fine without `redirect_uri`. The issue is reproducible in: * Module Version: 1.0.7 * JDK Version: Zulu 1.8.0_232 The steps to reproduce are: 1. Use the following sample (Kotlin) code with a valid `code`, `clientId`, and `clientSecret` (do not set `redirect_uri`): ``` val builder = OAuthV2AccessRequest.builder() .code(code) .clientId(clientId) .clientSecret(clientSecret) val response = methods.oauthV2Access(builder.build()) ``` 2. The expected result is the request should succeed. 3. The actual result is the following exception from OKHTTP: ``` java.lang.IllegalArgumentException: Parameter specified as non-null is null: method okhttp3.FormBody$Builder.add, parameter value at okhttp3.FormBody$Builder.add(FormBody.kt) ~[okhttp-4.6.0.jar!/:na] at com.slack.api.methods.impl.MethodsClientImpl.oauthV2Access(MethodsClientImpl.java:1638) ~[slack-api-client-1.0.7.jar!/:1.0.7] ``` Thank you for your amazing work! * [ x ] I've read and understood the [Contributing guidelines](https://github.com/slackapi/java-slack-sdk/blob/master/.github/contributing.md) and have done my best effort to follow them. * [ x ] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). * [ x ] I've searched for any related issues and avoided creating a duplicate issue.
432fbab2bbee68fbc88a90b0655d3e32b4785849
41a2e7ec6b7d29e414d607643fdf13eec243a001
https://github.com/slackapi/java-slack-sdk/compare/432fbab2bbee68fbc88a90b0655d3e32b4785849...41a2e7ec6b7d29e414d607643fdf13eec243a001
diff --git a/slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java b/slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java index 5ba4851d..f8430ce0 100644 --- a/slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java +++ b/slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java @@ -1680,7 +1680,9 @@ public class MethodsClientImpl implements MethodsClient { public OAuthAccessResponse oauthAccess(OAuthAccessRequest req) throws IOException, SlackApiException { FormBody.Builder form = new FormBody.Builder(); form.add("code", req.getCode()); - form.add("redirect_uri", req.getRedirectUri()); + if (req.getRedirectUri() != null) { + form.add("redirect_uri", req.getRedirectUri()); + } form.add("single_channel", req.isSingleChannel() ? "1" : "0"); String authorizationHeader = Credentials.basic(req.getClientId(), req.getClientSecret()); return postFormWithAuthorizationHeaderAndParseResponse(form, endpointUrlPrefix + Methods.OAUTH_ACCESS, authorizationHeader, OAuthAccessResponse.class); @@ -1695,7 +1697,9 @@ public class MethodsClientImpl implements MethodsClient { public OAuthV2AccessResponse oauthV2Access(OAuthV2AccessRequest req) throws IOException, SlackApiException { FormBody.Builder form = new FormBody.Builder(); form.add("code", req.getCode()); - form.add("redirect_uri", req.getRedirectUri()); + if (req.getRedirectUri() != null) { + form.add("redirect_uri", req.getRedirectUri()); + } String authorizationHeader = Credentials.basic(req.getClientId(), req.getClientSecret()); return postFormWithAuthorizationHeaderAndParseResponse(form, endpointUrlPrefix + Methods.OAUTH_V2_ACCESS, authorizationHeader, OAuthV2AccessResponse.class); } diff --git a/slack-api-client/src/test/java/test_locally/api/methods/OAuthTest.java b/slack-api-client/src/test/java/test_locally/api/methods/OAuthTest.java index 33789709..0b0a2316 100644 --- a/slack-api-client/src/test/java/test_locally/api/methods/OAuthTest.java +++ b/slack-api-client/src/test/java/test_locally/api/methods/OAuthTest.java @@ -41,6 +41,13 @@ public class OAuthTest { .isOk(), is(true)); } + @Test + public void issue_474() throws Exception { + assertThat(slack.methods(ValidToken).oauthAccess(r -> r.clientId("abc").clientSecret("xyz").code("xxx")).isOk(), is(true)); + assertThat(slack.methods(ValidToken).oauthToken(r -> r.clientId("abc").clientSecret("xyz").code("xxx")).isOk(), is(true)); + assertThat(slack.methods(ValidToken).oauthV2Access(r -> r.clientId("abc").clientSecret("xyz").code("xxx")).isOk(), is(true)); + } + @Test public void test_async() throws Exception { assertThat(slack.methodsAsync(ValidToken).oauthAccess(r ->
['slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java', 'slack-api-client/src/test/java/test_locally/api/methods/OAuthTest.java']
{'.java': 2}
2
2
0
0
2
1,566,719
316,821
47,067
1,107
347
76
8
1
2,446
267
604
60
4
4
1970-01-01T00:26:30
525
Java
{'Java': 5424202, 'Kotlin': 308094, 'Shell': 6494, 'Batchfile': 3120, 'Dockerfile': 253}
MIT License
1,010
slackapi/java-slack-sdk/427/426
slackapi
java-slack-sdk
https://github.com/slackapi/java-slack-sdk/issues/426
https://github.com/slackapi/java-slack-sdk/pull/427
https://github.com/slackapi/java-slack-sdk/pull/427
2
fix
url_verification request fails with bolt-micronaut
Trying to setup the Event API on the Slack App website and setting up the Event callback URL, seems Bolt is not able to parse the `UrlVerificationRequest` properly. I'm running Java 9 (through Kotlin), with Bolt 1.0.4 on Windows 10 ``` [pool-1-thread-2] WARN com.slack.api.bolt.util.SlackRequestParser - No request pattern detected for token=[some_token]&challenge=2dasp7C5rbnT22y2v3IAT95S6WnNUtdpnFckQEQyGl7HjnTa0Y0K&type=url_verification [pool-1-thread-2] DEBUG io.micronaut.http.server.netty.RoutingInBoundHandler - Encoding emitted response object [Invalid Request] using codec: io.micronaut.runtime.http.codec.TextPlainCodec@28561ca6 ```
137ab4d2a21954d828428d0674a1af822e0d4c4f
6386b1dc4b0fb8d0b4c473fea59e3e496fb39611
https://github.com/slackapi/java-slack-sdk/compare/137ab4d2a21954d828428d0674a1af822e0d4c4f...6386b1dc4b0fb8d0b4c473fea59e3e496fb39611
diff --git a/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppController.java b/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppController.java index 7a2ab34a..287f098b 100644 --- a/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppController.java +++ b/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppController.java @@ -9,8 +9,6 @@ import io.micronaut.http.annotation.Body; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Post; -import java.util.LinkedHashMap; - /** * The default Web controller that works in Micronaut apps. * This component requires singleton {@link App} instance managed by the Micronaut DI container. @@ -30,7 +28,7 @@ public class SlackAppController { } @Post(value = "/events", consumes = {MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON}) - public HttpResponse<String> dispatch(HttpRequest<String> request, @Body LinkedHashMap<String, String> body) throws Exception { + public HttpResponse<String> dispatch(HttpRequest<String> request, @Body String body) throws Exception { Request<?> slackRequest = adapter.toSlackRequest(request, body); return adapter.toMicronautResponse(slackApp.run(slackRequest)); } diff --git a/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppMicronautAdapter.java b/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppMicronautAdapter.java index 3755bf72..fc5d58b8 100644 --- a/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppMicronautAdapter.java +++ b/bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppMicronautAdapter.java @@ -13,14 +13,10 @@ import io.micronaut.http.server.netty.NettyHttpResponseFactory; import lombok.extern.slf4j.Slf4j; import javax.inject.Singleton; -import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; -import java.net.URLEncoder; import java.util.Collections; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; /** * The default adaptor that translates Micronaut specific interfaces into Bolt's ones. @@ -36,16 +32,7 @@ public class SlackAppMicronautAdapter { this.requestParser = new SlackRequestParser(appConfig); } - public Request<?> toSlackRequest(HttpRequest<?> req, LinkedHashMap<String, String> body) { - String requestBody = body.entrySet().stream().map(e -> { - try { - String k = URLEncoder.encode(e.getKey(), "UTF-8"); - String v = URLEncoder.encode(e.getValue(), "UTF-8"); - return k + "=" + v; - } catch (UnsupportedEncodingException ex) { - return e.getKey() + "=" + e.getValue(); - } - }).collect(Collectors.joining("&")); + public Request<?> toSlackRequest(HttpRequest<?> req, String requestBody) { RequestHeaders headers = new RequestHeaders( req.getHeaders() != null ? req.getHeaders().asMap() : Collections.emptyMap()); diff --git a/bolt-micronaut/src/test/java/example/app/AppFactory.java b/bolt-micronaut/src/test/java/example/app/AppFactory.java index ded24300..c37fe358 100644 --- a/bolt-micronaut/src/test/java/example/app/AppFactory.java +++ b/bolt-micronaut/src/test/java/example/app/AppFactory.java @@ -1,10 +1,10 @@ package example.app; -import com.slack.api.bolt.App; -import com.slack.api.bolt.AppConfig; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.slack.api.bolt.App; +import com.slack.api.bolt.AppConfig; import io.micronaut.context.annotation.Factory; import javax.inject.Singleton; diff --git a/bolt-micronaut/src/test/java/test_locally/AdapterTest.java b/bolt-micronaut/src/test/java/test_locally/AdapterTest.java index b790eff2..2df7fbe1 100644 --- a/bolt-micronaut/src/test/java/test_locally/AdapterTest.java +++ b/bolt-micronaut/src/test/java/test_locally/AdapterTest.java @@ -7,15 +7,16 @@ import com.slack.api.bolt.response.Response; import io.micronaut.core.convert.DefaultConversionService; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; -import io.micronaut.http.MediaType; import io.micronaut.http.simple.SimpleHttpHeaders; import io.micronaut.http.simple.SimpleHttpParameters; import org.junit.Test; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -39,11 +40,7 @@ public class AdapterTest { SimpleHttpParameters parameters = new SimpleHttpParameters(params, new DefaultConversionService()); when(req.getParameters()).thenReturn(parameters); - LinkedHashMap<String, String> body = new LinkedHashMap<>(); - body.put("token", "random"); - body.put("ssl_check", "1"); - - Request<?> slackRequest = adapter.toSlackRequest(req, body); + Request<?> slackRequest = adapter.toSlackRequest(req, "token=random&ssl_check=1"); assertNotNull(slackRequest); assertEquals("token=random&ssl_check=1", slackRequest.getRequestBodyAsString()); @@ -61,11 +58,7 @@ public class AdapterTest { InetSocketAddress isa = new InetSocketAddress("localhost", 443); when(req.getRemoteAddress()).thenReturn(isa); - LinkedHashMap<String, String> body = new LinkedHashMap<>(); - body.put("token", "random"); - body.put("ssl_check", "1"); - - Request<?> slackRequest = adapter.toSlackRequest(req, body); + Request<?> slackRequest = adapter.toSlackRequest(req, "token=random&ssl_check=1"); assertNotNull(slackRequest); assertEquals("127.0.0.1", slackRequest.getClientIpAddress()); diff --git a/bolt-micronaut/src/test/java/test_locally/ControllerTest.java b/bolt-micronaut/src/test/java/test_locally/ControllerTest.java index e76a74c6..06a730ab 100644 --- a/bolt-micronaut/src/test/java/test_locally/ControllerTest.java +++ b/bolt-micronaut/src/test/java/test_locally/ControllerTest.java @@ -12,7 +12,6 @@ import io.micronaut.http.simple.SimpleHttpParameters; import org.junit.Test; import java.util.HashMap; -import java.util.LinkedHashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -33,11 +32,7 @@ public class ControllerTest { SimpleHttpParameters parameters = new SimpleHttpParameters(new HashMap<>(), new DefaultConversionService()); when(req.getParameters()).thenReturn(parameters); - LinkedHashMap<String, String> body = new LinkedHashMap<>(); - body.put("token", "random"); - body.put("ssl_check", "1"); - - HttpResponse<String> response = controller.dispatch(req, body); + HttpResponse<String> response = controller.dispatch(req, "token=random&ssl_check=1"); assertEquals(200, response.getStatus().getCode()); } diff --git a/bolt-micronaut/src/test/java/test_locally/app/CommandsTest.java b/bolt-micronaut/src/test/java/test_locally/app/CommandsTest.java index b028812a..3ac8dc1e 100644 --- a/bolt-micronaut/src/test/java/test_locally/app/CommandsTest.java +++ b/bolt-micronaut/src/test/java/test_locally/app/CommandsTest.java @@ -1,12 +1,12 @@ package test_locally.app; -import com.slack.api.Slack; import com.slack.api.RequestConfigurator; +import com.slack.api.Slack; +import com.slack.api.app_backend.SlackSignature; +import com.slack.api.bolt.AppConfig; import com.slack.api.methods.MethodsClient; import com.slack.api.methods.SlackApiException; import com.slack.api.methods.response.auth.AuthTestResponse; -import com.slack.api.app_backend.SlackSignature; -import com.slack.api.bolt.AppConfig; import io.micronaut.context.annotation.Primary; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse;
['bolt-micronaut/src/test/java/example/app/AppFactory.java', 'bolt-micronaut/src/test/java/test_locally/app/CommandsTest.java', 'bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppMicronautAdapter.java', 'bolt-micronaut/src/main/java/com/slack/api/bolt/micronaut/SlackAppController.java', 'bolt-micronaut/src/test/java/test_locally/ControllerTest.java', 'bolt-micronaut/src/test/java/test_locally/AdapterTest.java']
{'.java': 6}
6
6
0
0
6
1,521,645
307,707
45,788
1,081
1,030
196
19
2
651
65
187
8
0
1
1970-01-01T00:26:26
525
Java
{'Java': 5424202, 'Kotlin': 308094, 'Shell': 6494, 'Batchfile': 3120, 'Dockerfile': 253}
MIT License
1,014
slackapi/java-slack-sdk/407/406
slackapi
java-slack-sdk
https://github.com/slackapi/java-slack-sdk/issues/406
https://github.com/slackapi/java-slack-sdk/pull/407
https://github.com/slackapi/java-slack-sdk/pull/407
1
fixes
Code breaks on receiving "user_change" event
### Issue Type - [x] Bug - [ ] Enhancement / Feature request - [ ] Question - [ ] Documentation ### Description When user_change event is sent, the code breaks with the following exception ``` java.lang.UnsupportedOperationException: JsonObject at com.google.gson.JsonElement.getAsString(JsonElement.java:179) at com.slack.api.bolt.middleware.builtin.IgnoringSelfEvents.apply(IgnoringSelfEvents.java:79) ``` This happens because code expects `user` to contain string but it contained jsonObject ``` { "token": ".....", "team_id": ".....", "enterprise_id": "....", "api_app_id": "....", "event": { "type": "user_change", "user": { "id": "....", "name": "gaurav", ...... } ``` --- The issue is reproducible in: * Module Version: 1.0.0 * JDK Version: 1.8.0_231 The steps to reproduce are: 1. subscribe to user_change event 2. Change any field to produce webhook The expected result is: Event to get handled The actual result is: exception is thrown --- * [x] I've read and understood the [Contributing guidelines](https://github.com/slackapi/java-slack-sdk/blob/master/.github/contributing.md) and have done my best effort to follow them. * [x] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). * [x] I've searched for any related issues and avoided creating a duplicate issue.
aca7d1aca1c1a89de155f62b38dd3161892bb76e
13a245ea604ce3131f03a629e5792306b1221043
https://github.com/slackapi/java-slack-sdk/compare/aca7d1aca1c1a89de155f62b38dd3161892bb76e...13a245ea604ce3131f03a629e5792306b1221043
diff --git a/bolt/src/main/java/com/slack/api/bolt/middleware/builtin/IgnoringSelfEvents.java b/bolt/src/main/java/com/slack/api/bolt/middleware/builtin/IgnoringSelfEvents.java index 5e77cf63..8067ed55 100644 --- a/bolt/src/main/java/com/slack/api/bolt/middleware/builtin/IgnoringSelfEvents.java +++ b/bolt/src/main/java/com/slack/api/bolt/middleware/builtin/IgnoringSelfEvents.java @@ -1,5 +1,13 @@ package com.slack.api.bolt.middleware.builtin; +import lombok.extern.slf4j.Slf4j; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -16,13 +24,6 @@ import com.slack.api.methods.response.bots.BotsInfoResponse; import com.slack.api.model.event.MemberJoinedChannelEvent; import com.slack.api.model.event.MemberLeftChannelEvent; import com.slack.api.util.json.GsonFactory; -import lombok.extern.slf4j.Slf4j; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; /** * Filters some events that may be generated by this app for Events API. @@ -75,7 +76,14 @@ public class IgnoringSelfEvents implements Middleware { JsonObject eventElem = extractEventElem(eventRequest.getRequestBodyAsString()); if (eventElem != null) { JsonElement eventUserIdElem = eventElem.get("user"); - String eventBotUserId = eventUserIdElem != null ? eventUserIdElem.getAsString() : null; + String eventBotUserId = null; + if (eventUserIdElem != null) { + if (eventUserIdElem.isJsonObject()) { + eventBotUserId = eventUserIdElem.getAsJsonObject().get("id").getAsString(); + } else { + eventBotUserId = eventUserIdElem.getAsString(); + } + } JsonElement botIdElem = eventElem.get("bot_id"); if (eventBotUserId == null && botIdElem != null) { String botId = botIdElem.getAsString(); diff --git a/bolt/src/test/java/test_locally/middleware/IgnoringSelfEventsTest.java b/bolt/src/test/java/test_locally/middleware/IgnoringSelfEventsTest.java index 8d3f4380..e375f776 100644 --- a/bolt/src/test/java/test_locally/middleware/IgnoringSelfEventsTest.java +++ b/bolt/src/test/java/test_locally/middleware/IgnoringSelfEventsTest.java @@ -1,29 +1,36 @@ package test_locally.middleware; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static util.MockSlackApi.InvalidToken; +import static util.MockSlackApi.ValidToken; + +import util.MockSlackApiServer; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + import com.slack.api.Slack; import com.slack.api.SlackConfig; import com.slack.api.app_backend.events.payload.MemberJoinedChannelPayload; import com.slack.api.app_backend.events.payload.MessagePayload; +import com.slack.api.app_backend.events.payload.UserChangePayload; import com.slack.api.bolt.middleware.MiddlewareChain; import com.slack.api.bolt.middleware.builtin.IgnoringSelfEvents; import com.slack.api.bolt.request.RequestHeaders; import com.slack.api.bolt.request.builtin.EventRequest; import com.slack.api.bolt.response.Response; import com.slack.api.methods.MethodsClient; +import com.slack.api.model.User; import com.slack.api.model.event.MemberJoinedChannelEvent; import com.slack.api.model.event.MessageEvent; +import com.slack.api.model.event.UserChangeEvent; import com.slack.api.util.json.GsonFactory; -import org.junit.Test; -import util.MockSlackApiServer; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.*; -import static util.MockSlackApi.InvalidToken; -import static util.MockSlackApi.ValidToken; public class IgnoringSelfEventsTest { @@ -77,6 +84,30 @@ public class IgnoringSelfEventsTest { assertEquals(404L, result.getStatusCode().longValue()); } + @Test + public void ignored_withUserObject() throws Exception { + IgnoringSelfEvents middleware = new IgnoringSelfEvents(SlackConfig.DEFAULT) { + @Override + public String findAndSaveBotUserId(MethodsClient client, String botId) { + return "U123BOT"; + } + }; + Map<String, List<String>> rawHeaders = new HashMap<>(); + RequestHeaders headers = new RequestHeaders(rawHeaders); + UserChangePayload payload = new UserChangePayload(); + payload.setTeamId("T123"); + UserChangeEvent event = new UserChangeEvent(); + User user = new User(); + user.setId("U123BOT"); + event.setUser(user); + payload.setEvent(event); + EventRequest req = new EventRequest(GsonFactory.createSnakeCase().toJson(payload), headers); + req.getContext().setBotUserId("U123BOT"); + Response resp = new Response(); + Response result = middleware.apply(req, resp, chain); + assertEquals(200L, result.getStatusCode().longValue()); + } + @Test public void not_ignored_no_botUserId() throws Exception { IgnoringSelfEvents middleware = new IgnoringSelfEvents(SlackConfig.DEFAULT) {
['bolt/src/test/java/test_locally/middleware/IgnoringSelfEventsTest.java', 'bolt/src/main/java/com/slack/api/bolt/middleware/builtin/IgnoringSelfEvents.java']
{'.java': 2}
2
2
0
0
2
1,520,359
307,494
45,752
1,081
928
164
24
1
1,444
169
353
56
2
2
1970-01-01T00:26:24
525
Java
{'Java': 5424202, 'Kotlin': 308094, 'Shell': 6494, 'Batchfile': 3120, 'Dockerfile': 253}
MIT License
1,015
slackapi/java-slack-sdk/360/359
slackapi
java-slack-sdk
https://github.com/slackapi/java-slack-sdk/issues/359
https://github.com/slackapi/java-slack-sdk/pull/360
https://github.com/slackapi/java-slack-sdk/pull/360
1
fix
Undefined signing secret causes NullPointerException
### Issue Type - [x] Bug - [ ] Enhancement / Feature request - [ ] Question - [ ] Documentation ### Description Failing to provide a `SLACK_SECRET` to `SlackSignature.Generator`'s constructor causes a `NullPointerException` when calling the resulting `Generator`'s `generate()` method. --- The issue is reproducible in: JSlack version: `3.4.1` OS: `OSX 10.15.3` (though this shouldn't matter) Repro steps: 1) First, initialize a `SlackSignature.Generator` object **without a signing secret**: ```java SlackSignature.Generator gen = new SlackSignature.Generator() ``` 2) Attempt to generate a message's signature: ```java gen.generate("1970-01-01T00:00:00Z", "{}") ``` The expected result is: An `Exception` warning that `SLACK_SECRET` is not defined The actual result is: A `NullPointerException` on [line 87 of `SlackSignature.java`](https://github.com/slackapi/java-slack-sdk/blob/8e8ef794e7033e1340aa86abd8acdb2dee5d704d/slack-app-backend/src/main/java/com/slack/api/app_backend/SlackSignature.java#L87). ### Requirements (place an `x` in each of the `[ ]`) * [x] I've read and understood the [Contributing guidelines](https://github.com/slackapi/java-slack-sdk/blob/master/.github/contributing.md) and have done my best effort to follow them. * [x] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). * [x] I've searched for any related issues and avoided creating a duplicate issue.
e49be394f9270f72cb0d22d3d0cf800930642199
6246fa0cbaeb2571b677efe271d47f0e75bd35b6
https://github.com/slackapi/java-slack-sdk/compare/e49be394f9270f72cb0d22d3d0cf800930642199...6246fa0cbaeb2571b677efe271d47f0e75bd35b6
diff --git a/bolt-micronaut/src/test/java/test_locally/ControllerTest.java b/bolt-micronaut/src/test/java/test_locally/ControllerTest.java index 97cac996..e76a74c6 100644 --- a/bolt-micronaut/src/test/java/test_locally/ControllerTest.java +++ b/bolt-micronaut/src/test/java/test_locally/ControllerTest.java @@ -23,7 +23,7 @@ public class ControllerTest { @Test public void test() throws Exception { - AppConfig config = AppConfig.builder().build(); + AppConfig config = AppConfig.builder().signingSecret("secret").build(); SlackAppController controller = new SlackAppController(new App(config), new SlackAppMicronautAdapter(config)); assertNotNull(controller); diff --git a/bolt/src/test/java/test_locally/AppTest.java b/bolt/src/test/java/test_locally/AppTest.java index b310d8d2..ced4bf10 100644 --- a/bolt/src/test/java/test_locally/AppTest.java +++ b/bolt/src/test/java/test_locally/AppTest.java @@ -17,6 +17,7 @@ public class AppTest { @Test public void getOauthInstallationUrl_v1() { AppConfig config = AppConfig.builder() + .signingSecret("secret") .clientId("123") .scope("commands,chat:write") .classicAppPermissionsEnabled(true) @@ -29,6 +30,7 @@ public class AppTest { @Test public void getOauthInstallationUrl_v2() { AppConfig config = AppConfig.builder() + .signingSecret("secret") .clientId("123") .scope("commands,chat:write") .userScope("search:read") @@ -47,7 +49,7 @@ public class AppTest { @Test public void status() { - App app = new App(); + App app = new App(AppConfig.builder().signingSecret("secret").build()); assertThat(app.status(), is(App.Status.Stopped)); app.start(); assertThat(app.status(), is(App.Status.Running)); @@ -64,7 +66,7 @@ public class AppTest { @Test public void builder_status() { - App app = new App(); + App app = new App(AppConfig.builder().signingSecret("secret").build()); assertNotNull(app.status()); assertThat(app.status(), is(App.Status.Stopped)); @@ -80,7 +82,7 @@ public class AppTest { @Test public void builder_config() { - App app = new App(); + App app = new App(AppConfig.builder().signingSecret("secret").build()); assertNotNull(app.config()); app = app.toBuilder().build(); @@ -95,7 +97,7 @@ public class AppTest { @Test public void initializer_called() { - App app = new App(); + App app = new App(AppConfig.builder().signingSecret("secret").build()); final AtomicBoolean called = new AtomicBoolean(false); assertThat(called.get(), is(false)); @@ -108,7 +110,7 @@ public class AppTest { @Test public void initializer_start() { - App app = new App(); + App app = new App(AppConfig.builder().signingSecret("secret").build()); final AtomicBoolean called = new AtomicBoolean(false); assertThat(called.get(), is(false)); @@ -121,7 +123,7 @@ public class AppTest { @Test public void initializer_same_key() { - App app = new App(); + App app = new App(AppConfig.builder().signingSecret("secret").build()); final AtomicBoolean called = new AtomicBoolean(false); assertThat(called.get(), is(false)); diff --git a/slack-app-backend/src/main/java/com/slack/api/app_backend/SlackSignature.java b/slack-app-backend/src/main/java/com/slack/api/app_backend/SlackSignature.java index 55a6ac62..667c2325 100644 --- a/slack-app-backend/src/main/java/com/slack/api/app_backend/SlackSignature.java +++ b/slack-app-backend/src/main/java/com/slack/api/app_backend/SlackSignature.java @@ -79,6 +79,9 @@ public class SlackSignature { } public Generator(String slackSigningSecret) { + if (slackSigningSecret == null || slackSigningSecret.trim().isEmpty()) { + throw new IllegalArgumentException("The signing secret is required to generate signature values. Set the env variable " + Secret.DEFAULT_ENV_NAME + " or pass the value to the single arg constructor."); + } this.slackSigningSecret = slackSigningSecret; } diff --git a/slack-app-backend/src/test/java/test_locally/app_backend/SlackSignatureTest.java b/slack-app-backend/src/test/java/test_locally/app_backend/SlackSignatureTest.java index e0ca9d25..700ee7f9 100644 --- a/slack-app-backend/src/test/java/test_locally/app_backend/SlackSignatureTest.java +++ b/slack-app-backend/src/test/java/test_locally/app_backend/SlackSignatureTest.java @@ -8,6 +8,19 @@ import static org.junit.Assert.*; public class SlackSignatureTest { + @Test + public void nullSigningSecret() { + String expectedMessage = "The signing secret is required to generate signature values. " + + "Set the env variable SLACK_SIGNING_SECRET or pass the value to the single arg constructor."; + try { + SlackSignature.Generator generator = new SlackSignature.Generator(null); + generator.generate(String.valueOf(System.currentTimeMillis() / 1000), "isNull=true"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals(expectedMessage, e.getMessage()); + } + } + @Test public void test() { // https://api.slack.com/docs/verifying-requests-from-slack diff --git a/slack-app-backend/src/test/java/test_locally/app_backend/events/EventsApiHandlerTest.java b/slack-app-backend/src/test/java/test_locally/app_backend/events/EventsApiHandlerTest.java index 2409e218..a37a5f6a 100644 --- a/slack-app-backend/src/test/java/test_locally/app_backend/events/EventsApiHandlerTest.java +++ b/slack-app-backend/src/test/java/test_locally/app_backend/events/EventsApiHandlerTest.java @@ -12,6 +12,7 @@ import com.slack.api.app_backend.events.servlet.SlackEventsApiServlet; import com.slack.api.util.json.GsonFactory; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.servlet.ServletTester; +import org.junit.Ignore; import org.junit.Test; import javax.servlet.annotation.WebServlet; @@ -21,6 +22,8 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +// TODO: These tests somehow fail on TravisCI builds. +// will come up with better ways to do the similar. public class EventsApiHandlerTest { @WebServlet(urlPatterns = "/") @@ -76,6 +79,7 @@ public class EventsApiHandlerTest { // ------------------------------------------------------------------- + @Ignore @Test public void urlVerification() throws Exception { ServletTester tester = getServletTester(); @@ -93,6 +97,7 @@ public class EventsApiHandlerTest { assertThat(response.get("Content-Type"), is(equalTo("text/plain"))); } + @Ignore @Test public void message() throws Exception { ServletTester tester = getServletTester(); @@ -127,6 +132,7 @@ public class EventsApiHandlerTest { assertThat(MESSAGE_CALL_COUNTER.get(), is(3)); } + @Ignore @Test public void app_uninstalled() throws Exception { ServletTester tester = getServletTester(); @@ -153,6 +159,7 @@ public class EventsApiHandlerTest { assertThat(APP_UNINSTALLED_CALL_COUNTER.get(), is(1)); } + @Ignore @Test public void goodbye() throws Exception { ServletTester tester = getServletTester();
['bolt/src/test/java/test_locally/AppTest.java', 'slack-app-backend/src/main/java/com/slack/api/app_backend/SlackSignature.java', 'slack-app-backend/src/test/java/test_locally/app_backend/SlackSignatureTest.java', 'slack-app-backend/src/test/java/test_locally/app_backend/events/EventsApiHandlerTest.java', 'bolt-micronaut/src/test/java/test_locally/ControllerTest.java']
{'.java': 5}
5
5
0
0
5
1,496,681
302,922
45,059
1,027
319
56
3
1
1,465
164
393
35
3
2
1970-01-01T00:26:22
525
Java
{'Java': 5424202, 'Kotlin': 308094, 'Shell': 6494, 'Batchfile': 3120, 'Dockerfile': 253}
MIT License
888
foundationdb/fdb-record-layer/230/227
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/227
https://github.com/FoundationDB/fdb-record-layer/pull/230
https://github.com/FoundationDB/fdb-record-layer/pull/230
1
fixes
The OnlineIndexerTest::closeWhileBuilding test sometimes hangs
I've seen the `OnlineIndexerTest::closeWhileBuilding` test hang a few times, possibly only when run on the CI server. There's presumably some timing issue, either with the test or with the code itself, that sometimes results in it waiting on a future that will never complete (if I had to guess). Either that, or its `whileTrue` loop is looping forever.
3ec34c630fa6e4c3505c8d246d4e5a1961f3c13a
dc87788b22b96408e2f406eadb3a3c4341b6a6e0
https://github.com/foundationdb/fdb-record-layer/compare/3ec34c630fa6e4c3505c8d246d4e5a1961f3c13a...dc87788b22b96408e2f406eadb3a3c4341b6a6e0
diff --git a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerBase.java b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerBase.java index a336321b..4bdcbfd9 100644 --- a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerBase.java +++ b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerBase.java @@ -281,7 +281,12 @@ public class OnlineIndexerBase<M extends Message> implements AutoCloseable { } } } - }).thenCompose(Function.identity()), runner.getExecutor()); + }).thenCompose(Function.identity()), runner.getExecutor()) + .whenComplete((vignore, e) -> { + if (e != null) { + ret.completeExceptionally(runner.getDatabase().mapAsyncToSyncException(e)); + } + }); return ret; } diff --git a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerTest.java b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerTest.java index 222a846a..bcdd022a 100644 --- a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerTest.java +++ b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerTest.java @@ -84,6 +84,7 @@ import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -144,6 +145,7 @@ public class OnlineIndexerTest { public void setUp() { if (fdb == null) { fdb = FDBDatabaseFactory.instance().getDatabase(); + fdb.setAsyncToSyncTimeout(5, TimeUnit.MINUTES); } if (subspace == null) { subspace = DirectoryLayer.getDefault().createOrOpen(fdb.database(), Arrays.asList("record-test", "unit", "oib")).join(); @@ -2206,7 +2208,7 @@ public class OnlineIndexerTest { recordStore.clearAndMarkIndexWriteOnly(index).join(); context.commit(); } - + final FDBStoreTimer timer = new FDBStoreTimer(); final CompletableFuture<Void> future; try (OnlineIndexer indexBuilder = OnlineIndexer.newBuilder()
['fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerBase.java', 'fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/OnlineIndexerTest.java']
{'.java': 2}
2
2
0
0
2
2,769,828
557,539
66,096
355
384
63
7
1
353
58
80
1
0
0
1970-01-01T00:25:45
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
887
foundationdb/fdb-record-layer/256/255
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/255
https://github.com/FoundationDB/fdb-record-layer/pull/256
https://github.com/FoundationDB/fdb-record-layer/pull/256
1
fixes
FlatMapPipelinedCursor can return a null continuation when outer cursor is not exhausted if the first future is delayed
Attentive readers may remember #222 and #240. This error is very similar to #240, but it has the additional twist that the error only presents itself when there is a delay in the future returned by the `outerCursor` a `FlatMapPipelinedCursor`, which is why the unit tests introduced to guard us against regressions of #240 didn't catch it. The bug is somewhat subtle, but essentially, the strategy used in the `FlatMapPipelinedCursor` to remember continuations in the case of a non-exhausted reason for the outer cursor stopping was to introduce a sentinel that remembered that sort of thing. However, the loop only added the sentinel if the outer future completed within the same run of the `tryToFillPipeline` loop, which wasn't guaranteed. The fix is to always add the sentinel.
a649a14d92f74245eac70e9f9bb8f620b99cdd9e
6845679a72339702a72a4d4affec60b050ca76e0
https://github.com/foundationdb/fdb-record-layer/compare/a649a14d92f74245eac70e9f9bb8f620b99cdd9e...6845679a72339702a72a4d4affec60b050ca76e0
diff --git a/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java b/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java index 52ea95fd..cb97f98b 100644 --- a/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java +++ b/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java @@ -21,6 +21,7 @@ package com.apple.foundationdb.record.cursors; import com.apple.foundationdb.async.AsyncUtil; +import com.apple.foundationdb.record.RecordCoreException; import com.apple.foundationdb.record.RecordCursor; import com.apple.foundationdb.record.RecordCursorProto; import com.apple.foundationdb.record.RecordCursorVisitor; @@ -236,13 +237,15 @@ public class FlatMapPipelinedCursor<T, V> implements RecordCursor<V> { } final PipelineQueueEntry<V> nextEntry = pipeline.peek(); if (nextEntry == null) { - // Nothing more in pipeline. + // Nothing in pipeline. if (waitOuterNext == null) { - // Stop when source empty. - return AsyncUtil.READY_FALSE; + // If there are no pipeline entries, this should only be because there is outstanding work to + // determine what the next entry should be. + throw new RecordCoreException("Empty pipeline but no outer future or entry"); } else { // Loop to whileTrue to fill pipeline. - return waitOuterNext; + // If the outer cursor has no more results, still loop once more to get the continuation and NoNextReason. + return waitOuterNext.thenApply(b -> true); } } else if (nextEntry.innerCursor == null) { // Hit sentinel; outer cursor has no more values. diff --git a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java index e6a11526..3dfd7cbd 100644 --- a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java +++ b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java @@ -23,6 +23,7 @@ package com.apple.foundationdb.record; import com.apple.foundationdb.async.AsyncUtil; import com.apple.foundationdb.async.MoreAsyncUtil; import com.apple.foundationdb.record.cursors.FilterCursor; +import com.apple.foundationdb.record.cursors.FirableCursor; import com.apple.foundationdb.record.cursors.LazyCursor; import com.apple.foundationdb.record.cursors.MapCursor; import com.apple.foundationdb.record.cursors.RowLimitedCursor; @@ -30,7 +31,6 @@ import com.apple.foundationdb.record.cursors.SkipCursor; import com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -import com.google.protobuf.InvalidProtocolBufferException; import org.apache.commons.lang3.tuple.Pair; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; @@ -58,6 +58,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; @@ -66,6 +67,7 @@ import java.util.stream.IntStream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isOneOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -407,7 +409,7 @@ public class RecordCursorTest { @EnumSource(TestHelpers.BooleanEnum.class) @ParameterizedTest(name = "pipelineWithInnerLimits [outOfBand = {0}]") - public void pipelineWithInnerLimits(TestHelpers.BooleanEnum outOfBandEnum) throws InvalidProtocolBufferException { + public void pipelineWithInnerLimits(TestHelpers.BooleanEnum outOfBandEnum) { final boolean outOfBand = outOfBandEnum.toBoolean(); final RecordCursor.NoNextReason[] possibleNoNextReasons = new RecordCursor.NoNextReason[]{ RecordCursor.NoNextReason.SOURCE_EXHAUSTED, @@ -440,7 +442,7 @@ public class RecordCursorTest { @EnumSource(TestHelpers.BooleanEnum.class) @ParameterizedTest(name = "pipelineWithOuterLimits [outOfBand = {0}]") - public void pipelineWithOuterLimits(TestHelpers.BooleanEnum outOfBandEnum) throws InvalidProtocolBufferException { + public void pipelineWithOuterLimits(TestHelpers.BooleanEnum outOfBandEnum) { final boolean outOfBand = outOfBandEnum.toBoolean(); final RecordCursor.NoNextReason[] possibleNoNextReasons = new RecordCursor.NoNextReason[]{ RecordCursor.NoNextReason.SOURCE_EXHAUSTED, @@ -489,6 +491,76 @@ public class RecordCursorTest { assertEquals(13, timer.getCount(FDBStoreTimer.Counts.QUERY_DISCARDED)); } + @EnumSource(TestHelpers.BooleanEnum.class) + @ParameterizedTest(name = "pipelineWithOuterLimitsWithSomeDelay [outOfBand = {0}]") + public void pipelineWithOuterLimitsWithSomeDelay(TestHelpers.BooleanEnum outOfBandEnum) { + final boolean outOfBand = outOfBandEnum.toBoolean(); + final RecordCursor.NoNextReason limitReason = outOfBand ? RecordCursor.NoNextReason.TIME_LIMIT_REACHED : RecordCursor.NoNextReason.RETURN_LIMIT_REACHED; + final List<Integer> ints = IntStream.range(0, 10).boxed().collect(Collectors.toList()); + + final BiFunction<Integer, byte[], RecordCursor<Pair<Integer, Integer>>> innerFunc = (x, continuation) -> RecordCursor.fromList(ints, continuation).map(y -> Pair.of(x, y)); + final AtomicReference<FirableCursor<Integer>> outerCursorRef = new AtomicReference<>(); + final Function<byte[], RecordCursor<Integer>> outerFunc = continuation -> { + final RecordCursor<Integer> intCursor = RecordCursor.fromList(ints, continuation); + final RecordCursor<Integer> limitedCursor; + if (outOfBand) { + limitedCursor = new FakeOutOfBandCursor<>(intCursor, 3); + } else { + limitedCursor = intCursor.limitRowsTo(3); + } + final FirableCursor<Integer> outerCursor = new FirableCursor<>(limitedCursor.filter(x -> x > 7)); + outerCursorRef.set(outerCursor); + return outerCursor; + }; + + // Outer cursor = 0, 1, 2, all filtered + RecordCursor<Pair<Integer, Integer>> cursor = RecordCursor.flatMapPipelined(outerFunc, innerFunc, null, 5); + assertThat(cursor.onHasNext().isDone(), is(false)); + outerCursorRef.get().fire(); + assertThat(cursor.hasNext(), is(false)); + assertEquals(limitReason, cursor.getNoNextReason()); + assertNotNull(cursor.getContinuation()); + byte[] continuation = cursor.getContinuation(); + + // Outer cursor = 3, 4, 5, all filtered + cursor = RecordCursor.flatMapPipelined(outerFunc, innerFunc, continuation, 5); + assertThat(cursor.onHasNext().isDone(), is(false)); + outerCursorRef.get().fire(); + assertThat(cursor.hasNext(), is(false)); + assertEquals(limitReason, cursor.getNoNextReason()); + assertNotNull(cursor.getContinuation()); + continuation = cursor.getContinuation(); + + // Outer cursor = 6 (filtered), 7 (filtered), 8 (not filtered) + cursor = RecordCursor.flatMapPipelined(outerFunc, innerFunc, continuation, 5); + outerCursorRef.get().fire(); + for (int i = 0; i < ints.size(); i++) { + Pair<Integer, Integer> nextValue = cursor.next(); + assertEquals(8, (int)nextValue.getLeft()); + assertEquals(i, (int)nextValue.getRight()); + } + assertThat(cursor.onHasNext().isDone(), is(false)); + outerCursorRef.get().fire(); + assertThat(cursor.hasNext(), is(false)); + assertEquals(limitReason, cursor.getNoNextReason()); + assertNotNull(cursor.getContinuation()); + continuation = cursor.getContinuation(); + + // Outer cursor = 9 (not filtered) + cursor = RecordCursor.flatMapPipelined(outerFunc, innerFunc, continuation, 5); + outerCursorRef.get().fire(); + for (int i = 0; i < ints.size(); i++) { + Pair<Integer, Integer> nextValue = cursor.next(); + assertEquals(9, (int)nextValue.getLeft()); + assertEquals(i, (int)nextValue.getRight()); + } + assertThat(cursor.onHasNext().isDone(), is(false)); + outerCursorRef.get().fire(); + assertThat(cursor.hasNext(), is(false)); + assertEquals(RecordCursor.NoNextReason.SOURCE_EXHAUSTED, cursor.getNoNextReason()); + assertNull(cursor.getContinuation()); + } + @Test public void lazyCursorTest() { LazyCursor<Integer> cursor = new LazyCursor<>(
['fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java', 'fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java']
{'.java': 2}
2
2
0
0
2
2,766,969
556,948
66,015
355
718
125
11
1
784
127
172
3
0
0
1970-01-01T00:25:46
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
889
foundationdb/fdb-record-layer/135/19
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/19
https://github.com/FoundationDB/fdb-record-layer/pull/135
https://github.com/FoundationDB/fdb-record-layer/pull/135
1
fixes
Text: Query.or leads to record rather than index scan
In a full text query, if we have something like: ```java Query.or( Query.field("text").text().containsAll("civil unclean blood", 4), Query.field("text").text().containsAll("king was 1016") ) ``` Then this gets planned as a scan over all records rather than an index scan. I suspect that this is because with an `OR` query, you need to be able to effectively take the union of elements, which the planner isn't quite smart enough to do with text queries, so it falls back to a full scan.
f3b47526379af534bbbc9f9858586050db74f52f
18c99fb0e7b663c6f8edf870e51f2a82155f34db
https://github.com/foundationdb/fdb-record-layer/compare/f3b47526379af534bbbc9f9858586050db74f52f...18c99fb0e7b663c6f8edf870e51f2a82155f34db
diff --git a/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/PlanOrderingKey.java b/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/PlanOrderingKey.java index ce504a93..13680440 100644 --- a/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/PlanOrderingKey.java +++ b/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/PlanOrderingKey.java @@ -27,7 +27,9 @@ import com.apple.foundationdb.record.metadata.expressions.ThenKeyExpression; import com.apple.foundationdb.record.query.plan.plans.RecordQueryFilterPlan; import com.apple.foundationdb.record.query.plan.plans.RecordQueryIndexPlan; import com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan; +import com.apple.foundationdb.record.query.plan.plans.RecordQueryPlanWithIndex; import com.apple.foundationdb.record.query.plan.plans.RecordQueryScanPlan; +import com.apple.foundationdb.record.query.plan.plans.RecordQueryTextIndexPlan; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -96,8 +98,8 @@ public class PlanOrderingKey { while (queryPlan instanceof RecordQueryFilterPlan) { queryPlan = ((RecordQueryFilterPlan)queryPlan).getInner(); } - if (queryPlan instanceof RecordQueryIndexPlan) { - final RecordQueryIndexPlan indexPlan = (RecordQueryIndexPlan)queryPlan; + if (queryPlan instanceof RecordQueryPlanWithIndex) { + final RecordQueryPlanWithIndex indexPlan = (RecordQueryPlanWithIndex)queryPlan; final Index index = metaData.getIndex(indexPlan.getIndexName()); final List<KeyExpression> keys = new ArrayList<>(index.getRootExpression().normalizeKeyForPositions()); int pkeyStart = keys.size(); @@ -111,7 +113,25 @@ public class PlanOrderingKey { pkeyStart = pos; } } - final int prefixSize = indexPlan.getComparisons().getEqualitySize(); + final int prefixSize; + if (indexPlan instanceof RecordQueryIndexPlan) { + prefixSize = ((RecordQueryIndexPlan)indexPlan).getComparisons().getEqualitySize(); + } else if (indexPlan instanceof RecordQueryTextIndexPlan) { + final TextScan textScan = ((RecordQueryTextIndexPlan)indexPlan).getTextScan(); + int groupingSize = textScan.getGroupingComparisons() != null ? textScan.getGroupingComparisons().getEqualitySize() : 0; + int suffixSize = textScan.getSuffixComparisons() != null ? textScan.getSuffixComparisons().getEqualitySize() : 0; + if (textScan.getTextComparison().getType().isEquality()) { + // Can use the equality comparisons in the grouping columns and any columns after the text index + // plus the text column itself. + prefixSize = groupingSize + suffixSize + 1; + } else { + // Can only using the grouping columns as the text index itself uses an inequality comparison + prefixSize = groupingSize; + } + } else { + // Some unknown index plan. Maybe this should throw an error? + return null; + } return new PlanOrderingKey(keys, prefixSize, pkeyStart, pKeyTail); } else if (queryPlan instanceof RecordQueryScanPlan) { final RecordQueryScanPlan scanPlan = (RecordQueryScanPlan)queryPlan; diff --git a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java index 55d90606..28dad9f0 100644 --- a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java +++ b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java @@ -72,9 +72,10 @@ import com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer; import com.apple.foundationdb.record.provider.foundationdb.FDBStoredRecord; import com.apple.foundationdb.record.provider.foundationdb.IndexMaintainerRegistryImpl; import com.apple.foundationdb.record.query.RecordQuery; -import com.apple.foundationdb.record.query.expressions.AndComponent; +import com.apple.foundationdb.record.query.expressions.AndOrComponent; import com.apple.foundationdb.record.query.expressions.Comparisons; import com.apple.foundationdb.record.query.expressions.ComponentWithComparison; +import com.apple.foundationdb.record.query.expressions.OrComponent; import com.apple.foundationdb.record.query.expressions.Query; import com.apple.foundationdb.record.query.expressions.QueryComponent; import com.apple.foundationdb.record.query.plan.RecordQueryPlanner; @@ -1203,8 +1204,8 @@ public class TextIndexTest extends FDBRecordStoreTestBase { private List<Long> querySimpleDocumentsWithIndex(@Nonnull QueryComponent filter, @Nonnull String indexName, @Nonnull QueryComponent textFilter, int planHash) throws InterruptedException, ExecutionException { if (textFilter instanceof ComponentWithComparison && ((ComponentWithComparison)textFilter).getComparison() instanceof Comparisons.TextComparison) { return querySimpleDocumentsWithIndex(filter, indexName, planHash, equalTo(((ComponentWithComparison)textFilter).getComparison())); - } else if (textFilter instanceof AndComponent) { - for (QueryComponent childFilter : ((AndComponent)textFilter).getChildren()) { + } else if (textFilter instanceof AndOrComponent) { + for (QueryComponent childFilter : ((AndOrComponent)textFilter).getChildren()) { List<Long> childResults = querySimpleDocumentsWithIndex(filter, indexName, childFilter, planHash); if (childResults != null) { return childResults; @@ -1385,19 +1386,16 @@ public class TextIndexTest extends FDBRecordStoreTestBase { Query.field("text").text().containsPrefix("blo") ), 912028198)); - // Some extra not's, or's, etc. - // These currently just perform a scan. Some of them could be improved. + // Performs a union of the two text queries. - // FIXME: the planner should be smart enough to turn this into an index scan on one or both of the text filters - // FIXME: Text: Query.or leads to record rather than index scan (https://github.com/FoundationDB/fdb-record-layer/issues/19) assertEquals(Arrays.asList(0L, 2L), - querySimpleDocumentsWithScan(Query.and( + querySimpleDocumentsWithIndex(Query.and( Query.field("group").equalsValue(0L), Query.or( Query.field("text").text().containsAll("civil unclean blood", 4), Query.field("text").text().containsAll("king was 1016") ) - ), 290979239)); + ), 1313228370)); // Just a not. There's not a lot this could query could do to be performed because it can return // a lot of results by its very nature. @@ -1643,7 +1641,11 @@ public class TextIndexTest extends FDBRecordStoreTestBase { final Matcher<RecordQueryPlan> planMatcher; final QueryComponent filter; if (additionalFilter != null) { - planMatcher = descendant(filter(skipFilterCheck ? any(QueryComponent.class) : equalTo(additionalFilter), descendant(textPlanMatcher))); + if (skipFilterCheck) { + planMatcher = descendant(textPlanMatcher); + } else { + planMatcher = descendant(filter(equalTo(additionalFilter), descendant(textPlanMatcher))); + } filter = Query.and(textFilter, additionalFilter, Query.field("group").equalsValue(group)); } else { planMatcher = descendant(coveringIndexScan(textPlanMatcher)); @@ -1662,6 +1664,18 @@ public class TextIndexTest extends FDBRecordStoreTestBase { return queryComplexDocumentsWithIndex(textFilter, null, group, planHash); } + @Nonnull + private List<Tuple> queryComplexDocumentsWithOr(@Nonnull OrComponent orFilter, long group, int planHash) throws InterruptedException, ExecutionException { + final Matcher<RecordQueryPlan> textPlanMatcher = textIndexScan(allOf( + indexName(COMPLEX_TEXT_BY_GROUP.getName()), + groupingBounds(allOf(notNullValue(), hasTupleString("[[" + group + "],[" + group + "]]"))), + textComparison(any(Comparisons.TextComparison.class)) + )); + final QueryComponent filter = Query.and(orFilter, Query.field("group").equalsValue(group)); + final Matcher<RecordQueryPlan> planMatcher = descendant(textPlanMatcher); + return queryComplexDocumentsWithPlan(filter, planHash, planMatcher); + } + @Test public void queryComplexDocuments() throws Exception { final List<String> textSamples = Arrays.asList( @@ -1765,13 +1779,19 @@ public class TextIndexTest extends FDBRecordStoreTestBase { Query.not(Query.field("tag").oneOfThem().equalsValue("3:2")), 1, 758136569)); - // This query plan leads to the same pathology as is listed here: - // FIXME: Text: Query.or leads to record rather than index scan (https://github.com/FoundationDB/fdb-record-layer/issues/19) - // assertEquals(Collections.singletonList(Tuple.from(1L, 1L)), - // queryComplexDocumentsWithIndex( - // Query.field("text").text().containsAll("fearful passage love", 7), - // Query.or(Query.field("tag").oneOfThem().equalsValue("3:2"), Query.field("tag").oneOfThem().equalsValue("3:0")), - // 1, 0)); + assertEquals(Arrays.asList(Tuple.from(0L, 0L), Tuple.from(0L, 6L)), + queryComplexDocumentsWithOr((OrComponent) Query.or( + Query.field("text").text().containsAll("unit named after"), + Query.field("text").text().containsPhrase("אן ארמיי און פלאט") + ), 0, -1558384887)); + + assertEquals(Collections.singletonList(Tuple.from(1L, 5L)), + queryComplexDocumentsWithIndex( + Query.field("text").text().containsAll("fearful passage love", 7), + Query.or( + Query.field("tag").oneOfThem().equalsValue("3:2"), + Query.field("tag").oneOfThem().equalsValue("3:0")), + true, 1, 299461731)); assertEquals(Collections.singletonList(Tuple.from(1L, 1L)), queryComplexDocumentsWithIndex(
['fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/PlanOrderingKey.java', 'fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java']
{'.java': 2}
2
2
0
0
2
2,656,670
534,023
63,207
343
1,841
354
26
1
505
78
122
10
0
1
1970-01-01T00:25:41
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
890
foundationdb/fdb-record-layer/129/126
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/126
https://github.com/FoundationDB/fdb-record-layer/pull/129
https://github.com/FoundationDB/fdb-record-layer/pull/129
1
fixes
Full Text: Queries Need to Sometimes Add Type Filters
If a full text query plan uses a multi-type or universal index and the query itself should only return records from a subset of the types (e.g., a single-type query), then a type filter needs to be added.
6f34443572a15a8a13e20f45e8beb02c9f873d6a
f4c26e58a76febbe9f45bfaa4a471a3a58946f47
https://github.com/foundationdb/fdb-record-layer/compare/6f34443572a15a8a13e20f45e8beb02c9f873d6a...f4c26e58a76febbe9f45bfaa4a471a3a58946f47
diff --git a/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java b/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java index 080fa450..9bd6a878 100644 --- a/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java +++ b/fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java @@ -940,6 +940,28 @@ public class RecordQueryPlanner implements QueryPlanner { } } + @Nonnull + private Set<String> getPossibleTypes(@Nonnull Index index) { + final Collection<RecordType> recordTypes = metaData.recordTypesForIndex(index); + if (recordTypes.size() == 1) { + final RecordType singleRecordType = recordTypes.iterator().next(); + return Collections.singleton(singleRecordType.getName()); + } else { + return recordTypes.stream().map(RecordType::getName).collect(Collectors.toSet()); + } + } + + @Nonnull + private RecordQueryPlan addTypeFilterIfNeeded(@Nonnull CandidateScan candidateScan, @Nonnull RecordQueryPlan plan, + @Nonnull Set<String> possibleTypes) { + Collection<String> allowedTypes = candidateScan.planContext.query.getRecordTypes(); + if (!allowedTypes.isEmpty() && !allowedTypes.containsAll(possibleTypes)) { + return new RecordQueryTypeFilterPlan(plan, allowedTypes); + } else { + return plan; + } + } + @Nullable private ScoredPlan planVersion(@Nonnull CandidateScan candidateScan, @Nonnull KeyExpression index, @@ -1038,7 +1060,10 @@ public class RecordQueryPlanner implements QueryPlanner { return null; } // TODO: Check the rest of the fields of the text index expression to see if the sort and unsatisfied filters can be helped. - final RecordQueryTextIndexPlan plan = new RecordQueryTextIndexPlan(index.getName(), scan, candidateScan.reverse); + RecordQueryPlan plan = new RecordQueryTextIndexPlan(index.getName(), scan, candidateScan.reverse); + // Add a type filter if the index is over more types than those the query specifies + Set<String> possibleTypes = getPossibleTypes(index); + plan = addTypeFilterIfNeeded(candidateScan, plan, possibleTypes); // This weight is fairly arbitrary, but it is supposed to be higher than for most indexes because // most of the time, the full text scan is believed to be more selective (and expensive to run as a post-filter) // than other indexes. @@ -1063,7 +1088,6 @@ public class RecordQueryPlanner implements QueryPlanner { if (scanComparisons == null) { scanComparisons = ScanComparisons.EMPTY; } - RecordQueryPlan plan; Set<String> possibleTypes; if (candidateScan.index == null) { @@ -1078,14 +1102,10 @@ public class RecordQueryPlanner implements QueryPlanner { scanType = IndexScanType.BY_VALUE; } plan = new RecordQueryIndexPlan(candidateScan.index.getName(), scanType, scanComparisons, candidateScan.reverse); - possibleTypes = metaData.recordTypesForIndex(candidateScan.index).stream().map(RecordType::getName).collect(Collectors.toSet()); + possibleTypes = getPossibleTypes(candidateScan.index); } - - Collection<String> allowedTypes = candidateScan.planContext.query.getRecordTypes(); - if (allowedTypes != null && allowedTypes.size() > 0 && !allowedTypes.containsAll(possibleTypes)) { - plan = new RecordQueryTypeFilterPlan(plan, allowedTypes); - } - + // Add a type filter if the query plan might return records of more types than the query specified + plan = addTypeFilterIfNeeded(candidateScan, plan, possibleTypes); return plan; } diff --git a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java index 474bad75..21b90813 100644 --- a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java +++ b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java @@ -189,6 +189,7 @@ public class TextIndexTest extends FDBRecordStoreTestBase { private static final Index COMBINED_TEXT_BY_GROUP = new Index("Combined$text_by_group", field("text").groupBy(field("group")), IndexTypes.TEXT); private static final Index COMPLEX_MULTI_TAG_INDEX = new Index("Complex$multi_tag", field("text").groupBy(field("tag", FanType.FanOut)), IndexTypes.TEXT); private static final Index COMPLEX_THEN_TAG_INDEX = new Index("Complex$text_tag", concat(field("text"), field("tag", FanType.FanOut)), IndexTypes.TEXT); + private static final Index MULTI_TYPE_INDEX = new Index("Simple&Complex$text", field("text"), IndexTypes.TEXT); private static final Index MAP_ON_VALUE_INDEX = new Index("Map$entry-value", new GroupingKeyExpression(field("entry", FanType.FanOut).nest(concatenateFields("key", "value")), 1), IndexTypes.TEXT); private static final Index MAP_ON_VALUE_PREFIX_LEGACY = new Index("Map$entry-value_prefix", new GroupingKeyExpression(field("entry", FanType.FanOut).nest(concatenateFields("key", "value")), 1), IndexTypes.TEXT, ImmutableMap.of(Index.TEXT_TOKENIZER_NAME_OPTION, PrefixTextTokenizer.NAME, Index.TEXT_TOKENIZER_VERSION_OPTION, "0")); @@ -1662,6 +1663,86 @@ public class TextIndexTest extends FDBRecordStoreTestBase { } } + @Nonnull + private List<Long> queryMultiTypeDocuments(@Nonnull QueryComponent textFilter, @Nonnull List<String> recordTypes, int planHash) throws InterruptedException, ExecutionException { + if (!(textFilter instanceof ComponentWithComparison)) { + throw new RecordCoreArgumentException("filter without comparison provided as text filter"); + } + Matcher<RecordQueryPlan> planMatcher = descendant(textIndexScan(allOf( + indexName(MULTI_TYPE_INDEX.getName()), + textComparison(equalTo(((ComponentWithComparison)textFilter).getComparison()) + )))); + if (recordTypes.size() != 2) { + planMatcher = descendant(typeFilter(contains(recordTypes.get(0)), planMatcher)); + } + return queryDocuments(recordTypes, Collections.singletonList(field("doc_id")), textFilter, planHash, planMatcher) + .map(t -> t.getLong(0)) + .asList() + .join(); + } + + @Test + public void queryMultiTypeDocuments() throws Exception { + final List<String> bothTypes = Arrays.asList(SIMPLE_DOC, COMPLEX_DOC); + final List<String> simpleTypes = Collections.singletonList(SIMPLE_DOC); + final List<String> complexTypes = Collections.singletonList(COMPLEX_DOC); + + final List<String> textSamples = Arrays.asList( + TextSamples.ROMEO_AND_JULIET_PROLOGUE, + TextSamples.ROMEO_AND_JULIET_PROLOGUE, + TextSamples.ANGSTROM, + TextSamples.AETHELRED, + TextSamples.FRENCH, + TextSamples.GERMAN + ); + final List<Message> documents = IntStream.range(0, textSamples.size()) + .mapToObj(i -> { + final String text = textSamples.get(i); + if (i % 2 == 0) { + return SimpleDocument.newBuilder() + .setDocId(i) + .setText(text) + .setGroup(i % 4) + .build(); + } else { + return ComplexDocument.newBuilder() + .setDocId(i) + .setText(text) + .setGroup(i % 4) + .build(); + } + }) + .collect(Collectors.toList()); + + try (FDBRecordContext context = openContext()) { + openRecordStore(context, metaDataBuilder -> { + metaDataBuilder.getRecordType(COMPLEX_DOC).setPrimaryKey(field("doc_id")); + metaDataBuilder.removeIndex(SIMPLE_DEFAULT_NAME); + metaDataBuilder.addMultiTypeIndex(Arrays.asList( + metaDataBuilder.getRecordType(SIMPLE_DOC), + metaDataBuilder.getRecordType(COMPLEX_DOC) + ), MULTI_TYPE_INDEX); + }); + documents.forEach(recordStore::saveRecord); + + assertEquals(Arrays.asList(0L, 1L), + queryMultiTypeDocuments(Query.field("text").text().containsPhrase("where we lay our scene"), bothTypes, 1755757799)); + assertEquals(Collections.singletonList(0L), + queryMultiTypeDocuments(Query.field("text").text().containsPhrase("where we lay our scene"), simpleTypes, -1489953292)); + assertEquals(Collections.singletonList(1L), + queryMultiTypeDocuments(Query.field("text").text().containsPhrase("where we lay our scene"), complexTypes, -1333764430)); + + assertEquals(Arrays.asList(2L, 4L, 5L), + queryMultiTypeDocuments(Query.field("text").text().containsPrefix("na"), bothTypes, -714642562)); + assertEquals(Arrays.asList(2L, 4L), + queryMultiTypeDocuments(Query.field("text").text().containsPrefix("na"), simpleTypes, 334613643)); + assertEquals(Collections.singletonList(5L), + queryMultiTypeDocuments(Query.field("text").text().containsPrefix("na"), complexTypes, 490802505)); + + commit(context); + } + } + @Nonnull private List<Long> queryMapDocumentsWithScan(@Nonnull QueryComponent filter, int planHash) throws InterruptedException, ExecutionException { return queryDocuments(Collections.singletonList(MAP_DOC), Collections.singletonList(field("doc_id")), filter, planHash,
['fdb-record-layer-core/src/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java', 'fdb-record-layer-core/test/unit/com/apple/foundationdb/record/provider/foundationdb/indexes/TextIndexTest.java']
{'.java': 2}
2
2
0
0
2
2,655,768
533,823
63,187
343
2,170
415
38
1
204
38
45
1
0
0
1970-01-01T00:25:41
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
881
foundationdb/fdb-record-layer/574/573
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/573
https://github.com/FoundationDB/fdb-record-layer/pull/574
https://github.com/FoundationDB/fdb-record-layer/pull/574
1
fixes
FilterCursors can shuffle off work to the wrong executor
The `whileTrue` loop in `FilterCursor` does not set an executor: https://github.com/FoundationDB/fdb-record-layer/blob/f2b43c13b39ba9bb9aa9e79174afdade3d62db00/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/cursors/FilterCursor.java#L68-L72 This means that if there are any asynchronous callbacks, they will be scheduled on the `ForkJoinPool.commonPool()` even if the user has specified a specific executor to use.
f2b43c13b39ba9bb9aa9e79174afdade3d62db00
a4054a41892dbe771b4a1722159ec8ec6ced9777
https://github.com/foundationdb/fdb-record-layer/compare/f2b43c13b39ba9bb9aa9e79174afdade3d62db00...a4054a41892dbe771b4a1722159ec8ec6ced9777
diff --git a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/cursors/FilterCursor.java b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/cursors/FilterCursor.java index 1a5f32d4..63c40013 100644 --- a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/cursors/FilterCursor.java +++ b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/cursors/FilterCursor.java @@ -69,7 +69,7 @@ public class FilterCursor<T> implements RecordCursor<T> { nextResult = innerResult; hasNext = innerResult.hasNext() && (Boolean.TRUE.equals(pred.apply(innerResult.get()))); // relies on short circuiting return innerResult.hasNext() && !hasNext; // keep looping only if we might find more records and we filtered a record out - })).thenApply(vignore -> { + }), getExecutor()).thenApply(vignore -> { mayGetContinuation = !hasNext; return nextResult; }); diff --git a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/ResolverMappingReplicator.java b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/ResolverMappingReplicator.java index f8477455..91e82a48 100644 --- a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/ResolverMappingReplicator.java +++ b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/ResolverMappingReplicator.java @@ -155,7 +155,7 @@ public class ResolverMappingReplicator implements AutoCloseable { .whenComplete((vignore, eignore) -> cursor.close()) .thenApply(vignore -> Objects.nonNull(continuation.get())); }); - }); + }, runner.getExecutor()); } @Override
['fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/cursors/FilterCursor.java', 'fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/ResolverMappingReplicator.java']
{'.java': 2}
2
2
0
0
2
3,558,326
716,086
82,988
434
133
27
4
2
439
38
115
5
1
0
1970-01-01T00:25:56
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
861
foundationdb/fdb-record-layer/223/222
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/222
https://github.com/FoundationDB/fdb-record-layer/pull/223
https://github.com/FoundationDB/fdb-record-layer/pull/223#issuecomment-447510854
1
fixes
The FlatMapPipelinedCursor can return null continuations when not done
There are situations where the `FlatMapPipelinedCursor` can return `null` continuations even if the code isn't done yet. In particular, this can happen in situations where the inner cursor hits a limit before a single result is returned. It also probably means the cursor is less aggressive about updating its continuations than it should be, which might cause performance problems.
6d80c66d312dbe12e5cbad7a05f9f0fd1e1e20e0
39977424d51e716c1ad34e3e73df35eaa1a0cb9b
https://github.com/foundationdb/fdb-record-layer/compare/6d80c66d312dbe12e5cbad7a05f9f0fd1e1e20e0...39977424d51e716c1ad34e3e73df35eaa1a0cb9b
diff --git a/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java b/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java index e7346488..dc25a85b 100644 --- a/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java +++ b/fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java @@ -100,7 +100,7 @@ public class FlatMapPipelinedCursor<T, V> implements RecordCursor<V> { if (nextFuture == null) { mayGetContinuation = false; nextFuture = AsyncUtil.whileTrue(this::tryToFillPipeline, getExecutor()).thenApply(vignore -> { - boolean result = !(pipeline.isEmpty() || (innerReason != null && innerReason.isOutOfBand())); + boolean result = !(pipeline.isEmpty() || (innerReason != null && !innerReason.isSourceExhausted())); mayGetContinuation = !result; return result; }); @@ -168,7 +168,7 @@ public class FlatMapPipelinedCursor<T, V> implements RecordCursor<V> { @Override public NoNextReason getNoNextReason() { - if (innerReason != null && innerReason.isOutOfBand()) { + if (innerReason != null && !innerReason.isSourceExhausted()) { return innerReason; } return outerCursor.getNoNextReason(); @@ -239,14 +239,22 @@ public class FlatMapPipelinedCursor<T, V> implements RecordCursor<V> { // Stop because next cursor has next. return AsyncUtil.READY_FALSE; } + // Update the last entry to this entry. This will implicitly advance the continuation. This is safe + // because we have already hit the limit of this inner cursor. If the cursor is not exhausted, the + // whole cursor will stop and the advanced continuation will let it resume from where the cursor + // hit the limit. If the cursor is exhausted, then every item from this cursor has been returned to + // the user. That means that if the cursor is stopped right now, it will be resumed from the first + // item of the next element of the outer cursor, which is fine. + lastEntry = nextEntry; pipeline.remove(); innerReason = nextEntry.innerCursor.getNoNextReason(); - if (innerReason.isOutOfBand()) { + if (!innerReason.isSourceExhausted()) { // Stop because inner cursor hit some limit. // Not valid to take from later in the pipeline, even if available already. return AsyncUtil.READY_FALSE; + } else { + return AsyncUtil.READY_TRUE; } - return AsyncUtil.READY_TRUE; } if (waitOuterNext == null) { // Recheck when cursor ready (pipeline is full). diff --git a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java index 5e2b1872..cad549f3 100644 --- a/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java +++ b/fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java @@ -27,11 +27,16 @@ import com.apple.foundationdb.record.cursors.LazyCursor; import com.apple.foundationdb.record.cursors.MapCursor; import com.apple.foundationdb.record.cursors.RowLimitedCursor; import com.apple.foundationdb.record.cursors.SkipCursor; +import com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; +import com.google.protobuf.InvalidProtocolBufferException; +import org.apache.commons.lang3.tuple.Pair; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -59,6 +64,9 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.isOneOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -362,6 +370,62 @@ public class RecordCursorTest { assertEquals(adjusted, pieces); } + @EnumSource(TestHelpers.BooleanEnum.class) + @ParameterizedTest(name = "pipelineWithInnerLimits [outOfBand = {0}]") + public void pipelineWithInnerLimits(TestHelpers.BooleanEnum outOfBandEnum) throws InvalidProtocolBufferException { + final boolean outOfBand = outOfBandEnum.toBoolean(); + final RecordCursor.NoNextReason[] possibleNoNextReasons = new RecordCursor.NoNextReason[]{ + RecordCursor.NoNextReason.SOURCE_EXHAUSTED, + outOfBand ? RecordCursor.NoNextReason.TIME_LIMIT_REACHED : RecordCursor.NoNextReason.RETURN_LIMIT_REACHED + }; + final List<Integer> ints = IntStream.range(0, 10).boxed().collect(Collectors.toList()); + + final FDBStoreTimer timer = new FDBStoreTimer(); + final BiFunction<Integer, byte[], RecordCursor<Pair<Integer, Integer>>> innerFunc = (x, continuation) -> { + final RecordCursor<Integer> intCursor = RecordCursor.fromList(ints, continuation); + final RecordCursor<Integer> limitedCursor; + if (outOfBand) { + limitedCursor = new FakeOutOfBandCursor<>(intCursor, 3); + } else { + limitedCursor = intCursor.limitRowsTo(3); + } + return limitedCursor + .filterInstrumented(y -> y < x, timer, FDBStoreTimer.Counts.QUERY_FILTER_GIVEN, FDBStoreTimer.Events.QUERY_FILTER, FDBStoreTimer.Counts.QUERY_FILTER_PASSED, FDBStoreTimer.Counts.QUERY_DISCARDED) + .map(y -> Pair.of(x, y)); + }; + final Function<byte[], RecordCursor<Integer>> outerFunc = continuation -> RecordCursor.fromList(ints, continuation); + + byte[] continuation = null; + int results = 0; + int leftSoFar = -1; + int rightSoFar = -1; + do { + RecordCursor<Pair<Integer, Integer>> cursor = RecordCursor.flatMapPipelined(outerFunc, innerFunc, continuation, 5); + while (cursor.hasNext()) { + Pair<Integer, Integer> value = cursor.next(); + assertNotNull(value); + assertThat(value.getLeft(), greaterThan(value.getRight())); + assertThat(value.getLeft(), greaterThanOrEqualTo(leftSoFar)); + if (value.getLeft() == leftSoFar) { + assertThat(value.getRight(), greaterThan(rightSoFar)); + rightSoFar = value.getRight(); + } else { + leftSoFar = value.getLeft(); + rightSoFar = value.getRight(); + } + results++; + } + assertThat(cursor.getNoNextReason(), isOneOf(possibleNoNextReasons)); + continuation = cursor.getContinuation(); + } while (continuation != null); + + int expectedResults = ints.size() * (ints.size() - 1) / 2; + assertEquals(expectedResults, results); + assertEquals(ints.size() * ints.size(), timer.getCount(FDBStoreTimer.Counts.QUERY_FILTER_GIVEN)); + assertEquals(expectedResults, timer.getCount(FDBStoreTimer.Counts.QUERY_FILTER_PASSED)); + assertEquals(ints.size() * ints.size() - expectedResults, timer.getCount(FDBStoreTimer.Counts.QUERY_DISCARDED)); + } + @Test public void lazyCursorTest() { LazyCursor<Integer> cursor = new LazyCursor<>(
['fdb-record-layer-core/test/unit/com/apple/foundationdb/record/RecordCursorTest.java', 'fdb-record-layer-core/src/com/apple/foundationdb/record/cursors/FlatMapPipelinedCursor.java']
{'.java': 2}
2
2
0
0
2
2,752,831
553,897
65,364
354
1,247
253
16
1
382
59
76
1
0
0
1970-01-01T00:25:44
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
865
foundationdb/fdb-record-layer/1954/1953
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/1953
https://github.com/FoundationDB/fdb-record-layer/pull/1954
https://github.com/FoundationDB/fdb-record-layer/pull/1954
1
fixes
LuceneRecordCursor.getTerms missing PrefixQuery
Because of the way this code is structured, it needs to know every possible Lucene search node.
a2a2f0d2be652fe766dbe8c42fad64b438329645
c610f52c5b3a17d5a7b86321f3f953683106644a
https://github.com/foundationdb/fdb-record-layer/compare/a2a2f0d2be652fe766dbe8c42fad64b438329645...c610f52c5b3a17d5a7b86321f3f953683106644a
diff --git a/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursor.java b/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursor.java index 59abf528..1e39d9e6 100644 --- a/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursor.java +++ b/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursor.java @@ -220,7 +220,7 @@ public class LuceneAutoCompleteResultCursor implements BaseCursor<IndexEntry> { if (timer != null) { timer.increment(LuceneEvents.Counts.LUCENE_SCAN_MATCHED_AUTO_COMPLETE_SUGGESTIONS, topDocs.scoreDocs.length); } - return createResults(searcher, topDocs, tokenSet, prefixToken); + return createResults(searcher, topDocs, tokenSet, prefixToken == null ? Collections.emptySet() : Collections.singleton(prefixToken)); } private Set<String> getAllIndexedFieldNames(IndexReader indexReader) { @@ -355,10 +355,10 @@ public class LuceneAutoCompleteResultCursor implements BaseCursor<IndexEntry> { protected RecordCursor<IndexEntry> createResults(IndexSearcher searcher, TopDocs topDocs, Set<String> queryTokens, - @Nullable String prefixToken) { + Set<String> prefixTokens) { return RecordCursor.flatMapPipelined( outerContinuation -> scoreDocsFromLookup(searcher, topDocs), - (scoreDocAndRecord, innerContinuation) -> findIndexEntriesInRecord(scoreDocAndRecord, queryTokens, prefixToken, innerContinuation), + (scoreDocAndRecord, innerContinuation) -> findIndexEntriesInRecord(scoreDocAndRecord, queryTokens, prefixTokens, innerContinuation), scoreDocAndRecord -> scoreDocAndRecord.rec.getPrimaryKey().pack(), null, 1 // Use a pipeline size of 1 because the inner cursors don't do I/O and the outer cursor has its own pipelining @@ -406,7 +406,7 @@ public class LuceneAutoCompleteResultCursor implements BaseCursor<IndexEntry> { } } - private RecordCursor<IndexEntry> findIndexEntriesInRecord(ScoreDocAndRecord scoreDocAndRecord, Set<String> queryTokens, @Nullable String prefixToken, @Nullable byte[] continuation) { + private RecordCursor<IndexEntry> findIndexEntriesInRecord(ScoreDocAndRecord scoreDocAndRecord, Set<String> queryTokens, Set<String> prefixTokens, @Nullable byte[] continuation) { // Extract the indexed fields from the document again final List<LuceneDocumentFromRecord.DocumentField> documentFields = LuceneDocumentFromRecord.getRecordFields(state.index.getRootExpression(), scoreDocAndRecord.rec) .get(groupingKey == null ? TupleHelpers.EMPTY : groupingKey) @@ -428,7 +428,7 @@ public class LuceneAutoCompleteResultCursor implements BaseCursor<IndexEntry> { // matched terms return null; } - String match = LuceneHighlighting.searchAllMaybeHighlight(documentField.getFieldName(), queryAnalyzer, text, queryTokens, prefixToken, true, + String match = LuceneHighlighting.searchAllMaybeHighlight(documentField.getFieldName(), queryAnalyzer, text, queryTokens, prefixTokens, true, new LuceneScanQueryParameters.LuceneQueryHighlightParameters(highlight), null); if (match == null) { // Text not found in this field diff --git a/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneHighlighting.java b/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneHighlighting.java index 651d692b..12b055cb 100644 --- a/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneHighlighting.java +++ b/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneHighlighting.java @@ -45,6 +45,7 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -64,7 +65,7 @@ public class LuceneHighlighting { @SuppressWarnings("squid:S3776") // Cognitive complexity is too high. Candidate for later refactoring @Nullable static String searchAllMaybeHighlight(@Nonnull String fieldName, @Nonnull Analyzer queryAnalyzer, @Nonnull String text, - @Nonnull Set<String> matchedTokens, @Nullable String prefixToken, + @Nonnull Set<String> matchedTokens, @Nonnull Set<String> prefixTokens, boolean allMatchingRequired, @Nonnull LuceneScanQueryParameters.LuceneQueryHighlightParameters luceneQueryHighlightParameters, @Nullable List<Pair<Integer, Integer>> highlightedPositions) { @@ -75,7 +76,7 @@ public class LuceneHighlighting { StringBuilder sb = luceneQueryHighlightParameters.isHighlight() ? new StringBuilder() : null; int upto = 0; Set<String> matchedInText = new HashSet<>(); - boolean matchedPrefix = false; + Set<String> matchedPrefixes = new HashSet<>(); ArrayDeque<String> pres = new ArrayDeque<>(); ArrayDeque<String> ends = new ArrayDeque<>(); int lastMatchPos = -tokenCountAfterHighlighted - 1; @@ -142,25 +143,30 @@ public class LuceneHighlighting { upto = endOffset; matchedInText.add(token); lastMatchPos = currentPos; - } else if (prefixToken != null && token.startsWith(prefixToken)) { - if (luceneQueryHighlightParameters.isHighlight()) { - if (!tokenAlreadyHighlighted(text, startOffset, endOffset, - luceneQueryHighlightParameters.getLeftTag(), luceneQueryHighlightParameters.getRightTag())) { - addPrefixMatch(sb, text.substring(startOffset, endOffset), prefixToken, - luceneQueryHighlightParameters.getLeftTag(), luceneQueryHighlightParameters.getRightTag(), - highlightedPositions); - } else { - addNonMatch(sb, text.substring(startOffset, endOffset)); + } else { + for (String prefixToken : prefixTokens) { + if (token.startsWith(prefixToken)) { + if (luceneQueryHighlightParameters.isHighlight()) { + if (!tokenAlreadyHighlighted(text, startOffset, endOffset, + luceneQueryHighlightParameters.getLeftTag(), luceneQueryHighlightParameters.getRightTag())) { + addPrefixMatch(sb, text.substring(startOffset, endOffset), prefixToken, + luceneQueryHighlightParameters.getLeftTag(), luceneQueryHighlightParameters.getRightTag(), + highlightedPositions); + } else { + addNonMatch(sb, text.substring(startOffset, endOffset)); + } + } + upto = endOffset; + matchedPrefixes.add(prefixToken); + break; } } - upto = endOffset; - matchedPrefix = true; } currentPos++; } ts.end(); - if (allMatchingRequired && ((prefixToken != null && !matchedPrefix) || (matchedInText.size() < matchedTokens.size()))) { + if (allMatchingRequired && (matchedPrefixes.size() < prefixTokens.size() || (matchedInText.size() < matchedTokens.size()))) { // Query text not actually found in document text. Return null return null; } @@ -294,19 +300,20 @@ public class LuceneHighlighting { if (terms.isEmpty()) { return; } + Set<String> prefixes = getPrefixTerms(terms); for (Map.Entry<Descriptors.FieldDescriptor, Object> entry : source.message.getAllFields().entrySet()) { final Descriptors.FieldDescriptor entryDescriptor = entry.getKey(); final Object entryValue = entry.getValue(); if (entryValue instanceof String) { buildIfMatch(source, fieldName, value, entryDescriptor, entryValue, 0, - terms, analyzerSelector, luceneQueryHighlightParameters); + terms, prefixes, analyzerSelector, luceneQueryHighlightParameters); } else if (entryValue instanceof List) { int index = 0; for (Object entryValueElement : ((List<?>) entryValue)) { buildIfMatch(source, fieldName, value, entryDescriptor, entryValueElement, index, - terms, analyzerSelector, luceneQueryHighlightParameters); + terms, prefixes, analyzerSelector, luceneQueryHighlightParameters); index++; } } @@ -314,17 +321,48 @@ public class LuceneHighlighting { }, null); } + private static Set<String> getPrefixTerms(@Nonnull Set<String> terms) { + Set<String> result = Collections.emptySet(); + Iterator<String> iter = terms.iterator(); + while (iter.hasNext()) { + String term = iter.next(); + if (term.endsWith("*")) { + term = term.substring(0, term.length() - 1); + if (result.isEmpty()) { + result = new HashSet<>(); + } + result.add(term); + iter.remove(); + } + } + return result; + } + private static <M extends Message> void buildIfMatch(RecordRebuildSource<M> source, String fieldName, Object fieldValue, Descriptors.FieldDescriptor entryDescriptor, Object entryValue, int index, - @Nonnull Set<String> terms, + @Nonnull Set<String> terms, @Nonnull Set<String> prefixes, @Nonnull LuceneAnalyzerCombinationProvider analyzerSelector, @Nonnull LuceneScanQueryParameters.LuceneQueryHighlightParameters luceneQueryHighlightParameters) { - if (entryValue.equals(fieldValue) && terms.stream().anyMatch(t -> StringUtils.containsIgnoreCase((String)entryValue, t))) { - String highlightedText = searchAllMaybeHighlight(fieldName, analyzerSelector.provideIndexAnalyzer((String)entryValue).getAnalyzer(), (String)entryValue, terms, null, false, luceneQueryHighlightParameters, null); + if (entryValue.equals(fieldValue) && isMatch((String)entryValue, terms, prefixes)) { + String highlightedText = searchAllMaybeHighlight(fieldName, analyzerSelector.provideIndexAnalyzer((String)entryValue).getAnalyzer(), (String)entryValue, terms, prefixes, false, luceneQueryHighlightParameters, null); source.buildMessage(highlightedText, entryDescriptor, null, null, true, index); } } + private static boolean isMatch(@Nonnull String candidate, @Nonnull Set<String> terms, @Nonnull Set<String> prefixes) { + for (String term : terms) { + if (StringUtils.containsIgnoreCase(candidate, term)) { + return true; + } + } + for (String term : prefixes) { + if (StringUtils.containsIgnoreCase(candidate, term)) { + return true; + } + } + return false; + } + static class RecordRebuildSource<M extends Message> implements LuceneIndexExpressions.RecordSource<RecordRebuildSource<M>> { @Nullable public final RecordRebuildSource<M> parent; @@ -508,9 +546,10 @@ public class LuceneHighlighting { if (terms.isEmpty()) { return; } - if (value instanceof String && terms.stream().anyMatch(t -> StringUtils.containsIgnoreCase((String)value, t))) { + Set<String> prefixes = getPrefixTerms(terms); + if (value instanceof String && isMatch((String)value, terms, prefixes)) { List<Pair<Integer, Integer>> highlightedPositions = new ArrayList<>(); - String highlightedText = searchAllMaybeHighlight(fieldName, analyzerSelector.provideIndexAnalyzer((String)value).getAnalyzer(), (String)value, terms, null, false, luceneQueryHighlightParameters, highlightedPositions); + String highlightedText = searchAllMaybeHighlight(fieldName, analyzerSelector.provideIndexAnalyzer((String)value).getAnalyzer(), (String)value, terms, prefixes, false, luceneQueryHighlightParameters, highlightedPositions); result.add(new HighlightedTerm(fieldName, highlightedText, highlightedPositions)); } }, null); diff --git a/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneRecordCursor.java b/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneRecordCursor.java index 29a9d53d..6c46839e 100644 --- a/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneRecordCursor.java +++ b/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneRecordCursor.java @@ -53,6 +53,7 @@ import org.apache.lucene.search.BoostQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MultiPhraseQuery; import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; @@ -434,6 +435,11 @@ class LuceneRecordCursor implements BaseCursor<IndexEntry> { Term term = spanTermQuery.getTerm(); map.putIfAbsent(term.field(), new HashSet<>()); map.get(term.field()).add(term.text().toLowerCase(Locale.ROOT)); + } else if (query instanceof PrefixQuery) { + PrefixQuery termQuery = (PrefixQuery) query; + Term term = termQuery.getPrefix(); + map.putIfAbsent(term.field(), new HashSet<>()); + map.get(term.field()).add(term.text().toLowerCase(Locale.ROOT) + "*"); } else { throw new RecordCoreException("This lucene query is not supported for highlighting"); } diff --git a/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursorTest.java b/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursorTest.java index 8b4415f4..b1d9ea0f 100644 --- a/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursorTest.java +++ b/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursorTest.java @@ -126,7 +126,7 @@ class LuceneAutoCompleteResultCursorTest { assertEquals(expectedPrefixToken, prefixToken); Set<String> queryTokenSet = new HashSet<>(tokens); - @Nullable String match = LuceneHighlighting.searchAllMaybeHighlight("text", analyzer, text, queryTokenSet, prefixToken, true, + @Nullable String match = LuceneHighlighting.searchAllMaybeHighlight("text", analyzer, text, queryTokenSet, prefixToken == null ? Collections.emptySet() : Collections.singleton(prefixToken), true, new LuceneScanQueryParameters.LuceneQueryHighlightParameters(highlight), null); assertEquals(expectedMatch, match); } diff --git a/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneIndexTest.java b/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneIndexTest.java index fbe12aa4..d6222f33 100644 --- a/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneIndexTest.java +++ b/fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneIndexTest.java @@ -778,6 +778,18 @@ public class LuceneIndexTest extends FDBRecordStoreTestBase { } } + @Test + void highlightedPrefix() { + try (FDBRecordContext context = openContext()) { + rebuildIndexMetaData(context, SIMPLE_DOC, SIMPLE_TEXT_SUFFIXES); + recordStore.saveRecord(createSimpleDocument(1645L, "Hello record layer", 1)); + assertRecordTexts(List.of("Hello <b>recor</b>d layer"), + recordStore.fetchIndexRecords( + recordStore.scanIndex(SIMPLE_TEXT_SUFFIXES, fullTextSearch(SIMPLE_TEXT_SUFFIXES, "recor*", true), null, ScanProperties.FORWARD_SCAN), + IndexOrphanBehavior.ERROR)); + } + } + @Test void testCommit() { try (FDBRecordContext context = openContext()) {
['fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneRecordCursor.java', 'fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursorTest.java', 'fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneAutoCompleteResultCursor.java', 'fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/LuceneHighlighting.java', 'fdb-record-layer-lucene/src/test/java/com/apple/foundationdb/record/lucene/LuceneIndexTest.java']
{'.java': 5}
5
5
0
0
5
9,001,734
1,787,635
206,823
1,026
7,533
1,294
97
3
97
17
20
2
0
0
1970-01-01T00:27:52
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
870
foundationdb/fdb-record-layer/1356/1355
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/1355
https://github.com/FoundationDB/fdb-record-layer/pull/1356
https://github.com/FoundationDB/fdb-record-layer/pull/1356
1
fixes
RecordQueryInUnionPlan doesn't handle dynamic input of 0 or 1 values
0 is empty; 1 doesn’t need the dynamic union.
93d52282529571c51c40ba8f6d77ccb4be9b8706
3ff27bb54ea7ebe3a7b9525bc91628a033423ab9
https://github.com/foundationdb/fdb-record-layer/compare/93d52282529571c51c40ba8f6d77ccb4be9b8706...3ff27bb54ea7ebe3a7b9525bc91628a033423ab9
diff --git a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/plans/RecordQueryInUnionPlan.java b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/plans/RecordQueryInUnionPlan.java index 12f1ad25..e5080e65 100644 --- a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/plans/RecordQueryInUnionPlan.java +++ b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/plans/RecordQueryInUnionPlan.java @@ -117,7 +117,14 @@ public class RecordQueryInUnionPlan implements RecordQueryPlanWithChild { if (size > maxNumberOfValuesAllowed) { throw new RecordCoreException("too many IN values").addLogInfo("size", size); } + if (size == 0) { + return RecordCursor.empty(); + } final RecordQueryPlan childPlan = getInnerPlan(); + if (size == 1) { + final EvaluationContext childContext = getValuesContexts(context).get(0); + return childPlan.executePlan(store, childContext, continuation, executeProperties); + } final ExecuteProperties childExecuteProperties; // Can pass the limit down to all sides, since that is the most we'll take total. if (executeProperties.getSkip() > 0) { diff --git a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBInQueryTest.java b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBInQueryTest.java index b15f19bb..638603a6 100644 --- a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBInQueryTest.java +++ b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBInQueryTest.java @@ -543,11 +543,19 @@ class FDBInQueryTest extends FDBRecordStoreQueryTestBase { assertEquals(1428066748, plan.planHash(PlanHashable.PlanHashKind.LEGACY)); assertEquals(1407869064, plan.planHash(PlanHashable.PlanHashKind.FOR_CONTINUATION)); assertEquals(65237271, plan.planHash(PlanHashable.PlanHashKind.STRUCTURAL_WITHOUT_LITERALS)); - assertEquals(30, querySimpleRecordStore(hook, plan, - () -> EvaluationContext.forBinding("inList", asList(1, 3, 4)), - record -> assertThat(record.getNumValue3Indexed(), anyOf(is(1), is(3), is(4))), - context -> { })); } + assertEquals(30, querySimpleRecordStore(hook, plan, + () -> EvaluationContext.forBinding("inList", asList(1, 3, 4)), + record -> assertThat(record.getNumValue3Indexed(), anyOf(is(1), is(3), is(4))), + context -> { })); + assertEquals(0, querySimpleRecordStore(hook, plan, + () -> EvaluationContext.forBinding("inList", asList()), + record -> fail("should not have any records"), + context -> { })); + assertEquals(10, querySimpleRecordStore(hook, plan, + () -> EvaluationContext.forBinding("inList", asList(3)), + record -> assertThat(record.getNumValue3Indexed(), is(3)), + context -> { })); } /**
['fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBInQueryTest.java', 'fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/plans/RecordQueryInUnionPlan.java']
{'.java': 2}
2
2
0
0
2
6,441,289
1,281,880
148,045
734
299
61
7
1
45
9
13
1
0
0
1970-01-01T00:27:08
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
871
foundationdb/fdb-record-layer/1210/1209
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/1209
https://github.com/FoundationDB/fdb-record-layer/pull/1210
https://github.com/FoundationDB/fdb-record-layer/pull/1210
1
fixes
planNestedFieldChild stop condition isn't quite right
The old planner optimization in #1143 can get confused about whether it can continue with more keys / conditions after the nested child, generating plans that use only part of the nested key's fields followed by non-nested, even though these follow some unbound nested keys.
0d8f610cd8acc09daedb0e8bbd5c921acd242c0e
7d848cb1abb2e0dc89036670735fffe10c76a936
https://github.com/foundationdb/fdb-record-layer/compare/0d8f610cd8acc09daedb0e8bbd5c921acd242c0e...7d848cb1abb2e0dc89036670735fffe10c76a936
diff --git a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java index e571b004..54509dd7 100644 --- a/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java +++ b/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java @@ -1827,6 +1827,10 @@ public class RecordQueryPlanner implements QueryPlanner { * True if the current child of the index {@link ThenKeyExpression Then} clause has a corresponding equality comparison in the filter. */ private boolean foundComparison; + /** + * True if {@code foundComparison} completely accounted for the child. + */ + private boolean foundCompleteComparison; /** * Accumulate matching comparisons here. */ @@ -1881,8 +1885,8 @@ public class RecordQueryPlanner implements QueryPlanner { for (KeyExpression child : indexChildren) { if (!doneComparing) { planChild(child); - if (!comparisons.isEquality() || !foundComparison) { - // Didn't add another equality; done matching filters to index. + if (!comparisons.isEquality() || !foundCompleteComparison) { + // Didn't add another equality or only did part of child; done matching filters to index. doneComparing = true; } } @@ -1941,12 +1945,13 @@ public class RecordQueryPlanner implements QueryPlanner { } private void planChild(@Nonnull KeyExpression child) { - foundComparison = false; + foundCompleteComparison = foundComparison = false; if (child instanceof RecordTypeKeyExpression) { if (candidateScan.planContext.query.getRecordTypes().size() == 1) { // Can scan just the one requested record type. final RecordTypeKeyComparison recordTypeKeyComparison = new RecordTypeKeyComparison(candidateScan.planContext.query.getRecordTypes().iterator().next()); addToComparisons(recordTypeKeyComparison.getComparison()); + foundCompleteComparison = true; } return; } @@ -1971,10 +1976,14 @@ public class RecordQueryPlanner implements QueryPlanner { } if (nestedFilters.size() > 1) { final NestedField nestedAnd = new NestedField(parent.getFieldName(), Query.and(nestedChildren)); - if (planNestedFieldChild(child, nestedAnd, null)) { - unsatisfiedFilters.removeAll(nestedFilters); + final List<QueryComponent> saveUnsatisfiedFilters = new ArrayList<>(unsatisfiedFilters); + unsatisfiedFilters.removeAll(nestedFilters); + unsatisfiedFilters.add(nestedAnd); + if (planNestedFieldChild(child, nestedAnd, nestedAnd)) { return; } + unsatisfiedFilters.clear(); + unsatisfiedFilters.addAll(saveUnsatisfiedFilters); } } } @@ -1998,7 +2007,7 @@ public class RecordQueryPlanner implements QueryPlanner { } } - private boolean planNestedFieldChild(@Nonnull KeyExpression child, @Nonnull NestedField filterField, @Nullable QueryComponent filterChild) { + private boolean planNestedFieldChild(@Nonnull KeyExpression child, @Nonnull NestedField filterField, @Nonnull QueryComponent filterChild) { ScoredPlan scoredPlan = planNestedField(candidateScan, child, filterField, null); ScanComparisons nextComparisons = getPlanComparisons(scoredPlan); if (nextComparisons != null) { @@ -2014,15 +2023,17 @@ public class RecordQueryPlanner implements QueryPlanner { } else if (currentSort != null) { // Didn't plan to equality, need to try with sorting. scoredPlan = planNestedField(candidateScan, child, filterField, currentSort); + if (scoredPlan != null) { + advanceCurrentSort(); + } } if (scoredPlan != null) { - if (filterChild != null) { - unsatisfiedFilters.remove(filterChild); - } + unsatisfiedFilters.remove(filterChild); unsatisfiedFilters.addAll(scoredPlan.unsatisfiedFilters); comparisons.addAll(nextComparisons); if (nextComparisons.isEquality()) { foundComparison = true; + foundCompleteComparison = nextComparisons.getEqualitySize() == child.getColumnSize(); } return true; } @@ -2053,10 +2064,7 @@ public class RecordQueryPlanner implements QueryPlanner { FieldKeyExpression indexField = (FieldKeyExpression) child; if (Objects.equals(field.getFieldName(), indexField.getFieldName())) { if (addToComparisons(field.getComparison())) { - unsatisfiedFilters.remove(filterChild); - if (foundComparison && currentSortMatches(child)) { - advanceCurrentSort(); - } + addedComparison(child, filterChild); } } } @@ -2065,10 +2073,7 @@ public class RecordQueryPlanner implements QueryPlanner { private void planWithComparisonChild(@Nonnull KeyExpression child, @Nonnull QueryKeyExpressionWithComparison queryKeyExpression, @Nonnull QueryComponent filterChild) { if (child.equals(queryKeyExpression.getKeyExpression())) { if (addToComparisons(queryKeyExpression.getComparison())) { - unsatisfiedFilters.remove(filterChild); - if (foundComparison && currentSortMatches(child)) { - advanceCurrentSort(); - } + addedComparison(child, filterChild); } } } @@ -2078,10 +2083,7 @@ public class RecordQueryPlanner implements QueryPlanner { FieldKeyExpression indexField = (FieldKeyExpression) child; if (Objects.equals(oneOfThem.getFieldName(), indexField.getFieldName()) && indexField.getFanType() == FanType.FanOut) { if (addToComparisons(oneOfThem.getComparison())) { - unsatisfiedFilters.remove(filterChild); - if (foundComparison && currentSortMatches(child)) { - advanceCurrentSort(); - } + addedComparison(child, filterChild); } } } @@ -2090,10 +2092,7 @@ public class RecordQueryPlanner implements QueryPlanner { private void planWithVersionComparisonChild(@Nonnull KeyExpression child, @Nonnull QueryRecordFunctionWithComparison filter, @Nonnull QueryComponent filterChild) { if (child instanceof VersionKeyExpression) { if (addToComparisons(filter.getComparison())) { - unsatisfiedFilters.remove(filterChild); - if (foundComparison && currentSortMatches(child)) { - advanceCurrentSort(); - } + addedComparison(child, filterChild); } } } @@ -2119,6 +2118,16 @@ public class RecordQueryPlanner implements QueryPlanner { return false; } + private void addedComparison(@Nonnull KeyExpression child, @Nonnull QueryComponent filterChild) { + unsatisfiedFilters.remove(filterChild); + if (foundComparison) { + foundCompleteComparison = true; + if (currentSortMatches(child)) { + advanceCurrentSort(); + } + } + } + } } diff --git a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBNestedFieldQueryTest.java b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBNestedFieldQueryTest.java index 12eca779..4e30d392 100644 --- a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBNestedFieldQueryTest.java +++ b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBNestedFieldQueryTest.java @@ -69,8 +69,10 @@ import static com.apple.foundationdb.record.query.plan.match.PlanMatchers.indexS import static com.apple.foundationdb.record.query.plan.match.PlanMatchers.primaryKeyDistinct; import static com.apple.foundationdb.record.query.plan.match.PlanMatchers.queryPredicateDescendant; import static com.apple.foundationdb.record.query.plan.match.PlanMatchers.scan; +import static com.apple.foundationdb.record.query.plan.match.PlanMatchers.typeFilter; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -246,6 +248,33 @@ public class FDBNestedFieldQueryTest extends FDBRecordStoreQueryTestBase { assertEquals(Collections.singletonList(101L), fetchResultValues(plan, TestRecords4Proto.RestaurantRecord.REST_NO_FIELD_NUMBER, this::openNestedRecordStore, TestHelpers::assertDiscardedNone)); + + QueryComponent reviewFilter = Query.field("reviews").oneOfThem().matches(Query.and( + Query.field("rating").equalsValue(5), + Query.field("reviewer").equalsValue(1L))); + query = RecordQuery.newBuilder() + .setRecordType("RestaurantRecord") + .setFilter(reviewFilter) + .build(); + plan = planner.plan(query); + if (planner instanceof RecordQueryPlanner) { + assertThat(plan, filter(reviewFilter, primaryKeyDistinct(indexScan(allOf(indexName("review_rating"), bounds(hasTupleString("[[5],[5]]"))))))); + assertEquals(1252155441, plan.planHash(PlanHashable.PlanHashKind.LEGACY)); + assertEquals(-1754925686, plan.planHash(PlanHashable.PlanHashKind.FOR_CONTINUATION)); + assertEquals(1387591835, plan.planHash(PlanHashable.PlanHashKind.STRUCTURAL_WITHOUT_LITERALS)); + assertEquals(Collections.singletonList(102L), fetchResultValues(plan, TestRecords4Proto.RestaurantRecord.REST_NO_FIELD_NUMBER, + this::openNestedRecordStore, + TestHelpers::assertDiscardedNone)); + } else { + // TODO: Costing issue with full scan versus index scan. + assertThat(plan, filter(reviewFilter, typeFilter(contains("RestaurantRecord"), scan()))); + assertEquals(277825167, plan.planHash(PlanHashable.PlanHashKind.LEGACY)); + assertEquals(49070805, plan.planHash(PlanHashable.PlanHashKind.FOR_CONTINUATION)); + assertEquals(-1447620295, plan.planHash(PlanHashable.PlanHashKind.STRUCTURAL_WITHOUT_LITERALS)); + assertEquals(Collections.singletonList(102L), fetchResultValues(plan, TestRecords4Proto.RestaurantRecord.REST_NO_FIELD_NUMBER, + this::openNestedRecordStore, + context -> TestHelpers.assertDiscardedAtMost(3, context))); + } } /** @@ -436,6 +465,41 @@ public class FDBNestedFieldQueryTest extends FDBRecordStoreQueryTestBase { assertEquals(plan, planner.plan(query)); } + /** + * Verify that matching part of a nested field only uses part of the index. + */ + @DualPlannerTest + public void nestedThenWithAndPartial() throws Exception { + final RecordMetaDataHook hook = metaData -> { + metaData.addIndex("RestaurantReviewer", "hometownEmail", concat(field("stats").nest(concatenateFields("hometown", "school_name", "start_date")), field("email"))); + }; + nestedWithAndSetup(hook); + + RecordQuery query = RecordQuery.newBuilder() + .setRecordType("RestaurantReviewer") + .setFilter(Query.and( + Query.field("stats").matches(Query.and( + Query.field("hometown").equalsValue("Home Town"), + Query.field("school_name").equalsValue("University of Learning"))), + Query.field("email").equalsValue("pmp@example.com"))) + .build(); + RecordQueryPlan plan = planner.plan(query); + assertThat(plan, filter(Query.field("email").equalsValue("pmp@example.com"), + indexScan(allOf(indexName("hometownEmail"), bounds(hasTupleString("[[Home Town, University of Learning],[Home Town, University of Learning]]")))))); + if (planner instanceof RecordQueryPlanner) { + assertEquals(895882018, plan.planHash(PlanHashable.PlanHashKind.LEGACY)); + assertEquals(1929345776, plan.planHash(PlanHashable.PlanHashKind.FOR_CONTINUATION)); + assertEquals(391991162, plan.planHash(PlanHashable.PlanHashKind.STRUCTURAL_WITHOUT_LITERALS)); + } else { + assertEquals(-1385621911, plan.planHash(PlanHashable.PlanHashKind.LEGACY)); + assertEquals(-1566008386, plan.planHash(PlanHashable.PlanHashKind.FOR_CONTINUATION)); + assertEquals(1191604296, plan.planHash(PlanHashable.PlanHashKind.STRUCTURAL_WITHOUT_LITERALS)); + } + assertEquals(Collections.singletonList(1L), fetchResultValues(plan, TestRecords4Proto.RestaurantReviewer.ID_FIELD_NUMBER, + context -> openNestedRecordStore(context, hook), + TestHelpers::assertDiscardedNone)); + } + /** * Verify that an AND query on a nested record store that can be mostly implemented by a scan of a concatenated index * still filters on predicates that are not satisfied by scanning that index. diff --git a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/query/plan/match/FilterMatcherWithComponent.java b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/query/plan/match/FilterMatcherWithComponent.java index 6cb6be61..b2ddf367 100644 --- a/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/query/plan/match/FilterMatcherWithComponent.java +++ b/fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/query/plan/match/FilterMatcherWithComponent.java @@ -86,7 +86,7 @@ public class FilterMatcherWithComponent extends PlanMatcherWithChild { return predicate.semanticEquals(componentAsPredicateSupplier.get(), AliasMap.of(planBaseAlias, baseAlias)) && super.matchesSafely(plan); } else if (predicate instanceof QueryComponentPredicate) { - return component.equals(((QueryComponentPredicate)predicate).getQueryComponent()); + return component.equals(((QueryComponentPredicate)predicate).getQueryComponent()) && super.matchesSafely(plan); } else { return false; }
['fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/query/plan/match/FilterMatcherWithComponent.java', 'fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/query/FDBNestedFieldQueryTest.java', 'fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/RecordQueryPlanner.java']
{'.java': 3}
3
3
0
0
3
5,860,290
1,170,897
135,924
674
3,505
528
59
1
274
45
54
1
0
0
1970-01-01T00:26:56
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
869
foundationdb/fdb-record-layer/1359/1358
foundationdb
fdb-record-layer
https://github.com/FoundationDB/fdb-record-layer/issues/1358
https://github.com/FoundationDB/fdb-record-layer/pull/1359
https://github.com/FoundationDB/fdb-record-layer/pull/1359
1
fixes
Support cluster event parsing on FDB 6.3
The cluster event parsing tool contains the cluster protocol version within it, and it will only parse events if the protocol version matches. That value is still hard coded to the FDB 6.2 protocol version, so we should update it to be able to parse FDB 6.3 versions. FDB also added a few extra changes in the transaction sampling data in 6.3 that we should be aware of and try and properly parse. See the changes here (based on the FDB protocol version): https://github.com/apple/foundationdb/blob/c942ee995ebe0718420e24e1dabe1ddb2e0af30c/contrib/transaction_profiling_analyzer/transaction_profiling_analyzer.py
9f2fdb7f9d52664b882e274873aa34567ed21735
2cd94ad79b1834b8eedb4db3674487d7537b3caf
https://github.com/foundationdb/fdb-record-layer/compare/9f2fdb7f9d52664b882e274873aa34567ed21735...2cd94ad79b1834b8eedb4db3674487d7537b3caf
diff --git a/fdb-extensions/src/main/java/com/apple/foundationdb/clientlog/FDBClientLogEvents.java b/fdb-extensions/src/main/java/com/apple/foundationdb/clientlog/FDBClientLogEvents.java index 8b69ff13..f09e7ca0 100644 --- a/fdb-extensions/src/main/java/com/apple/foundationdb/clientlog/FDBClientLogEvents.java +++ b/fdb-extensions/src/main/java/com/apple/foundationdb/clientlog/FDBClientLogEvents.java @@ -36,6 +36,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneId; import java.util.Arrays; @@ -62,8 +63,9 @@ public class FDBClientLogEvents { public static final long PROTOCOL_VERSION_6_0 = 0x0FDB00A570010001L; public static final long PROTOCOL_VERSION_6_1 = 0x0FDB00B061060001L; public static final long PROTOCOL_VERSION_6_2 = 0x0FDB00B062010001L; + public static final long PROTOCOL_VERSION_6_3 = 0x0FDB00B063010001L; private static final long[] SUPPORTED_PROTOCOL_VERSIONS = { - PROTOCOL_VERSION_5_2, PROTOCOL_VERSION_6_0, PROTOCOL_VERSION_6_1, PROTOCOL_VERSION_6_2 + PROTOCOL_VERSION_5_2, PROTOCOL_VERSION_6_0, PROTOCOL_VERSION_6_1, PROTOCOL_VERSION_6_2, PROTOCOL_VERSION_6_3 }; // 0 1 2 3 4 5 6 7 @@ -99,14 +101,16 @@ public class FDBClientLogEvents { */ public abstract static class Event { protected final double startTimestamp; + protected final String dcId; - protected Event(double startTimestamp) { + protected Event(double startTimestamp, String dcId) { this.startTimestamp = startTimestamp; + this.dcId = dcId; } public abstract int getType(); - public double getStartTimestampDouoble() { + public double getStartTimestampDouble() { return startTimestamp; } @@ -124,6 +128,19 @@ public class FDBClientLogEvents { Instant startTimestamp = getStartTimestamp(); return startTimestamp.atOffset(ZoneId.systemDefault().getRules().getOffset(startTimestamp)).toString(); } + + public String getDcId() { + return dcId; + } + + protected StringJoiner toStringBase() { + StringJoiner joiner = new StringJoiner(", ", getClass().getSimpleName() + "[", "]") + .add("startTimestamp=" + getStartTimestampString()); + if (dcId.length() > 0) { + joiner.add("dcId=" + dcId); + } + return joiner; + } } /** @@ -145,11 +162,13 @@ public class FDBClientLogEvents { public static class EventGetVersion extends Event { private final double latency; private final int priority; + private final long readVersion; - public EventGetVersion(double startTimestamp, double latency, int priority) { - super(startTimestamp); + public EventGetVersion(double startTimestamp, String dcId, double latency, int priority, long readVersion) { + super(startTimestamp, dcId); this.latency = latency; this.priority = priority; + this.readVersion = readVersion; } @Override @@ -165,12 +184,16 @@ public class FDBClientLogEvents { return priority; } + public long getReadVersion() { + return readVersion; + } + @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("latency=" + latency) .add("priority=" + priority) + .add("readVersion=" + readVersion) .toString(); } } @@ -185,8 +208,8 @@ public class FDBClientLogEvents { @Nonnull private final byte[] key; - public EventGet(double startTimestamp, double latency, int size, @Nonnull byte[] key) { - super(startTimestamp); + public EventGet(double startTimestamp, String dcId, double latency, int size, @Nonnull byte[] key) { + super(startTimestamp, dcId); this.latency = latency; this.size = size; this.key = key; @@ -212,8 +235,7 @@ public class FDBClientLogEvents { @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("latency=" + latency) .add("size=" + size) .add("key=" + ByteArrayUtil.printable(key)) @@ -230,8 +252,8 @@ public class FDBClientLogEvents { @Nonnull private final Range range; - public EventGetRange(double startTimestamp, double latency, int size, @Nonnull Range range) { - super(startTimestamp); + public EventGetRange(double startTimestamp, String dcId, double latency, int size, @Nonnull Range range) { + super(startTimestamp, dcId); this.latency = latency; this.size = size; this.range = range; @@ -257,8 +279,7 @@ public class FDBClientLogEvents { @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("latency=" + latency) .add("size=" + size) .add("range=" + range) @@ -273,15 +294,17 @@ public class FDBClientLogEvents { private final double latency; private final int numMutations; private final int commitBytes; + private final long commitVersion; @Nonnull private final CommitRequest commitRequest; - public EventCommit(double startTimestamp, double latency, int numMutations, int commitBytes, + public EventCommit(double startTimestamp, String dcId, double latency, int numMutations, int commitBytes, long commitVersion, @Nonnull CommitRequest commitRequest) { - super(startTimestamp); + super(startTimestamp, dcId); this.latency = latency; this.numMutations = numMutations; this.commitBytes = commitBytes; + this.commitVersion = commitVersion; this.commitRequest = commitRequest; } @@ -309,11 +332,11 @@ public class FDBClientLogEvents { @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("latency=" + latency) .add("numMutations=" + numMutations) .add("commitBytes=" + commitBytes) + .add("commitVersion=" + commitVersion) .add("commitRequest=" + commitRequest) .toString(); } @@ -328,8 +351,8 @@ public class FDBClientLogEvents { @Nonnull private final byte[] key; - public EventGetError(double startTimestamp, int errorCode, @Nonnull byte[] key) { - super(startTimestamp); + public EventGetError(double startTimestamp, String dcId, int errorCode, @Nonnull byte[] key) { + super(startTimestamp, dcId); this.errorCode = errorCode; this.key = key; } @@ -350,8 +373,7 @@ public class FDBClientLogEvents { @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("errorCode=" + errorCode) .add("key=" + Arrays.toString(key)) .toString(); @@ -366,8 +388,8 @@ public class FDBClientLogEvents { @Nonnull private final Range range; - public EventGetRangeError(double startTimestamp, int errorCode, @Nonnull Range range) { - super(startTimestamp); + public EventGetRangeError(double startTimestamp, String dcId, int errorCode, @Nonnull Range range) { + super(startTimestamp, dcId); this.errorCode = errorCode; this.range = range; } @@ -388,8 +410,7 @@ public class FDBClientLogEvents { @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("errorCode=" + errorCode) .add("range=" + range) .toString(); @@ -404,8 +425,8 @@ public class FDBClientLogEvents { @Nonnull private final CommitRequest commitRequest; - public EventCommitError(double startTimestamp, int errorCode, @Nonnull CommitRequest commitRequest) { - super(startTimestamp); + public EventCommitError(double startTimestamp, String dcId, int errorCode, @Nonnull CommitRequest commitRequest) { + super(startTimestamp, dcId); this.errorCode = errorCode; this.commitRequest = commitRequest; } @@ -426,8 +447,7 @@ public class FDBClientLogEvents { @Override public String toString() { - return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") - .add("startTimestamp=" + getStartTimestampString()) + return toStringBase() .add("errorCode=" + errorCode) .add("commitRequest=" + commitRequest) .toString(); @@ -501,13 +521,18 @@ public class FDBClientLogEvents { @Nonnull private final Mutation[] mutations; private final long snapshotVersion; + private final boolean reportConflictingKeys; - public CommitRequest(@Nonnull Range[] readConflictRanges, @Nonnull Range[] writeConflictRanges, - @Nonnull Mutation[] mutations, long snapshotVersion) { + public CommitRequest(@Nonnull Range[] readConflictRanges, + @Nonnull Range[] writeConflictRanges, + @Nonnull Mutation[] mutations, + long snapshotVersion, + boolean reportConflictingKeys) { this.readConflictRanges = readConflictRanges; this.writeConflictRanges = writeConflictRanges; this.mutations = mutations; this.snapshotVersion = snapshotVersion; + this.reportConflictingKeys = reportConflictingKeys; } @Nonnull @@ -529,6 +554,10 @@ public class FDBClientLogEvents { return snapshotVersion; } + public boolean isReportConflictingKeys() { + return reportConflictingKeys; + } + @Override public String toString() { return new StringJoiner(", ", CommitRequest.class.getSimpleName() + "[", "]") @@ -536,6 +565,7 @@ public class FDBClientLogEvents { .add("writeConflictRanges=" + Arrays.toString(writeConflictRanges)) .add("mutations=" + Arrays.toString(mutations)) .add("snapshotVersion=" + snapshotVersion) + .add("reportConflictingKeys=" + reportConflictingKeys) .toString(); } } @@ -554,29 +584,42 @@ public class FDBClientLogEvents { } return AsyncUtil.whileTrue(() -> { final int type = buffer.getInt(); + final double startTime = buffer.getDouble(); + String dcId = ""; + if (protocolVersion >= PROTOCOL_VERSION_6_3) { + int dcIdLength = buffer.getInt(); + if (dcIdLength > 0) { + byte[] dcIdBytes = new byte[dcIdLength]; + buffer.get(dcIdBytes); + dcId = new String(dcIdBytes, StandardCharsets.UTF_8); + } + } final Event event; switch (type) { case GET_VERSION_LATENCY: - event = new EventGetVersion(buffer.getDouble(), buffer.getDouble(), - protocolVersion < PROTOCOL_VERSION_6_2 ? 0 : buffer.getInt()); + event = new EventGetVersion(startTime, dcId, buffer.getDouble(), + protocolVersion < PROTOCOL_VERSION_6_2 ? 0 : buffer.getInt(), + protocolVersion < PROTOCOL_VERSION_6_3 ? 0L : buffer.getLong()); break; case GET_LATENCY: - event = new EventGet(buffer.getDouble(), buffer.getDouble(), buffer.getInt(), deserializeByteArray(buffer)); + event = new EventGet(startTime, dcId, buffer.getDouble(), buffer.getInt(), deserializeByteArray(buffer)); break; case GET_RANGE_LATENCY: - event = new EventGetRange(buffer.getDouble(), buffer.getDouble(), buffer.getInt(), deserializeRange(buffer)); + event = new EventGetRange(startTime, dcId, buffer.getDouble(), buffer.getInt(), deserializeRange(buffer)); break; case COMMIT_LATENCY: - event = new EventCommit(buffer.getDouble(), buffer.getDouble(), buffer.getInt(), buffer.getInt(), deserializeCommit(buffer)); + event = new EventCommit(startTime, dcId, buffer.getDouble(), buffer.getInt(), buffer.getInt(), + protocolVersion < PROTOCOL_VERSION_6_3 ? 0L : buffer.getLong(), + deserializeCommit(protocolVersion, buffer)); break; case ERROR_GET: - event = new EventGetError(buffer.getDouble(), buffer.getInt(), deserializeByteArray(buffer)); + event = new EventGetError(startTime, dcId, buffer.getInt(), deserializeByteArray(buffer)); break; case ERROR_GET_RANGE: - event = new EventGetRangeError(buffer.getDouble(), buffer.getInt(), deserializeRange(buffer)); + event = new EventGetRangeError(startTime, dcId, buffer.getInt(), deserializeRange(buffer)); break; case ERROR_COMMIT: - event = new EventCommitError(buffer.getDouble(), buffer.getInt(), deserializeCommit(buffer)); + event = new EventCommitError(startTime, dcId, buffer.getInt(), deserializeCommit(protocolVersion, buffer)); break; default: throw new IllegalStateException("Unknown event type: " + type); @@ -624,9 +667,13 @@ public class FDBClientLogEvents { } @Nonnull - protected static CommitRequest deserializeCommit(@Nonnull ByteBuffer buffer) { - return new CommitRequest(deserializeRangeArray(buffer), deserializeRangeArray(buffer), - deserializeMutationArray(buffer), buffer.getLong()); + protected static CommitRequest deserializeCommit(long protocolVersion, @Nonnull ByteBuffer buffer) { + return new CommitRequest( + deserializeRangeArray(buffer), + deserializeRangeArray(buffer), + deserializeMutationArray(buffer), + buffer.getLong(), + protocolVersion >= PROTOCOL_VERSION_6_3 && (buffer.get() != 0)); } protected static class EventDeserializer implements AsyncConsumer<KeyValue> { diff --git a/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/ClientLogEventCounterTest.java b/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/ClientLogEventCounterTest.java index 880f0251..e4cd261a 100644 --- a/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/ClientLogEventCounterTest.java +++ b/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/ClientLogEventCounterTest.java @@ -53,7 +53,7 @@ class ClientLogEventCounterTest { countReads = "READ".equals(arg) || "BOTH".equals(arg); countWrites = "WRITE".equals(arg) || "BOTH".equals(arg); } - FDB fdb = FDB.selectAPIVersion(600); + FDB fdb = FDB.selectAPIVersion(630); Database database = fdb.open(cluster); Executor executor = database.getExecutor(); TupleKeyCountTree root = new TupleKeyCountTree(); diff --git a/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/DatabaseClientLogEventsTest.java b/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/DatabaseClientLogEventsTest.java index 83ef819c..f505b267 100644 --- a/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/DatabaseClientLogEventsTest.java +++ b/fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/DatabaseClientLogEventsTest.java @@ -44,7 +44,7 @@ class DatabaseClientLogEventsTest { if (args.length > 2) { end = ZonedDateTime.parse(args[2]).toInstant(); } - FDB fdb = FDB.selectAPIVersion(600); + FDB fdb = FDB.selectAPIVersion(630); Database database = fdb.open(cluster); Executor executor = database.getExecutor(); DatabaseClientLogEvents.EventConsumer consumer = (tr, event) -> {
['fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/ClientLogEventCounterTest.java', 'fdb-extensions/src/test/java/com/apple/foundationdb/clientlog/DatabaseClientLogEventsTest.java', 'fdb-extensions/src/main/java/com/apple/foundationdb/clientlog/FDBClientLogEvents.java']
{'.java': 3}
3
3
0
0
3
6,512,699
1,295,086
149,496
741
8,828
1,633
135
1
615
84
150
3
1
0
1970-01-01T00:27:08
508
Java
{'Java': 15870980, 'Raku': 7494480, 'Shell': 29023, 'Python': 19103, 'HTML': 5563}
Apache License 2.0
671
opencubicchunks/cubicchunks/252/250
opencubicchunks
cubicchunks
https://github.com/OpenCubicChunks/CubicChunks/issues/250
https://github.com/OpenCubicChunks/CubicChunks/pull/252
https://github.com/OpenCubicChunks/CubicChunks/pull/252
1
fixes
Cube/Column inconsistency... again
This issue is back, again. Another instance of issue similar to #103, now failing a much earlier sanity check. Crash report: [crash-2017-07-13_17.44.43-server.txt](https://github.com/OpenCubicChunks/CubicChunks/files/1149037/crash-2017-07-13_17.44.43-server.txt)
fd6da38c416a40eed475cd1f48a8c047f9e73558
2a09cfbdddd31010e2566dd486956b18417a40af
https://github.com/opencubicchunks/cubicchunks/compare/fd6da38c416a40eed475cd1f48a8c047f9e73558...2a09cfbdddd31010e2566dd486956b18417a40af
diff --git a/src/main/java/cubicchunks/util/XYZMap.java b/src/main/java/cubicchunks/util/XYZMap.java index c02de1cc..bd4cc5db 100644 --- a/src/main/java/cubicchunks/util/XYZMap.java +++ b/src/main/java/cubicchunks/util/XYZMap.java @@ -25,17 +25,14 @@ package cubicchunks.util; import mcp.MethodsReturnNonnullByDefault; -import java.util.ArrayList; import java.util.Iterator; -import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; /** - * Hash table implementation for objects in a 3-dimensional cartesian coordinate - * system. + * Hash table implementation for objects in a 3-dimensional cartesian coordinate system. * * @param <T> class of the objects to be contained in this map * @@ -50,25 +47,24 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { */ private static final int HASH_SEED = 1183822147; + /** * backing array containing all elements of this map */ @Nonnull private XYZAddressable[] buckets; - @Nonnull private int[] pointers; + /** * the current number of elements in this map */ - private int size = 0; + private int size; /** - * the maximum permissible load of the backing array, after reaching it the - * array will be resized + * the maximum permissible load of the backing array, after reaching it the array will be resized */ private float loadFactor; /** - * the load threshold of the backing array, after reaching it the array will - * be resized + * the load threshold of the backing array, after reaching it the array will be resized */ private int loadThreshold; @@ -77,9 +73,10 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { */ private int mask; + /** - * Creates a new XYZMap with the given load factor and initial capacity. The - * map will automatically grow if the specified load is surpassed. + * Creates a new XYZMap with the given load factor and initial capacity. The map will automatically grow if + * the specified load is surpassed. * * @param loadFactor the load factor * @param capacity the initial capacity @@ -97,11 +94,11 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { tCapacity <<= 1; } this.buckets = new XYZAddressable[tCapacity]; - this.pointers = new int[tCapacity]; this.refreshFields(); } + /** * Returns the number of elements in this map * @@ -111,6 +108,7 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { return this.size; } + /** * Computes a 32b hash based on the given coordinates. * @@ -132,65 +130,69 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { } /** - * Computes the desired pointer index for the given coordinates, based on - * the map's current capacity. + * Computes the desired bucket's index for the given coordinates, based on the map's current capacity. * * @param x the x-coordinate * @param y the y-coordinate * @param z the z-coordinate * - * @return the desired pointer index for the given coordinates + * @return the desired bucket's index for the given coordinates */ - private int getPointerIndex(int x, int y, int z) { + private int getIndex(int x, int y, int z) { return hash(x, y, z) & this.mask; } /** - * Computes the next index to the right of the given index, wrapping around - * if necessary. + * Computes the next index to the right of the given index, wrapping around if necessary. * * @param index the previous index * * @return the next index */ - private int getNextPointerIndex(int pointerIndex) { - return ++pointerIndex & this.mask; + private int getNextIndex(int index) { + return (index + 1) & this.mask; } + /** - * Associates the given value with its xyz-coordinates. If the map - * previously contained a mapping for these coordinates, the old value is - * replaced. + * Associates the given value with its xyz-coordinates. If the map previously contained a mapping for these + * coordinates, the old value is replaced. * * @param value value to be associated with its coordinates * - * @return the previous value associated with the given value's coordinates - * or null if no such value exists + * @return the previous value associated with the given value's coordinates or null if no such value exists */ - @Nullable - @SuppressWarnings("unchecked") + @Nullable @SuppressWarnings("unchecked") public T put(T value) { + int x = value.getX(); int y = value.getY(); int z = value.getZ(); - int pointerIndex = this.getPointerIndex(x, y, z); - int index = pointers[pointerIndex]; + int index = getIndex(x, y, z); - while (index != 0) { - XYZAddressable bucket = this.buckets[index]; + // find the closest empty space or the element to be replaced + XYZAddressable bucket = this.buckets[index]; + while (bucket != null) { + + // If there exists an element at the given element's position, overwrite it. if (bucket.getX() == x && bucket.getY() == y && bucket.getZ() == z) { this.buckets[index] = value; return (T) bucket; } - pointerIndex = this.getNextPointerIndex(pointerIndex); - index = pointers[pointerIndex]; + + index = getNextIndex(index); + bucket = this.buckets[index]; } - this.buckets[++size] = value; - pointers[pointerIndex] = size; + + // Insert the element into the empty bucket. + this.buckets[index] = value; // If the load threshold has been reached, increase the map's size. - if (this.size > this.loadThreshold) + ++this.size; + if (this.size > this.loadThreshold) { grow(); + } + return null; } @@ -201,28 +203,26 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { * @param y the y-coordinate * @param z the z-coordinate * - * @return the entry associated with the specified coordinates or null if no - * such entry exists + * @return the entry associated with the specified coordinates or null if no such entry exists */ - @Nullable - @SuppressWarnings("unchecked") + @Nullable @SuppressWarnings("unchecked") public T remove(int x, int y, int z) { - int pointerIndex = this.getPointerIndex(x, y, z); - int index = pointers[pointerIndex]; + int index = getIndex(x, y, z); - // Search for the element. Only the buckets from the element's supposed - // index up to the next free slot must + // Search for the element. Only the buckets from the element's supposed index up to the next free slot must // be checked. - while (index != 0) { - XYZAddressable bucket = this.buckets[index]; + XYZAddressable bucket = this.buckets[index]; + while (bucket != null) { + // If the correct bucket was found, remove it. if (bucket.getX() == x && bucket.getY() == y && bucket.getZ() == z) { - this.collapseBucket(pointerIndex, index); + this.collapseBucket(index); return (T) bucket; } - pointerIndex = this.getNextPointerIndex(pointerIndex); - index = pointers[pointerIndex]; + + index = getNextIndex(index); + bucket = this.buckets[index]; } // nothing was removed @@ -230,45 +230,41 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { } /** - * Removes and returns the given value from this map. More specifically, - * removes the entry whose xyz-coordinates equal the given value's - * coordinates. + * Removes and returns the given value from this map. More specifically, removes the entry whose xyz-coordinates + * equal the given value's coordinates. * * @param value the value to be removed * - * @return the entry associated with the given value's coordinates or null - * if no such entry exists + * @return the entry associated with the given value's coordinates or null if no such entry exists */ - @Nullable - public T remove(T value) { + @Nullable public T remove(T value) { return this.remove(value.getX(), value.getY(), value.getZ()); } /** - * Returns the value associated with the given coordinates or null if no - * such value exists. + * Returns the value associated with the given coordinates or null if no such value exists. * * @param x the x-coordinate * @param y the y-coordinate * @param z the z-coordinate * - * @return the entry associated with the specified coordinates or null if no - * such value exists + * @return the entry associated with the specified coordinates or null if no such value exists */ - @Nullable - @SuppressWarnings("unchecked") + @Nullable @SuppressWarnings("unchecked") public T get(int x, int y, int z) { - int pointerIndex = this.getPointerIndex(x, y, z); - int index = pointers[pointerIndex]; - while (index != 0) { - XYZAddressable bucket = this.buckets[index]; + int index = getIndex(x, y, z); + + XYZAddressable bucket = this.buckets[index]; + while (bucket != null) { + // If the correct bucket was found, return it. if (bucket.getX() == x && bucket.getY() == y && bucket.getZ() == z) { return (T) bucket; } - pointerIndex = this.getNextPointerIndex(pointerIndex); - index = pointers[pointerIndex]; + + index = getNextIndex(index); + bucket = this.buckets[index]; } // nothing was found @@ -276,28 +272,28 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { } /** - * Returns true if there exists an entry associated with the given - * xyz-coordinates in this map. + * Returns true if there exists an entry associated with the given xyz-coordinates in this map. * * @param x the x-coordinate * @param y the z-coordinate * @param z the y-coordinate * - * @return true if there exists an entry associated with the given - * coordinates in this map + * @return true if there exists an entry associated with the given coordinates in this map */ public boolean contains(int x, int y, int z) { - int pointerIndex = this.getPointerIndex(x, y, z); - int index = pointers[pointerIndex]; - while (index != 0) { - XYZAddressable bucket = this.buckets[index]; - // If the correct bucket was found, return it. + int index = getIndex(x, y, z); + + XYZAddressable bucket = this.buckets[index]; + while (bucket != null) { + + // If the correct bucket was found, return true. if (bucket.getX() == x && bucket.getY() == y && bucket.getZ() == z) { return true; } - pointerIndex = this.getNextPointerIndex(pointerIndex); - index = pointers[pointerIndex]; + + index = getNextIndex(index); + bucket = this.buckets[index]; } // nothing was found @@ -305,9 +301,8 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { } /** - * Returns true if the given value is contained within this map. More - * specifically, returns true if there exists an entry in this map whose - * xyz-coordinates equal the given value's coordinates. + * Returns true if the given value is contained within this map. More specifically, returns true if there exists + * an entry in this map whose xyz-coordinates equal the given value's coordinates. * * @param value the value * @@ -318,120 +313,132 @@ public class XYZMap<T extends XYZAddressable> implements Iterable<T> { } /** - * Doubles the size of the backing array and redistributes all contained - * values accordingly. + * Doubles the size of the backing array and redistributes all contained values accordingly. */ private void grow() { - int newLength = this.buckets.length * 2; - this.mask = newLength - 1; - XYZAddressable[] newBuckets = new XYZAddressable[newLength]; - int[] newPointers = new int[newLength]; - for (int i = 1; i <= size; i++) { - XYZAddressable bucket = buckets[i]; - newBuckets[i] = bucket; - int pointerIndex = this.getPointerIndex(bucket.getX(), bucket.getY(), bucket.getZ()); - while (newPointers[pointerIndex] != 0) - pointerIndex = this.getNextPointerIndex(pointerIndex); - newPointers[pointerIndex] = i; + + XYZAddressable[] oldBuckets = this.buckets; + + // double the size! + this.buckets = new XYZAddressable[this.buckets.length * 2]; + this.refreshFields(); + + // Move the old entries to the new array. + for (XYZAddressable oldBucket : oldBuckets) { + + // Skip empty buckets. + if (oldBucket == null) { + continue; + } + + // Get the desired index of the old bucket and insert it into the first available slot. + int index = getIndex(oldBucket.getX(), oldBucket.getY(), oldBucket.getZ()); + XYZAddressable bucket = this.buckets[index]; + while (bucket != null) { + bucket = this.buckets[index = getNextIndex(index)]; + } + this.buckets[index] = oldBucket; } - buckets = newBuckets; - pointers = newPointers; - loadThreshold = (int) (newLength * this.loadFactor) - 1; } /** - * Removes the value contained at the given index by shifting suitable - * values on its right to the left. - * - * @param index + * Removes the value contained at the given index by shifting suitable values on its right to the left. * - * @param holePointerIndex the index of the ponter to be collapsed - * @param holeIndex an index of the bucket to be collapsed + * @param hole the index of the bucket to be collapsed */ - private void collapseBucket(final int holePointerIndex, final int holeIndex) { - final int lastElement = size; - final int oldLastPointerIndex = getElementPointerIndex(lastElement); + private void collapseBucket(int hole) { - List<XYZAddressable> nextPointersBuckets = new ArrayList<XYZAddressable>(10); - List<Integer> nextBucketIndexes = new ArrayList<Integer>(10); + // This method must not be called on empty buckets. + assert this.buckets[hole] != null; + --this.size; - this.pointers[oldLastPointerIndex] = holeIndex; - this.pointers[holePointerIndex] = 0; + int currentIndex = hole; + while (true) { + currentIndex = getNextIndex(currentIndex); - int pointerIndex = this.getNextPointerIndex(holePointerIndex); - int index = pointers[pointerIndex]; - while (index != 0) { - XYZAddressable bucket = this.buckets[index]; - nextPointersBuckets.add(bucket); - nextBucketIndexes.add(index); - pointers[pointerIndex] = 0; - pointerIndex = this.getNextPointerIndex(pointerIndex); - index = pointers[pointerIndex]; - } - - this.buckets[holeIndex] = this.buckets[lastElement]; - size--; - - for (int i = 0; i < nextPointersBuckets.size(); i++) { - XYZAddressable bucket = nextPointersBuckets.get(i); - int x = bucket.getX(); - int y = bucket.getY(); - int z = bucket.getZ(); - int newBucketPointerIndex = this.getPointerIndex(x, y, z); - int newIndex = pointers[newBucketPointerIndex]; - while (newIndex != 0) { - newBucketPointerIndex = this.getNextPointerIndex(newBucketPointerIndex); - newIndex = pointers[newBucketPointerIndex]; + // If there exists no element at the given index, there is nothing to fill the hole with. + XYZAddressable bucket = this.buckets[currentIndex]; + if (bucket == null) { + this.buckets[hole] = null; + return; } - pointers[newBucketPointerIndex] = nextBucketIndexes.get(i); - } - } + // If the hole lies to the left of the currentIndex and to the right of the targetIndex, move the current + // element. These if conditions are necessary due to the bucket array wrapping around. + int targetIndex = getIndex(bucket.getX(), bucket.getY(), bucket.getZ()); + + // normal + if (hole < currentIndex) { + if (targetIndex <= hole || currentIndex < targetIndex) { + this.buckets[hole] = bucket; + hole = currentIndex; + } + } - private int getElementPointerIndex(int index) { - XYZAddressable lastElement = this.buckets[index]; - int pointerIndex = this.getPointerIndex(lastElement.getX(), lastElement.getY(), lastElement.getZ()); - while (pointers[pointerIndex] != index) { - pointerIndex = this.getNextPointerIndex(pointerIndex); + // wrap around! + else { + if (hole >= targetIndex && targetIndex > currentIndex) { + this.buckets[hole] = bucket; + hole = currentIndex; + } + } } - return pointerIndex; } /** - * Updates the load threshold and the index mask based on the backing - * array's current size. + * Updates the load threshold and the index mask based on the backing array's current size. */ private void refreshFields() { // we need that 1 extra space, make shore it will be there - this.loadThreshold = (int) (this.buckets.length * this.loadFactor) - 1; + this.loadThreshold = Math.min(this.buckets.length - 1, (int) (this.buckets.length * this.loadFactor)); this.mask = this.buckets.length - 1; } - // Interface: Iterable<T> - // ------------------------------------------------------------------------------------------ + + // Interface: Iterable<T> ------------------------------------------------------------------------------------------ public Iterator<T> iterator() { return new Iterator<T>() { - - int at = 1; + int at = -1; + int next = -1; @Override public boolean hasNext() { - return at <= size; + if (next > at) { + return true; + } + for (next++; next < buckets.length; next++) { + if (buckets[next] != null) { + return true; + } + } + return false; } - @Nullable - @Override + @Nullable @Override @SuppressWarnings("unchecked") public T next() { - return (T) buckets[at++]; + if (next > at) { + at = next; + return (T) buckets[at]; + } + for (next++; next < buckets.length; next++) { + if (buckets[next] != null) { + at = next; + return (T) buckets[at]; + } + } + return null; } + //TODO: WARNING: risk of iterating over the same item more than once if this is used + // do to items wrapping back around form the front of the buckets array @Override public void remove() { - int pointerIndex = getElementPointerIndex(--at); - collapseBucket(pointerIndex, at); + collapseBucket(at); + next = at = at - 1; // There could be a new item in the removed bucket } }; } + } diff --git a/src/main/java/cubicchunks/world/column/CubeMap.java b/src/main/java/cubicchunks/world/column/CubeMap.java index 95c2c03e..59d89660 100644 --- a/src/main/java/cubicchunks/world/column/CubeMap.java +++ b/src/main/java/cubicchunks/world/column/CubeMap.java @@ -69,9 +69,7 @@ public class CubeMap implements Iterable<Cube> { public void put(Cube cube) { int searchIndex = binarySearch(cube.getY()); if (this.contains(cube.getY(), searchIndex)) { - Cube existing = cubes.get(searchIndex); - throw new IllegalArgumentException("Cube at " + cube.getY() + " already exists! "+ - "Existing "+existing+" Attempt to add "+cube); + throw new IllegalArgumentException("Cube at " + cube.getY() + " already exists!"); } cubes.add(searchIndex, cube); } diff --git a/src/main/java/cubicchunks/world/cube/Cube.java b/src/main/java/cubicchunks/world/cube/Cube.java index 4ca76636..847a52af 100644 --- a/src/main/java/cubicchunks/world/cube/Cube.java +++ b/src/main/java/cubicchunks/world/cube/Cube.java @@ -732,9 +732,4 @@ public class Cube implements XYZAddressable { public boolean isCubeLoaded() { return this.isCubeLoaded; } - - @Override - public String toString(){ - return "cube"+"{"+getX()+";"+getY()+";"+getZ()+"}"; - } } diff --git a/src/test/java/cubicchunks/TestXYZMap.java b/src/test/java/cubicchunks/TestXYZMap.java index d675d2e7..54cb4b91 100644 --- a/src/test/java/cubicchunks/TestXYZMap.java +++ b/src/test/java/cubicchunks/TestXYZMap.java @@ -26,7 +26,6 @@ package cubicchunks; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -34,13 +33,12 @@ import static org.junit.Assert.assertTrue; import cubicchunks.util.XYZAddressable; import cubicchunks.util.XYZMap; import mcp.MethodsReturnNonnullByDefault; - import org.junit.Test; import java.util.HashSet; -import java.util.Iterator; import java.util.Random; import java.util.Set; + import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; @@ -120,7 +118,7 @@ public class TestXYZMap { map.put(values[i]); for (int j = 0; j <= i; ++j) { - assertTrue(map.contains(values[j].getX(), values[j].getY(), values[j].getZ())); + assertTrue(map.contains(values[i].getX(), values[i].getY(), values[i].getZ())); } } } @@ -140,19 +138,6 @@ public class TestXYZMap { } } } - - @Test - public void testRemove() { - XYZMap<XYZAddressable> map = new XYZMap<>(0.75f, 10); - //set seed so that tests are predictable - Random rand = new Random(42); - int maxPuts = 500; - Addressable[] values = new Addressable[maxPuts]; - testPutRandom(map, rand, maxPuts, values); - map.remove(values[maxPuts/2]); - assertTrue(!map.contains(values[maxPuts/2])); - } - @Test public void testIterator() { @@ -163,27 +148,15 @@ public class TestXYZMap { for (int i = 0; i < maxPut; i++) { Addressable newElement = new Addressable(rand.nextInt(), rand.nextInt(), rand.nextInt(), String.valueOf(i)); map.put(newElement); - assertTrue(map.contains(newElement)); allElements.add(newElement); } for (XYZAddressable element : map) { - assertTrue(map.contains(element)); assertThat(allElements, hasItem(element)); allElements.remove(element); } assertThat(allElements, empty()); - Iterator<XYZAddressable> it = map.iterator(); - while(it.hasNext()){ - XYZAddressable xyza = it.next(); - assertNotNull(xyza); - assertTrue(map.contains(xyza)); - int sizeBefore = map.getSize(); - it.remove(); - assertTrue(!map.contains(xyza)); - assertEquals(map.getSize(),sizeBefore-1); - } } - + /** * Simple implementation of Addressable for testing, equal only if id of them is equal */
['src/main/java/cubicchunks/world/cube/Cube.java', 'src/test/java/cubicchunks/TestXYZMap.java', 'src/main/java/cubicchunks/util/XYZMap.java', 'src/main/java/cubicchunks/world/column/CubeMap.java']
{'.java': 4}
4
4
0
0
4
1,450,892
323,357
36,265
277
16,044
3,226
332
3
269
22
83
5
1
0
1970-01-01T00:25:00
506
Java
{'Java': 1717928, 'Kotlin': 23097}
MIT License
590
vaadin/flow/7140/7126
vaadin
flow
https://github.com/vaadin/flow/issues/7126
https://github.com/vaadin/flow/pull/7140
https://github.com/vaadin/flow/pull/7140
1
fixes
app does not start when using V15 alpha7 and flow.serverSideRoute
Steps to reproduce: - check out the `ccdm` branch of the https://github.com/vaadin/bookstore-example/ repo (currently uses Vaadin 15.0.0.alpha7) - install `@vaadin/router`: `npm install --save @vaadin/router` - add a custom `index.ts` ```typescript import {Router} from '@vaadin/router'; import {Flow} from '@vaadin/flow-frontend/Flow'; const router = new Router(document.body); const {serverSideRoutes} = new Flow({ imports: () => import('../target/frontend/generated-flow-imports') }); router.setRoutes([ // pass all unmatched paths to server-side ...serverSideRoutes ]); ``` - start the app with `mvn jetty:run` - open the app in the browser - see that the page stays blank and there is a constant stream of new requests to `http://localhost:8080/?v-r=uidl&v-uiId=0` in the DevTools' network tab.
c0ac450a465e8d19f7776d9e9d2098b970ff996d
b72d1e0f512fd15474c7967eb11e4ef54f30f776
https://github.com/vaadin/flow/compare/c0ac450a465e8d19f7776d9e9d2098b970ff996d...b72d1e0f512fd15474c7967eb11e4ef54f30f776
diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java index 8e763329a5..95e140a59d 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java @@ -50,6 +50,11 @@ import com.vaadin.flow.theme.ThemeDefinition; public class JavaScriptBootstrapUI extends UI { public static final String SERVER_ROUTING = "clientRoutingMode"; + static final String CLIENT_PUSHSTATE_TO = + "window.history.pushState(null, '', $0)"; + static final String CLIENT_NAVIGATE_TO = + "window.dispatchEvent(new CustomEvent('vaadin-router-go', {detail: new URL($0, document.baseURI)}))"; + Element wrapperElement; private NavigationState clientViewNavigationState; @@ -165,21 +170,27 @@ public class JavaScriptBootstrapUI extends UI { getInternals().clearLastHandledNavigation(); } return false; - } private boolean shouldHandleNavigation(Location location) { - if (getInternals().hasLastHandledLocation()) { - return !location.getPathWithQueryParameters().equals(getInternals() - .getLastHandledLocation().getPathWithQueryParameters()); - } - return true; + return !getInternals().hasLastHandledLocation() || !sameLocation( + getInternals().getLastHandledLocation(), location); + } + + private boolean sameLocation(Location oldLocation, Location newLocation) { + return removeLastSlash(newLocation.getPathWithQueryParameters()) + .equals(removeLastSlash( + oldLocation.getPathWithQueryParameters())); } private String removeFirstSlash(String route) { return route.replaceFirst("^/+", ""); } + private String removeLastSlash(String route) { + return route.replaceFirst("/+$", ""); + } + private boolean handleNavigation(Location location, NavigationState navigationState) { NavigationEvent navigationEvent = new NavigationEvent(getRouter(), @@ -225,12 +236,20 @@ public class JavaScriptBootstrapUI extends UI { // server-side routing renderViewForRoute(location); } else { - // client-side routing - getPage().executeJs( - "window.dispatchEvent(new CustomEvent('vaadin-router-go'," - + " {detail: new URL($0, document.baseURI)}))", - location.getPathWithQueryParameters() - ); + String execJs; + if (getInternals().hasLastHandledLocation()) { + // There is an in-progress navigation + if (sameLocation(getInternals().getLastHandledLocation(), location)) { + // There are no changes, prevent looping + return; + } + // Update browser URL but do not fire client-side navigation + execJs = CLIENT_PUSHSTATE_TO; + } else { + // There is navigation, let client-side to handle it + execJs = CLIENT_NAVIGATE_TO; + } + getPage().executeJs(execJs, location.getPathWithQueryParameters()); } } diff --git a/flow-server/src/test/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUITest.java b/flow-server/src/test/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUITest.java index d45bca3b52..1cd5f9dba8 100644 --- a/flow-server/src/test/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUITest.java +++ b/flow-server/src/test/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUITest.java @@ -5,20 +5,24 @@ import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.mockito.Spy; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.HasComponents; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.UI; +import com.vaadin.flow.component.page.Page; import com.vaadin.flow.internal.CurrentInstance; import com.vaadin.flow.router.BeforeLeaveEvent; import com.vaadin.flow.router.BeforeLeaveObserver; +import com.vaadin.flow.router.Location; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.MockServletServiceSessionSetup; import com.vaadin.flow.server.VaadinRequest; -import static com.vaadin.flow.component.internal.JavaScriptBootstrapUI.SERVER_ROUTING; +import static com.vaadin.flow.component.internal.JavaScriptBootstrapUI.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -78,6 +82,10 @@ public class JavaScriptBootstrapUITest { ProductView.class, Collections.emptyList()); ui = new JavaScriptBootstrapUI(); ui.getInternals().setSession(mocks.getSession()); + + Mockito.when(mocks.getSession().getAttribute(SERVER_ROUTING)) + .thenReturn(Boolean.FALSE); + CurrentInstance.setCurrent(ui); } @@ -191,16 +199,69 @@ public class JavaScriptBootstrapUITest { ui.getInternals().hasLastHandledLocation()); } + @Test + public void should_invoke_clientRoute_when_navigationHasNotBeenStarted() { + ui = Mockito.spy(ui); + Page page = Mockito.mock(Page.class); + + Mockito.when(ui.getPage()).thenReturn(page); + + ArgumentCaptor<String> execJs = ArgumentCaptor.forClass(String.class); + ArgumentCaptor<String> execArg = ArgumentCaptor.forClass(String.class); + + ui.navigate("whatever"); + Mockito.verify(page).executeJs(execJs.capture(), execArg.capture()); + + assertEquals(CLIENT_NAVIGATE_TO, execJs.getValue()); + assertEquals("whatever", execArg.getValue()); + } + + @Test + public void should_update_pushState_when_navigationHasBeenAlreadyStarted() { + ui = Mockito.spy(ui); + Page page = Mockito.mock(Page.class); + UIInternals internals = Mockito.mock(UIInternals.class); + + Mockito.when(ui.getPage()).thenReturn(page); + Mockito.when(ui.getInternals()).thenReturn(internals); + + Mockito.when(internals.hasLastHandledLocation()).thenReturn(true); + Location lastLocation = new Location("clean"); + Mockito.when(internals.getLastHandledLocation()).thenReturn(lastLocation); + + ArgumentCaptor<String> execJs = ArgumentCaptor.forClass(String.class); + ArgumentCaptor<String> execArg = ArgumentCaptor.forClass(String.class); + + ui.navigate("clean/1"); + Mockito.verify(page).executeJs(execJs.capture(), execArg.capture()); + + assertEquals(CLIENT_PUSHSTATE_TO, execJs.getValue()); + assertEquals("clean/1", execArg.getValue()); + } + + @Test + public void should_not_notify_clientRoute_when_navigatingToTheSame() { + ui = Mockito.spy(ui); + Page page = Mockito.mock(Page.class); + UIInternals internals = Mockito.mock(UIInternals.class); + + Mockito.when(ui.getPage()).thenReturn(page); + Mockito.when(ui.getInternals()).thenReturn(internals); + + Mockito.when(internals.hasLastHandledLocation()).thenReturn(true); + Location lastLocation = new Location("clean"); + Mockito.when(internals.getLastHandledLocation()).thenReturn(lastLocation); + + ui.navigate("clean/"); + Mockito.verify(page, Mockito.never()).executeJs(Mockito.anyString(), Mockito.anyString()); + } + @Test public void should_not_navigate_when_client_routing() { ui.connectClient("foo", "bar", "/clean"); assertEquals(Tag.HEADER, ui.wrapperElement.getChild(0).getTag()); assertEquals(Tag.H2, ui.wrapperElement.getChild(0).getChild(0).getTag()); - - Mockito.when(mocks.getSession().getAttribute(SERVER_ROUTING)) - .thenReturn(Boolean.FALSE); - // Dirty view is allowed after clean view ui.navigate("dirty"); assertEquals(Tag.HEADER, ui.wrapperElement.getChild(0).getTag());
['flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java', 'flow-server/src/test/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUITest.java']
{'.java': 2}
2
2
0
0
2
5,749,053
1,177,914
166,878
1,005
2,042
367
43
1
867
101
227
21
2
1
1970-01-01T00:26:16
502
Java
{'Java': 14177457, 'TypeScript': 439450, 'JavaScript': 319247, 'Kotlin': 117586, 'HTML': 61855, 'CSS': 15678, 'Mustache': 6354, 'Shell': 6177, 'Scala': 2828, 'Smarty': 175, 'SCSS': 124}
Apache License 2.0
1,300
alphawallet/alpha-wallet-android/1269/1266
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/1266
https://github.com/AlphaWallet/alpha-wallet-android/pull/1269
https://github.com/AlphaWallet/alpha-wallet-android/pull/1269
1
fixes
Value to tx is not added from TokenScript
Normally the value param allows you to add eth to your transaction, this does not work in android when the amount to add is not user-entry
3329b4d9d24d811de94abd59b1b380e23e3fa08a
3757ebd49628c5fcc1da520575931e41f0dff712
https://github.com/alphawallet/alpha-wallet-android/compare/3329b4d9d24d811de94abd59b1b380e23e3fa08a...3757ebd49628c5fcc1da520575931e41f0dff712
diff --git a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java index 5367c9196..0a540f145 100644 --- a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java +++ b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java @@ -12,6 +12,7 @@ import android.os.FileObserver; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; +import android.text.TextUtils; import android.util.SparseArray; import com.alphawallet.app.C; @@ -41,7 +42,6 @@ import com.alphawallet.token.entity.ContractInfo; import com.alphawallet.token.entity.EventDefinition; import com.alphawallet.token.entity.FunctionDefinition; import com.alphawallet.token.entity.MethodArg; -import com.alphawallet.token.entity.NonFungibleToken; import com.alphawallet.token.entity.ParseResult; import com.alphawallet.token.entity.SigReturnType; import com.alphawallet.token.entity.TSAction; @@ -53,6 +53,7 @@ import com.alphawallet.token.entity.XMLDsigDescriptor; import com.alphawallet.token.tools.Numeric; import com.alphawallet.token.tools.TokenDefinition; +import org.jetbrains.annotations.NotNull; import org.web3j.abi.FunctionEncoder; import org.web3j.abi.datatypes.Function; import org.web3j.crypto.WalletUtils; @@ -60,7 +61,6 @@ import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.request.EthFilter; import org.web3j.protocol.core.methods.response.EthBlock; import org.web3j.protocol.core.methods.response.EthLog; -import org.web3j.protocol.core.methods.response.EthTransaction; import org.web3j.protocol.core.methods.response.Log; import org.xml.sax.SAXException; @@ -76,7 +76,6 @@ import java.math.BigInteger; import java.net.HttpURLConnection; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; @@ -85,7 +84,6 @@ import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; import io.reactivex.Completable; import io.reactivex.Observable; @@ -1835,4 +1833,16 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface generateAndSendEvents(); } } + + public void resolveReference(@NotNull Token token, TSAction action, TokenscriptElement arg, BigInteger tokenId) + { + TokenDefinition td = getAssetDefinition(token.tokenInfo.chainId, token.getAddress()); + if (td == null || TextUtils.isEmpty(arg.ref)) return; + AttributeType attributeType = (action != null && action.attributeTypes != null) ? action.attributeTypes.get(arg.ref) : null; // try locals first + if (attributeType == null) attributeType = td.attributeTypes.get(arg.ref); // now try globals + if (attributeType != null) + { + arg.value = tokenscriptUtility.fetchAttrResult(tokensService.getCurrentAddress(), attributeType, tokenId, null, td, this, 0).blockingSingle().text; + } + } } diff --git a/app/src/main/java/com/alphawallet/app/ui/ConfirmationActivity.java b/app/src/main/java/com/alphawallet/app/ui/ConfirmationActivity.java index d038a007b..4a427e35a 100644 --- a/app/src/main/java/com/alphawallet/app/ui/ConfirmationActivity.java +++ b/app/src/main/java/com/alphawallet/app/ui/ConfirmationActivity.java @@ -7,6 +7,7 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; +import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -135,6 +136,7 @@ public class ConfirmationActivity extends BaseActivity implements SignAuthentica String tokenList = getIntent().getStringExtra(C.EXTRA_TOKENID_LIST); token = getIntent().getParcelableExtra(C.EXTRA_TOKEN_ID); chainId = token != null ? token.tokenInfo.chainId : getIntent().getIntExtra(C.EXTRA_NETWORKID, 1); + String functionDetails = getIntent().getStringExtra(C.EXTRA_FUNCTION_NAME); String amountString; @@ -191,6 +193,7 @@ public class ConfirmationActivity extends BaseActivity implements SignAuthentica contractAddrLabel.setVisibility(View.VISIBLE); contractAddrText.setText(contractAddress); amountString = getIntent().getStringExtra(C.EXTRA_ACTION_NAME); + if (!TextUtils.isEmpty(functionDetails)) amountString = functionDetails; symbolText.setVisibility(View.GONE); transactionHex = getIntent().getStringExtra(C.EXTRA_TRANSACTION_DATA); diff --git a/app/src/main/java/com/alphawallet/app/viewmodel/TokenFunctionViewModel.java b/app/src/main/java/com/alphawallet/app/viewmodel/TokenFunctionViewModel.java index 5c6b354d4..485af7cf9 100644 --- a/app/src/main/java/com/alphawallet/app/viewmodel/TokenFunctionViewModel.java +++ b/app/src/main/java/com/alphawallet/app/viewmodel/TokenFunctionViewModel.java @@ -6,6 +6,7 @@ import android.arch.lifecycle.MutableLiveData; import android.content.Context; import android.content.Intent; import android.support.annotation.Nullable; +import android.text.TextUtils; import com.alphawallet.app.C; import com.alphawallet.app.R; @@ -39,6 +40,7 @@ import com.alphawallet.token.entity.SigReturnType; import com.alphawallet.token.entity.TSAction; import com.alphawallet.token.entity.TicketRange; import com.alphawallet.token.entity.TokenScriptResult; +import com.alphawallet.token.entity.TokenscriptElement; import com.alphawallet.token.entity.XMLDsigDescriptor; import java.math.BigDecimal; @@ -371,11 +373,14 @@ public class TokenFunctionViewModel extends BaseViewModel String value = "0"; if (action.function.tx != null && action.function.tx.args.containsKey("value")) { + TokenscriptElement arg = action.function.tx.args.get("value"); + //resolve reference + assetDefinitionService.resolveReference(token, action, arg, tokenId); //this is very specific but 'value' is a specifically handled param - value = action.function.tx.args.get("value").value; - BigDecimal valCorrected = getCorrectedBalance(value, 18); + value = arg.value; + Token currency = getCurrency(token.tokenInfo.chainId); - functionEffect = valCorrected.toString() + " " + currency.getSymbol() + " to " + action.function.method; + functionEffect = getCorrectedBalance(value, 18) + " " + currency.getSymbol() + " to " + action.function.method; } //finished resolving attributes, blank definition cache so definition is re-loaded when next needed @@ -431,13 +436,13 @@ public class TokenFunctionViewModel extends BaseViewModel } } - private BigDecimal getCorrectedBalance(String value, int scale) + private BigDecimal getCorrectedBalance(String value, int divisor) { BigDecimal val = BigDecimal.ZERO; try { val = new BigDecimal(value); - BigDecimal decimalDivisor = new BigDecimal(Math.pow(10, scale)); + BigDecimal decimalDivisor = new BigDecimal(Math.pow(10, divisor)); val = val.divide(decimalDivisor); } catch (Exception e) @@ -445,7 +450,7 @@ public class TokenFunctionViewModel extends BaseViewModel e.printStackTrace(); } - return val.setScale(scale, RoundingMode.HALF_DOWN).stripTrailingZeros(); + return val.setScale(4, RoundingMode.HALF_DOWN).stripTrailingZeros(); } public OpenseaService getOpenseaService()
['app/src/main/java/com/alphawallet/app/ui/ConfirmationActivity.java', 'app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java', 'app/src/main/java/com/alphawallet/app/viewmodel/TokenFunctionViewModel.java']
{'.java': 3}
3
3
0
0
3
2,488,038
483,616
71,925
539
2,413
479
38
3
138
26
28
1
0
0
1970-01-01T00:26:25
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,306
alphawallet/alpha-wallet-android/1089/1087
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/1087
https://github.com/AlphaWallet/alpha-wallet-android/pull/1089
https://github.com/AlphaWallet/alpha-wallet-android/pull/1089
1
closes
TokenScripts don't update after conditional on props
Example: Compound requires you enable the dai contract before using supply or withdraw, our TokenScript checks if you have enabled and if so, allows you to supply/withdraw and if not displays a message saying you must enable first. In Android this does not work, when you have updated, the prop check fails to update the screen to allow you to supply/withdraw after checking the allowance prop to see if it is enabled.
d339125891914fcd510081ab3860522515b18745
9b1338342e7feaa8b6e3acb2e5e132ff7d8cd3a1
https://github.com/alphawallet/alpha-wallet-android/compare/d339125891914fcd510081ab3860522515b18745...9b1338342e7feaa8b6e3acb2e5e132ff7d8cd3a1
diff --git a/app/src/main/java/com/alphawallet/app/entity/tokenscript/TokenscriptFunction.java b/app/src/main/java/com/alphawallet/app/entity/tokenscript/TokenscriptFunction.java index 1878d2ac4..13f4567e0 100644 --- a/app/src/main/java/com/alphawallet/app/entity/tokenscript/TokenscriptFunction.java +++ b/app/src/main/java/com/alphawallet/app/entity/tokenscript/TokenscriptFunction.java @@ -563,6 +563,29 @@ public abstract class TokenscriptFunction } } + /** + * Fetches a TokenScript attribute + * + * May either return a static attribute sourced from the Token ID or a dynamic one from a contract function + * + * If a dynamic function, then test to see if we can source the value from the result cache - + * Test to see if the contract has seen any transactions AFTER the result was cached, if so then invalidate the result and re-fetch + * + * TODO: there is currently an optimisation issue with this. If the contract being called to resolve the attribute is not the token + * contract which the script refers to then the result is not cached. This can be seen eg with 'ENABLE' functions which permit + * the script contract to manipulate the tokens which the 'ENABLE' function is being called on. + * It may not be possible to always safely cache these values; even with an event handler we have to interpret those events and invalidate + * any cached results. However if we're tracking the referenced contract as a token then it should be safe + * + * @param walletAddress + * @param attribute + * @param tokenId + * @param cAddr + * @param td + * @param attrIf + * @param transactionUpdate + * @return + */ public Observable<TokenScriptResult.Attribute> fetchAttrResult(String walletAddress, String attribute, BigInteger tokenId, ContractAddress cAddr, TokenDefinition td, AttributeInterface attrIf, long transactionUpdate) { AttributeType attr = td.attributeTypes.get(attribute); @@ -576,17 +599,17 @@ public abstract class TokenscriptFunction ContractAddress useAddress; if (cAddr == null) useAddress = new ContractAddress(attr.function); else useAddress = new ContractAddress(attr.function, cAddr.chainId, cAddr.address); - TransactionResult transactionResult = attrIf.getFunctionResult(useAddress, attr, tokenId); //Needs to allow for multiple tokenIds - if (attrIf.resolveOptimisedAttr(useAddress, attr, transactionResult) || !transactionResult.needsUpdating(transactionUpdate)) //can we use wallet's known data or cached value? + TransactionResult cachedResult = attrIf.getFunctionResult(useAddress, attr, tokenId); //Needs to allow for multiple tokenIds + if (cAddr != null && !useAddress.address.equalsIgnoreCase(cAddr.address)) transactionUpdate = 0; //If calling a function which isn't the main tokenscript function retrieve from contract call not cache + if (attrIf.resolveOptimisedAttr(useAddress, attr, cachedResult) || !cachedResult.needsUpdating(transactionUpdate)) //can we use wallet's known data or cached value? { - return resultFromDatabase(transactionResult, attr); + return resultFromDatabase(cachedResult, attr); } - else //if value is old or there wasn't any previous value + else //if cached value is invalid or if value is dynamic { - //for function query, never need wallet address return fetchResultFromEthereum(walletAddress, useAddress, attr, tokenId, td, attrIf, transactionUpdate) // Fetch function result from blockchain - .map(result -> restoreFromDBIfRequired(result, transactionResult)) // If network unavailable restore value from cache - .map(attrIf::storeAuxData) // store new data + .map(result -> restoreFromDBIfRequired(result, cachedResult)) // If network unavailable restore value from cache + .map(attrIf::storeAuxData) // store new data .map(result -> parseFunctionResult(result, attr)); // write returned data into attribute } } @@ -640,16 +663,16 @@ public abstract class TokenscriptFunction /** * Restore result from Database if required (eg connection failure), and if there was a database value to restore - * @param result - * @param transactionResult + * @param result return from calling contract function + * @param cachedResult previous return value, restored from database * @return */ - private TransactionResult restoreFromDBIfRequired(TransactionResult result, TransactionResult transactionResult) + private TransactionResult restoreFromDBIfRequired(TransactionResult result, TransactionResult cachedResult) { - if (result.resultTime == 0 && transactionResult != null) + if (result.resultTime == 0 && cachedResult != null && result.result == null) { - result.result = transactionResult.result; - result.resultTime = transactionResult.resultTime; + result.result = cachedResult.result; + result.resultTime = cachedResult.resultTime; } return result; diff --git a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java index a939a6533..e3ea9e263 100644 --- a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java +++ b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java @@ -1122,7 +1122,6 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface @Override public void onStart() { - if (tResult.result == null) tResult.result = ""; if (!WalletUtils.isValidAddress(tokensService.getCurrentAddress())) return; realm = realmManager.getAuxRealmInstance(tokensService.getCurrentAddress()); ContractAddress cAddr = new ContractAddress(tResult.contractChainId, tResult.contractAddress); @@ -1137,7 +1136,7 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface realm.beginTransaction(); createAuxData(realm, tResult); } - else if (realmToken.getResultTime() != tResult.resultTime) + else if (tResult.result != null) { TransactionsRealmCache.addRealm(); realm.beginTransaction(); diff --git a/app/src/main/java/com/alphawallet/app/viewmodel/TransactionsViewModel.java b/app/src/main/java/com/alphawallet/app/viewmodel/TransactionsViewModel.java index 932b6a67a..2cc63b199 100644 --- a/app/src/main/java/com/alphawallet/app/viewmodel/TransactionsViewModel.java +++ b/app/src/main/java/com/alphawallet/app/viewmodel/TransactionsViewModel.java @@ -146,11 +146,11 @@ public class TransactionsViewModel extends BaseViewModel private void checkUnknownTokens() { - if (queryUnknownTokensDisposable == null && !unknownTokens.isEmpty()) + if (queryUnknownTokensDisposable == null) { UnknownToken t = unknownTokens.poll(); - if (tokensService.getToken(t.chainId, t.address) == null) + if (t != null && tokensService.getToken(t.chainId, t.address) == null) { queryUnknownTokensDisposable = setupTokensInteract.addToken(t.address, t.chainId) //fetch tokenInfo .filter(tokenInfo -> tokenInfo.name != null) @@ -255,6 +255,8 @@ public class TransactionsViewModel extends BaseViewModel if (!txMap.containsKey(tx.hash)) { txMap.put(tx.hash, tx); + //does this transaction correspond to a known token? + checkTokenTransactions(tx); } } @@ -262,6 +264,18 @@ public class TransactionsViewModel extends BaseViewModel fetchTransactionDisposable = null; } + private void checkTokenTransactions(Transaction tx) + { + Token t = tokensService.getToken(tx.chainId, tx.to); + Long blockNumber = Long.parseLong(tx.blockNumber); + if (t != null && !t.isEthereum() && t.lastBlockCheck < blockNumber) + { + t.lastBlockCheck = blockNumber; + t.lastTxTime = tx.timeStamp*1000; //update last transaction received time + addTokenInteract.updateBlockRead(t, defaultWallet().getValue()); + } + } + private void onUpdateTransactions(Transaction[] transactions, Token token) { fetchTransactionDisposable = null;
['app/src/main/java/com/alphawallet/app/entity/tokenscript/TokenscriptFunction.java', 'app/src/main/java/com/alphawallet/app/viewmodel/TransactionsViewModel.java', 'app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java']
{'.java': 3}
3
3
0
0
3
2,342,840
455,545
67,896
524
4,893
969
70
3
425
72
85
5
0
0
1970-01-01T00:26:19
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,305
alphawallet/alpha-wallet-android/1127/1103
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/1103
https://github.com/AlphaWallet/alpha-wallet-android/pull/1127
https://github.com/AlphaWallet/alpha-wallet-android/pull/1127
1
closes
Unnecessary prompt to backup wallet after keystore import
- Import from keystore - enter keystore password - authorise OS - (wallet imported and taken to wallet tab) - shows prompt to backup wallet - Expect: no prompt to backup imported wallet? - click on Settings, `Back up this Wallet` already shown as 100% secure
a779e6867aa21ca59a6a3fdf27b69838b8552251
e346bb5c5a178469d5349be98850e8820b8a2314
https://github.com/alphawallet/alpha-wallet-android/compare/a779e6867aa21ca59a6a3fdf27b69838b8552251...e346bb5c5a178469d5349be98850e8820b8a2314
diff --git a/app/src/main/java/com/alphawallet/app/ui/HomeActivity.java b/app/src/main/java/com/alphawallet/app/ui/HomeActivity.java index d439f3df0..b12560a7e 100644 --- a/app/src/main/java/com/alphawallet/app/ui/HomeActivity.java +++ b/app/src/main/java/com/alphawallet/app/ui/HomeActivity.java @@ -222,7 +222,6 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick } viewModel.cleanDatabases(this); - showBackupWalletDialog(); } private void onBackup(String address) @@ -233,23 +232,32 @@ public class HomeActivity extends BaseNavigationActivity implements View.OnClick } } - public void showBackupWalletDialog() { - if (!viewModel.isFindWalletAddressDialogShown()) { - int lighterBackground = Color.argb(102, 0, 0, 0); //40% opacity - backupWalletDialog = TutoShowcase.from(this); - backupWalletDialog.setContentView(R.layout.showcase_backup_wallet) - .setBackgroundColor(lighterBackground) - .onClickContentView(R.id.btn_close, view -> { - backupWalletDialog.dismiss(); - }) - .on(R.id.settings_tab) - .addCircle() - .onClick(v -> { - backupWalletDialog.dismiss(); - showPage(SETTINGS); - }) - .show(); - viewModel.setFindWalletAddressDialogShown(true); + public void showBackupWalletDialog(boolean walletImported) { + if (!viewModel.isFindWalletAddressDialogShown()) + { + //check if wallet was imported - in which case no need to display + if (walletImported) + { + viewModel.setFindWalletAddressDialogShown(true); + } + else + { + int lighterBackground = Color.argb(102, 0, 0, 0); //40% opacity + backupWalletDialog = TutoShowcase.from(this); + backupWalletDialog.setContentView(R.layout.showcase_backup_wallet) + .setBackgroundColor(lighterBackground) + .onClickContentView(R.id.btn_close, view -> { + backupWalletDialog.dismiss(); + }) + .on(R.id.settings_tab) + .addCircle() + .onClick(v -> { + backupWalletDialog.dismiss(); + showPage(SETTINGS); + }) + .show(); + viewModel.setFindWalletAddressDialogShown(true); + } } } diff --git a/app/src/main/java/com/alphawallet/app/ui/WalletFragment.java b/app/src/main/java/com/alphawallet/app/ui/WalletFragment.java index 520d3b03e..e24851af1 100644 --- a/app/src/main/java/com/alphawallet/app/ui/WalletFragment.java +++ b/app/src/main/java/com/alphawallet/app/ui/WalletFragment.java @@ -101,6 +101,7 @@ public class WalletFragment extends Fragment implements OnTokenClickListener, Vi viewModel.tokenUpdate().observe(this, this::onToken); viewModel.tokensReady().observe(this, this::tokensReady); viewModel.backupEvent().observe(this, this::backupEvent); + viewModel.defaultWallet().observe(this, this::onDefaultWallet); adapter = new TokensAdapter(this, viewModel.getAssetDefinitionService(), viewModel.getTokensService()); adapter.setHasStableIds(true); @@ -122,6 +123,12 @@ public class WalletFragment extends Fragment implements OnTokenClickListener, Vi return view; } + private void onDefaultWallet(Wallet wallet) + { + //Do we display new user backup popup? + ((HomeActivity)getActivity()).showBackupWalletDialog(wallet.lastBackupTime > 0); + } + private void refreshList() { adapter.clear(); diff --git a/app/src/main/java/com/alphawallet/app/viewmodel/WalletViewModel.java b/app/src/main/java/com/alphawallet/app/viewmodel/WalletViewModel.java index 4369328a2..249b4f9af 100644 --- a/app/src/main/java/com/alphawallet/app/viewmodel/WalletViewModel.java +++ b/app/src/main/java/com/alphawallet/app/viewmodel/WalletViewModel.java @@ -60,6 +60,7 @@ public class WalletViewModel extends BaseViewModel private final MutableLiveData<BigDecimal> total = new MutableLiveData<>(); private final MutableLiveData<Token> tokenUpdate = new MutableLiveData<>(); private final MutableLiveData<Boolean> tokensReady = new MutableLiveData<>(); + private final MutableLiveData<Wallet> defaultWallet = new MutableLiveData<>(); private final MutableLiveData<GenericWalletInteract.BackupLevel> backupEvent = new MutableLiveData<>(); private final FetchTokensInteract fetchTokensInteract; @@ -130,6 +131,7 @@ public class WalletViewModel extends BaseViewModel } public LiveData<Token> tokenUpdate() { return tokenUpdate; } public LiveData<Boolean> tokensReady() { return tokensReady; } + public LiveData<Wallet> defaultWallet() { return defaultWallet; } public LiveData<GenericWalletInteract.BackupLevel> backupEvent() { return backupEvent; } public String getWalletAddr() { return currentWallet != null ? currentWallet.address : null; } @@ -465,6 +467,7 @@ public class WalletViewModel extends BaseViewModel private void onDefaultWallet(@NotNull Wallet wallet) { tokensService.setCurrentAddress(wallet.address); currentWallet = wallet; + defaultWallet.postValue(wallet); fetchTokens(); }
['app/src/main/java/com/alphawallet/app/ui/HomeActivity.java', 'app/src/main/java/com/alphawallet/app/viewmodel/WalletViewModel.java', 'app/src/main/java/com/alphawallet/app/ui/WalletFragment.java']
{'.java': 3}
3
3
0
0
3
2,342,663
455,546
67,878
523
2,566
438
54
3
264
46
62
7
0
0
1970-01-01T00:26:20
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,304
alphawallet/alpha-wallet-android/1129/914
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/914
https://github.com/AlphaWallet/alpha-wallet-android/pull/1129
https://github.com/AlphaWallet/alpha-wallet-android/pull/1129
1
closes
TokenScript cards should take the localised name defined in the TokenScript
At the moment it is taking the name from the smart contract, instead it should take the name defined in the tokenscript file and fallback to english if the user's language is not there. Useful for Devcon because we renamed the discovery card to devcon5 goodies but not a show stopper.
7c6de64249afd5458d445d51496d5e011fb57f5a
02271fb3e66cff2fd477ec8db07001f1c1fbce52
https://github.com/alphawallet/alpha-wallet-android/compare/7c6de64249afd5458d445d51496d5e011fb57f5a...02271fb3e66cff2fd477ec8db07001f1c1fbce52
diff --git a/app/src/main/java/com/alphawallet/app/entity/tokens/ERC721Token.java b/app/src/main/java/com/alphawallet/app/entity/tokens/ERC721Token.java index 9ee45e25b..369746cb7 100644 --- a/app/src/main/java/com/alphawallet/app/entity/tokens/ERC721Token.java +++ b/app/src/main/java/com/alphawallet/app/entity/tokens/ERC721Token.java @@ -129,7 +129,7 @@ public class ERC721Token extends Token implements Parcelable holder.balanceEth.setVisibility(View.VISIBLE); - addTokenName(holder); + addTokenName(holder, definition); } @Override diff --git a/app/src/main/java/com/alphawallet/app/entity/tokens/Token.java b/app/src/main/java/com/alphawallet/app/entity/tokens/Token.java index 53c308e0c..05cba885c 100644 --- a/app/src/main/java/com/alphawallet/app/entity/tokens/Token.java +++ b/app/src/main/java/com/alphawallet/app/entity/tokens/Token.java @@ -216,6 +216,7 @@ public class Token implements Parcelable public String getAddress() { return tokenInfo.address; } + public String getFullName() { if (isTerminated()) return SetupTokensInteract.EXPIRED_CONTRACT; @@ -227,11 +228,14 @@ public class Token implements Parcelable public String getFullName(AssetDefinitionService assetDefinition, int count) { - String name = getFullName(); - String tokenTypeName = assetDefinition.getTokenName(tokenInfo.chainId, tokenInfo.address, count); - if (name != null && tokenTypeName != null && !name.contains(tokenTypeName)) name = name + " " + tokenTypeName; - - return name; + //override contract name with TS defined name + String name = assetDefinition.getTokenName(tokenInfo.chainId, tokenInfo.address, count); + if (name != null) { + String symbol = (tokenInfo.symbol == null || tokenInfo.symbol.length() == 0) ? "" : " (" + tokenInfo.symbol.toUpperCase() + ")"; + return name + symbol; + } else { + return getFullName(); + } } public void clickReact(BaseViewModel viewModel, Context context) @@ -281,7 +285,7 @@ public class Token implements Parcelable holder.layoutValueDetails.setVisibility(View.GONE); } - addTokenName(holder); + addTokenName(holder, definition); //populate ticker if we have it if (ticker != null) @@ -306,13 +310,13 @@ public class Token implements Parcelable holder.balanceEth.setVisibility(View.VISIBLE); } - void addTokenName(TokenHolder holder) + void addTokenName(TokenHolder holder, AssetDefinitionService definitionService) { String balance = holder.balanceEth.getText().toString(); String symbolStr = tokenInfo.symbol != null ? tokenInfo.symbol.toUpperCase() : ""; String nameTxt = TextUtils.isEmpty(tokenInfo.name) ? symbolStr - : getFullName(); + : getFullName(definitionService, getTicketCount()); String composite = balance + " " + nameTxt; holder.balanceEth.setText(composite);
['app/src/main/java/com/alphawallet/app/entity/tokens/Token.java', 'app/src/main/java/com/alphawallet/app/entity/tokens/ERC721Token.java']
{'.java': 2}
2
2
0
0
2
2,349,843
456,937
68,099
524
1,109
217
22
2
289
51
63
3
0
0
1970-01-01T00:26:20
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,301
alphawallet/alpha-wallet-android/1178/1177
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/1177
https://github.com/AlphaWallet/alpha-wallet-android/pull/1178
https://github.com/AlphaWallet/alpha-wallet-android/pull/1178
1
fixes
"Scan QR Code" from Browser Tab home shows "Invalid Scan Result"
This only occurs on the home screen of the browser "My DApps", "Discover DApps", "History"... This does not occur if a webpage is loaded. In that scenario the QR-code url loads successfully.
8dd94a2333218f581352916e192fff616ce44ab6
c80b6e1d67079f246af6ccb428395a98a51b8c44
https://github.com/alphawallet/alpha-wallet-android/compare/8dd94a2333218f581352916e192fff616ce44ab6...c80b6e1d67079f246af6ccb428395a98a51b8c44
diff --git a/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java b/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java index 0e8621d0a..8a537e904 100644 --- a/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java +++ b/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java @@ -9,6 +9,7 @@ import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; +import android.os.Handler; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; @@ -161,6 +162,8 @@ public class DappBrowserFragment extends Fragment implements OnSignTransactionLi private TextView balance; private TextView symbol; + private final Handler handler; + private String currentWebpageTitle; private String currentFragment; @@ -183,6 +186,7 @@ public class DappBrowserFragment extends Fragment implements OnSignTransactionLi myDappsFragment = new MyDappsFragment(); discoverDappsFragment = new DiscoverDappsFragment(); browserHistoryFragment = new BrowserHistoryFragment(); + handler = new Handler(); } @Override @@ -1084,7 +1088,7 @@ public class DappBrowserFragment extends Fragment implements OnSignTransactionLi else { //attempt to go to site - loadUrl(qrCode); + loadUrlRemote(qrCode); } } } @@ -1107,6 +1111,15 @@ public class DappBrowserFragment extends Fragment implements OnSignTransactionLi } } + /** + * Loads URL from remote process; this converts a request to load URL which isn't on the app's thread + * @param qrCode + */ + private void loadUrlRemote(final String qrCode) + { + handler.post(() -> loadUrl(qrCode)); + } + private void showCameraDenied() { if (getActivity() == null) return;
['app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java']
{'.java': 1}
1
1
0
0
1
2,390,993
464,549
69,269
532
467
94
15
1
191
32
44
2
0
0
1970-01-01T00:26:22
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,308
alphawallet/alpha-wallet-android/944/908
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/908
https://github.com/AlphaWallet/alpha-wallet-android/pull/944
https://github.com/AlphaWallet/alpha-wallet-android/pull/944
1
fixes
cDAI tokenscript is incorrectly bound to DAI card
Should only apply to the cDAI card but is also attached to the regular DAI card.
390cad8e708a63fc6883b5cb13cce50410b5070a
730c34c55475277f0530c96eb580325770cebe44
https://github.com/alphawallet/alpha-wallet-android/compare/390cad8e708a63fc6883b5cb13cce50410b5070a...730c34c55475277f0530c96eb580325770cebe44
diff --git a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java index 2dcce0588..f1e3f2232 100644 --- a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java +++ b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java @@ -272,12 +272,13 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface //try cache if (cachedDefinition != null) { - for (String contractName : cachedDefinition.contracts.keySet()) + //only match holding token + ContractInfo holdingContracts = cachedDefinition.contracts.get(cachedDefinition.holdingToken); + if (holdingContracts != null && holdingContracts.addresses.containsKey(chainId)) { - if (cachedDefinition.contracts.get(contractName).addresses.containsKey(chainId) - && cachedDefinition.contracts.get(contractName).addresses.get(chainId).contains(address)) + for (String addr : holdingContracts.addresses.get(chainId)) { - return cachedDefinition; + if (addr.equalsIgnoreCase(address.toLowerCase())) return cachedDefinition; } } }
['app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java']
{'.java': 1}
1
1
0
0
1
2,269,103
440,671
66,196
523
745
119
9
1
81
16
21
1
0
0
1970-01-01T00:26:11
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,298
alphawallet/alpha-wallet-android/1457/1455
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/1455
https://github.com/AlphaWallet/alpha-wallet-android/pull/1457
https://github.com/AlphaWallet/alpha-wallet-android/pull/1457
1
closes
Selection condition fails when comparing admin attribute to ownerAddress
To reproduce: Watch: 0xD40EBAaA4Cb7fC3a5D7B373309F68B2ABCe5F1C5 go to GFO(GFO) token that has a server TS Expected: About Issue Move View actions should be present because ownerAddress == admin Actual: Only About is shown, this happens when the user is not an admin TokenScript: https://github.com/AlphaWallet/gf.network/blob/master/TS/GFO/GFO-TokenScript.xml#L30
d4ee0a0146adc9a6486c1a3587d421e9718a7e07
cf4d951eeac3e4d642aa1317c54489e57d25536a
https://github.com/alphawallet/alpha-wallet-android/compare/d4ee0a0146adc9a6486c1a3587d421e9718a7e07...cf4d951eeac3e4d642aa1317c54489e57d25536a
diff --git a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java index 3653a2375..7e8840111 100644 --- a/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java +++ b/app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java @@ -1523,6 +1523,7 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface //get required Attribute Results for this tokenId & selection List<String> requiredAttributeNames = selection.getRequiredAttrs(); Map<String, TokenScriptResult.Attribute> idAttrResults = getAttributeResultsForTokenIds(attrResults, requiredAttributeNames, tokenId); + addIntrinsicAttributes(idAttrResults, token, tokenId); //adding intrinsic attributes eg ownerAddress, tokenId, contractAddress //Now evaluate the selection boolean exclude = EvaluateSelection.evaluate(selection.head, idAttrResults); @@ -1540,6 +1541,14 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface }); } + private void addIntrinsicAttributes(Map<String, TokenScriptResult.Attribute> attrs, Token token, BigInteger tokenId) + { + //add tokenId, ownerAddress & contractAddress + attrs.put("tokenId", new TokenScriptResult.Attribute("tokenId", "tokenId", tokenId, tokenId.toString(10))); + attrs.put("ownerAddress", new TokenScriptResult.Attribute("ownerAddress", "ownerAddress", BigInteger.ZERO, token.getWallet())); + attrs.put("contractAddress", new TokenScriptResult.Attribute("contractAddress", "contractAddress", BigInteger.ZERO, token.getAddress())); + } + public String checkFunctionDenied(Token token, String actionName, List<BigInteger> tokenIds) { String denialMessage = null; @@ -1564,6 +1573,8 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface if (attrResult != null) attrs.put(attrId, attrResult); } + addIntrinsicAttributes(attrs, token, tokenId); + boolean exclude = EvaluateSelection.evaluate(selection.head, attrs); if (exclude && !TextUtils.isEmpty(selection.denialMessage)) { diff --git a/lib/src/main/java/com/alphawallet/token/entity/FilterType.java b/lib/src/main/java/com/alphawallet/token/entity/FilterType.java index a875a5f42..e593172d3 100644 --- a/lib/src/main/java/com/alphawallet/token/entity/FilterType.java +++ b/lib/src/main/java/com/alphawallet/token/entity/FilterType.java @@ -5,5 +5,5 @@ package com.alphawallet.token.entity; */ public enum FilterType { - AND, OR, NOT, GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL_TO, GREATER_THAN, LESS_THAN, EQUAL, VALUE, START_BRACE, END_BRACE + AND, OR, NOT, GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL_TO, GREATER_THAN, LESS_THAN, EQUAL, VALUE, ATTRIBUTE, START_BRACE, END_BRACE } \\ No newline at end of file diff --git a/lib/src/main/java/com/alphawallet/token/entity/TSFilterNode.java b/lib/src/main/java/com/alphawallet/token/entity/TSFilterNode.java index 990577c91..c72abf2ce 100644 --- a/lib/src/main/java/com/alphawallet/token/entity/TSFilterNode.java +++ b/lib/src/main/java/com/alphawallet/token/entity/TSFilterNode.java @@ -2,6 +2,9 @@ package com.alphawallet.token.entity; import java.math.BigInteger; import java.util.Map; +import java.util.regex.Matcher; + +import static com.alphawallet.token.entity.TSSelection.decodeParam; /** * Created by JB on 21/05/2020. @@ -17,9 +20,14 @@ public class TSFilterNode String strValue = null; LogicState logic = LogicState.NONE; - public TSFilterNode(String val, TSFilterNode p) + public TSFilterNode(String val, TSFilterNode p, FilterType t) { - type = FilterType.VALUE; + if (t == FilterType.ATTRIBUTE) + { + val = extractAttribute(val); + } + + type = t; try { value = new BigInteger(val); @@ -166,7 +174,7 @@ public class TSFilterNode { returnValue = node.logic.toString(); } - else if (node.strValue != null && node.strValue.length() > 0) + else if (node.type == FilterType.ATTRIBUTE) { TokenScriptResult.Attribute attr = attrs.get(node.strValue); if (attr != null) @@ -174,10 +182,10 @@ public class TSFilterNode //found an attribute returnValue = attr.text; } - else - { - returnValue = node.strValue; - } + } + else if (node.strValue != null && node.strValue.length() > 0) + { + returnValue = node.strValue; } return returnValue; @@ -210,6 +218,20 @@ public class TSFilterNode } } + private String extractAttribute(String val) + { + Matcher matcher = decodeParam.matcher(val); + if (matcher.find() && !matcher.group(1).isEmpty()) + { + //found an attribute param + return matcher.group(1); + } + else + { + return val; + } + } + enum LogicState { NONE, TRUE, FALSE diff --git a/lib/src/main/java/com/alphawallet/token/entity/TSSelection.java b/lib/src/main/java/com/alphawallet/token/entity/TSSelection.java index 997790326..f9ec64e0b 100644 --- a/lib/src/main/java/com/alphawallet/token/entity/TSSelection.java +++ b/lib/src/main/java/com/alphawallet/token/entity/TSSelection.java @@ -7,6 +7,8 @@ import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Created by JB on 21/05/2020. @@ -19,6 +21,8 @@ public class TSSelection private boolean negate = false; public String name = null; + public static final Pattern decodeParam = Pattern.compile("[$][{](\\\\w*)[}]$"); + public TSSelection(String filterExpression) throws SAXException { //tokenise @@ -137,14 +141,14 @@ public class TSSelection String b = tokens.next(); FilterType typeB = getType(b); - if (typeB != FilterType.VALUE) + if (!(typeB == FilterType.VALUE || typeB == FilterType.ATTRIBUTE)) { throw new SAXException("PARSE ERROR: Invalid subject after '" + a + logic); } TSFilterNode comparator = new TSFilterNode(typeLogic, currentNode); - comparator.first = new TSFilterNode(a, comparator); - comparator.second = new TSFilterNode(b, comparator); + comparator.first = new TSFilterNode(a, comparator, FilterType.ATTRIBUTE); + comparator.second = new TSFilterNode(b, comparator, typeB); if (negate) { comparator.negate = true; @@ -190,7 +194,7 @@ public class TSSelection type = FilterType.NOT; break; default: - type = FilterType.VALUE; + type = unwrapValue(token); break; } @@ -291,6 +295,20 @@ public class TSSelection return attrs; } + private FilterType unwrapValue(String token) + { + Matcher matcher = decodeParam.matcher(token); + if (matcher.find() && !matcher.group(1).isEmpty()) + { + //found an attribute param + return FilterType.ATTRIBUTE; + } + else + { + return FilterType.VALUE; + } + } + public boolean checkParse() { return name != null && name.length() > 0
['lib/src/main/java/com/alphawallet/token/entity/TSSelection.java', 'app/src/main/java/com/alphawallet/app/service/AssetDefinitionService.java', 'lib/src/main/java/com/alphawallet/token/entity/FilterType.java', 'lib/src/main/java/com/alphawallet/token/entity/TSFilterNode.java']
{'.java': 4}
4
4
0
0
4
2,687,729
522,301
78,004
568
3,140
655
75
4
382
42
113
14
1
0
1970-01-01T00:26:32
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,311
alphawallet/alpha-wallet-android/409/405
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/405
https://github.com/AlphaWallet/alpha-wallet-android/pull/409
https://github.com/AlphaWallet/alpha-wallet-android/pull/409
2
fix
Can you adopt a pet dog success?
Please open the websitehttp://112.124.104.209:3000/ in alpha-wallet-android DAPP browser with selecting the network of the ropsten test network. Click "Adopt" Button when to adopt a dog. Can it be success? I can't get sucess, and I want to know how to debug in alpha-wallet-android DAPP browser ?
ea1a972702a3640d3917364cfa2bcaaefee37c43
61637ab8811d9e1b72ec50f5f5a576dff0182884
https://github.com/alphawallet/alpha-wallet-android/compare/ea1a972702a3640d3917364cfa2bcaaefee37c43...61637ab8811d9e1b72ec50f5f5a576dff0182884
diff --git a/app/src/main/java/io/stormbird/wallet/repository/EthereumNetworkRepository.java b/app/src/main/java/io/stormbird/wallet/repository/EthereumNetworkRepository.java index 5f50695b3..4c0c31651 100644 --- a/app/src/main/java/io/stormbird/wallet/repository/EthereumNetworkRepository.java +++ b/app/src/main/java/io/stormbird/wallet/repository/EthereumNetworkRepository.java @@ -33,7 +33,7 @@ public class EthereumNetworkRepository implements EthereumNetworkRepositoryType new NetworkInfo(ETHEREUM_NETWORK_NAME, ETH_SYMBOL, "https://mainnet.infura.io/v3/da3717f25f824cc1baa32d812386d93f", "https://etherscan.io/tx/",1, true, - "https://ethereum.awallet.io/", + "https://mainnet.infura.io/v3/da3717f25f824cc1baa32d812386d93f", "https://api.etherscan.io/"), new NetworkInfo(CLASSIC_NETWORK_NAME, ETC_SYMBOL, "https://mewapi.epool.io/", @@ -44,7 +44,7 @@ public class EthereumNetworkRepository implements EthereumNetworkRepositoryType new NetworkInfo(KOVAN_NETWORK_NAME, ETH_SYMBOL, "https://kovan.infura.io/v3/da3717f25f824cc1baa32d812386d93f", "https://kovan.etherscan.io/tx/", 42, false, - null, + "https://kovan.infura.io/v3/da3717f25f824cc1baa32d812386d93f", "https://api-kovan.etherscan.io/"), new NetworkInfo(ROPSTEN_NETWORK_NAME, ETH_SYMBOL, "http://66.96.208.58:8545/", diff --git a/app/src/main/java/io/stormbird/wallet/ui/DappBrowserFragment.java b/app/src/main/java/io/stormbird/wallet/ui/DappBrowserFragment.java index 53002ef27..33c0178ac 100644 --- a/app/src/main/java/io/stormbird/wallet/ui/DappBrowserFragment.java +++ b/app/src/main/java/io/stormbird/wallet/ui/DappBrowserFragment.java @@ -185,8 +185,10 @@ public class DappBrowserFragment extends Fragment implements if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG); } - web3.setChainId(1); - web3.setRpcUrl(C.ETH_RPC_URL); + web3.setChainId(networkInfo.chainId); + String rpcURL = networkInfo.rpcServerUrl; + if (networkInfo.backupNodeUrl != null) rpcURL = networkInfo.backupNodeUrl; + web3.setRpcUrl(rpcURL); web3.setWalletAddress(new Address(wallet.address)); web3.setWebChromeClient(new WebChromeClient() {
['app/src/main/java/io/stormbird/wallet/repository/EthereumNetworkRepository.java', 'app/src/main/java/io/stormbird/wallet/ui/DappBrowserFragment.java']
{'.java': 2}
2
2
0
0
2
1,569,701
306,182
46,494
442
480
148
10
2
298
46
76
3
1
0
1970-01-01T00:25:41
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,310
alphawallet/alpha-wallet-android/817/814
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/814
https://github.com/AlphaWallet/alpha-wallet-android/pull/817
https://github.com/AlphaWallet/alpha-wallet-android/pull/817
1
fixes
Transactions involving ether crash
Go to WETH tokencard and wrap ether for WETH, it will crash. We need to fix this before the tutorial
cdd88977f546cd7434bbfdd93cc3b2eb2d823ce8
f5ba577165ebaab3d8a1c2682a18a4632ef2b9b0
https://github.com/alphawallet/alpha-wallet-android/compare/cdd88977f546cd7434bbfdd93cc3b2eb2d823ce8...f5ba577165ebaab3d8a1c2682a18a4632ef2b9b0
diff --git a/app/src/main/java/io/stormbird/wallet/entity/Token.java b/app/src/main/java/io/stormbird/wallet/entity/Token.java index 0d751151b..f990f8d60 100644 --- a/app/src/main/java/io/stormbird/wallet/entity/Token.java +++ b/app/src/main/java/io/stormbird/wallet/entity/Token.java @@ -41,6 +41,7 @@ public class Token implements Parcelable public boolean balanceChanged; public boolean walletUIUpdateRequired; public boolean hasTokenScript; + public boolean hasDebugTokenscript; public boolean refreshCheck; public long lastTxUpdate = 0; @@ -80,6 +81,7 @@ public class Token implements Parcelable lastTxUpdate = oldToken.lastTxUpdate; balanceChanged = oldToken.balanceChanged; hasTokenScript = oldToken.hasTokenScript; + hasDebugTokenscript = oldToken.hasDebugTokenscript; } refreshCheck = false; } @@ -96,7 +98,9 @@ public class Token implements Parcelable lastTxCheck = in.readLong(); lastTxUpdate = in.readLong(); int readTS = in.readByte(); + int readDTS = in.readByte(); hasTokenScript = readTS == 1; + hasDebugTokenscript = readDTS == 1; balanceChanged = false; if (readType <= ContractType.CREATION.ordinal()) { @@ -154,6 +158,7 @@ public class Token implements Parcelable dest.writeLong(lastTxCheck); dest.writeLong(lastTxUpdate); dest.writeByte(hasTokenScript?(byte)1:(byte)0); + dest.writeByte(hasDebugTokenscript?(byte)1:(byte)0); } public void setRealmBalance(RealmToken realmToken) @@ -201,6 +206,7 @@ public class Token implements Parcelable public BigDecimal getCorrectedBalance(int scale) { + if (balance.equals(BigDecimal.ZERO)) return BigDecimal.ZERO; BigDecimal decimalDivisor = new BigDecimal(Math.pow(10, tokenInfo.decimals)); BigDecimal ethBalance = tokenInfo.decimals > 0 ? balance.divide(decimalDivisor) : balance; diff --git a/app/src/main/java/io/stormbird/wallet/service/AssetDefinitionService.java b/app/src/main/java/io/stormbird/wallet/service/AssetDefinitionService.java index 2b84fe3c3..f0c243ffc 100644 --- a/app/src/main/java/io/stormbird/wallet/service/AssetDefinitionService.java +++ b/app/src/main/java/io/stormbird/wallet/service/AssetDefinitionService.java @@ -885,6 +885,8 @@ public class AssetDefinitionService implements ParseResult, AttributeInterface Token token = tokensService.getToken(networkId, address); if (token != null) { + File tokenDef = defMap.get(address); + if (tokenDef != null && tokenDef.getAbsolutePath().contains(ALPHAWALLET_DIR)) token.hasDebugTokenscript = true; token.hasTokenScript = true; TokenDefinition td = getAssetDefinition(networkId, address); ContractInfo cInfo = td.contracts.get(td.holdingToken); diff --git a/app/src/main/java/io/stormbird/wallet/ui/FunctionActivity.java b/app/src/main/java/io/stormbird/wallet/ui/FunctionActivity.java index cb82363b9..0effaf4a9 100644 --- a/app/src/main/java/io/stormbird/wallet/ui/FunctionActivity.java +++ b/app/src/main/java/io/stormbird/wallet/ui/FunctionActivity.java @@ -437,7 +437,17 @@ public class FunctionActivity extends BaseActivity implements View.OnClickListen isValid = false; } - String to = function.tx.args.get("to").value; + //is 'to' overridden? + String to = null; + if (function.tx.args.get("to") != null) + { + to = function.tx.args.get("to").value; + } + else if (function.contract.addresses.get(token.tokenInfo.chainId) != null) + { + to = function.contract.addresses.get(token.tokenInfo.chainId).get(0); + } + if (to == null || !Utils.isAddressValid(to)) { errorInvalidAddress(to); diff --git a/app/src/main/java/io/stormbird/wallet/ui/widget/adapter/TokensAdapter.java b/app/src/main/java/io/stormbird/wallet/ui/widget/adapter/TokensAdapter.java index b86f48af2..a909fa808 100644 --- a/app/src/main/java/io/stormbird/wallet/ui/widget/adapter/TokensAdapter.java +++ b/app/src/main/java/io/stormbird/wallet/ui/widget/adapter/TokensAdapter.java @@ -222,7 +222,7 @@ public class TokensAdapter extends RecyclerView.Adapter<BinderViewHolder> { return allowThroughFilter && //Add token to display list if it's the base currency, or if it has balance ((token.isEthereum() && token.tokenInfo.chainId == MAINNET_ID) || (!token.isTerminated() && !token.isBad() && - (token.hasPositiveBalance()))); + (token.hasDebugTokenscript || token.hasPositiveBalance()))); } private void populateTokens(Token[] tokens) diff --git a/lib/src/main/java/io/stormbird/token/tools/TokenDefinition.java b/lib/src/main/java/io/stormbird/token/tools/TokenDefinition.java index 0c2017ff0..66592f1f7 100644 --- a/lib/src/main/java/io/stormbird/token/tools/TokenDefinition.java +++ b/lib/src/main/java/io/stormbird/token/tools/TokenDefinition.java @@ -11,6 +11,9 @@ import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; import java.util.*; import static org.w3c.dom.Node.ELEMENT_NODE; @@ -283,7 +286,7 @@ public class TokenDefinition { NodeList nList = xml.getElementsByTagNameNS(nameSpace, "token"); - if (nList.getLength() == 0 || !nameSpace.equals(TOKENSCRIPT)) + if (nList.getLength() == 0 || nameSpace == null) { System.out.println("Legacy XML format - no longer supported"); return; @@ -413,15 +416,51 @@ public class TokenDefinition { //check attributes for (int j = 0; j < n.getAttributes().getLength(); j++) { - Node thisAttr = n.getAttributes().item(j); - if (thisAttr.getNodeValue().contains(TOKENSCRIPTBASE)) + try { - nameSpace = TOKENSCRIPT; - if (result != null && !thisAttr.getNodeValue().equals(TOKENSCRIPT)) + Node thisAttr = n.getAttributes().item(j); + if (thisAttr.getNodeValue().contains(TOKENSCRIPTBASE)) { - result.parseMessage(ParseResult.ParseResultId.OK); + nameSpace = thisAttr.getNodeValue(); + + int dateIndex = nameSpace.indexOf(TOKENSCRIPTBASE) + TOKENSCRIPTBASE.length(); + int lastSeparator = nameSpace.lastIndexOf("/"); + if ((lastSeparator - dateIndex) == 7) + { + DateFormat format = new SimpleDateFormat("yyyy/MM", Locale.ENGLISH); + Date thisDate = format.parse(nameSpace.substring(dateIndex, lastSeparator)); + Date schemaDate = format.parse(TOKENSCRIPT_CURRENT_SCHEMA); + + if (thisDate.equals(schemaDate)) + { + //all good + if (result != null) result.parseMessage(ParseResult.ParseResultId.OK); + } + else if (thisDate.before(schemaDate)) + { + //still acceptable + if (result != null) result.parseMessage(ParseResult.ParseResultId.XML_OUT_OF_DATE); + } + else + { + //cannot parse future schema + if (result != null) result.parseMessage(ParseResult.ParseResultId.PARSER_OUT_OF_DATE); + nameSpace = null; + } + } + else + { + if (result != null) result.parseMessage(ParseResult.ParseResultId.PARSE_FAILED); + nameSpace = null; + } + return; } - return; + } + catch (Exception e) + { + if (result != null) result.parseMessage(ParseResult.ParseResultId.PARSE_FAILED); + nameSpace = null; + e.printStackTrace(); } } } diff --git a/lib/src/test/java/io/stormbird/token/tools/TokenDefinitionTest.java b/lib/src/test/java/io/stormbird/token/tools/TokenDefinitionTest.java index b0f4176bc..a07f6919d 100644 --- a/lib/src/test/java/io/stormbird/token/tools/TokenDefinitionTest.java +++ b/lib/src/test/java/io/stormbird/token/tools/TokenDefinitionTest.java @@ -14,7 +14,7 @@ import java.util.stream.Stream; import static org.junit.Assert.*; -public class TokenDefinitionTest implements AttributeInterface +public class TokenDefinitionTest implements AttributeInterface, ParseResult { Stream<BigInteger> ticketIDs = Stream.of( "1015b4a28f000000000000000000000", "1015b4a28f000000000000000000000", @@ -25,7 +25,7 @@ public class TokenDefinitionTest implements AttributeInterface @Test public void TokenInformationCanBeExtracted() throws IOException, SAXException { assertTrue(file.exists()); - TokenDefinition entryToken = new TokenDefinition(new FileInputStream(file), new Locale("en"), null); + TokenDefinition entryToken = new TokenDefinition(new FileInputStream(file), new Locale("en"), this); assertFalse(entryToken.attributeTypes.isEmpty()); for (String contractName : entryToken.contracts.keySet()) { @@ -49,7 +49,7 @@ public class TokenDefinitionTest implements AttributeInterface @Test public void AttributeTypesShouldParse() throws IOException, SAXException { - TokenDefinition entryToken = new TokenDefinition(new FileInputStream(file), new Locale("en"), null); + TokenDefinition entryToken = new TokenDefinition(new FileInputStream(file), new Locale("en"), this); BigInteger tokenId = new BigInteger("1015b4a28f000000000000000000000", 16); //StringBuilder tokenData = new StringBuilder(); @@ -72,14 +72,14 @@ public class TokenDefinitionTest implements AttributeInterface @Test public void XMLSignatureShouldValidate() throws IOException, SAXException { - TokenDefinition entryToken = new TokenDefinition(new FileInputStream(file), new Locale("en"), null); + TokenDefinition entryToken = new TokenDefinition(new FileInputStream(file), new Locale("en"), this); assertEquals("EntryToken", entryToken.holdingToken); // TODO: actually validate XML signature } @Test(expected = SAXException.class) public void BadLocaleShouldThrowException() throws IOException, SAXException { - TokenDefinition ticketAsset = new TokenDefinition(new FileInputStream(file), new Locale("asdf"), null); + TokenDefinition ticketAsset = new TokenDefinition(new FileInputStream(file), new Locale("asdf"), this); } @@ -103,4 +103,26 @@ public class TokenDefinitionTest implements AttributeInterface { return false; } + + @Override + public void parseMessage(ParseResultId parseResult) + { + switch (parseResult) + { + case OK: + System.out.println("Schema date is correct."); + break; + case XML_OUT_OF_DATE: + System.out.println("Parsing outdated schema. It's an older schema but it checks out."); + break; + case PARSER_OUT_OF_DATE: + System.out.println("Parser attempting to parse future schema. Code base needs to be updated."); + fail(); + break; + case PARSE_FAILED: + System.out.println("Parser Error."); + fail(); + break; + } + } }
['app/src/main/java/io/stormbird/wallet/ui/FunctionActivity.java', 'app/src/main/java/io/stormbird/wallet/service/AssetDefinitionService.java', 'app/src/main/java/io/stormbird/wallet/ui/widget/adapter/TokensAdapter.java', 'lib/src/test/java/io/stormbird/token/tools/TokenDefinitionTest.java', 'lib/src/main/java/io/stormbird/token/tools/TokenDefinition.java', 'app/src/main/java/io/stormbird/wallet/entity/Token.java']
{'.java': 6}
6
6
0
0
6
1,979,361
383,758
58,332
505
3,949
661
75
5
101
20
27
1
0
0
1970-01-01T00:26:06
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
8,594
crawljax/crawljax/234/226
crawljax
crawljax
https://github.com/crawljax/crawljax/issues/226
https://github.com/crawljax/crawljax/pull/234
https://github.com/crawljax/crawljax/pull/234
1
fixes
Max number of states is incorrect
Some crawls quit because the maximum number of states was reached, while it hasn't.
7a483a5d9ac3fcc83c9c0661c0c8c7b5df6bc780
b8cb6a2c7d986b8d435daaccb5c80e0db26353ac
https://github.com/crawljax/crawljax/compare/7a483a5d9ac3fcc83c9c0661c0c8c7b5df6bc780...b8cb6a2c7d986b8d435daaccb5c80e0db26353ac
diff --git a/core/src/main/java/com/crawljax/core/state/StateFlowGraph.java b/core/src/main/java/com/crawljax/core/state/StateFlowGraph.java index a9d3c2b7..a2291d7d 100644 --- a/core/src/main/java/com/crawljax/core/state/StateFlowGraph.java +++ b/core/src/main/java/com/crawljax/core/state/StateFlowGraph.java @@ -38,6 +38,7 @@ public class StateFlowGraph implements Serializable { * Thread-safety. */ private final AtomicInteger stateCounter = new AtomicInteger(); + private final AtomicInteger nextStateNameCounter = new AtomicInteger(); private final StateVertex initialState; @@ -53,6 +54,7 @@ public class StateFlowGraph implements Serializable { sfg.addVertex(initialState); stateCounter.incrementAndGet(); this.initialState = initialState; + LOG.debug("Initialized the stateflowgraph with an initial state"); } /** @@ -69,8 +71,8 @@ public class StateFlowGraph implements Serializable { * @return the clone if one is detected null otherwise. * @see org.jgrapht.Graph#addVertex(Object) */ - public StateVertex addState(StateVertex stateVertix) { - return addState(stateVertix, true); + public StateVertex putIfAbsent(StateVertex stateVertix) { + return putIfAbsent(stateVertix, true); } /** @@ -90,19 +92,20 @@ public class StateFlowGraph implements Serializable { * @see org.jgrapht.Graph#addVertex(Object) */ @GuardedBy("sfg") - public StateVertex addState(StateVertex stateVertix, boolean correctName) { + public StateVertex putIfAbsent(StateVertex stateVertix, boolean correctName) { synchronized (sfg) { - if (!sfg.addVertex(stateVertix)) { - // Graph already contained the vertix - LOG.debug("Graph already contained vertex {}", stateVertix); - return this.getStateInGraph(stateVertix); - } else { + boolean added = sfg.addVertex(stateVertix); + if (added) { int count = stateCounter.incrementAndGet(); LOG.debug("Number of states is now {}", count); if (correctName) { correctStateName(stateVertix); } return null; + } else { + // Graph already contained the vertix + LOG.debug("Graph already contained vertex {}", stateVertix); + return this.getStateInGraph(stateVertix); } } } @@ -369,8 +372,7 @@ public class StateFlowGraph implements Serializable { * @return State name the name of the state */ public String getNewStateName() { - stateCounter.getAndIncrement(); - String state = makeStateName(stateCounter.get(), false); + String state = makeStateName(nextStateNameCounter.incrementAndGet(), false); return state; } diff --git a/core/src/main/java/com/crawljax/core/state/StateMachine.java b/core/src/main/java/com/crawljax/core/state/StateMachine.java index 8858d5eb..73c51c89 100644 --- a/core/src/main/java/com/crawljax/core/state/StateMachine.java +++ b/core/src/main/java/com/crawljax/core/state/StateMachine.java @@ -96,7 +96,7 @@ public class StateMachine { currentState.getName(), newState.getName()); // Add the state to the stateFlowGraph. Store the result - StateVertex cloneState = stateFlowGraph.addState(newState); + StateVertex cloneState = stateFlowGraph.putIfAbsent(newState); // Is there a clone detected? if (cloneState != null) { diff --git a/core/src/main/java/com/crawljax/plugins/savecrawlsession/SessionReader.java b/core/src/main/java/com/crawljax/plugins/savecrawlsession/SessionReader.java index 3a4e17af..a02c7d03 100644 --- a/core/src/main/java/com/crawljax/plugins/savecrawlsession/SessionReader.java +++ b/core/src/main/java/com/crawljax/plugins/savecrawlsession/SessionReader.java @@ -39,7 +39,7 @@ public class SessionReader { if (sfg == null) { sfg = new StateFlowGraph(state); } else { - sfg.addState(state, false); + sfg.putIfAbsent(state, false); } } for (Transition transition : savedCrawlSession.getTransitions()) { diff --git a/core/src/test/java/com/crawljax/core/state/EventableTest.java b/core/src/test/java/com/crawljax/core/state/EventableTest.java index 4e07ca80..7ceb5c83 100644 --- a/core/src/test/java/com/crawljax/core/state/EventableTest.java +++ b/core/src/test/java/com/crawljax/core/state/EventableTest.java @@ -108,7 +108,7 @@ public class EventableTest { StateVertex s2 = new StateVertex("stateTarget", "dom2"); StateFlowGraph sfg = new StateFlowGraph(s1); - sfg.addState(s2); + sfg.putIfAbsent(s2); Eventable e = new Eventable(); diff --git a/core/src/test/java/com/crawljax/core/state/StateFlowGraphTest.java b/core/src/test/java/com/crawljax/core/state/StateFlowGraphTest.java index 987424fc..b3e6d56b 100644 --- a/core/src/test/java/com/crawljax/core/state/StateFlowGraphTest.java +++ b/core/src/test/java/com/crawljax/core/state/StateFlowGraphTest.java @@ -45,12 +45,12 @@ public class StateFlowGraphTest { @Test public void testSFG() throws Exception { StateVertex DOUBLE = new StateVertex("index", "<table><div>index</div></table>"); - assertTrue(graph.addState(state2) == null); - assertTrue(graph.addState(state3) == null); - assertTrue(graph.addState(state4) == null); - assertTrue(graph.addState(state5) == null); + assertTrue(graph.putIfAbsent(state2) == null); + assertTrue(graph.putIfAbsent(state3) == null); + assertTrue(graph.putIfAbsent(state4) == null); + assertTrue(graph.putIfAbsent(state5) == null); - assertFalse(graph.addState(DOUBLE) == null); + assertFalse(graph.putIfAbsent(DOUBLE) == null); assertTrue(graph.addEdge(index, state2, new Eventable(new Identification(How.xpath, "/body/div[4]"), EventType.click))); @@ -116,8 +116,8 @@ public class StateFlowGraphTest { StateVertex state3clone2 = new StateVertex("STATE_THREE", "<table><div>state2</div></table>"); - assertTrue(graph.addState(state2) == null); - assertTrue(graph.addState(state4) == null); + assertTrue(graph.putIfAbsent(state2) == null); + assertTrue(graph.putIfAbsent(state4) == null); // assertFalse(graph.addState(state3)); assertTrue(graph.addEdge(index, state2, new Eventable(new Identification(How.xpath, "/body/div[4]"), EventType.click))); @@ -149,7 +149,7 @@ public class StateFlowGraphTest { + "<body><div id='firstdiv' class='orange'>"; StateFlowGraph g = new StateFlowGraph(new StateVertex("", HTML1)); - g.addState(new StateVertex("", HTML2)); + g.putIfAbsent(new StateVertex("", HTML2)); assertEquals(206, g.getMeanStateStringSize()); } @@ -161,8 +161,8 @@ public class StateFlowGraphTest { Eventable c2 = new Eventable(new Identification(How.xpath, "/body/div[4]/div[2]"), EventType.click); - graph.addState(index); - graph.addState(state2); + graph.putIfAbsent(index); + graph.putIfAbsent(state2); graph.addEdge(index, state2, c1); graph.addEdge(index, state2, c2); @@ -171,10 +171,10 @@ public class StateFlowGraphTest { @Test public void testAllPossiblePaths() { - graph.addState(state2); - graph.addState(state3); - graph.addState(state4); - graph.addState(state5); + graph.putIfAbsent(state2); + graph.putIfAbsent(state3); + graph.putIfAbsent(state4); + graph.putIfAbsent(state5); graph.addEdge(index, state2, new Eventable(new Identification(How.xpath, "/index/2"), EventType.click)); @@ -218,10 +218,10 @@ public class StateFlowGraphTest { @Test public void largetTest() { - graph.addState(state2); - graph.addState(state3); - graph.addState(state4); - graph.addState(state5); + graph.putIfAbsent(state2); + graph.putIfAbsent(state3); + graph.putIfAbsent(state4); + graph.putIfAbsent(state5); graph.addEdge(index, state2, new Eventable(new Identification(How.xpath, "/index/2"), EventType.click)); @@ -271,31 +271,31 @@ public class StateFlowGraphTest { @Test public void guidedCrawlingFlag() { - graph.addState(state2); - graph.addState(state3); - graph.addState(state4); - graph.addState(state5); + graph.putIfAbsent(state2); + graph.putIfAbsent(state3); + graph.putIfAbsent(state4); + graph.putIfAbsent(state5); assertThat(graph, hasStates(5)); StateVertex state6 = new StateVertex("STATE_FIVE", "<table><div>state5</div></table>"); state6.setGuidedCrawling(false); - graph.addState(state6); + graph.putIfAbsent(state6); assertThat(graph, hasStates(5)); state6.setGuidedCrawling(true); - graph.addState(state6); + graph.putIfAbsent(state6); assertThat(graph, hasStates(6)); } @Test public void testEdges() throws Exception { - assertTrue(graph.addState(state2) == null); - assertTrue(graph.addState(state3) == null); - assertTrue(graph.addState(state4) == null); + assertTrue(graph.putIfAbsent(state2) == null); + assertTrue(graph.putIfAbsent(state3) == null); + assertTrue(graph.putIfAbsent(state4) == null); Eventable e1 = new Eventable(new Identification(How.xpath, "/4/index"), EventType.click); @@ -333,9 +333,9 @@ public class StateFlowGraphTest { new Eventable(new Identification(How.xpath, "/body/div[4]/div[6]"), EventType.click); - graph.addState(index); - graph.addState(state2); - graph.addState(state3); + graph.putIfAbsent(index); + graph.putIfAbsent(state2); + graph.putIfAbsent(state3); graph.addEdge(index, state2, c1); graph.addEdge(index, state2, c2); @@ -356,7 +356,7 @@ public class StateFlowGraphTest { @Test public void whenStateAddedTheGraphCouterIsIncremented() { assertThat(graph.getNumberOfStates(), is(1)); - graph.addState(state2); + graph.putIfAbsent(state2); assertThat(graph.getNumberOfStates(), is(2)); }
['core/src/test/java/com/crawljax/core/state/StateFlowGraphTest.java', 'core/src/main/java/com/crawljax/core/state/StateMachine.java', 'core/src/main/java/com/crawljax/core/state/StateFlowGraph.java', 'core/src/main/java/com/crawljax/plugins/savecrawlsession/SessionReader.java', 'core/src/test/java/com/crawljax/core/state/EventableTest.java']
{'.java': 5}
5
5
0
0
5
471,170
109,878
16,713
153
1,313
291
26
3
85
14
19
2
0
0
1970-01-01T00:22:45
493
Java
{'Java': 2321919, 'JavaScript': 1023004, 'HTML': 766291, 'CSS': 21008, 'Dockerfile': 1832, 'Shell': 310}
Apache License 2.0
1,303
alphawallet/alpha-wallet-android/1151/947
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/947
https://github.com/AlphaWallet/alpha-wallet-android/pull/1151
https://github.com/AlphaWallet/alpha-wallet-android/pull/1151
1
closes
Problem bookmarking with mydapps in browser
- Go to browser tab - Navigate to any page (eg twitter.com) - Tap "..." in top right corner, then "Add to My DApps" - Title: "Twitter. It's what's happening / Twitter" - Address: "https://mobile.twitter.com/" - Change Title and/or URL, tap done - Tap "Add" (returns to twitter) - Tap Browser tab, shows original text. Expect: changed title - Tap twitter icon, goes to original URL. Expect: changed URL
533288d990ef415a2461777a79e8147289abb073
7462d3dc4446ccffda0e9ebae05dd17e72f67350
https://github.com/alphawallet/alpha-wallet-android/compare/533288d990ef415a2461777a79e8147289abb073...7462d3dc4446ccffda0e9ebae05dd17e72f67350
diff --git a/app/src/main/java/com/alphawallet/app/ui/AddEditDappActivity.java b/app/src/main/java/com/alphawallet/app/ui/AddEditDappActivity.java index c41e94a4c..f93b6fd85 100644 --- a/app/src/main/java/com/alphawallet/app/ui/AddEditDappActivity.java +++ b/app/src/main/java/com/alphawallet/app/ui/AddEditDappActivity.java @@ -78,7 +78,10 @@ public class AddEditDappActivity extends BaseActivity { button.setText(R.string.action_add); name.setText(dapp.getName()); url.setText(dapp.getUrl()); - button.setOnClickListener(v -> add(dapp)); + button.setOnClickListener(v -> { + dapp.setName(name.getEditableText().toString()); + dapp.setUrl(url.getEditableText().toString()); + add(dapp); }); break; } case MODE_EDIT: { @@ -86,7 +89,9 @@ public class AddEditDappActivity extends BaseActivity { button.setText(R.string.action_save); url.setText(dapp.getUrl()); name.setText(dapp.getName()); - button.setOnClickListener(v -> save(dapp)); + button.setOnClickListener(v -> { + save(dapp); + }); break; } default: { diff --git a/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java b/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java index 6f4fb2992..d7741dd3c 100644 --- a/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java +++ b/app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java @@ -345,7 +345,8 @@ public class DappBrowserFragment extends Fragment implements OnSignTransactionLi else { attachFragment(dappHomeFragment, DAPP_HOME); - urlTv.getText().clear(); + if (urlTv != null) + urlTv.getText().clear(); if (web3 != null) web3.stopLoading(); }
['app/src/main/java/com/alphawallet/app/ui/AddEditDappActivity.java', 'app/src/main/java/com/alphawallet/app/ui/DappBrowserFragment.java']
{'.java': 2}
2
2
0
0
2
2,380,027
462,642
69,001
533
559
88
12
2
413
69
108
9
1
0
1970-01-01T00:26:21
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
8,592
crawljax/crawljax/357/339
crawljax
crawljax
https://github.com/crawljax/crawljax/issues/339
https://github.com/crawljax/crawljax/pull/357
https://github.com/crawljax/crawljax/pull/357
1
fixes
Escape domain detection has a leak
When crawljax asserts if it has left the domain it checks if the host of its current url is in the new url. This is done here in [Crawljax.java](https://github.com/crawljax/crawljax/blob/fa5a31390f202f6e8d55f4bb6f229c02a867c530/core/src/main/java/com/crawljax/core/Crawler.java#L410-L413) However, when it visits a social platform like Google+, that new URL has the domain int it as well, as a parameter. Crawljax should check that the hostname occurs in the host part of the current URL.
754e59e46ae1349be3c6eeefa95f56093bb12b61
38c754d786a41622ac23b975385c2090d2d63880
https://github.com/crawljax/crawljax/compare/754e59e46ae1349be3c6eeefa95f56093bb12b61...38c754d786a41622ac23b975385c2090d2d63880
diff --git a/core/src/main/java/com/crawljax/core/Crawler.java b/core/src/main/java/com/crawljax/core/Crawler.java index 9ab526f3..1d4d51a0 100644 --- a/core/src/main/java/com/crawljax/core/Crawler.java +++ b/core/src/main/java/com/crawljax/core/Crawler.java @@ -408,8 +408,7 @@ public class Crawler { } private boolean crawlerLeftDomain() { - return !browser.getCurrentUrl().toLowerCase() - .contains(url.getHost().toLowerCase()); + return !UrlUtils.isSameDomain(browser.getCurrentUrl(), url); } private long parseWaitTimeOrReturnDefault(Matcher m) { diff --git a/core/src/main/java/com/crawljax/util/UrlUtils.java b/core/src/main/java/com/crawljax/util/UrlUtils.java index 969832ed..048c7ab0 100644 --- a/core/src/main/java/com/crawljax/util/UrlUtils.java +++ b/core/src/main/java/com/crawljax/util/UrlUtils.java @@ -1,6 +1,8 @@ package com.crawljax.util; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.regex.PatternSyntaxException; @@ -93,6 +95,26 @@ public class UrlUtils { return null; } + /** + * Checks if the given URL is part of the domain, or a subdomain of the given {@link URL}. + * + * @param currentUrl + * The url you want to check. + * @param url + * The URL acting as the base. + * @return If the URL is part of the domain. + */ + public static boolean isSameDomain(String currentUrl, URL url) { + try { + String current = URI.create(currentUrl).getHost().toLowerCase(); + String original = url.toURI().getHost().toLowerCase(); + return current.endsWith(original); + } catch (URISyntaxException e) { + LOG.warn("Could not parse URI {}", currentUrl); + return false; + } + } + private UrlUtils() { } diff --git a/core/src/test/java/com/crawljax/util/UrlUtilsTest.java b/core/src/test/java/com/crawljax/util/UrlUtilsTest.java index 598c9851..6c2ca3f5 100644 --- a/core/src/test/java/com/crawljax/util/UrlUtilsTest.java +++ b/core/src/test/java/com/crawljax/util/UrlUtilsTest.java @@ -65,4 +65,23 @@ public class UrlUtilsTest { } + @Test + public void testIsSameDomain() throws MalformedURLException { + + // Same URL + assertThat(UrlUtils.isSameDomain("http://example.com", + new URL("http://example.com")), is(true)); + + // Different URL + assertThat(UrlUtils.isSameDomain("http://test.com", + new URL("http://example.com")), is(false)); + + // Same URL with subdomain + assertThat(UrlUtils.isSameDomain("http://test.example.com", + new URL("http://example.com")), is(true)); + + // Same URL but with HTTPS + assertThat(UrlUtils.isSameDomain("https://example.com", + new URL("http://example.com")), is(true)); + } }
['core/src/test/java/com/crawljax/util/UrlUtilsTest.java', 'core/src/main/java/com/crawljax/util/UrlUtils.java', 'core/src/main/java/com/crawljax/core/Crawler.java']
{'.java': 3}
3
3
0
0
3
453,766
104,377
15,958
151
865
201
25
2
494
66
136
8
1
0
1970-01-01T00:23:03
493
Java
{'Java': 2321919, 'JavaScript': 1023004, 'HTML': 766291, 'CSS': 21008, 'Dockerfile': 1832, 'Shell': 310}
Apache License 2.0
1,299
alphawallet/alpha-wallet-android/1291/1281
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/1281
https://github.com/AlphaWallet/alpha-wallet-android/pull/1291
https://github.com/AlphaWallet/alpha-wallet-android/pull/1291
1
fixes
"no data" on TokenScript action pages
Expected: - Open ENS and click on any action button - See the action page Actual: - Open ENS and click on any action button - See "no data" in page (works only the first time, each time after requires you to kill the app and do it again) Happening on xiaomi redmi
b9ed76ac56f55bf82d6e7cad2ea40fdacd6c0644
501e4c4c1d8157b21c3d0e96cceaa56498d17563
https://github.com/alphawallet/alpha-wallet-android/compare/b9ed76ac56f55bf82d6e7cad2ea40fdacd6c0644...501e4c4c1d8157b21c3d0e96cceaa56498d17563
diff --git a/app/src/main/java/com/alphawallet/app/di/RepositoriesModule.java b/app/src/main/java/com/alphawallet/app/di/RepositoriesModule.java index aeee6300f..cbeec7704 100644 --- a/app/src/main/java/com/alphawallet/app/di/RepositoriesModule.java +++ b/app/src/main/java/com/alphawallet/app/di/RepositoriesModule.java @@ -123,13 +123,11 @@ public class RepositoriesModule { TokenRepositoryType provideTokenRepository( EthereumNetworkRepositoryType ethereumNetworkRepository, TokenLocalSource tokenLocalSource, - GasService gasService, - TokensService tokensService) { + GasService gasService) { return new TokenRepository( ethereumNetworkRepository, tokenLocalSource, - gasService, - tokensService); + gasService); } @Singleton @@ -146,8 +144,8 @@ public class RepositoriesModule { @Singleton @Provides - TokensService provideTokensService(EthereumNetworkRepositoryType ethereumNetworkRepository, RealmManager realmManager, OkHttpClient okHttpClient, PreferenceRepositoryType preferenceRepository) { - return new TokensService(ethereumNetworkRepository, realmManager, okHttpClient, preferenceRepository); + TokensService provideTokensService(EthereumNetworkRepositoryType ethereumNetworkRepository, TokenRepositoryType tokenRepository, OkHttpClient okHttpClient, PreferenceRepositoryType preferenceRepository) { + return new TokensService(ethereumNetworkRepository, tokenRepository, okHttpClient, preferenceRepository); } @Singleton diff --git a/app/src/main/java/com/alphawallet/app/interact/FetchTokensInteract.java b/app/src/main/java/com/alphawallet/app/interact/FetchTokensInteract.java index b15f3910d..4efda255f 100644 --- a/app/src/main/java/com/alphawallet/app/interact/FetchTokensInteract.java +++ b/app/src/main/java/com/alphawallet/app/interact/FetchTokensInteract.java @@ -33,7 +33,7 @@ public class FetchTokensInteract { public Observable<Token> fetchStoredToken(NetworkInfo network, Wallet wallet, String tokenAddress) { if (TextUtils.isEmpty(tokenAddress)) tokenAddress = wallet.address.toLowerCase(); - return tokenRepository.fetchCachedSingleToken(network, wallet.address, tokenAddress) + return tokenRepository.fetchCachedSingleToken(network.chainId, wallet.address, tokenAddress) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } diff --git a/app/src/main/java/com/alphawallet/app/repository/TokenLocalSource.java b/app/src/main/java/com/alphawallet/app/repository/TokenLocalSource.java index 37cafa886..1b01421c4 100644 --- a/app/src/main/java/com/alphawallet/app/repository/TokenLocalSource.java +++ b/app/src/main/java/com/alphawallet/app/repository/TokenLocalSource.java @@ -18,10 +18,11 @@ public interface TokenLocalSource { Single<Token[]> saveTokens(Wallet wallet, Token[] items); void updateTokenBalance(NetworkInfo network, Wallet wallet, Token token); Token getTokenBalance(NetworkInfo network, Wallet wallet, String address); + Token fetchToken(int chainId, Wallet wallet, String address); Map<Integer, Token> getTokenBalances(Wallet wallet, String address); void setEnable(NetworkInfo network, Wallet wallet, Token token, boolean isEnabled); - Single<Token> fetchEnabledToken(NetworkInfo networkInfo, Wallet wallet, String address); + Single<Token> fetchEnabledToken(int chainId, Wallet wallet, String address); Single<Token[]> fetchTokensWithBalance(Wallet wallet); Single<Token> saveTicker(Wallet wallet, Token token); Single<Token[]> saveTickers(Wallet wallet, Token[] tokens); diff --git a/app/src/main/java/com/alphawallet/app/repository/TokenRepository.java b/app/src/main/java/com/alphawallet/app/repository/TokenRepository.java index d028bfa48..8064f5dc1 100644 --- a/app/src/main/java/com/alphawallet/app/repository/TokenRepository.java +++ b/app/src/main/java/com/alphawallet/app/repository/TokenRepository.java @@ -77,7 +77,6 @@ public class TokenRepository implements TokenRepositoryType { private final TokenLocalSource localSource; private final EthereumNetworkRepositoryType ethereumNetworkRepository; private final GasService gasService; - private final TokensService tokensService; public static final String INVALID_CONTRACT = "<invalid>"; @@ -96,13 +95,11 @@ public class TokenRepository implements TokenRepositoryType { public TokenRepository( EthereumNetworkRepositoryType ethereumNetworkRepository, TokenLocalSource localSource, - GasService gasService, - TokensService tokensService) { + GasService gasService) { this.ethereumNetworkRepository = ethereumNetworkRepository; this.localSource = localSource; this.ethereumNetworkRepository.addOnChangeDefaultNetwork(this::buildWeb3jClient); this.gasService = gasService; - this.tokensService = tokensService; web3jNodeServers = new ConcurrentHashMap<>(); okClient = new OkHttpClient.Builder() @@ -249,19 +246,26 @@ public class TokenRepository implements TokenRepositoryType { NetworkInfo network = ethereumNetworkRepository.getNetworkByChain(token.tokenInfo.chainId); Wallet wallet = new Wallet(walletAddress); return Single.merge( - fetchCachedToken(network, wallet, token.getAddress()), + fetchCachedToken(network.chainId, wallet, token.getAddress()), updateBalance(network, wallet, token)) // Looking for new tokens .toObservable(); } @Override - public Observable<Token> fetchCachedSingleToken(NetworkInfo network, String walletAddress, String tokenAddress) + public Observable<Token> fetchCachedSingleToken(int chainId, String walletAddress, String tokenAddress) { Wallet wallet = new Wallet(walletAddress); - return fetchCachedToken(network, wallet, tokenAddress) + return fetchCachedToken(chainId, wallet, tokenAddress) .toObservable(); } + @Override + public Token fetchToken(int chainId, String walletAddress, String address) + { + Wallet wallet = new Wallet(walletAddress); + return localSource.fetchToken(chainId, wallet, address); + } + /** * Just updates the balance of a token * @@ -582,7 +586,7 @@ public class TokenRepository implements TokenRepositoryType { private void updateInService(Token t) { t.walletUIUpdateRequired = true; - tokensService.addToken(t); + TokensService.setInterfaceSpec(t.tokenInfo.chainId, t.getAddress(), t.getInterfaceSpec()); } /** @@ -638,15 +642,15 @@ public class TokenRepository implements TokenRepositoryType { .fetchTokensWithBalance(wallet); } - private Single<Token> fetchCachedToken(NetworkInfo network, Wallet wallet, String address) + private Single<Token> fetchCachedToken(int chainId, Wallet wallet, String address) { return localSource - .fetchEnabledToken(network, wallet, address); + .fetchEnabledToken(chainId, wallet, address); } private BigDecimal updatePending(Token oldToken, BigDecimal pendingBalance) { - if (!tokensService.getCurrentAddress().equals(oldToken.getWallet())) + if (!TokensService.getCurrentWalletAddress().equals(oldToken.getWallet())) { oldToken.pendingBalance = oldToken.balance; } diff --git a/app/src/main/java/com/alphawallet/app/repository/TokenRepositoryType.java b/app/src/main/java/com/alphawallet/app/repository/TokenRepositoryType.java index d0bda136b..29fe9e662 100644 --- a/app/src/main/java/com/alphawallet/app/repository/TokenRepositoryType.java +++ b/app/src/main/java/com/alphawallet/app/repository/TokenRepositoryType.java @@ -23,7 +23,7 @@ public interface TokenRepositoryType { Observable<Token[]> fetchStored(String walletAddress); Observable<Token[]> fetchActiveStoredPlusEth(String walletAddress); Observable<Token> fetchActiveSingle(String walletAddress, Token token); - Observable<Token> fetchCachedSingleToken(NetworkInfo network, String walletAddress, String tokenAddress); + Observable<Token> fetchCachedSingleToken(int chainId, String walletAddress, String tokenAddress); Observable<Token> fetchActiveTokenBalance(String walletAddress, Token token); Single<ContractResult> getTokenResponse(String address, int chainId, String method); Completable setEnable(Wallet wallet, Token token, boolean isEnabled); @@ -36,6 +36,7 @@ public interface TokenRepositoryType { Single<TokenTicker> getTokenTicker(Token token); Single<Token> getEthBalance(NetworkInfo network, Wallet wallet); Single<BigInteger> fetchLatestBlockNumber(int chainId); + Token fetchToken(int chainId, String walletAddress, String address); Disposable terminateToken(Token token, Wallet wallet, NetworkInfo network); diff --git a/app/src/main/java/com/alphawallet/app/repository/TokensRealmSource.java b/app/src/main/java/com/alphawallet/app/repository/TokensRealmSource.java index 65f597fe2..c321d496e 100644 --- a/app/src/main/java/com/alphawallet/app/repository/TokensRealmSource.java +++ b/app/src/main/java/com/alphawallet/app/repository/TokensRealmSource.java @@ -167,18 +167,22 @@ public class TokensRealmSource implements TokenLocalSource { } @Override - public Single<Token> fetchEnabledToken(NetworkInfo networkInfo, Wallet wallet, String address) { - return Single.fromCallable(() -> { - try (Realm realm = realmManager.getRealmInstance(wallet)) - { - RealmToken realmItem = realm.where(RealmToken.class) - .equalTo("address", databaseKey(networkInfo.chainId, address)) - .equalTo("chainId", networkInfo.chainId) - .findFirst(); + public Single<Token> fetchEnabledToken(int chainId, Wallet wallet, String address) { + return Single.fromCallable(() -> fetchToken(chainId, wallet, address)); + } - return convertSingle(realmItem, realm, null, wallet); - } - }); + @Override + public Token fetchToken(int chainId, Wallet wallet, String address) + { + try (Realm realm = realmManager.getRealmInstance(wallet)) + { + RealmToken realmItem = realm.where(RealmToken.class) + .equalTo("address", databaseKey(chainId, address)) + .equalTo("chainId", chainId) + .findFirst(); + + return convertSingle(realmItem, realm, null, wallet); + } } @Override diff --git a/app/src/main/java/com/alphawallet/app/service/TokensService.java b/app/src/main/java/com/alphawallet/app/service/TokensService.java index 5bea89b37..5de13737f 100644 --- a/app/src/main/java/com/alphawallet/app/service/TokensService.java +++ b/app/src/main/java/com/alphawallet/app/service/TokensService.java @@ -10,6 +10,8 @@ import com.alphawallet.app.entity.tokens.TokenTicker; import com.alphawallet.app.interact.GenericWalletInteract; import com.alphawallet.app.repository.EthereumNetworkRepositoryType; import com.alphawallet.app.repository.PreferenceRepositoryType; +import com.alphawallet.app.repository.TokenRepositoryType; +import com.alphawallet.app.repository.entity.RealmToken; import java.util.ArrayList; import java.util.Arrays; @@ -17,27 +19,28 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import io.realm.Realm; import okhttp3.OkHttpClient; public class TokensService { private final Map<String, SparseArray<Token>> tokenMap = new ConcurrentHashMap<>(); private static final Map<String, SparseArray<ContractType>> interfaceSpecMap = new ConcurrentHashMap<>(); - private String currentAddress = null; + private static String currentAddress = null; private boolean loaded; private final EthereumNetworkRepositoryType ethereumNetworkRepository; - private final RealmManager realmManager; + private final TokenRepositoryType tokenRepository; private final List<Integer> networkFilter; private Token focusToken; private final OkHttpClient okHttpClient; private int currencyCheckCount; public TokensService(EthereumNetworkRepositoryType ethereumNetworkRepository, - RealmManager realmManager, + TokenRepositoryType tokenRepository, OkHttpClient client, PreferenceRepositoryType preferenceRepository) { this.ethereumNetworkRepository = ethereumNetworkRepository; - this.realmManager = realmManager; + this.tokenRepository = tokenRepository; loaded = false; networkFilter = new ArrayList<>(10); setupFilter(); @@ -54,8 +57,6 @@ public class TokensService */ public Token addToken(Token t) { - Token e = getToken(t.tokenInfo.chainId, t.tokenInfo.address); - if (e != null && e.walletUIUpdateRequired) return t; //ensure tokens marked as requiring UI update complete operation if (t.checkTokenWallet(currentAddress)) { if (t.equals(focusToken)) @@ -93,29 +94,26 @@ public class TokensService } tokenAddr.put(chainId, t); - setSpec(t); + updatedSpec(t); } - private void setSpec(Token t) + public Token getToken(int chainId, String addr) { - SparseArray<ContractType> types = interfaceSpecMap.get(t.getAddress()); - if (types != null && types.get(t.tokenInfo.chainId, null) != null) + Token token = null; + if (addr != null) { - if (t.getInterfaceSpec() == null || t.getInterfaceSpec() == ContractType.NOT_SET || t.getInterfaceSpec() == ContractType.OTHER) + if (tokenMap.containsKey(addr.toLowerCase())) { - t.setInterfaceSpec(interfaceSpecMap.get(t.getAddress()).get(t.tokenInfo.chainId)); + token = tokenMap.get(addr.toLowerCase()).get(chainId, null); } - } - } - public Token getToken(int chainId, String addr) - { - if (addr != null && tokenMap.containsKey(addr.toLowerCase())) - { - return tokenMap.get(addr.toLowerCase()).get(chainId, null); + if (token == null) + { + token = tokenRepository.fetchToken(chainId, currentAddress, addr); + } } - return null; + return token; } public String getTokenName(int chainId, String addr) @@ -309,25 +307,27 @@ public class TokensService networkFilter.addAll(ethereumNetworkRepository.getFilterNetworkList()); } - public ContractType getInterfaceSpec(int chainId, String address) + private boolean updatedSpec(Token token) { - SparseArray<ContractType> types = interfaceSpecMap.get(address); - ContractType result = types != null ? types.get(chainId) : ContractType.OTHER; - - if (result == ContractType.OTHER && tokenMap.containsKey(address)) + String normalisedAddr = token.getAddress().toLowerCase(); + SparseArray<ContractType> types = interfaceSpecMap.get(normalisedAddr); + if (types != null) { - List<Token> tokens = getAllAtAddress(address); - for (Token token : tokens) + ContractType updatedType = types.get(token.tokenInfo.chainId); + if (updatedType != null) { - if (token.tokenInfo.chainId == chainId && token.getInterfaceSpec() != null) + token.setInterfaceSpec(updatedType); + //clean up the revise spec map + interfaceSpecMap.get(normalisedAddr).delete(token.tokenInfo.chainId); + if (interfaceSpecMap.get(normalisedAddr).size() == 0) { - result = token.getInterfaceSpec(); - break; + interfaceSpecMap.remove(normalisedAddr); } + return true; } } - return result; + return false; } private List<Token> getAllClass(int chainId, ContractType[] filter) @@ -472,4 +472,9 @@ public class TokensService { return ethereumNetworkRepository.getTokenTicker(token); } + + public static String getCurrentWalletAddress() + { + return currentAddress; + } }
['app/src/main/java/com/alphawallet/app/repository/TokenRepositoryType.java', 'app/src/main/java/com/alphawallet/app/di/RepositoriesModule.java', 'app/src/main/java/com/alphawallet/app/service/TokensService.java', 'app/src/main/java/com/alphawallet/app/interact/FetchTokensInteract.java', 'app/src/main/java/com/alphawallet/app/repository/TokenRepository.java', 'app/src/main/java/com/alphawallet/app/repository/TokenLocalSource.java', 'app/src/main/java/com/alphawallet/app/repository/TokensRealmSource.java']
{'.java': 7}
7
7
0
0
7
2,432,371
472,327
70,412
534
7,603
1,441
137
7
275
53
70
9
0
0
1970-01-01T00:26:26
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
1,296
alphawallet/alpha-wallet-android/959/718
alphawallet
alpha-wallet-android
https://github.com/AlphaWallet/alpha-wallet-android/issues/718
https://github.com/AlphaWallet/alpha-wallet-android/pull/959
https://github.com/AlphaWallet/alpha-wallet-android/pull/959#issuecomment-550086373
1
fixes
With a new install, ALL is empty until we tap to CURRENCY and back
i.e. the Ethereum card doesn't show up. ~~Doesn't happen if I create a new wallet.~~ [updated to remove confusion] Xiaomi. 7.1.2 N2G47H.
ceff9ca8bf42aab84e2b6efd8a3493b51ad04875
2d6ace83c1fe26096ef978bfdae38195f18deaba
https://github.com/alphawallet/alpha-wallet-android/compare/ceff9ca8bf42aab84e2b6efd8a3493b51ad04875...2d6ace83c1fe26096ef978bfdae38195f18deaba
diff --git a/app/src/awallet/java/com/alphawallet/app/repository/EthereumNetworkRepository.java b/app/src/awallet/java/com/alphawallet/app/repository/EthereumNetworkRepository.java index 743479046..3178c1a72 100644 --- a/app/src/awallet/java/com/alphawallet/app/repository/EthereumNetworkRepository.java +++ b/app/src/awallet/java/com/alphawallet/app/repository/EthereumNetworkRepository.java @@ -9,6 +9,8 @@ import com.alphawallet.app.entity.NetworkInfo; import com.alphawallet.app.service.TickerService; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; public class EthereumNetworkRepository extends EthereumNetworkBase @@ -37,7 +39,7 @@ public class EthereumNetworkRepository extends EthereumNetworkBase public static List<Integer> addDefaultNetworks() { - return new ArrayList<>(EthereumNetworkRepository.MAINNET_ID); + return new ArrayList<>(Collections.singletonList(EthereumNetworkRepository.MAINNET_ID)); } public static String getNodeURLByNetworkId(int networkId) {
['app/src/awallet/java/com/alphawallet/app/repository/EthereumNetworkRepository.java']
{'.java': 1}
1
1
0
0
1
2,281,149
442,939
66,403
524
225
40
4
1
142
22
46
5
0
0
1970-01-01T00:26:12
493
Java
{'Java': 5657087, 'HTML': 59789, 'Kotlin': 32774, 'CSS': 9174, 'C': 6887, 'JavaScript': 5178, 'Shell': 4131, 'SCSS': 3063, 'Ruby': 2021, 'CMake': 652}
MIT License
8,591
crawljax/crawljax/389/388
crawljax
crawljax
https://github.com/crawljax/crawljax/issues/388
https://github.com/crawljax/crawljax/pull/389
https://github.com/crawljax/crawljax/pull/389
1
fixes
Missing URL Parameter
Hi, There is a issue with this configuration: CrawljaxConfigurationBuilder builder = CrawljaxConfiguration.builderFor("http://site.com/page.aspx?q=biography") .setBrowserConfig(new BrowserConfiguration(BrowserType.FIREFOX, 1)) .setProxyConfig(ProxyConfiguration.manualProxyOn("web-proxy", 8080)) .setBasicAuth("$iapsearch001", "run.sat.hot-287"); As you can see the URL is: http://site.com/page.aspx?q=biography and I have a basic Authentication. That combination, for any reason when the Crawljax start crawling the URL is updated by http://site.com/page.aspx, as you can see the query parameter is missing :( Tested on 3.4 and 3.5 Regards
339266aab9a40da6f35457ba42d3039c75960b6b
8e56215e27d746df2b4f3af79f9d49d321dd1b2d
https://github.com/crawljax/crawljax/compare/339266aab9a40da6f35457ba42d3039c75960b6b...8e56215e27d746df2b4f3af79f9d49d321dd1b2d
diff --git a/core/src/main/java/com/crawljax/core/configuration/CrawljaxConfiguration.java b/core/src/main/java/com/crawljax/core/configuration/CrawljaxConfiguration.java index 869887cd..f8ec5141 100644 --- a/core/src/main/java/com/crawljax/core/configuration/CrawljaxConfiguration.java +++ b/core/src/main/java/com/crawljax/core/configuration/CrawljaxConfiguration.java @@ -49,10 +49,8 @@ public class CrawljaxConfiguration { try { String encodedUsername = URLEncoder.encode(username, "UTF-8"); String encodedPassword = URLEncoder.encode(password, "UTF-8"); - config.url = URI.create(config.url.getScheme() - + "://" + encodedUsername - + ":" + encodedPassword + "@" + config.url.getAuthority() - + config.url.getPath()); + String hostPrefix = encodedUsername + ":" + encodedPassword + "@"; + config.url = URI.create(config.url.toString().replaceFirst("://", "://" + hostPrefix)); } catch (UnsupportedEncodingException e) { throw new CrawljaxException("Could not parse the username/password to a URL", e); diff --git a/core/src/test/java/com/crawljax/core/configuration/CrawljaxConfigurationBuilderTest.java b/core/src/test/java/com/crawljax/core/configuration/CrawljaxConfigurationBuilderTest.java index 75256930..73f63fa0 100644 --- a/core/src/test/java/com/crawljax/core/configuration/CrawljaxConfigurationBuilderTest.java +++ b/core/src/test/java/com/crawljax/core/configuration/CrawljaxConfigurationBuilderTest.java @@ -6,9 +6,9 @@ import static org.junit.Assert.assertThat; import java.io.File; import java.util.concurrent.TimeUnit; -import org.junit.Test; - import com.crawljax.core.configuration.CrawljaxConfiguration.CrawljaxConfigurationBuilder; +import org.hamcrest.core.Is; +import org.junit.Test; public class CrawljaxConfigurationBuilderTest { @@ -49,4 +49,14 @@ public class CrawljaxConfigurationBuilderTest { testBuilder().setOutputDirectory(file).build(); } + + @Test + public void whenSpecifyingBasicAuthTheUrlShouldBePreserved() { + String url = "https://example.com/test/?a=b#anchor"; + CrawljaxConfiguration conf = CrawljaxConfiguration.builderFor(url) + .setBasicAuth("username", "password") + .build(); + assertThat(conf.getUrl().toString(), Is.is("https://username:password@example.com/test/?a=b#anchor")); + } + }
['core/src/main/java/com/crawljax/core/configuration/CrawljaxConfiguration.java', 'core/src/test/java/com/crawljax/core/configuration/CrawljaxConfigurationBuilderTest.java']
{'.java': 2}
2
2
0
0
2
557,395
128,431
19,825
191
352
79
6
1
646
65
161
18
3
0
1970-01-01T00:23:15
493
Java
{'Java': 2321919, 'JavaScript': 1023004, 'HTML': 766291, 'CSS': 21008, 'Dockerfile': 1832, 'Shell': 310}
Apache License 2.0
5,511
branchmetrics/react-native-branch-deep-linking-attribution/188/187
branchmetrics
react-native-branch-deep-linking-attribution
https://github.com/BranchMetrics/react-native-branch-deep-linking-attribution/issues/187
https://github.com/BranchMetrics/react-native-branch-deep-linking-attribution/pull/188
https://github.com/BranchMetrics/react-native-branch-deep-linking-attribution/pull/188
1
fix
Crash when opening a link on Android (2.0.0-beta.2)
This is due to a recent change in 2.0.0-beta.2. A fix will be released quickly. ``` 04-26 14:33:32.218 12830-12830/com.webview_example W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference 04-26 14:33:32.219 12830-12830/com.webview_example W/System.err: at io.branch.rnbranch.RNBranchModule$1.onInitFinished(RNBranchModule.java:96) ```
5867bb4c36b6cba29964861b5b1c42d47c58b8b1
a5fc5f4df555f7afaae19d007556901bb5dbd978
https://github.com/branchmetrics/react-native-branch-deep-linking-attribution/compare/5867bb4c36b6cba29964861b5b1c42d47c58b8b1...a5fc5f4df555f7afaae19d007556901bb5dbd978
diff --git a/android/src/main/java/io/branch/rnbranch/RNBranchModule.java b/android/src/main/java/io/branch/rnbranch/RNBranchModule.java index a95d0bef..3e49511a 100644 --- a/android/src/main/java/io/branch/rnbranch/RNBranchModule.java +++ b/android/src/main/java/io/branch/rnbranch/RNBranchModule.java @@ -93,9 +93,9 @@ public class RNBranchModule extends ReactContextBaseJavaModule { BranchUniversalObject branchUniversalObject = BranchUniversalObject.getReferredBranchUniversalObject(); LinkProperties linkProperties = LinkProperties.getReferredLinkProperties(); - Branch.BranchUniversalReferralInitListener listener = initListener.get(); - if (listener != null) { - listener.onInitFinished(branchUniversalObject, linkProperties, error); + if (initListener != null) { + Branch.BranchUniversalReferralInitListener listener = initListener.get(); + if (listener != null) listener.onInitFinished(branchUniversalObject, linkProperties, error); } generateLocalBroadcast(referringParams, uri, branchUniversalObject, linkProperties, error); }
['android/src/main/java/io/branch/rnbranch/RNBranchModule.java']
{'.java': 1}
1
1
0
0
1
50,010
9,321
1,382
14
477
79
6
1
450
40
130
6
0
1
1970-01-01T00:24:53
491
Objective-C
{'Objective-C': 87711, 'Java': 72584, 'JavaScript': 46121, 'TypeScript': 16463, 'Ruby': 5070, 'Objective-C++': 1732, 'Shell': 854}
MIT License
834
nationalsecurityagency/datawave/1220/1218
nationalsecurityagency
datawave
https://github.com/NationalSecurityAgency/datawave/issues/1218
https://github.com/NationalSecurityAgency/datawave/pull/1220
https://github.com/NationalSecurityAgency/datawave/pull/1220
1
fixes
Geo to GeoWave function conversion results in inaccurate bounds
When converting geo functions to geowave functions, the precision of the coordinates is not being preserved.
4d8e8200c9e62c880701da195987d452c3f22668
d84b86953f305747aa0120ba8cb8339dd0e0ad6b
https://github.com/nationalsecurityagency/datawave/compare/4d8e8200c9e62c880701da195987d452c3f22668...d84b86953f305747aa0120ba8cb8339dd0e0ad6b
diff --git a/warehouse/query-core/src/main/java/datawave/query/jexl/functions/GeoFunctionsDescriptor.java b/warehouse/query-core/src/main/java/datawave/query/jexl/functions/GeoFunctionsDescriptor.java index ee81a503f4..d67c2e34f1 100644 --- a/warehouse/query-core/src/main/java/datawave/query/jexl/functions/GeoFunctionsDescriptor.java +++ b/warehouse/query-core/src/main/java/datawave/query/jexl/functions/GeoFunctionsDescriptor.java @@ -28,12 +28,13 @@ import org.apache.commons.jexl2.parser.JexlNode; import org.apache.commons.jexl2.parser.ParserTreeConstants; import org.apache.log4j.Logger; import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.Envelope; +import org.locationtech.jts.geom.CoordinateXY; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.util.GeometricShapeFactory; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -388,10 +389,14 @@ public class GeoFunctionsDescriptor implements JexlFunctionArgumentDescriptorFac } private Polygon createRectangle(double minLon, double maxLon, double minLat, double maxLat) { - GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); - shapeFactory.setEnvelope(new Envelope(minLon, maxLon, minLat, maxLat)); - shapeFactory.setNumPoints(4); - return shapeFactory.createRectangle(); + GeometryFactory geomFactory = new GeometryFactory(); + List<Coordinate> coordinates = new ArrayList<>(); + coordinates.add(new CoordinateXY(minLon, minLat)); + coordinates.add(new CoordinateXY(maxLon, minLat)); + coordinates.add(new CoordinateXY(maxLon, maxLat)); + coordinates.add(new CoordinateXY(minLon, maxLat)); + coordinates.add(new CoordinateXY(minLon, minLat)); + return geomFactory.createPolygon(coordinates.toArray(new Coordinate[0])); } private MultiPolygon createMultiPolygon(Polygon poly1, Polygon poly2) { diff --git a/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoFunctionsDescriptorTest.java b/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoFunctionsDescriptorTest.java index 61445668e2..991dbb8c06 100644 --- a/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoFunctionsDescriptorTest.java +++ b/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoFunctionsDescriptorTest.java @@ -1,5 +1,6 @@ package datawave.query.jexl.functions; +import com.google.common.collect.Sets; import datawave.query.jexl.JexlASTHelper; import datawave.query.jexl.functions.arguments.JexlArgumentDescriptor; import datawave.query.jexl.visitors.JexlStringBuildingVisitor; @@ -10,6 +11,17 @@ import org.junit.Test; public class GeoFunctionsDescriptorTest { + @Test + public void testGeoToGeoWaveFunction() throws Exception { + String query = "geo:within_bounding_box(GEO_FIELD, \\"-12.74,16.30\\", \\"-3.31,26.16\\")"; + JexlNode node = JexlASTHelper.parseJexlQuery(query); + GeoFunctionsDescriptor.GeoJexlArgumentDescriptor argDesc = (GeoFunctionsDescriptor.GeoJexlArgumentDescriptor) new GeoFunctionsDescriptor() + .getArgumentDescriptor((ASTFunctionNode) node.jjtGetChild(0).jjtGetChild(0)); + JexlNode queryNode = argDesc.toGeoWaveFunction(Sets.newHashSet("GEO_FIELD")); + Assert.assertEquals("geowave:intersects(GEO_FIELD, 'POLYGON ((16.3 -12.74, 26.16 -12.74, 26.16 -3.31, 16.3 -3.31, 16.3 -12.74))')", + JexlStringBuildingVisitor.buildQuery(queryNode)); + } + @Test public void antiMeridianTest1() throws Exception { String query = "geo:within_bounding_box(GEO_FIELD, '40_170', '50_-170')";
['warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoFunctionsDescriptorTest.java', 'warehouse/query-core/src/main/java/datawave/query/jexl/functions/GeoFunctionsDescriptor.java']
{'.java': 2}
2
2
0
0
2
11,613,797
2,457,398
289,430
1,659
915
169
15
1
110
16
21
1
0
0
1970-01-01T00:27:06
484
Java
{'Java': 17524398, 'Shell': 336944, 'HTML': 34795, 'JavaScript': 28894, 'Dockerfile': 7456, 'Python': 5806, 'CSS': 4835, 'XSLT': 535}
Apache License 2.0
833
nationalsecurityagency/datawave/1222/1221
nationalsecurityagency
datawave
https://github.com/NationalSecurityAgency/datawave/issues/1221
https://github.com/NationalSecurityAgency/datawave/pull/1222
https://github.com/NationalSecurityAgency/datawave/pull/1222
1
fixes
Expose geowave configuration from ShardQueryConfiguration in ShardQueryLogic
There are a few configuration options available for geowave in shardqueryconfiguration which are not exposed in shardquerylogic. This makes it impossible to change these settings without rebuilding the jar. We should fix this.
8f0dcde0aecded4566f5a6ee700dd8b5c0734fd1
41a9f2c846667591441a2d267753d573a69db9f8
https://github.com/nationalsecurityagency/datawave/compare/8f0dcde0aecded4566f5a6ee700dd8b5c0734fd1...41a9f2c846667591441a2d267753d573a69db9f8
diff --git a/warehouse/query-core/src/main/java/datawave/query/tables/ShardQueryLogic.java b/warehouse/query-core/src/main/java/datawave/query/tables/ShardQueryLogic.java index 8616807ee4..7a08ec5fca 100644 --- a/warehouse/query-core/src/main/java/datawave/query/tables/ShardQueryLogic.java +++ b/warehouse/query-core/src/main/java/datawave/query/tables/ShardQueryLogic.java @@ -2186,6 +2186,30 @@ public class ShardQueryLogic extends BaseQueryLogic<Entry<Key,Value>> { getConfig().setPointMaxExpansion(pointMaxExpansion); } + public int getGeoWaveRangeSplitThreshold() { + return getConfig().getGeoWaveRangeSplitThreshold(); + } + + public void setGeoWaveRangeSplitThreshold(int geoWaveRangeSplitThreshold) { + getConfig().setGeoWaveRangeSplitThreshold(geoWaveRangeSplitThreshold); + } + + public double getGeoWaveMaxRangeOverlap() { + return getConfig().getGeoWaveMaxRangeOverlap(); + } + + public void setGeoWaveMaxRangeOverlap(double geoWaveMaxRangeOverlap) { + getConfig().setGeoWaveMaxRangeOverlap(geoWaveMaxRangeOverlap); + } + + public boolean isOptimizeGeoWaveRanges() { + return getConfig().isOptimizeGeoWaveRanges(); + } + + public void setOptimizeGeoWaveRanges(boolean optimizeGeoWaveRanges) { + getConfig().setOptimizeGeoWaveRanges(optimizeGeoWaveRanges); + } + public int getGeoWaveMaxEnvelopes() { return getConfig().getGeoWaveMaxEnvelopes(); }
['warehouse/query-core/src/main/java/datawave/query/tables/ShardQueryLogic.java']
{'.java': 1}
1
1
0
0
1
11,612,969
2,457,217
289,406
1,659
851
181
24
1
228
33
44
1
0
0
1970-01-01T00:27:06
484
Java
{'Java': 17524398, 'Shell': 336944, 'HTML': 34795, 'JavaScript': 28894, 'Dockerfile': 7456, 'Python': 5806, 'CSS': 4835, 'XSLT': 535}
Apache License 2.0
832
nationalsecurityagency/datawave/1336/1334
nationalsecurityagency
datawave
https://github.com/NationalSecurityAgency/datawave/issues/1334
https://github.com/NationalSecurityAgency/datawave/pull/1336
https://github.com/NationalSecurityAgency/datawave/pull/1336
1
fixes
Intersection can return inconsistent shard after seeking
When an intersection contains days only and is seeked with a day_shard the following next call will return just the day that was returned with the day_shard rather than the next day. Add consistent checks when calling next to ensure the underlying iterators have been advanced beyond the last returned value.
e961dce064c171283b37dac11927696350db7bb7
baf89910b4299aefca1f91ffa4a04d89a39d4010
https://github.com/nationalsecurityagency/datawave/compare/e961dce064c171283b37dac11927696350db7bb7...baf89910b4299aefca1f91ffa4a04d89a39d4010
diff --git a/warehouse/query-core/src/main/java/datawave/query/index/lookup/Intersection.java b/warehouse/query-core/src/main/java/datawave/query/index/lookup/Intersection.java index 5f42ecf9e4..3501c03daf 100644 --- a/warehouse/query-core/src/main/java/datawave/query/index/lookup/Intersection.java +++ b/warehouse/query-core/src/main/java/datawave/query/index/lookup/Intersection.java @@ -210,6 +210,13 @@ public class Intersection extends BaseIndexStream { final SortedSet<String> keys = children.keySet(); if (keys.size() == 1) { intersect(keys); + + // ensure consistency with current state since underlying iterators may not be updated to reflect previous seek calls + // the next key should be beyond the current key, otherwise look again + if (next != null && ret != null && next.first().compareTo(ret.first()) <= 0) { + // force it to compute again + next = null; + } } else { // Seek all child IndexStreams to the highest top key. String max = children.keySet().last(); diff --git a/warehouse/query-core/src/test/java/datawave/query/index/lookup/IntersectionTest.java b/warehouse/query-core/src/test/java/datawave/query/index/lookup/IntersectionTest.java index c2b5533b3f..dd8f08cfb2 100644 --- a/warehouse/query-core/src/test/java/datawave/query/index/lookup/IntersectionTest.java +++ b/warehouse/query-core/src/test/java/datawave/query/index/lookup/IntersectionTest.java @@ -165,6 +165,49 @@ public class IntersectionTest { assertFalse(intersection.hasNext()); } + /** + * Following a seek of a day_shard against day only tuples calling next would result in the last returned day being returned again rather than the next one + */ + @Test + public void testIntersectionAfterSeek() { + // Build a peeking iterator for a left side term + List<IndexMatch> leftMatches = buildIndexMatches("FIELD", "VALUE", "doc1", "doc2", "doc3"); + IndexInfo left = new IndexInfo(leftMatches); + left.setNode(JexlNodeFactory.buildEQNode("FIELD", "VALUE")); + + List<Tuple2<String,IndexInfo>> tupleList = new ArrayList(); + tupleList.add(Tuples.tuple("20190314", left)); + tupleList.add(Tuples.tuple("20190315", left)); + tupleList.add(Tuples.tuple("20190316", left)); + + PeekingIterator<Tuple2<String,IndexInfo>> leftIter = Iterators.peekingIterator(tupleList.iterator()); + + // Build a peeking iterator for a right side term. + List<IndexMatch> rightMatches = buildIndexMatches("FIELD", "VALUE", "doc2", "doc3", "doc4"); + IndexInfo right = new IndexInfo(rightMatches); + right.setNode(JexlNodeFactory.buildEQNode("FIELD", "VALUE")); + + tupleList = new ArrayList(); + tupleList.add(Tuples.tuple("20190314", right)); + tupleList.add(Tuples.tuple("20190315", right)); + tupleList.add(Tuples.tuple("20190316", right)); + + PeekingIterator<Tuple2<String,IndexInfo>> rightIter = Iterators.peekingIterator(tupleList.iterator()); + + // Build the Intersection. + IndexStream leftStream = ScannerStream.withData(leftIter, JexlNodeFactory.buildEQNode("FIELD", "VALUE")); + IndexStream rightStream = ScannerStream.withData(rightIter, JexlNodeFactory.buildEQNode("FIELD", "VALUE")); + List<IndexStream> indexStreams = Lists.newArrayList(leftStream, rightStream); + + Intersection intersection = new Intersection(indexStreams, new IndexInfo()); + assertTrue(intersection.hasNext()); + assertEquals("20190314", intersection.peek().first()); + assertEquals("20190315_11", intersection.seek("20190315_11")); + assertTrue(intersection.hasNext()); + intersection.next(); + assertEquals("20190316", intersection.peek().first()); + } + /** * Intersection of day range with a shard range within the day range is possible. */
['warehouse/query-core/src/test/java/datawave/query/index/lookup/IntersectionTest.java', 'warehouse/query-core/src/main/java/datawave/query/index/lookup/Intersection.java']
{'.java': 2}
2
2
0
0
2
11,823,735
2,502,300
294,337
1,682
439
75
7
1
308
51
58
1
0
0
1970-01-01T00:27:15
484
Java
{'Java': 17524398, 'Shell': 336944, 'HTML': 34795, 'JavaScript': 28894, 'Dockerfile': 7456, 'Python': 5806, 'CSS': 4835, 'XSLT': 535}
Apache License 2.0
831
nationalsecurityagency/datawave/1647/1645
nationalsecurityagency
datawave
https://github.com/NationalSecurityAgency/datawave/issues/1645
https://github.com/NationalSecurityAgency/datawave/pull/1647
https://github.com/NationalSecurityAgency/datawave/pull/1647
1
fixes
GeoWavePruning visitor should not be run against legacy geo fields
The GeoWavePruning visitor throws an exception if it runs against a legacy-geo field. This breaks the ability to query legacy geo types with the geowave functions. We should update the geowave pruning visitor to ignore these legacy fields.
e863fd09ee8053db7386f21cde2e907aaea6d3d9
02eaaa91082b8b939d04ac329b61af36a4847b4b
https://github.com/nationalsecurityagency/datawave/compare/e863fd09ee8053db7386f21cde2e907aaea6d3d9...02eaaa91082b8b939d04ac329b61af36a4847b4b
diff --git a/warehouse/query-core/src/main/java/datawave/query/jexl/visitors/GeoWavePruningVisitor.java b/warehouse/query-core/src/main/java/datawave/query/jexl/visitors/GeoWavePruningVisitor.java index 5bd7154bcb..695338ea40 100644 --- a/warehouse/query-core/src/main/java/datawave/query/jexl/visitors/GeoWavePruningVisitor.java +++ b/warehouse/query-core/src/main/java/datawave/query/jexl/visitors/GeoWavePruningVisitor.java @@ -3,12 +3,15 @@ package datawave.query.jexl.visitors; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import datawave.data.normalizer.GeometryNormalizer; +import datawave.data.type.AbstractGeometryType; +import datawave.data.type.Type; import datawave.query.jexl.JexlASTHelper; import datawave.query.jexl.functions.GeoWaveFunctionsDescriptor; import datawave.query.jexl.functions.JexlFunctionArgumentDescriptorFactory; import datawave.query.jexl.functions.arguments.JexlArgumentDescriptor; import datawave.query.util.GeoWaveUtils; import datawave.query.util.MetadataHelper; +import datawave.webservice.common.logging.ThreadConfigurableLogger; import org.apache.commons.jexl2.parser.ASTAndNode; import org.apache.commons.jexl2.parser.ASTEQNode; import org.apache.commons.jexl2.parser.ASTFalseNode; @@ -18,10 +21,11 @@ import org.apache.commons.jexl2.parser.ASTReference; import org.apache.commons.jexl2.parser.ASTReferenceExpression; import org.apache.commons.jexl2.parser.JexlNode; import org.apache.commons.jexl2.parser.ParserTreeConstants; +import org.apache.log4j.Logger; import org.locationtech.jts.geom.Geometry; import java.util.Collection; -import java.util.Collections; +import java.util.HashSet; import java.util.Set; import static org.apache.commons.jexl2.parser.JexlNodes.children; @@ -33,6 +37,8 @@ import static org.apache.commons.jexl2.parser.JexlNodes.children; */ public class GeoWavePruningVisitor extends RebuildingVisitor { + private static final Logger log = ThreadConfigurableLogger.getLogger(GeoWavePruningVisitor.class); + private final Multimap<String,String> prunedTerms; private final MetadataHelper metadataHelper; @@ -61,10 +67,12 @@ public class GeoWavePruningVisitor extends RebuildingVisitor { JexlArgumentDescriptor desc = JexlFunctionArgumentDescriptorFactory.F.getArgumentDescriptor((ASTFunctionNode) child); if (desc instanceof GeoWaveFunctionsDescriptor.GeoWaveJexlArgumentDescriptor) { GeoWaveFunctionsDescriptor.GeoWaveJexlArgumentDescriptor geoWaveDesc = (GeoWaveFunctionsDescriptor.GeoWaveJexlArgumentDescriptor) desc; - Geometry geom = GeometryNormalizer.parseGeometry(geoWaveDesc.getWkt()); - Set<String> fields = geoWaveDesc.fields(metadataHelper, Collections.emptySet()); - for (String field : fields) { - fieldToGeometryMap.put(field, geom); + if (isPrunable(geoWaveDesc)) { + Geometry geom = GeometryNormalizer.parseGeometry(geoWaveDesc.getWkt()); + Set<String> fields = geoWaveDesc.fields(metadataHelper, null); + for (String field : fields) { + fieldToGeometryMap.put(field, geom); + } } } } @@ -72,6 +80,21 @@ public class GeoWavePruningVisitor extends RebuildingVisitor { return super.visit(node, (fieldToGeometryMap.isEmpty() ? null : fieldToGeometryMap)); } + private boolean isPrunable(GeoWaveFunctionsDescriptor.GeoWaveJexlArgumentDescriptor geoWaveDesc) { + Set<String> fields = geoWaveDesc.fields(metadataHelper, null); + return fields.stream().anyMatch(field -> getDatatypesForField(field).stream().anyMatch(type -> type instanceof AbstractGeometryType)); + } + + private Set<Type<?>> getDatatypesForField(String field) { + Set<Type<?>> dataTypes = new HashSet<>(); + try { + dataTypes.addAll(metadataHelper.getDatatypesForField(field)); + } catch (Exception e) { + log.warn("Unable to determine types for field: " + field, e); + } + return dataTypes; + } + @Override public Object visit(ASTOrNode node, Object data) { JexlNode copiedNode = (JexlNode) super.visit(node, data); @@ -108,13 +131,20 @@ public class GeoWavePruningVisitor extends RebuildingVisitor { if (queryGeometries != null && !queryGeometries.isEmpty()) { String value = (String) JexlASTHelper.getLiteralValue(node); if (value != null) { - Geometry nodeGeometry = GeoWaveUtils.positionToGeometry(value); - // if the node geometry doesn't intersect the query geometry, get rid of this node - if (fieldToGeometryMap.get(field).stream().noneMatch(nodeGeometry::intersects)) { - if (prunedTerms != null) { - prunedTerms.put(field, value); + Geometry nodeGeometry = null; + try { + nodeGeometry = GeoWaveUtils.positionToGeometry(value); + } catch (Exception e) { + log.warn("Unable to extract geometry from geo term: " + value, e); + } + if (nodeGeometry != null) { + // if the node geometry doesn't intersect the query geometry, get rid of this node + if (fieldToGeometryMap.get(field).stream().noneMatch(nodeGeometry::intersects)) { + if (prunedTerms != null) { + prunedTerms.put(field, value); + } + return new ASTFalseNode(ParserTreeConstants.JJTFALSENODE); } - return new ASTFalseNode(ParserTreeConstants.JJTFALSENODE); } } } diff --git a/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoWaveFunctionsDescriptorTest.java b/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoWaveFunctionsDescriptorTest.java index f1315beadc..64251f1427 100644 --- a/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoWaveFunctionsDescriptorTest.java +++ b/warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoWaveFunctionsDescriptorTest.java @@ -5,6 +5,7 @@ import datawave.query.config.ShardQueryConfiguration; import datawave.query.jexl.JexlASTHelper; import datawave.query.jexl.functions.arguments.JexlArgumentDescriptor; import datawave.query.jexl.visitors.JexlStringBuildingVisitor; +import datawave.query.util.MetadataHelper; import datawave.query.util.MockMetadataHelper; import org.apache.commons.jexl2.parser.ASTFunctionNode; import org.apache.commons.jexl2.parser.ASTJexlScript; @@ -40,18 +41,21 @@ public class GeoWaveFunctionsDescriptorTest { ShardQueryConfiguration config = new ShardQueryConfiguration(); + MockMetadataHelper helper = new MockMetadataHelper(); + helper.addField("GEO_FIELD", "datawave.data.type.GeometryType"); + // DEFAULT, maxEnvelopes = 4 - String defaultExpandedQuery = convertFunctionToIndexQuery(query, config); + String defaultExpandedQuery = convertFunctionToIndexQuery(query, config, helper); Assert.assertEquals(expandedWkt.get(0), defaultExpandedQuery); // maxEnvelopes = 1 config.setGeoWaveMaxEnvelopes(1); - String oneEnvelopeExpandedQuery = convertFunctionToIndexQuery(query, config); + String oneEnvelopeExpandedQuery = convertFunctionToIndexQuery(query, config, helper); Assert.assertEquals(expandedWkt.get(1), oneEnvelopeExpandedQuery); // maxEnvelopes = 2 config.setGeoWaveMaxEnvelopes(2); - String twoEnvelopesExpandedQuery = convertFunctionToIndexQuery(query, config); + String twoEnvelopesExpandedQuery = convertFunctionToIndexQuery(query, config, helper); Assert.assertEquals(expandedWkt.get(2), twoEnvelopesExpandedQuery); // Test the the default number of envelopes produces a different expanded query than the single envelope expansion @@ -97,14 +101,12 @@ public class GeoWaveFunctionsDescriptorTest { } } - public static String convertFunctionToIndexQuery(String queryStr, ShardQueryConfiguration config) throws ParseException { + public static String convertFunctionToIndexQuery(String queryStr, ShardQueryConfiguration config, MetadataHelper metadataHelper) throws ParseException { ASTJexlScript script = JexlASTHelper.parseJexlQuery(queryStr); ASTFunctionNode func = find(script); JexlArgumentDescriptor desc = new GeoWaveFunctionsDescriptor().getArgumentDescriptor(func); - MockMetadataHelper helper = new MockMetadataHelper(); - helper.addField("GEO_FIELD", "datawave.data.type.GeometryType"); - JexlNode indexQuery = desc.getIndexQuery(config, helper, null, null); + JexlNode indexQuery = desc.getIndexQuery(config, metadataHelper, null, null); return JexlStringBuildingVisitor.buildQuery(indexQuery); } diff --git a/warehouse/query-core/src/test/java/datawave/query/jexl/visitors/GeoWavePruningVisitorTest.java b/warehouse/query-core/src/test/java/datawave/query/jexl/visitors/GeoWavePruningVisitorTest.java index 343a794979..127df25f0c 100644 --- a/warehouse/query-core/src/test/java/datawave/query/jexl/visitors/GeoWavePruningVisitorTest.java +++ b/warehouse/query-core/src/test/java/datawave/query/jexl/visitors/GeoWavePruningVisitorTest.java @@ -4,12 +4,14 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import datawave.query.config.ShardQueryConfiguration; import datawave.query.jexl.JexlASTHelper; +import datawave.query.util.MockMetadataHelper; import datawave.test.JexlNodeAssert; import org.apache.commons.jexl2.parser.ASTJexlScript; import org.apache.commons.jexl2.parser.ASTReference; import org.apache.commons.jexl2.parser.ASTReferenceExpression; import org.apache.commons.jexl2.parser.JexlNode; import org.apache.commons.jexl2.parser.ParseException; +import org.junit.BeforeClass; import org.junit.Test; import static datawave.query.jexl.functions.GeoWaveFunctionsDescriptorTest.convertFunctionToIndexQuery; @@ -18,11 +20,20 @@ import static org.junit.Assert.assertFalse; public class GeoWavePruningVisitorTest { + private static MockMetadataHelper metadataHelper; + + @BeforeClass + public static void setup() { + metadataHelper = new MockMetadataHelper(); + metadataHelper.addField("GEO_FIELD", "datawave.data.type.GeometryType"); + metadataHelper.addField("LEGACY_GEO_FIELD", "datawave.data.type.GeoType"); + } + @Test public void testNonIntersectingTermIsPruned() throws ParseException { String function = "geowave:intersects(GEO_FIELD, 'POLYGON((10 10, 20 10, 20 20, 10 20, 10 10))')"; // Get the expanded geowave terms. - String indexQuery = convertFunctionToIndexQuery(function, new ShardQueryConfiguration()); + String indexQuery = convertFunctionToIndexQuery(function, new ShardQueryConfiguration(), metadataHelper); // Add a term that should be pruned. String query = function + " && (GEO_FIELD == '0100' || " + indexQuery + ")"; @@ -38,7 +49,7 @@ public class GeoWavePruningVisitorTest { public void testPrunedWrappedTermDoesNotLeaveEmptyWrappedTerm() throws ParseException { String function = "geowave:intersects(GEO_FIELD, 'POLYGON((10 10, 20 10, 20 20, 10 20, 10 10))')"; // Get the expanded geowave terms. - String indexQuery = convertFunctionToIndexQuery(function, new ShardQueryConfiguration()); + String indexQuery = convertFunctionToIndexQuery(function, new ShardQueryConfiguration(), metadataHelper); // Add a wrapped term that should be pruned. String query = function + " && ((GEO_FIELD == '0100') || " + indexQuery + ")"; @@ -50,11 +61,39 @@ public class GeoWavePruningVisitorTest { assertResult(query, expected, expectedPrunedTerms); } + @Test + public void testNonGeometryTermsNotPruned() throws ParseException { + String function = "geowave:intersects(LEGACY_GEO_FIELD, 'POLYGON((10 10, 20 10, 20 20, 10 20, 10 10))')"; + // Get the expanded geowave terms. + String indexQuery = convertFunctionToIndexQuery(function, new ShardQueryConfiguration(), metadataHelper); + + // Add a term that should be pruned. + String query = function + " && (" + indexQuery + ")"; + + Multimap<String,String> expectedPrunedTerms = HashMultimap.create(); + + assertResult(query, query, expectedPrunedTerms); + } + + @Test + public void testIgnoreImproperlyFormattedTerms() throws ParseException { + String function = "geowave:intersects(GEO_FIELD, 'POLYGON((10 10, 20 10, 20 20, 10 20, 10 10))')"; + // Get the expanded geowave terms. + String indexQuery = convertFunctionToIndexQuery(function, new ShardQueryConfiguration(), metadataHelper); + + // Add a term that should be pruned. + String query = function + " && (GEO_FIELD == '1f123..456' || " + indexQuery + ")"; + + Multimap<String,String> expectedPrunedTerms = HashMultimap.create(); + + assertResult(query, query, expectedPrunedTerms); + } + private void assertResult(String original, String expected, Multimap<String,String> expectedPrunedTerms) throws ParseException { ASTJexlScript originalScript = JexlASTHelper.parseJexlQuery(original); Multimap<String,String> prunedTerms = HashMultimap.create(); - ASTJexlScript actualScript = GeoWavePruningVisitor.pruneTree(originalScript, prunedTerms, null); + ASTJexlScript actualScript = GeoWavePruningVisitor.pruneTree(originalScript, prunedTerms, metadataHelper); // Verify the result is as expected, with a valid lineage. JexlNodeAssert.assertThat(actualScript).isEqualTo(expected).hasValidLineage(); @@ -63,7 +102,7 @@ public class GeoWavePruningVisitorTest { assertNoChildlessReferences(actualScript); // Verify the correct terms were pruned. - assertEquals(prunedTerms, expectedPrunedTerms); + assertEquals(expectedPrunedTerms, prunedTerms); // Verify the original script was not modified, and has a valid lineage. JexlNodeAssert.assertThat(originalScript).isEqualTo(original).hasValidLineage();
['warehouse/query-core/src/test/java/datawave/query/jexl/visitors/GeoWavePruningVisitorTest.java', 'warehouse/query-core/src/main/java/datawave/query/jexl/visitors/GeoWavePruningVisitor.java', 'warehouse/query-core/src/test/java/datawave/query/jexl/functions/GeoWaveFunctionsDescriptorTest.java']
{'.java': 3}
3
3
0
0
3
11,900,911
2,522,568
296,192
1,693
3,049
552
52
1
241
38
52
1
0
0
1970-01-01T00:27:37
484
Java
{'Java': 17524398, 'Shell': 336944, 'HTML': 34795, 'JavaScript': 28894, 'Dockerfile': 7456, 'Python': 5806, 'CSS': 4835, 'XSLT': 535}
Apache License 2.0
2,106
datadog/dd-trace-java/327/325
datadog
dd-trace-java
https://github.com/DataDog/dd-trace-java/issues/325
https://github.com/DataDog/dd-trace-java/pull/327
https://github.com/DataDog/dd-trace-java/pull/327
1
closes
ClassCastException with Slick
Using Slick 3.2.1, I see the following exceptions in the logs: > Caused by: java.lang.ClassCastException: datadog.trace.instrumentation.java.concurrent.ExecutorInstrumentation$RunnableWrapper cannot be cast to slick.util.AsyncExecutor$PrioritizedRunnable at slick.util.ManagedArrayBlockingQueue.offer(ManagedArrayBlockingQueue.scala:13) at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1371) at slick.util.AsyncExecutor$$anon$2$$anon$3.execute(AsyncExecutor.scala:120) ... at slick.basic.BasicBackend$DatabaseDef.runSynchronousDatabaseAction(BasicBackend.scala:231) at slick.basic.BasicBackend$DatabaseDef.runSynchronousDatabaseAction$(BasicBackend.scala:229) at slick.jdbc.JdbcBackend$DatabaseDef.runSynchronousDatabaseAction(JdbcBackend.scala:37) at slick.basic.BasicBackend$DatabaseDef.runInContext(BasicBackend.scala:208) at slick.basic.BasicBackend$DatabaseDef.runInContext$(BasicBackend.scala:140) at slick.jdbc.JdbcBackend$DatabaseDef.runInContext(JdbcBackend.scala:37) at slick.basic.BasicBackend$DatabaseDef.runInternal(BasicBackend.scala:76) at slick.basic.BasicBackend$DatabaseDef.runInternal$(BasicBackend.scala:75) at slick.jdbc.JdbcBackend$DatabaseDef.runInternal(JdbcBackend.scala:37) at slick.basic.BasicBackend$DatabaseDef.run(BasicBackend.scala:73) at slick.basic.BasicBackend$DatabaseDef.run$(BasicBackend.scala:73) at slick.jdbc.JdbcBackend$DatabaseDef.run(JdbcBackend.scala:37) Looks like the Java APM agent is interfering with a cast that occurs in Slick. Let me know if you need any other details.
f74710a3bcadc7312fb0ff2edf11dce1f2c474c3
1641c5444818bff910a3de84e053b7808d0c0e68
https://github.com/datadog/dd-trace-java/compare/f74710a3bcadc7312fb0ff2edf11dce1f2c474c3...1641c5444818bff910a3de84e053b7808d0c0e68
diff --git a/dd-java-agent/instrumentation/java-concurrent/src/main/java/datadog/trace/instrumentation/java/concurrent/ExecutorInstrumentation.java b/dd-java-agent/instrumentation/java-concurrent/src/main/java/datadog/trace/instrumentation/java/concurrent/ExecutorInstrumentation.java index 0ecbf2ae84..2dca101cbc 100644 --- a/dd-java-agent/instrumentation/java-concurrent/src/main/java/datadog/trace/instrumentation/java/concurrent/ExecutorInstrumentation.java +++ b/dd-java-agent/instrumentation/java-concurrent/src/main/java/datadog/trace/instrumentation/java/concurrent/ExecutorInstrumentation.java @@ -137,12 +137,13 @@ public final class ExecutorInstrumentation extends Instrumenter.Configurable { public static class WrapRunnableAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static DatadogWrapper wrapJob( - @Advice.Argument(value = 0, readOnly = false) Runnable task) { + @Advice.This Object dis, @Advice.Argument(value = 0, readOnly = false) Runnable task) { final Scope scope = GlobalTracer.get().scopeManager().active(); if (scope instanceof TraceScope && ((TraceScope) scope).isAsyncPropagating() && task != null - && !(task instanceof DatadogWrapper)) { + && !(task instanceof DatadogWrapper) + && (!dis.getClass().getName().startsWith("slick.util.AsyncExecutor"))) { task = new RunnableWrapper(task, (TraceScope) scope); return (RunnableWrapper) task; } @@ -161,12 +162,13 @@ public final class ExecutorInstrumentation extends Instrumenter.Configurable { public static class WrapCallableAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static DatadogWrapper wrapJob( - @Advice.Argument(value = 0, readOnly = false) Callable<?> task) { + @Advice.This Object dis, @Advice.Argument(value = 0, readOnly = false) Callable<?> task) { final Scope scope = GlobalTracer.get().scopeManager().active(); if (scope instanceof TraceScope && ((TraceScope) scope).isAsyncPropagating() && task != null - && !(task instanceof DatadogWrapper)) { + && !(task instanceof DatadogWrapper) + && (!dis.getClass().getName().startsWith("slick.util.AsyncExecutor"))) { task = new CallableWrapper<>(task, (TraceScope) scope); return (CallableWrapper) task; } @@ -185,9 +187,12 @@ public final class ExecutorInstrumentation extends Instrumenter.Configurable { public static class WrapCallableCollectionAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static Collection<?> wrapJob( + @Advice.This Object dis, @Advice.Argument(value = 0, readOnly = false) Collection<? extends Callable<?>> tasks) { final Scope scope = GlobalTracer.get().scopeManager().active(); - if (scope instanceof TraceScope && ((TraceScope) scope).isAsyncPropagating()) { + if (scope instanceof TraceScope + && ((TraceScope) scope).isAsyncPropagating() + && (!dis.getClass().getName().startsWith("slick.util.AsyncExecutor"))) { final Collection<Callable<?>> wrappedTasks = new ArrayList<>(tasks.size()); for (Callable<?> task : tasks) { if (task != null) {
['dd-java-agent/instrumentation/java-concurrent/src/main/java/datadog/trace/instrumentation/java/concurrent/ExecutorInstrumentation.java']
{'.java': 1}
1
1
0
0
1
445,439
94,145
13,185
163
1,009
222
15
1
1,696
76
373
21
0
0
1970-01-01T00:25:26
464
Java
{'Java': 9643226, 'Groovy': 5984559, 'Scala': 68384, 'Shell': 30037, 'Kotlin': 22935, 'HTML': 4385, 'Dockerfile': 3384, 'Python': 2020, 'JavaScript': 1629, 'FreeMarker': 697, 'Mustache': 286, 'Batchfile': 138}
Apache License 2.0
565
wro4j/wro4j/981/980
wro4j
wro4j
https://github.com/wro4j/wro4j/issues/980
https://github.com/wro4j/wro4j/pull/981
https://github.com/wro4j/wro4j/pull/981
1
close
Stale wro4j-core.jar when undeployed on windows tomcat
My application cannot be undeployed correctly on windows tomcat because there seems to be a file-lock on the wro4j-core.....jar event after application shutdown. I tried to manually call WroManagerFactory.destroy() without any luck. I suspect wro4j itself causing this file to be locked. How do I correctly shutdown wro4j correctly?
d1ff205bab699461215f80d35ff0888d6f232e24
b9a4e954c0ca1507a1c4b4ad4cb4f35d6ebccb16
https://github.com/wro4j/wro4j/compare/d1ff205bab699461215f80d35ff0888d6f232e24...b9a4e954c0ca1507a1c4b4ad4cb4f35d6ebccb16
diff --git a/wro4j-core/src/main/java/ro/isdc/wro/util/WroUtil.java b/wro4j-core/src/main/java/ro/isdc/wro/util/WroUtil.java index 2fa8c3979..e8ee3f09f 100644 --- a/wro4j-core/src/main/java/ro/isdc/wro/util/WroUtil.java +++ b/wro4j-core/src/main/java/ro/isdc/wro/util/WroUtil.java @@ -321,6 +321,7 @@ public final class WroUtil { try { final InputStream stream = WroUtil.class.getResourceAsStream("regexp.properties"); final Properties props = new RegexpProperties().load(stream); + stream.close(); return props.getProperty(key); } catch (final IOException e) { throw new WroRuntimeException("Could not load pattern with key: " + key + " from property file", e);
['wro4j-core/src/main/java/ro/isdc/wro/util/WroUtil.java']
{'.java': 1}
1
1
0
0
1
1,154,157
258,566
36,829
346
20
4
1
1
335
49
75
7
0
0
1970-01-01T00:24:03
459
Java
{'Java': 1927066, 'CSS': 381699, 'JavaScript': 301910, 'SCSS': 69119, 'Groovy': 11147, 'Handlebars': 6306, 'Less': 3633, 'CoffeeScript': 1407, 'TypeScript': 939}
Apache License 2.0
8,885
mockbukkit/mockbukkit/757/691
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/691
https://github.com/MockBukkit/MockBukkit/pull/757
https://github.com/MockBukkit/MockBukkit/pull/757
1
fixes
Disconnect doesn't call PlayerQuitEvent if PlayerMock is constructed with ServerMock#addPlayer(String)
### Is there an existing issue for this? - [X] I have searched the existing issues ### Are you using the latest version of MockBukkit? - [X] I am using the latest version of MockBukkit. ### Minecraft Version 1.19 ### Describe the bug Disconnect doesn't appear to be calling PlayerQuitEvent if the PlayerMock is built using only a name and not a UUID. If a player is created with just a name, no UUID, the `online` field in the PlayerMock is set to false, even though `isOnline()` will return true because they're in the online player list. `disconnect()` uses that `online` field to determine if the event should fire but it is `false`, so the event doesn't fire. If I create the player with new and with a UUID, the disconnect method works as I would assume it should but with just the ServerMock#addPlayer it does not. ### Reproducible Test ```java @Test public void quitNoWork() { PlayerMock travja = server.addPlayer("Travja"); // Comment ^ and uncomment below and it works // PlayerMock travja = new PlayerMock(server, "Travja", UUID.randomUUID()); // server.addPlayer(travja); travja.disconnect(); server.getPluginManager().assertEventFired(PlayerQuitEvent.class, e -> { System.out.println("Event was fired!"); return true; }); } ``` ### Anything else? [PlayerMock:164](https://github.com/MockBukkit/MockBukkit/blob/v1.19/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java#L164) indicates the player should be considered offline, but this field is not updated when `ServerMock#addPlayer` is called.
a0e92944c6c868843c0e91cde1429ead78ebded6
efdd67b6a0931b9d50e1f91d2309d47d44db2a7d
https://github.com/mockbukkit/mockbukkit/compare/a0e92944c6c868843c0e91cde1429ead78ebded6...efdd67b6a0931b9d50e1f91d2309d47d44db2a7d
diff --git a/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java b/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java index 7c6e02af..64afa194 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java @@ -345,7 +345,7 @@ public class ServerMock extends Server.Spigot implements Server public @NotNull PlayerMock addPlayer(@NotNull String name) { AsyncCatcher.catchOp("player add"); - PlayerMock player = new PlayerMock(this, name); + PlayerMock player = new PlayerMock(this, name, UUID.randomUUID()); addPlayer(player); return player; } diff --git a/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java b/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java index a654fbb8..9c16cbdc 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java @@ -179,9 +179,7 @@ public class PlayerMock extends HumanEntityMock implements Player, SoundReceiver */ public PlayerMock(@NotNull ServerMock server, @NotNull String name) { - this(server, name, UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8))); - this.online = false; - this.scoreboard = server.getScoreboardManager().getMainScoreboard(); + this(server, name, UUID.randomUUID()); } /** diff --git a/src/test/java/be/seeseemelk/mockbukkit/entity/PlayerMockTest.java b/src/test/java/be/seeseemelk/mockbukkit/entity/PlayerMockTest.java index 72a61699..b667e48c 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/entity/PlayerMockTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/entity/PlayerMockTest.java @@ -1783,7 +1783,7 @@ class PlayerMockTest @Test void testKickWithOfflinePlayer() { - PlayerMock player = new PlayerMock(server, "testPlayer"); + PlayerMock player = new PlayerMock(server, "testPlayer", UUID.randomUUID()); player.kick(Component.text("test"), PlayerKickEvent.Cause.KICK_COMMAND); server.getPluginManager().assertEventNotFired(PlayerKickEvent.class); } @@ -2152,6 +2152,14 @@ class PlayerMockTest }); } + @Test + void testPlayerQuitEventGetFired() + { + PlayerMock player = server.addPlayer("Player"); + player.disconnect(); + server.getPluginManager().assertEventFired(PlayerQuitEvent.class); + } + public static Stream<Arguments> provideInstrument() { return Stream.of(
['src/test/java/be/seeseemelk/mockbukkit/entity/PlayerMockTest.java', 'src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java', 'src/main/java/be/seeseemelk/mockbukkit/ServerMock.java']
{'.java': 3}
3
3
0
0
3
1,034,228
244,487
43,133
258
364
84
6
2
1,653
213
388
38
1
1
1970-01-01T00:28:02
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
8,884
mockbukkit/mockbukkit/765/763
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/763
https://github.com/MockBukkit/MockBukkit/pull/765
https://github.com/MockBukkit/MockBukkit/pull/765
1
fixes
assertGameMode does not detect the change of gamemode
### Is there an existing issue for this? - [X] I have searched the existing issues ### Are you using the latest version of MockBukkit? - [X] I am using the latest version of MockBukkit. ### Minecraft Version 1.18 ### Describe the bug When I type this code ```java PlayerMock player = new PlayerMock(server, "test") ; player.setGameMode(GameMode.CREATIVE) ; player.assertGameMode(GameMode.CREATIVE) ; ``` assertGameMode keeps the player's GameMode.SURVIVAL state the response : ``` org.opentest4j.AssertionFailedError: Expected :CREATIVE Actual :SURVIVAL ``` ### Reproducible Test ```java PlayerMock player = new PlayerMock(server, "test") ; player.setGameMode(GameMode.CREATIVE) ; player.assertGameMode(GameMode.CREATIVE) ; ``` ### Anything else? _No response_
f3190f6ff0c5b26f051c486088afaec52c6a2d67
d26534dcd3cd244d04b3883ddb2b7f17e5508873
https://github.com/mockbukkit/mockbukkit/compare/f3190f6ff0c5b26f051c486088afaec52c6a2d67...d26534dcd3cd244d04b3883ddb2b7f17e5508873
diff --git a/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java b/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java index 3c0bcc84..e87ca931 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java @@ -133,8 +133,7 @@ public class PlayerMock extends HumanEntityMock implements Player, SoundReceiver private static final Component DEFAULT_KICK_COMPONENT = Component.text("You are not whitelisted on this server!"); - private @NotNull GameMode gamemode = GameMode.SURVIVAL; - private @NotNull GameMode previousGamemode = gamemode; + private @NotNull GameMode previousGamemode = super.getGameMode(); private boolean online; private @Nullable Component displayName = null; @@ -359,7 +358,7 @@ public class PlayerMock extends HumanEntityMock implements Player, SoundReceiver public @Nullable BlockDamageEvent simulateBlockDamage(@NotNull Block block) { Preconditions.checkNotNull(block, "Block cannot be null"); - if (gamemode != GameMode.SURVIVAL) + if (super.getGameMode() != GameMode.SURVIVAL) { return null; } @@ -387,8 +386,8 @@ public class PlayerMock extends HumanEntityMock implements Player, SoundReceiver public @Nullable BlockBreakEvent simulateBlockBreak(@NotNull Block block) { Preconditions.checkNotNull(block, "Block cannot be null"); - if ((gamemode == GameMode.SPECTATOR || gamemode == GameMode.ADVENTURE) - || (gamemode == GameMode.SURVIVAL && simulateBlockDamagePure(block).isCancelled())) + if ((super.getGameMode() == GameMode.SPECTATOR || super.getGameMode() == GameMode.ADVENTURE) + || (super.getGameMode() == GameMode.SURVIVAL && simulateBlockDamagePure(block).isCancelled())) return null; BlockBreakEvent event = new BlockBreakEvent(block, this); @@ -411,7 +410,7 @@ public class PlayerMock extends HumanEntityMock implements Player, SoundReceiver { Preconditions.checkNotNull(material, "Material cannot be null"); Preconditions.checkNotNull(location, "Location cannot be null"); - if (gamemode == GameMode.ADVENTURE || gamemode == GameMode.SPECTATOR) + if (super.getGameMode() == GameMode.ADVENTURE || super.getGameMode() == GameMode.SPECTATOR) return null; Block block = location.getBlock(); BlockState blockState = block.getState(); @@ -510,25 +509,19 @@ public class PlayerMock extends HumanEntityMock implements Player, SoundReceiver return event; } - @Override - public @NotNull GameMode getGameMode() - { - return this.gamemode; - } - @Override public void setGameMode(@NotNull GameMode mode) { Preconditions.checkNotNull(mode, "GameMode cannot be null"); - if (this.gamemode == mode) + if (super.getGameMode() == mode) return; PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(this, mode, PlayerGameModeChangeEvent.Cause.UNKNOWN, null); if (!event.callEvent()) return; - this.previousGamemode = this.gamemode; - this.gamemode = mode; + this.previousGamemode = super.getGameMode(); + super.setGameMode(mode); } @Override
['src/main/java/be/seeseemelk/mockbukkit/entity/PlayerMock.java']
{'.java': 1}
1
1
0
0
1
1,034,198
244,526
43,156
258
1,093
296
23
1
817
98
209
41
0
3
1970-01-01T00:28:02
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
8,886
mockbukkit/mockbukkit/559/444
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/444
https://github.com/MockBukkit/MockBukkit/pull/559
https://github.com/MockBukkit/MockBukkit/pull/559
1
closes
Player#isPermissionSet(String) returns false when PermissionAttachment set to false
```java Player permissible = server.addPlayer(); permissible.addAttachment( plugin, "test.perm", false, ); permissible.isPermissionSet("test.perm"); // returns false but it should be true permissible.permissionValue("test.perm"); // returns TriState.NOT_SET but is should be TriState.FALSE ``` Maybe permission check logic has a bug?
d71d70f197776b42ca928e31f187a24c9425167e
7ce7c5b1bb47a483431a61edcd36ce79ef0570f8
https://github.com/mockbukkit/mockbukkit/compare/d71d70f197776b42ca928e31f187a24c9425167e...7ce7c5b1bb47a483431a61edcd36ce79ef0570f8
diff --git a/src/main/java/be/seeseemelk/mockbukkit/entity/EntityMock.java b/src/main/java/be/seeseemelk/mockbukkit/entity/EntityMock.java index 282e9cc0..9c68830b 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/entity/EntityMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/entity/EntityMock.java @@ -33,10 +33,10 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleExitEvent; import org.bukkit.metadata.MetadataValue; +import org.bukkit.permissions.PermissibleBase; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.permissions.PermissionRemovedExecutor; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.plugin.Plugin; import org.bukkit.util.BoundingBox; @@ -50,8 +50,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; -import java.util.Locale; -import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.UUID; @@ -80,7 +78,7 @@ public abstract class EntityMock extends Entity.Spigot implements Entity, Messag private boolean invulnerable; private boolean glowingFlag = false; private final Queue<Component> messages = new LinkedTransferQueue<>(); - private final Set<PermissionAttachment> permissionAttachments = new HashSet<>(); + private final PermissibleBase perms; private @NotNull Vector velocity = new Vector(0, 0, 0); private float fallDistance; private int fireTicks = -20; @@ -96,6 +94,8 @@ public abstract class EntityMock extends Entity.Spigot implements Entity, Messag this.server = server; this.uuid = uuid; + this.perms = new PermissibleBase(this); + if (!Bukkit.getWorlds().isEmpty()) location = Bukkit.getWorlds().get(0).getSpawnLocation(); else @@ -426,115 +426,67 @@ public abstract class EntityMock extends Entity.Spigot implements Entity, Messag @Override public boolean isPermissionSet(@NotNull String name) { - Preconditions.checkNotNull(name, "Name cannot be null"); - return permissionAttachments.stream() - .map(PermissionAttachment::getPermissions) - .anyMatch(permissions -> permissions.containsKey(name) && permissions.get(name)); + return this.perms.isPermissionSet(name); } @Override public boolean isPermissionSet(@NotNull Permission perm) { - Preconditions.checkNotNull(perm, "Permission cannot be null"); - return isPermissionSet(perm.getName().toLowerCase(Locale.ENGLISH)); + return this.perms.isPermissionSet(perm); } @Override public boolean hasPermission(@NotNull String name) { - Preconditions.checkNotNull(name, "Name cannot be null"); - if (isPermissionSet(name)) - { - return true; - } - - Permission perm = server.getPluginManager().getPermission(name); - return perm != null ? hasPermission(perm) : Permission.DEFAULT_PERMISSION.getValue(isOp()); + return this.perms.hasPermission(name); } @Override public boolean hasPermission(@NotNull Permission perm) { - Preconditions.checkNotNull(perm, "Permission cannot be null"); - return isPermissionSet(perm) || perm.getDefault().getValue(isOp()); + return this.perms.hasPermission(perm); } @Override public @NotNull PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value) { - Preconditions.checkNotNull(plugin, "Plugin cannot be null"); - Preconditions.checkNotNull(name, "Name cannot be null"); - PermissionAttachment attachment = addAttachment(plugin); - attachment.setPermission(name, value); - return attachment; + return this.perms.addAttachment(plugin, name, value); } @Override public @NotNull PermissionAttachment addAttachment(@NotNull Plugin plugin) { - Preconditions.checkNotNull(plugin, "Plugin cannot be null"); - PermissionAttachment attachment = new PermissionAttachment(plugin, this); - permissionAttachments.add(attachment); - return attachment; + return this.perms.addAttachment(plugin); } @Override public PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value, int ticks) { - // TODO Auto-generated constructor stub - throw new UnimplementedOperationException(); + return this.perms.addAttachment(plugin, name, value, ticks); } @Override public PermissionAttachment addAttachment(@NotNull Plugin plugin, int ticks) { - // TODO Auto-generated constructor stub - throw new UnimplementedOperationException(); + return this.perms.addAttachment(plugin, ticks); } @Override public void removeAttachment(@NotNull PermissionAttachment attachment) { - Preconditions.checkNotNull(attachment, "Attachment cannot be null"); - - if (permissionAttachments.contains(attachment)) - { - permissionAttachments.remove(attachment); - PermissionRemovedExecutor ex = attachment.getRemovalCallback(); - - if (ex != null) - { - ex.attachmentRemoved(attachment); - } - - recalculatePermissions(); - } - else - { - throw new IllegalArgumentException("Given attachment is not part of Permissible object " + this); - } + this.perms.removeAttachment(attachment); } @Override public void recalculatePermissions() { - + this.perms.recalculatePermissions(); } @Override public @NotNull Set<PermissionAttachmentInfo> getEffectivePermissions() { - HashSet<PermissionAttachmentInfo> permissionAttachmentInfos = new HashSet<>(); - - for (PermissionAttachment permissionAttachment : permissionAttachments) - { - for (Map.Entry<String, Boolean> entry : permissionAttachment.getPermissions().entrySet()) - { - permissionAttachmentInfos.add(new PermissionAttachmentInfo(this, entry.getKey(), permissionAttachment, entry.getValue())); - } - } - - return permissionAttachmentInfos; + return this.perms.getEffectivePermissions(); } @Override diff --git a/src/test/java/be/seeseemelk/mockbukkit/entity/EntityMockTest.java b/src/test/java/be/seeseemelk/mockbukkit/entity/EntityMockTest.java index 5fb41446..897637f6 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/entity/EntityMockTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/entity/EntityMockTest.java @@ -392,89 +392,103 @@ class EntityMockTest } @Test - void hasPermission_NotAddedNotDefault_DoesNotHavePermission() + void addAttachment_True_Has() { - Permission permission = new Permission("mockbukkit.perm", PermissionDefault.FALSE); - server.getPluginManager().addPermission(permission); - assertFalse(entity.hasPermission("mockbukkit.perm")); + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true); + assertTrue(entity.hasPermission("test.permission")); } @Test - void hasPermission_NotAddedButDefault_DoesPermission() + void addAttachment_False_DoesntHave() { - MockPlugin plugin = MockBukkit.createMockPlugin(); - Permission permission = new Permission("mockbukkit.perm", PermissionDefault.TRUE); - server.getPluginManager().addPermission(permission); - entity.addAttachment(plugin, "mockbukkit.perm", true); - assertTrue(entity.hasPermission("mockbukkit.perm")); + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", false); + assertFalse(entity.hasPermission("test.permission")); } @Test - void addAttachment_PermissionObject_PermissionAdded() + void addAttachment_RemovedAfterTicks() { - MockPlugin plugin = MockBukkit.createMockPlugin(); - Permission permission = new Permission("mockbukkit.perm", PermissionDefault.FALSE); - server.getPluginManager().addPermission(permission); - PermissionAttachment attachment = entity.addAttachment(plugin); - attachment.setPermission(permission, true); - assertTrue(entity.hasPermission("mockbukkit.perm")); + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true, 10); + assertTrue(entity.isPermissionSet("test.permission")); + server.getScheduler().performTicks(9); + assertTrue(entity.isPermissionSet("test.permission")); + server.getScheduler().performTicks(10); + assertFalse(entity.isPermissionSet("test.permission")); } @Test - void addAttachment_PermissionName_PermissionAdded() + void removeAttachment_RemovesAttachment() { - MockPlugin plugin = MockBukkit.createMockPlugin(); - Permission permission = new Permission("mockbukkit.perm", PermissionDefault.TRUE); - server.getPluginManager().addPermission(permission); - PermissionAttachment attachment = entity.addAttachment(plugin); - attachment.setPermission(permission.getName(), true); - assertTrue(entity.hasPermission("mockbukkit.perm")); + PermissionAttachment att = entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true); + assertTrue(entity.hasPermission("test.permission")); + entity.removeAttachment(att); + assertFalse(entity.hasPermission("test.permission")); } @Test - void addPermission_String_PermissionAdded() + void isPermissionSet_String_IsSet_True() { - MockPlugin plugin = MockBukkit.createMockPlugin(); - Permission permission = new Permission("mockbukkit.perm", PermissionDefault.TRUE); - server.getPluginManager().addPermission(permission); - PermissionAttachment attachment = entity.addAttachment(plugin); - attachment.setPermission(permission.getName(), true); - assertTrue(entity.hasPermission("mockbukkit.perm")); + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true); + assertTrue(entity.isPermissionSet("test.permission")); } @Test - void getEffectivePermissions_GetPermissionsList() + void isPermissionSet_String_IsntSet_False() { - MockPlugin plugin = MockBukkit.createMockPlugin(); - entity.addAttachment(plugin, "mockbukkit.perm", true); - entity.addAttachment(plugin, "mockbukkit.perm2", true); - entity.addAttachment(plugin, "mockbukkit.perm3", false); + assertFalse(entity.isPermissionSet("test.permission")); + } - Set<PermissionAttachmentInfo> effectivePermissions = entity.getEffectivePermissions(); - assertEquals(3, effectivePermissions.size()); + @Test + void isPermissionSet_Permission_IsSet_True() + { + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true); + assertTrue(entity.isPermissionSet(new Permission("test.permission"))); + } - Set<String> permissions = effectivePermissions.stream().map(PermissionAttachmentInfo::getPermission).collect(Collectors.toSet()); - assertTrue(permissions.contains("mockbukkit.perm")); - assertTrue(permissions.contains("mockbukkit.perm2")); - assertTrue(permissions.contains("mockbukkit.perm3")); + @Test + void isPermissionSet_Permission_IsntSet_False() + { + assertFalse(entity.isPermissionSet(new Permission("test.permission"))); + } - Optional<PermissionAttachmentInfo> first = effectivePermissions.stream().filter(permissionAttachmentInfo -> permissionAttachmentInfo.getPermission().equals("mockbukkit.perm3")).findFirst(); - assertTrue(first.isPresent()); - assertFalse(first.get().getValue()); + @Test + void hasPermission_String_SetTrue_True() + { + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true); + assertTrue(entity.hasPermission("test.permission")); } @Test - void removeAttachment_RemovesPermission() + void hasPermission_String_SetFalse_True() { - MockPlugin plugin = MockBukkit.createMockPlugin(); - Permission permission = new Permission("mockbukkit.perm"); - server.getPluginManager().addPermission(permission); - PermissionAttachment attachment = entity.addAttachment(plugin); - attachment.setPermission(permission.getName(), true); - assertTrue(entity.hasPermission("mockbukkit.perm")); - - entity.removeAttachment(attachment); - assertFalse(entity.hasPermission("mockbukkit.perm")); + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", false); + assertFalse(entity.hasPermission("test.permission")); + } + + @Test + void hasPermission_String_NotSet_True() + { + assertFalse(entity.hasPermission("test.permission")); + } + + @Test + void hasPermission_Permission_SetTrue_True() + { + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", true); + assertTrue(entity.hasPermission(new Permission("test.permission"))); + } + + @Test + void hasPermission_Permission_SetFalse_True() + { + entity.addAttachment(MockBukkit.createMockPlugin(), "test.permission", false); + assertFalse(entity.hasPermission(new Permission("test.permission"))); + } + + @Test + void hasPermission_Permission_NotSet_True() + { + assertTrue(entity.hasPermission(new Permission("test.permission", PermissionDefault.TRUE))); } @Test
['src/main/java/be/seeseemelk/mockbukkit/entity/EntityMock.java', 'src/test/java/be/seeseemelk/mockbukkit/entity/EntityMockTest.java']
{'.java': 2}
2
2
0
0
2
822,526
192,502
34,871
220
3,186
645
78
1
363
36
77
12
0
1
1970-01-01T00:27:38
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
8,887
mockbukkit/mockbukkit/546/543
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/543
https://github.com/MockBukkit/MockBukkit/pull/546
https://github.com/MockBukkit/MockBukkit/pull/546
1
closes
Value of `getBukkitVersion()` is nonstandard
### Is there an existing issue for this? - [X] I have searched the existing issues ### Are you using the latest version of MockBukkit? - [X] I am using the latest version of MockBukkit. ### Minecraft Version 1.19 ### Describe the bug The value of `Bukkit.getBukkitVersion()` does not conform to the expected format containing a revision number and a snapshot qualifier. ### Reproducible Test Compile this MWE using your tool of choice: ```java package net.ssterling.example; import org.bukkit.Bukkit; import be.seeseemelk.mockbukkit.MockBukkit; import be.seeseemelk.mockbukkit.ServerMock; class ServerVersionTest { public static void main(String[] args) { ServerMock server = MockBukkit.mock(); String version_string = Bukkit.getBukkitVersion(); System.out.println("Bukkit API version: " + version_string); MockBukkit.unmock(); } } ``` The output is `1.19`, not the expected `1.19-R0.1-SNAPSHOT`. ### Anything else? I’m currently working on a utility to more easily process Bukkit API and vanilla Minecraft version strings. I’m using MockBukkit for unit tests; one of those tests makes sure the value of `Bukkit.getBukkitVersion()` is correctly detected as a valid Bukkit API server string, making sure I didn’t accidentally screw up the regex. You can see why the “server” itself providing an incorrect string is a problem for me. I’d provide a link to the source for the project in question for context, but it’s still a pre-0.1.0 WIP.
633f1551c617cebe053f02234a359eb8dc83108d
1983eb54964f29ec3015e320522c1df7d7ff8e97
https://github.com/mockbukkit/mockbukkit/compare/633f1551c617cebe053f02234a359eb8dc83108d...1983eb54964f29ec3015e320522c1df7d7ff8e97
diff --git a/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java b/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java index 5ae359da..93d89bd6 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java @@ -486,18 +486,16 @@ public class ServerMock extends Server.Spigot implements Server @Override public @NotNull String getBukkitVersion() { - return getMinecraftVersion(); + Preconditions.checkNotNull(this.buildProperties, "Failed to load build properties!"); + String apiVersion = buildProperties.getProperty("full-api-version"); + Preconditions.checkNotNull(apiVersion, "Failed to get full-api-version from the build properties!"); + return apiVersion; } @Override public @NotNull String getMinecraftVersion() { - String apiVersion; - if (buildProperties == null || (apiVersion = buildProperties.getProperty("full-api-version")) == null) - { - throw new IllegalStateException("Minecraft version could not be determined"); - } - return apiVersion.split("-")[0]; + return this.getBukkitVersion().split("-")[0]; } @Override diff --git a/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java b/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java index 56e4240f..b7222b1a 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java @@ -183,6 +183,24 @@ class ServerMockTest assertNotNull(server.getBukkitVersion()); } + @Test + void getBukkitVersion_CorrectPattern() + { + assertTrue(server.getBukkitVersion().matches("1\\\\.[0-9]+(\\\\.[0-9]+)?-.*SNAPSHOT.*")); + } + + @Test + void getMinecraftVersion_NotNull() + { + assertNotNull(server.getMinecraftVersion()); + } + + @Test + void getMinecraftVersion_CorrectPattern() + { + assertTrue(server.getMinecraftVersion().matches("1\\\\.[0-9]+(\\\\.[0-9]+)?")); + } + @Test void getName_NotNull() { diff --git a/src/test/java/be/seeseemelk/mockbukkit/UnsafeValuesTest.java b/src/test/java/be/seeseemelk/mockbukkit/UnsafeValuesTest.java index 4c472bd9..6d097ea0 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/UnsafeValuesTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/UnsafeValuesTest.java @@ -51,9 +51,9 @@ class UnsafeValuesTest } @Test - void checkSupported_currentServerVersion() throws InvalidPluginException + void checkSupported_currentServerVersion() { - String currentVersion = server.getBukkitVersion(); + String currentVersion = server.getMinecraftVersion(); // if version is in pattern MAJOR.MINOR.FIX, transform to MAJOR.MINOR if (Pattern.matches(".{1,3}\\\\..{1,3}\\\\..*", currentVersion)) {
['src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java', 'src/test/java/be/seeseemelk/mockbukkit/UnsafeValuesTest.java', 'src/main/java/be/seeseemelk/mockbukkit/ServerMock.java']
{'.java': 3}
3
3
0
0
3
789,169
184,459
33,422
200
624
129
12
1
1,489
208
354
48
0
1
1970-01-01T00:27:37
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
8,889
mockbukkit/mockbukkit/364/251
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/251
https://github.com/MockBukkit/MockBukkit/pull/364
https://github.com/MockBukkit/MockBukkit/pull/364
1
closes
Wait for async event execution?
Is there a proper way to wait for async events to finish? I saw that `BukkitSchedulerMock#waitAsyncTasksFinished()` exists, but it doesn't cover async events like `AsyncPlayerChatEvent`. I am currently trying to test a plugin's reaction on `PlayerMock#chat(String)` and calling `Thread#sleep(long)` isn't optimal in any way. I am currently using `MockBukkit-v1.16` version `1.5.2`.
23197ee5aaa679e087e4cfd24818ce368bd8ade8
53108c92fb7e537446384db323f6fbcc5b881b29
https://github.com/mockbukkit/mockbukkit/compare/23197ee5aaa679e087e4cfd24818ce368bd8ade8...53108c92fb7e537446384db323f6fbcc5b881b29
diff --git a/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java b/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java index e0ad468a..9e4d7df6 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java @@ -50,13 +50,16 @@ public class BukkitSchedulerMock implements BukkitScheduler }; } - + /** + * Sets the maximum time to wait for async tasks to finish before terminating them. + * + * @param timeout The timeout in milliseconds. + */ public void setShutdownTimeout(long timeout) { this.executorTimeout = timeout; } - /** * Shuts the scheduler down. Note that this function will throw exception that where thrown by old asynchronous * tasks. @@ -64,10 +67,36 @@ public class BukkitSchedulerMock implements BukkitScheduler public void shutdown() { waitAsyncTasksFinished(); - pool.shutdown(); + + shutdownPool(pool); + if (asyncException.get() != null) throw new AsyncTaskException(asyncException.get()); - asyncEventExecutor.shutdownNow(); + + shutdownPool(asyncEventExecutor); + } + + /** + * Shuts down the given executor service, waiting up to the shutdown timeout for all tasks to finish. + * + * @param pool The pool to shut down. + * @see #setShutdownTimeout(long) + */ + private void shutdownPool(ExecutorService pool) + { + pool.shutdown(); + try + { + if (!pool.awaitTermination(this.executorTimeout, TimeUnit.MILLISECONDS)) + { + pool.shutdownNow(); + } + } + catch (InterruptedException e) + { + pool.shutdownNow(); + Thread.currentThread().interrupt(); + } } public @NotNull Future<?> executeAsyncEvent(Event event) @@ -150,7 +179,7 @@ public class BukkitSchedulerMock implements BukkitScheduler /** * Waits until all asynchronous tasks have finished executing. If you have an asynchronous task that runs - * indefinitely, this function will never return. + * indefinitely, this function will never return. Note that this will not wait for async events to finish. */ public void waitAsyncTasksFinished() { @@ -184,8 +213,8 @@ public class BukkitSchedulerMock implements BukkitScheduler } if (System.currentTimeMillis() > (systemTime + executorTimeout)) { - // If a plugin has left a a runnable going and not cancelled it we could call this bad practice. - // we should now force interrupt all these runnables forcing them to throw Interrupted Exceptions. + // If a plugin has left a runnable going and not cancelled it we could call this bad practice. + // We should force interrupt all those runnables forcing them to throw Interrupted Exceptions- // if they handle that for (ScheduledTask task : scheduledTasks.getCurrentTaskList()) { diff --git a/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java b/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java index d42ea9a1..f014e89a 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java @@ -15,7 +15,12 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import be.seeseemelk.mockbukkit.MockBukkit; +import be.seeseemelk.mockbukkit.ServerMock; import be.seeseemelk.mockbukkit.TestPlugin; +import io.papermc.paper.event.player.AsyncChatEvent; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; import org.junit.jupiter.api.BeforeEach; @@ -197,10 +202,10 @@ class BukkitSchedulerMockTest @Test public void cancellingAllTaskByPlugin() { - MockBukkit.mock(); + ServerMock server = MockBukkit.mock(); MockBukkit.load(TestPlugin.class); - Plugin plugin = MockBukkit.getMock().getPluginManager().getPlugin("MockBukkitTestPlugin"); - BukkitSchedulerMock scheduler1 = MockBukkit.getMock().getScheduler(); + Plugin plugin = server.getPluginManager().getPlugin("MockBukkitTestPlugin"); + BukkitSchedulerMock scheduler1 = server.getScheduler(); assertEquals(0, scheduler1.getNumberOfQueuedAsyncTasks()); scheduler1.runTaskLaterAsynchronously(plugin, () -> {}, 5); scheduler1.runTaskLaterAsynchronously(plugin, () -> {}, 10); @@ -295,4 +300,29 @@ class BukkitSchedulerMockTest scheduler.shutdown(); }); } + + @Test + void shutdown_waitsForAsyncEvents() + { + MockBukkit.mock(); + AtomicBoolean done = new AtomicBoolean(false); + Bukkit.getPluginManager().registerEvents(new Listener() + { + @EventHandler + public void onChat(AsyncChatEvent event) throws Exception + { + Thread.sleep(50); + done.set(true); + } + }, MockBukkit.createMockPlugin()); + AsyncChatEvent event = new AsyncChatEvent(true, null, null, null, null, null); + scheduler.executeAsyncEvent(event); + assertFalse(done.get()); + + scheduler.shutdown(); + + assertTrue(done.get()); + MockBukkit.unmock(); + } + }
['src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java', 'src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java']
{'.java': 2}
2
2
0
0
2
615,045
142,100
26,803
118
1,361
300
43
1
390
51
99
7
0
0
1970-01-01T00:27:33
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
8,890
mockbukkit/mockbukkit/358/345
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/345
https://github.com/MockBukkit/MockBukkit/pull/358
https://github.com/MockBukkit/MockBukkit/pull/358
1
closes
AsyncPlayerPreLoginEvent not being called on ServerMock#addPlayer
I use AsyncPlayerPreLoginEvent to fetch player heads asynchronously. However, this doesn't work in test environment simply because ServerMock#addPlayer does not fire AsyncPlayerPreLoginEvent. ```java @EventHandler public void onAsyncPlayerPreLogin(AsyncPlayerPreLoginEvent e) { if (e.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return; ItemStack itemStack = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()); SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); skullMeta.setOwningPlayer(Bukkit.getOfflinePlayer(e.getUniqueId())); itemStack.setItemMeta(skullMeta); ... } ```
39988a3553f1480ff42ae6fc4dbdb770bcde7223
2d8d1cc15d76dcd8853ec9d61626759edde922b1
https://github.com/mockbukkit/mockbukkit/compare/39988a3553f1480ff42ae6fc4dbdb770bcde7223...2d8d1cc15d76dcd8853ec9d61626759edde922b1
diff --git a/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java b/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java index 2ee2be4f..4bf2762e 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/ServerMock.java @@ -40,6 +40,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; import net.md_5.bungee.api.chat.BaseComponent; import org.apache.commons.lang.Validate; +import org.apache.commons.lang3.StringUtils; import org.bukkit.BanEntry; import org.bukkit.BanList; import org.bukkit.BanList.Type; @@ -76,6 +77,7 @@ import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.entity.SpawnCategory; import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.generator.ChunkGenerator.ChunkData; import org.bukkit.inventory.Inventory; @@ -114,6 +116,7 @@ import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CountDownLatch; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.LogManager; @@ -225,8 +228,23 @@ public class ServerMock extends Server.Spigot implements Server { AsyncCatcher.catchOp("player add"); playerList.addPlayer(player); - PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, - String.format(JOIN_MESSAGE, player.getDisplayName())); + + CountDownLatch conditionLatch = new CountDownLatch(1); + + AsyncPlayerPreLoginEvent preLoginEvent = new AsyncPlayerPreLoginEvent(player.getName(), player.getAddress().getAddress(), player.getUniqueId()); + getPluginManager().callEventAsynchronously(preLoginEvent, (e) -> conditionLatch.countDown()); + + try + { + conditionLatch.await(); + } + catch (InterruptedException e) + { + getLogger().severe("Interrupted while waiting for AsyncPlayerPreLoginEvent! " + (StringUtils.isEmpty(e.getMessage()) ? "" : e.getMessage())); + Thread.currentThread().interrupt(); + } + + PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, String.format(JOIN_MESSAGE, player.getDisplayName())); Bukkit.getPluginManager().callEvent(playerJoinEvent); player.setLastPlayed(getCurrentServerTime()); diff --git a/src/main/java/be/seeseemelk/mockbukkit/plugin/PluginManagerMock.java b/src/main/java/be/seeseemelk/mockbukkit/plugin/PluginManagerMock.java index 9600e0ce..902e114f 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/plugin/PluginManagerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/plugin/PluginManagerMock.java @@ -55,6 +55,7 @@ import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Consumer; import java.util.function.Predicate; import java.util.logging.Level; import java.util.stream.Collectors; @@ -441,6 +442,18 @@ public class PluginManagerMock implements PluginManager * @param event The asynchronous {@link Event} to call. */ public void callEventAsynchronously(@NotNull Event event) + { + callEventAsynchronously(event, null); + } + + /** + * This method invokes {@link #callEvent(Event)} from a different {@link Thread} + * using the {@link BukkitSchedulerMock}. + * + * @param event The asynchronous {@link Event} to call. + * @param func A function to invoke after the event has been called. + */ + public <T extends Event> void callEventAsynchronously(@NotNull T event, Consumer<T> func) { if (!event.isAsynchronous()) { @@ -448,7 +461,7 @@ public class PluginManagerMock implements PluginManager } // Our Scheduler will call the Event on a dedicated Event Thread Executor - server.getScheduler().executeAsyncEvent(event); + server.getScheduler().executeAsyncEvent(event, func); } private void callRegisteredListener(@NotNull RegisteredListener registration, @NotNull Event event) diff --git a/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java b/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java index 3073db21..b0adea7e 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java @@ -103,8 +103,19 @@ public class BukkitSchedulerMock implements BukkitScheduler public @NotNull Future<?> executeAsyncEvent(Event event) { - Validate.notNull(event, "Cannot schedule an Event that is null!"); - Future<?> future = asyncEventExecutor.submit(() -> MockBukkit.getMock().getPluginManager().callEvent(event)); + return executeAsyncEvent(event, null); + } + + public <T extends Event> @NotNull Future<?> executeAsyncEvent(T event, Consumer<T> func) + { + Validate.notNull(event, "Cannot call a null event!"); + Future<?> future = asyncEventExecutor.submit(() -> { + MockBukkit.getMock().getPluginManager().callEvent(event); + if (func != null) + { + func.accept(event); + } + }); queuedAsyncEvents.add(future); return future; } @@ -218,8 +229,8 @@ public class BukkitSchedulerMock implements BukkitScheduler if (System.currentTimeMillis() > (systemTime + executorTimeout)) { // If a plugin has left a runnable going and not cancelled it we could call this bad practice. - // We should force interrupt all those runnables forcing them to throw Interrupted Exceptions- - // if they handle that + // We should force interrupt all these runnables, forcing them to throw Interrupted Exceptions + // if they handle that. for (ScheduledTask task : scheduledTasks.getCurrentTaskList()) { if (task.isRunning()) diff --git a/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java b/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java index 8c2b4e7b..9749bfab 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java @@ -22,6 +22,8 @@ import org.bukkit.block.data.BlockData; import org.bukkit.command.Command; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.potion.PotionEffectType; @@ -129,6 +131,20 @@ class ServerMockTest assertNotEquals(player1, player2); } + @Test + void addPlayer_Calls_AsyncPreLoginEvent() + { + PlayerMock player = server.addPlayer(); + server.getPluginManager().assertEventFired(AsyncPlayerPreLoginEvent.class); + } + + @Test + void addPlayer_Calls_PlayerJoinEvent() + { + PlayerMock player = server.addPlayer(); + server.getPluginManager().assertEventFired(PlayerJoinEvent.class); + } + @Test void setPlayers_Two_TwoUniquePlayers() {
['src/test/java/be/seeseemelk/mockbukkit/ServerMockTest.java', 'src/main/java/be/seeseemelk/mockbukkit/plugin/PluginManagerMock.java', 'src/main/java/be/seeseemelk/mockbukkit/ServerMock.java', 'src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java']
{'.java': 4}
4
4
0
0
4
622,371
144,960
27,080
135
2,362
532
56
3
660
52
150
14
0
1
1970-01-01T00:27:33
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
8,891
mockbukkit/mockbukkit/86/20
mockbukkit
mockbukkit
https://github.com/MockBukkit/MockBukkit/issues/20
https://github.com/MockBukkit/MockBukkit/pull/86
https://github.com/MockBukkit/MockBukkit/pull/86
1
fixes
Using runTaskTimer with a 0 delay doesnt execute the first cycle.
`BukkitTask task = Bukkit.getScheduler().runTaskTimer(plugin, this::doTimer, 0, 20L); ` This creates a repeating task with a scheduledtick at 0 but the current tick is 0 yet it doesnt actually trigger the task instantly. Hence it appears the task wont trigger. ``` AtomicInteger count = new AtomicInteger(0); Runnable callback = () -> count.incrementAndGet(); BukkitTask task = scheduler.runTaskTimer(null, callback, 0, 2L); assertNotNull(task); assertEquals(0, count.get()); scheduler.performTicks(1L); assertEquals(1, count.get());``` will cause a test failure. Actually the first assert should fail but it doesnt ...the second fails.
5c06c1218145f938ffd578a05412fe9f8d4faa99
7b52212469a84c138115b4e97d8dafbd60d5af64
https://github.com/mockbukkit/mockbukkit/compare/5c06c1218145f938ffd578a05412fe9f8d4faa99...7b52212469a84c138115b4e97d8dafbd60d5af64
diff --git a/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java b/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java index 51dbf710..e3948aee 100644 --- a/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java +++ b/src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java @@ -143,6 +143,7 @@ public class BukkitSchedulerMock implements BukkitScheduler @Override public BukkitTask runTaskLater(Plugin plugin, Runnable task, long delay) { + delay = Math.max(delay, 1); ScheduledTask scheduledTask = new ScheduledTask(id++, plugin, true, currentTick + delay, task); tasks.add(scheduledTask); return scheduledTask; @@ -151,6 +152,7 @@ public class BukkitSchedulerMock implements BukkitScheduler @Override public BukkitTask runTaskTimer(Plugin plugin, Runnable task, long delay, long period) { + delay = Math.max(delay, 1); RepeatingTask repeatingTask = new RepeatingTask(id++, plugin, true, currentTick + delay, period, task); tasks.add(repeatingTask); return repeatingTask; diff --git a/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java b/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java index 4077ffca..1ad845e2 100644 --- a/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java +++ b/src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java @@ -100,6 +100,17 @@ public class BukkitSchedulerMockTest assertEquals(2, count.get()); } + @Test + public void runTaskTimer_ZeroDelay_DoesntExecuteTaskImmediately() + { + AtomicInteger count = new AtomicInteger(0); + Runnable callback = () -> count.incrementAndGet(); + scheduler.runTaskTimer(null, callback, 0, 2L); + assertEquals(0, count.get()); + scheduler.performTicks(1L); + assertEquals(1, count.get()); + } + @Test public void runTaskAsynchronously_TaskExecutedOnSeperateThread() throws InterruptedException, BrokenBarrierException, TimeoutException {
['src/main/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMock.java', 'src/test/java/be/seeseemelk/mockbukkit/scheduler/BukkitSchedulerMockTest.java']
{'.java': 2}
2
2
0
0
2
333,296
75,986
14,390
71
61
20
2
1
665
81
161
14
0
1
1970-01-01T00:26:33
457
Java
{'Java': 1921509, 'Kotlin': 4941}
MIT License
1,006
thelastpickle/cassandra-reaper/1214/1211
thelastpickle
cassandra-reaper
https://github.com/thelastpickle/cassandra-reaper/issues/1211
https://github.com/thelastpickle/cassandra-reaper/pull/1214
https://github.com/thelastpickle/cassandra-reaper/pull/1214
1
fixes
millisSinceLastRepairForSchedule metric isn't cleaned up in distributed mode
Unlike schedules, which are persisted into the database, metrics only exist in memory for all Reaper instances. When a schedule gets deleted, a cleanup is done to remove the corresponding `millisSinceLastRepairForSchedule` metric, but in distributed mode, only a single instance will get the deletion call. This means that we need to clean up this metric on a regular basis by checking if there's a corresponding schedule for all registered metrics. ┆Issue is synchronized with this [Jira Task](https://k8ssandra.atlassian.net/browse/K8SSAND-1629) by [Unito](https://www.unito.io) ┆friendlyId: K8SSAND-1629 ┆priority: Medium
870cc88b40335fe59397e2681aa275bd82577106
dcddc0812a2bdc8789cf92e66d549e81d5ec4a1e
https://github.com/thelastpickle/cassandra-reaper/compare/870cc88b40335fe59397e2681aa275bd82577106...dcddc0812a2bdc8789cf92e66d549e81d5ec4a1e
diff --git a/src/server/src/main/java/io/cassandrareaper/service/RepairScheduleService.java b/src/server/src/main/java/io/cassandrareaper/service/RepairScheduleService.java index 2ee21e94..f5a9bdea 100644 --- a/src/server/src/main/java/io/cassandrareaper/service/RepairScheduleService.java +++ b/src/server/src/main/java/io/cassandrareaper/service/RepairScheduleService.java @@ -39,6 +39,7 @@ import static io.cassandrareaper.metrics.MetricNameUtils.cleanName; public final class RepairScheduleService { + public static final String MILLIS_SINCE_LAST_REPAIR_METRIC_NAME = "millisSinceLastRepairForSchedule"; private final AppContext context; private final RepairUnitService repairUnitService; @@ -143,7 +144,7 @@ public final class RepairScheduleService { private void registerScheduleMetrics(UUID repairScheduleId) { RepairSchedule schedule = context.storage.getRepairSchedule(repairScheduleId).get(); RepairUnit repairUnit = context.storage.getRepairUnit(schedule.getRepairUnitId()); - String metricName = metricName("millisSinceLastRepairForSchedule", + String metricName = metricName(MILLIS_SINCE_LAST_REPAIR_METRIC_NAME, repairUnit.getClusterName(), repairUnit.getKeyspaceName(), schedule.getId()); @@ -157,7 +158,7 @@ public final class RepairScheduleService { Optional<RepairSchedule> schedule = context.storage.getRepairSchedule(repairScheduleId); schedule.ifPresent(sched -> { RepairUnit repairUnit = context.storage.getRepairUnit(sched.getRepairUnitId()); - String metricName = metricName("millisSinceLastRepairForSchedule", + String metricName = metricName(MILLIS_SINCE_LAST_REPAIR_METRIC_NAME, repairUnit.getClusterName(), repairUnit.getKeyspaceName(), sched.getId()); diff --git a/src/server/src/main/java/io/cassandrareaper/service/SchedulingManager.java b/src/server/src/main/java/io/cassandrareaper/service/SchedulingManager.java index 5b995133..fdddb438 100644 --- a/src/server/src/main/java/io/cassandrareaper/service/SchedulingManager.java +++ b/src/server/src/main/java/io/cassandrareaper/service/SchedulingManager.java @@ -106,8 +106,11 @@ public final class SchedulingManager extends TimerTask { LOG.debug("Checking for repair schedules..."); UUID lastId = null; try { + Collection<RepairSchedule> schedules = context.storage.getAllRepairSchedules(); + // Cleanup metric registry from deleted schedules + cleanupMetricsRegistry(schedules); + // Start repairs for schedules that require it if (currentReaperIsSchedulingLeader()) { - Collection<RepairSchedule> schedules = context.storage.getAllRepairSchedules(); boolean anyRunStarted = false; for (RepairSchedule schedule : schedules) { lastId = schedule.getId(); @@ -142,6 +145,19 @@ public final class SchedulingManager extends TimerTask { } } + // Cleanup metric registry from deleted schedules + // Such metrics are named after the following pattern: + // "millisSinceLastRepairForSchedule.<cluster>.<keyspace>.<schedule id>" + @VisibleForTesting + void cleanupMetricsRegistry(Collection<RepairSchedule> schedules) { + // Cycle through the metrics registry and delete any metrics that are not in the current schedules + context.metricRegistry.getMetrics().keySet().stream() + .filter(key -> key.startsWith(RepairScheduleService.MILLIS_SINCE_LAST_REPAIR_METRIC_NAME)) + .filter(key -> !schedules.stream().anyMatch( + schedule -> schedule.getId().toString().equals(key.split("\\\\.")[3]))) + .forEach(context.metricRegistry::remove); + } + /** * Manage, i.e. check whether a new repair run should be started with this schedule. * diff --git a/src/server/src/test/java/io/cassandrareaper/service/SchedulingManagerTest.java b/src/server/src/test/java/io/cassandrareaper/service/SchedulingManagerTest.java index a29acca3..be17df9f 100644 --- a/src/server/src/test/java/io/cassandrareaper/service/SchedulingManagerTest.java +++ b/src/server/src/test/java/io/cassandrareaper/service/SchedulingManagerTest.java @@ -28,13 +28,18 @@ import io.cassandrareaper.core.RepairUnit; import io.cassandrareaper.storage.CassandraStorage; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; import java.util.stream.IntStream; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; import com.datastax.driver.core.utils.UUIDs; import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import org.apache.cassandra.repair.RepairParallelism; import org.joda.time.DateTime; @@ -362,4 +367,38 @@ public final class SchedulingManagerTest { // We're below the threshold and the repair shouldn't start Mockito.verify(context.repairManager, Mockito.times(0)).startRepairRun(any()); } + + @Test + public void cleanupMetricsRegistryTest() { + AppContext context = new AppContext(); + context.storage = mock(CassandraStorage.class); + context.config = new ReaperApplicationConfiguration(); + context.config.setPercentRepairedCheckIntervalMinutes(10); + context.metricRegistry = mock(MetricRegistry.class); + List<UUID> scheduleIds = Lists.newArrayList(); + IntStream.range(0, 4).forEach(i -> scheduleIds.add(UUIDs.timeBased())); + HashMap<String, Metric> metrics = Maps.newHashMap(); + scheduleIds.stream().forEach(scheduleId -> + metrics.put(MetricRegistry.name(RepairScheduleService.MILLIS_SINCE_LAST_REPAIR_METRIC_NAME, + "test", "test", scheduleId.toString()), null)); + + List<RepairSchedule> repairSchedules = scheduleIds.stream().map(scheduleId -> + RepairSchedule.builder(scheduleId) + .daysBetween(1) + .nextActivation(DateTime.now().plusDays(1)) + .repairParallelism(RepairParallelism.PARALLEL) + .intensity(1) + .segmentCountPerNode(10) + .lastRun(UUIDs.timeBased()) + .percentUnrepairedThreshold(5) + .state(RepairSchedule.State.ACTIVE) + .build(scheduleId)).collect(Collectors.toList()); + + // Removing a schedule should trigger the removal of one metric + repairSchedules.remove(0); + when(context.metricRegistry.getMetrics()).thenReturn(metrics); + SchedulingManager schedulingManager = SchedulingManager.create(context, () -> null); + schedulingManager.cleanupMetricsRegistry(repairSchedules); + Mockito.verify(context.metricRegistry, Mockito.times(1)).remove(any()); + } }
['src/server/src/main/java/io/cassandrareaper/service/SchedulingManager.java', 'src/server/src/main/java/io/cassandrareaper/service/RepairScheduleService.java', 'src/server/src/test/java/io/cassandrareaper/service/SchedulingManagerTest.java']
{'.java': 3}
3
3
0
0
3
893,991
190,879
25,370
131
1,478
312
23
2
628
83
148
9
2
0
1970-01-01T00:27:37
455
Java
{'Java': 1768221, 'JavaScript': 400173, 'Less': 276331, 'Shell': 53504, 'Python': 44156, 'Gherkin': 42529, 'Dockerfile': 9771, 'SCSS': 3775, 'Makefile': 3683, 'EJS': 1984, 'HTML': 1182}
Apache License 2.0
1,007
thelastpickle/cassandra-reaper/1130/1128
thelastpickle
cassandra-reaper
https://github.com/thelastpickle/cassandra-reaper/issues/1128
https://github.com/thelastpickle/cassandra-reaper/pull/1130
https://github.com/thelastpickle/cassandra-reaper/pull/1130
1
fixes
table repair fails when limited on one DC
I am using reaper 2.3.1, OSS 3.11.10. If I schedule a repair on a table which is replicated to 2 DCs, rf 3, and limit it to be run in one DC only, the repair fails with: "`Replica set changed for segment 3d13c51f-283b-11ec-af04-a9ec581eeeb8 on range io.cassandrareaper.core.Segment@28d0f9f0`" I've tried a different table, same error. No issues running repairs without limiting to a DC. Thanks!
351939deb131ff87f7f6995dcfb87c4cf42c3e28
4a4a978b3aa9d1da1f6cc2bafcadbea96bf0283d
https://github.com/thelastpickle/cassandra-reaper/compare/351939deb131ff87f7f6995dcfb87c4cf42c3e28...4a4a978b3aa9d1da1f6cc2bafcadbea96bf0283d
diff --git a/src/server/src/main/java/io/cassandrareaper/service/RepairRunService.java b/src/server/src/main/java/io/cassandrareaper/service/RepairRunService.java index 41314eb2..021c9c73 100644 --- a/src/server/src/main/java/io/cassandrareaper/service/RepairRunService.java +++ b/src/server/src/main/java/io/cassandrareaper/service/RepairRunService.java @@ -204,7 +204,8 @@ public final class RepairRunService { Segment.builder() .withBaseRange(segment.getBaseRange()) .withTokenRanges(segment.getTokenRanges()) - .withReplicas(getDCsByNodeForRepairSegment(targetCluster, segment, repairUnit.getKeyspaceName())) + .withReplicas(getDCsByNodeForRepairSegment( + targetCluster, segment, repairUnit.getKeyspaceName(), repairUnit)) .build()); } @@ -214,7 +215,8 @@ public final class RepairRunService { private Map<String, String> getDCsByNodeForRepairSegment( Cluster cluster, Segment segment, - String keyspace) throws ReaperException { + String keyspace, + RepairUnit repairUnit) throws ReaperException { final int maxAttempts = 2; for (int attempt = 0; attempt < maxAttempts; attempt++) { @@ -224,7 +226,13 @@ public final class RepairRunService { Collection<String> nodes = clusterFacade.tokenRangeToEndpoint(cluster, keyspace, segment); Map<String, String> dcByNode = Maps.newHashMap(); nodes.forEach(node -> dcByNode.put(node, EndpointSnitchInfoProxy.create(jmxConnection).getDataCenter(node))); - return dcByNode; + if (repairUnit.getDatacenters().isEmpty()) { + return dcByNode; + } else { + return dcByNode.entrySet().stream() + .filter(entry -> repairUnit.getDatacenters().contains(entry.getValue())) + .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); + } } catch (RuntimeException e) { if (attempt < maxAttempts - 1) { LOG.warn("Failed getting replicas for token range {}. Attempt {} of {}",
['src/server/src/main/java/io/cassandrareaper/service/RepairRunService.java']
{'.java': 1}
1
1
0
0
1
883,951
188,734
25,186
128
756
147
14
1
400
63
130
6
0
0
1970-01-01T00:27:14
455
Java
{'Java': 1768221, 'JavaScript': 400173, 'Less': 276331, 'Shell': 53504, 'Python': 44156, 'Gherkin': 42529, 'Dockerfile': 9771, 'SCSS': 3775, 'Makefile': 3683, 'EJS': 1984, 'HTML': 1182}
Apache License 2.0
368
adobe-consulting-services/acs-aem-commons/388/387
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/387
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/388
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/387#issuecomment-65863901
1
resolves
Adding an async index throws Exception as it tries to remove the unique property which does not exist.
Try adding an index which is async (but not unique => by definition). It throws following Exception: ``` java 05.12.2014 09:43:02.147 *INFO* [CM Event Dispatcher (Fire ConfigurationEvent: pid=com.adobe.acs.commons.oak.impl.EnsurePropertyIndex.9fe8dd22-995c-4688-a7ec-7a8b43fd9538)] com.adobe.acs.commons.oak.impl.EnsurePropertyIndex creating index givenName 05.12.2014 09:43:02.159 *ERROR* [CM Event Dispatcher (Fire ConfigurationEvent: pid=com.adobe.acs.commons.oak.impl.EnsurePropertyIndex.9fe8dd22-995c-4688-a7ec-7a8b43fd9538)] com.adobe.acs.commons.oak.impl.EnsurePropertyIndex Unable to create index javax.jcr.PathNotFoundException: unique not found on /oak:index/givenName at org.apache.jackrabbit.oak.jcr.session.NodeImpl$11.perform(NodeImpl.java:616) at org.apache.jackrabbit.oak.jcr.session.NodeImpl$11.perform(NodeImpl.java:611) at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.perform(SessionDelegate.java:293) at org.apache.jackrabbit.oak.jcr.session.ItemImpl.perform(ItemImpl.java:113) at org.apache.jackrabbit.oak.jcr.session.NodeImpl.getProperty(NodeImpl.java:611) at com.adobe.acs.commons.oak.impl.EnsurePropertyIndex.createOrUpdateIndex(EnsurePropertyIndex.java:113) at com.adobe.acs.commons.oak.impl.EnsurePropertyIndex.activate(EnsurePropertyIndex.java:167) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:231) at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:39) at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:624) at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:508) at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:149) at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:315) at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:127) at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:871) at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:838) at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:850) at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:419) at org.apache.felix.scr.impl.config.ConfigurableComponentHolder.configurationUpdated(ConfigurableComponentHolder.java:334) at org.apache.felix.scr.impl.config.ConfigurationSupport.configurationEvent(ConfigurationSupport.java:290) at org.apache.felix.cm.impl.ConfigurationManager$FireConfigurationEvent.sendEvent(ConfigurationManager.java:2032) at org.apache.felix.cm.impl.ConfigurationManager$FireConfigurationEvent.run(ConfigurationManager.java:2002) at org.apache.felix.cm.impl.UpdateThread.run(UpdateThread.java:103) at java.lang.Thread.run(Thread.java:745) ``` Tested with AEM 6.0.1 - OAK 1.0.8 FP
cf9156ac96f19cc4a4212a937cdd02732d4c63a4
308c478bbae2c4c7b3f77eb6d8bc226185ed3311
https://github.com/adobe-consulting-services/acs-aem-commons/compare/cf9156ac96f19cc4a4212a937cdd02732d4c63a4...308c478bbae2c4c7b3f77eb6d8bc226185ed3311
diff --git a/bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsurePropertyIndex.java b/bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsurePropertyIndex.java index ca604b18d..47d5d2ee2 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsurePropertyIndex.java +++ b/bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsurePropertyIndex.java @@ -110,7 +110,9 @@ public class EnsurePropertyIndex { if (def.unique) { indexNode.setProperty(PN_UNIQUE, true); } else if (indexNode.hasProperty(PN_ASYNC)) { - indexNode.getProperty(PN_UNIQUE).remove(); + if(indexNode.hasNode(PN_UNIQUE)){ + indexNode.getProperty(PN_UNIQUE).remove(); + } } if (def.declaringNodeTypes != null && def.declaringNodeTypes.length > 0) { Value[] values = new Value[def.declaringNodeTypes.length];
['bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsurePropertyIndex.java']
{'.java': 1}
1
1
0
0
1
1,011,365
205,858
28,478
225
166
34
4
1
3,351
118
808
38
0
1
1970-01-01T00:23:37
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
369
adobe-consulting-services/acs-aem-commons/954/946
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/946
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/954
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/946#issuecomment-291854495
2
fixes
3.7.0 breaks system notifications.
Hello, I upgraded ACS commons from 3.4.0 to latest 3.7.0 on an AEM 6.2 instance. Now the notification feature does not work and throws an exception. I downgraded to 3.6.2 and the feature works on that version. Are there plans to fix this in 3.7.x next release? ``` Error during include of component '/apps/acs-commons/components/utilities/system-notifications' Error Message: java.lang.ExceptionInInitializerError Processing Info: Page = /etc/acs-commons/notifications/test Resource Path = /etc/acs-commons/notifications/test/jcr:content Cell = system-notifications Cell Search Path = system-notifications Component Path = /apps/acs-commons/components/utilities/system-notifications Sling Request Progress: ``` [Full exception ](https://gist.github.com/cru-Luis-Rodriguez/e398029b0ba3ce7ccb9e6300595b2c82)
366c15948fcc97169b206dda5b11cd8e0d5d6a76
4deb1837d8c9fab57936a7ac0329d596ba5f5cb9
https://github.com/adobe-consulting-services/acs-aem-commons/compare/366c15948fcc97169b206dda5b11cd8e0d5d6a76...4deb1837d8c9fab57936a7ac0329d596ba5f5cb9
diff --git a/bundle/src/main/java/com/adobe/acs/commons/xss/XSSFunctions.java b/bundle/src/main/java/com/adobe/acs/commons/xss/XSSFunctions.java index dbc4802b3..a573af401 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/xss/XSSFunctions.java +++ b/bundle/src/main/java/com/adobe/acs/commons/xss/XSSFunctions.java @@ -20,7 +20,7 @@ package com.adobe.acs.commons.xss; import aQute.bnd.annotation.ProviderType; -import org.apache.sling.xss.XSSAPI; +import com.adobe.granite.xss.XSSAPI; import tldgen.Function; import java.util.regex.Pattern; diff --git a/bundle/src/main/java/com/adobe/acs/commons/xss/package-info.java b/bundle/src/main/java/com/adobe/acs/commons/xss/package-info.java index 7fd084c83..76348868f 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/xss/package-info.java +++ b/bundle/src/main/java/com/adobe/acs/commons/xss/package-info.java @@ -20,6 +20,6 @@ /** * XSS JSP Functions. */ -@aQute.bnd.annotation.Version("2.0.0") +@aQute.bnd.annotation.Version("3.0.0") @tldgen.TagLibrary(value = "http://www.adobe.com/consulting/acs-aem-commons/xss", descriptorFile = "xss.tld") package com.adobe.acs.commons.xss; \\ No newline at end of file diff --git a/bundle/src/test/java/com/adobe/acs/commons/xss/XSSFunctionsTest.java b/bundle/src/test/java/com/adobe/acs/commons/xss/XSSFunctionsTest.java index 1d6b01be1..d14d5f19f 100644 --- a/bundle/src/test/java/com/adobe/acs/commons/xss/XSSFunctionsTest.java +++ b/bundle/src/test/java/com/adobe/acs/commons/xss/XSSFunctionsTest.java @@ -19,8 +19,8 @@ */ package com.adobe.acs.commons.xss; +import com.adobe.granite.xss.XSSAPI; import org.apache.commons.lang.RandomStringUtils; -import org.apache.sling.xss.XSSAPI; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock;
['bundle/src/main/java/com/adobe/acs/commons/xss/package-info.java', 'bundle/src/test/java/com/adobe/acs/commons/xss/XSSFunctionsTest.java', 'bundle/src/main/java/com/adobe/acs/commons/xss/XSSFunctions.java']
{'.java': 3}
3
3
0
0
3
2,252,038
455,002
62,290
535
153
52
4
2
840
85
220
22
1
1
1970-01-01T00:24:51
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
375
adobe-consulting-services/acs-aem-commons/670/668
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/668
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/670
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/670
2
fixes
Versioned ClientLibs
Hi team, We are using the versioned clientlibs of ACS commons.Everything was working as expected with the hash numbers for example: "//localhost:4502/etc/ui/xyz/clientlibs/**one_two**.51fa0469aee8be9249c96195c63e7b73.js" "//localhost:4502/etc/ui/xyz/clientlibs/**one_two**.51fa0469aee8be9249c96195c67e7b73.css" However when we renamed to the following naming convention,the hashing is not done for CSS files. "//localhost:4502/etc/ui/xyz/clientlibs/**one.two**.51fa0469aee8be9249c96195c63e7b73.js" "//localhost:4502/etc/ui/xyz/clientlibs/**one.two**.css" Can you please let us know if there is way to get this # generated even with the dot notation for css since it is working for JS. Regards Kartheek
24167c1975f05f55343ab8de9eb142aed89253bf
115a9fb20b82dd39e11c8dd241276e64717c593d
https://github.com/adobe-consulting-services/acs-aem-commons/compare/24167c1975f05f55343ab8de9eb142aed89253bf...115a9fb20b82dd39e11c8dd241276e64717c593d
diff --git a/bundle/src/main/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactory.java b/bundle/src/main/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactory.java index f33aaa6f4..4b5f5944d 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactory.java +++ b/bundle/src/main/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactory.java @@ -56,7 +56,6 @@ import org.xml.sax.helpers.AttributesImpl; import com.adobe.acs.commons.rewriter.AbstractTransformer; import com.adobe.acs.commons.util.impl.AbstractGuavaCacheMBean; import com.adobe.acs.commons.util.impl.GenericCacheMBean; -import com.day.cq.commons.PathInfo; import com.day.cq.widget.HtmlLibrary; import com.day.cq.widget.HtmlLibraryManager; import com.day.cq.widget.LibraryType; @@ -94,6 +93,9 @@ public final class VersionedClientlibsTransformerFactory extends AbstractGuavaCa private static final String CSS_TYPE = "text/css"; private static final String JS_TYPE = "text/javascript"; + private static final String MIN_SELECTOR = "min"; + private static final String MIN_SELECTOR_SEGMENT = "." + MIN_SELECTOR; + private Cache<VersionedClientLibraryMd5CacheKey, String> md5Cache; @Reference @@ -180,25 +182,29 @@ public final class VersionedClientlibsTransformerFactory extends AbstractGuavaCa private String getVersionedPath(final String originalPath, final LibraryType libraryType) { try { - final PathInfo pathInfo = new PathInfo(originalPath); + boolean appendMinSelector = false; + String libraryPath = StringUtils.substringBeforeLast(originalPath, "."); + if (libraryPath.endsWith(MIN_SELECTOR_SEGMENT)) { + appendMinSelector = true; + libraryPath = StringUtils.substringBeforeLast(libraryPath, "."); + } - final HtmlLibrary htmlLibrary = htmlLibraryManager.getLibrary(libraryType, pathInfo.getResourcePath()); + final HtmlLibrary htmlLibrary = htmlLibraryManager.getLibrary(libraryType, libraryPath); if (htmlLibrary != null) { StringBuilder builder = new StringBuilder(); builder.append(htmlLibrary.getLibraryPath()); builder.append("."); - String selector = pathInfo.getSelectorString(); - if (selector != null) { - builder.append(selector).append("."); + if (appendMinSelector) { + builder.append(MIN_SELECTOR).append("."); } builder.append(getMd5(htmlLibrary)); builder.append(libraryType.extension); return builder.toString(); } else { - log.debug("Could not find HtmlLibrary at path: {}", pathInfo.getResourcePath()); + log.debug("Could not find HtmlLibrary at path: {}", libraryPath); return null; } } catch (Exception ex) { diff --git a/bundle/src/test/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactoryTest.java b/bundle/src/test/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactoryTest.java index 81d5471d5..56466d1db 100644 --- a/bundle/src/test/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactoryTest.java +++ b/bundle/src/test/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactoryTest.java @@ -106,7 +106,6 @@ public class VersionedClientlibsTransformerFactoryTest { assertEquals(PATH + ".css", attributesCaptor.getValue().getValue(0)); } - @Test public void testCSSClientLibrary() throws Exception { @@ -127,6 +126,28 @@ public class VersionedClientlibsTransformerFactoryTest { assertEquals(PATH + "."+ FAKE_STREAM_CHECKSUM +".css", attributesCaptor.getValue().getValue(0)); } + @Test + public void testCSSClientLibraryWithDot() throws Exception { + final String path = PATH + ".foo"; + + when(htmlLibraryManager.getLibrary(eq(LibraryType.CSS), eq(path))).thenReturn(htmlLibrary); + when(htmlLibrary.getLibraryPath()).thenReturn(path); + + final AttributesImpl in = new AttributesImpl(); + in.addAttribute("", "href", "", "CDATA", path + ".css"); + in.addAttribute("", "type", "", "CDATA", "text/css"); + in.addAttribute("", "rel", "", "CDATA", "stylesheet"); + + transformer.startElement(null, "link", null, in); + + ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class); + + verify(handler, only()).startElement(isNull(String.class), eq("link"), isNull(String.class), + attributesCaptor.capture()); + + assertEquals(path + "."+ FAKE_STREAM_CHECKSUM +".css", attributesCaptor.getValue().getValue(0)); + } + @Test public void testMinifiedCSSClientLibrary() throws Exception { @@ -166,6 +187,27 @@ public class VersionedClientlibsTransformerFactoryTest { assertEquals(PATH + "."+ FAKE_STREAM_CHECKSUM +".js", attributesCaptor.getValue().getValue(0)); } + @Test + public void testJavaScriptClientLibraryWithDot() throws Exception { + final String path = PATH + ".foo"; + + when(htmlLibraryManager.getLibrary(eq(LibraryType.JS), eq(path))).thenReturn(htmlLibrary); + when(htmlLibrary.getLibraryPath()).thenReturn(path); + + final AttributesImpl in = new AttributesImpl(); + in.addAttribute("", "src", "", "CDATA", path + ".js"); + in.addAttribute("", "type", "", "CDATA", "text/javascript"); + + transformer.startElement(null, "script", null, in); + + ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class); + + verify(handler, only()).startElement(isNull(String.class), eq("script"), isNull(String.class), + attributesCaptor.capture()); + + assertEquals(path + "."+ FAKE_STREAM_CHECKSUM +".js", attributesCaptor.getValue().getValue(0)); + } + @Test public void testMinifiedJavaScriptClientLibrary() throws Exception {
['bundle/src/test/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactoryTest.java', 'bundle/src/main/java/com/adobe/acs/commons/rewriter/impl/VersionedClientlibsTransformerFactory.java']
{'.java': 2}
2
2
0
0
2
1,647,258
333,119
45,895
388
1,243
219
20
1
710
71
214
19
0
0
1970-01-01T00:24:16
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
376
adobe-consulting-services/acs-aem-commons/573/462
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/462
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/573
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/573
1
resolve
Issue with email service
1. If we have more than one recipients. The second recipient is getting one attachment which is the mail template. Third recipient gets two attachments etc. This is the behaviour in outlook. 2. When we are sending mail to gmail or other. Second recipient getting two mails. Third receipt getting three mails etc.
480c0601957b8486f3fc5869e52588313633289e
2ecf5b642b2e865f645fa99d8a22350b95130135
https://github.com/adobe-consulting-services/acs-aem-commons/compare/480c0601957b8486f3fc5869e52588313633289e...2ecf5b642b2e865f645fa99d8a22350b95130135
diff --git a/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java b/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java index 0c7a5c4cb..5dfea54d2 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java +++ b/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java @@ -19,33 +19,34 @@ */ package com.adobe.acs.commons.email.impl; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.jcr.Session; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; - -import org.apache.commons.lang.StringUtils; +import com.adobe.acs.commons.email.EmailService; +import com.adobe.acs.commons.email.EmailServiceConstants; +import com.day.cq.commons.mail.MailTemplate; +import com.day.cq.mailer.MessageGateway; +import com.day.cq.mailer.MessageGatewayService; import org.apache.commons.lang.text.StrLookup; import org.apache.commons.mail.Email; +import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.apache.commons.mail.SimpleEmail; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; +import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.adobe.acs.commons.email.EmailService; -import com.adobe.acs.commons.email.EmailServiceConstants; -import com.day.cq.commons.mail.MailTemplate; -import com.day.cq.mailer.MessageGateway; -import com.day.cq.mailer.MessageGatewayService; +import javax.jcr.Session; +import javax.mail.MessagingException; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; /** * ACS AEM Commons - E-mail Service @@ -64,9 +65,12 @@ public final class EmailServiceImpl implements EmailService { private ResourceResolverFactory resourceResolverFactory; @Override - public List<String> sendEmail(final String templatePath, final Map<String, String> emailParams, - final String... recipients) { + public List<String> sendEmail(final String templatePath, + final Map<String, String> emailParams, + final String... recipients) { + List<String> failureList = new ArrayList<String>(); + if (recipients == null || recipients.length <= 0) { throw new IllegalArgumentException("Invalid Recipients"); } @@ -80,7 +84,7 @@ public final class EmailServiceImpl implements EmailService { } } InternetAddress[] iAddressRecipients = addresses.toArray(new InternetAddress[addresses.size()]); - List<InternetAddress> failureInternetAddresses = sendEmail(templatePath, emailParams, iAddressRecipients); + List<InternetAddress> failureInternetAddresses = sendEmail(templatePath, emailParams, iAddressRecipients); for (InternetAddress address : failureInternetAddresses) { failureList.add(address.toString()); @@ -92,7 +96,7 @@ public final class EmailServiceImpl implements EmailService { @Override public List<InternetAddress> sendEmail(final String templatePath, final Map<String, String> emailParams, - final InternetAddress... recipients) { + final InternetAddress... recipients) { List<InternetAddress> failureList = new ArrayList<InternetAddress>(); @@ -100,65 +104,69 @@ public final class EmailServiceImpl implements EmailService { throw new IllegalArgumentException("Invalid Recipients"); } - if (StringUtils.isBlank(templatePath)) { - throw new IllegalArgumentException("Template path is null or empty"); - } - Email email = getEmail(templatePath, emailParams); + final MailTemplate mailTemplate = this.getMailTemplate(templatePath); + final Class<? extends Email> mailType = this.getMailType(templatePath); + final MessageGateway<Email> messageGateway = messageGatewayService.getGateway(mailType); - if (email == null) { - throw new IllegalArgumentException("Error while creating template"); - } - - MessageGateway<Email> messageGateway = messageGatewayService.getGateway(email.getClass()); - - for (InternetAddress address : recipients) { + for (final InternetAddress address : recipients) { try { + // Get a new email per recipient to avoid duplicate attachments + final Email email = getEmail(mailTemplate, mailType, emailParams); email.setTo(Collections.singleton(address)); messageGateway.send(email); } catch (Exception e) { failureList.add(address); - log.error("Exception sending email to " + address, e); + log.error("Error sending email to [ " + address + " ]", e); } - } + } return failureList; } - private Email getEmail(String templatePath, Map<String, String> emailParams) { - ResourceResolver resourceResolver = null; - try { - resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); + private Email getEmail(final MailTemplate mailTemplate, + final Class<? extends Email> mailType, + final Map<String, String> params) throws EmailException, MessagingException, IOException { - final MailTemplate mailTemplate = MailTemplate.create(templatePath, resourceResolver.adaptTo(Session.class)); + final Email email = mailTemplate.getEmail(StrLookup.mapLookup(params), mailType); - if (mailTemplate == null) { - log.warn("Email template at {} could not be created.", templatePath); - return null; - } + if (params.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS) + && params.containsKey(EmailServiceConstants.SENDER_NAME)) { - Class<? extends Email> emailClass = templatePath.endsWith(".html") ? HtmlEmail.class : SimpleEmail.class; + email.setFrom( + params.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS), + params.get(EmailServiceConstants.SENDER_NAME)); - final Email email = mailTemplate.getEmail(StrLookup.mapLookup(emailParams), emailClass); + } else if (params.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS)) { + email.setFrom(params.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS)); + } - if (emailParams.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS) - && emailParams.containsKey(EmailServiceConstants.SENDER_NAME)) { - email.setFrom(emailParams.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS), - emailParams.get(EmailServiceConstants.SENDER_NAME)); - } else if (emailParams.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS)) { - email.setFrom(emailParams.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS)); - } + return email; + } - return email; + private Class<? extends Email> getMailType(String templatePath) { + return templatePath.endsWith(".html") ? HtmlEmail.class : SimpleEmail.class; + } - } catch (Exception e) { - log.error("Unable to construct email from template " + templatePath, e); + private MailTemplate getMailTemplate(String templatePath) throws IllegalArgumentException { + MailTemplate mailTemplate = null; + ResourceResolver resourceResolver = null; + try { + resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); + mailTemplate = MailTemplate.create(templatePath, resourceResolver.adaptTo(Session.class)); + + if (mailTemplate == null) { + throw new IllegalArgumentException("Mail template path [ " + + templatePath + " ] could not resolve to a valid template"); + } + } catch (LoginException e) { + log.error("Unable to obtain an administrative resource resolver to get the Mail Template at [ " + + templatePath + " ]", e); } finally { if (resourceResolver != null) { resourceResolver.close(); } } - return null; + return mailTemplate; } - } diff --git a/bundle/src/test/java/com/adobe/acs/commons/email/EmailServiceImplTest.java b/bundle/src/test/java/com/adobe/acs/commons/email/EmailServiceImplTest.java index 2ce06ba75..904c390c7 100644 --- a/bundle/src/test/java/com/adobe/acs/commons/email/EmailServiceImplTest.java +++ b/bundle/src/test/java/com/adobe/acs/commons/email/EmailServiceImplTest.java @@ -19,19 +19,10 @@ */ package com.adobe.acs.commons.email; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.FileInputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.jcr.Session; - +import com.adobe.acs.commons.email.impl.EmailServiceImpl; +import com.day.cq.commons.mail.MailTemplate; +import com.day.cq.mailer.MessageGateway; +import com.day.cq.mailer.MessageGatewayService; import org.apache.commons.mail.SimpleEmail; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; @@ -50,10 +41,17 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.adobe.acs.commons.email.impl.EmailServiceImpl; -import com.day.cq.commons.mail.MailTemplate; -import com.day.cq.mailer.MessageGateway; -import com.day.cq.mailer.MessageGatewayService; +import javax.jcr.Session; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(MailTemplate.class) @@ -185,7 +183,7 @@ public class EmailServiceImplTest { final Map<String, String> params = new HashMap<String, String>(); final String recipient = "upasanac@acs.com"; thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Template path is null or empty"); + thrown.expectMessage("Mail template path [ null ] could not resolve to a valid template"); emailService.sendEmail(templatePath, params, recipient); } @@ -196,7 +194,7 @@ public class EmailServiceImplTest { final Map<String, String> params = new HashMap<String, String>(); final String recipient = "upasanac@acs.com"; thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Error while creating template"); + thrown.expectMessage("Mail template path [ /invalidTemplatePath.txt ] could not resolve to a valid template"); emailService.sendEmail(templatePath, params, recipient); }
['bundle/src/test/java/com/adobe/acs/commons/email/EmailServiceImplTest.java', 'bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java']
{'.java': 2}
2
2
0
0
2
1,384,620
279,519
38,695
307
6,499
1,258
118
1
313
53
62
3
0
0
1970-01-01T00:24:06
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
378
adobe-consulting-services/acs-aem-commons/410/409
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/409
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/410
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/410
2
fixes
TraversingCursor when creating ACL packages
Hi, we're running into TraversingCursor warnings when building an ACL package: ``` 31.01.2015 18:48:13.956 *WARN* [0:0:0:0:0:0:0:1 [1422724031258] POST /etc/acs-commons/packagers/test/_jcr_content.package.json HTTP/1.1] org.apache.jackrabbit.oak.spi.query.Cursors$TraversingCursor Traversed 3455000 nodes with filter Filter(query=SELECT * FROM [rep:ACL], path=*); consider creating an index or changing the query ``` Guess that comes from findResources(QUERY, QUERY_LANG) in https://github.com/Adobe-Consulting-Services/acs-aem-commons/blob/master/bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java#L224 What is the recommended solution? Create an index and fingers crossed that the query finishes faster? :) What is the reason for query on `path=*` ?
98bb4a7865de2bf7d864cb7d92ffaef75e219350
3002545d4dfa8475b1fc30f75abf74e2f8200a53
https://github.com/adobe-consulting-services/acs-aem-commons/compare/98bb4a7865de2bf7d864cb7d92ffaef75e219350...3002545d4dfa8475b1fc30f75abf74e2f8200a53
diff --git a/bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java b/bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java index ebb2e8f77..606cfd353 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java +++ b/bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java @@ -21,6 +21,7 @@ package com.adobe.acs.commons.packaging.impl; import com.adobe.acs.commons.packaging.PackageHelper; +import com.adobe.acs.commons.util.AemCapabilityHelper; import com.day.cq.wcm.api.Page; import com.day.cq.wcm.api.PageManager; import com.day.jcr.vault.fs.api.PathFilterSet; @@ -105,16 +106,26 @@ public class ACLPackagerServletImpl extends SlingAllMethodsServlet { private static final boolean DEFAULT_INCLUDE_CONFIGURATION = false; - private static final String QUERY = "SELECT * FROM [rep:ACL]"; - private static final String QUERY_LANG = Query.JCR_SQL2; + private static final String CQ5_QUERY = "SELECT * FROM [rep:ACL]"; + + private static final String[] CQ5_QUERIES = new String[] {CQ5_QUERY}; + + // rep:ACE covers rep:GrantACE and rep:DenyACE + private static final String AEM6_QUERY_ACE = "SELECT * FROM [rep:ACE] where [rep:principalName] is not null"; + + private static final String[] AEM6_QUERIES = new String[] {AEM6_QUERY_ACE}; + private static final String ACL_PACKAGE_THUMBNAIL_RESOURCE_PATH = "/apps/acs-commons/components/utilities/packager/acl-packager/definition/package-thumbnail.png"; @Reference private PackageHelper packageHelper; + @Reference + private AemCapabilityHelper aemCapabilityHelper; + @Override public final void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException { @@ -217,36 +228,60 @@ public class ACLPackagerServletImpl extends SlingAllMethodsServlet { private List<PathFilterSet> findResources(final ResourceResolver resourceResolver, final List<String> principalNames, final List<Pattern> includePatterns) { + boolean isOak = true; + try { + isOak = aemCapabilityHelper.isOak(); + } catch (RepositoryException e) { + isOak = true; + } final Set<Resource> resources = new TreeSet<Resource>(resourceComparator); final List<PathFilterSet> pathFilterSets = new ArrayList<PathFilterSet>(); - final Iterator<Resource> repPolicies = resourceResolver.findResources(QUERY, QUERY_LANG); + String[] queries = CQ5_QUERIES; + if (isOak) { + queries = AEM6_QUERIES; + } - while (repPolicies.hasNext()) { - final Resource repPolicy = repPolicies.next(); + for (final String query : queries) { + final Iterator<Resource> hits = resourceResolver.findResources(query, QUERY_LANG); + + while (hits.hasNext()) { + final Resource hit = hits.next(); + Resource repPolicy = null; + + if (isOak) { + // If Oak, get the parent node since the query is for the Grant/Deny nodes + if (hit.getParent() != null) { + repPolicy = hit.getParent(); + } + } else { + // If not Oak, then the rep:ACL is the hit + repPolicy = hit; + } - if (this.isIncluded(repPolicy, includePatterns)) { - log.debug("Included by pattern [ {} ]", repPolicy.getPath()); - } else { - continue; - } + if (this.isIncluded(repPolicy, includePatterns)) { + log.debug("Included by pattern [ {} ]", repPolicy.getPath()); + } else { + continue; + } - final Iterator<Resource> aces = repPolicy.listChildren(); + final Iterator<Resource> aces = repPolicy.listChildren(); - while (aces.hasNext()) { - final Resource ace = aces.next(); - final ValueMap props = ace.adaptTo(ValueMap.class); - final String repPrincipalName = props.get("rep:principalName", String.class); + while (aces.hasNext()) { + final Resource ace = aces.next(); + final ValueMap props = ace.adaptTo(ValueMap.class); + final String repPrincipalName = props.get("rep:principalName", String.class); - if (principalNames == null - || principalNames.isEmpty() - || principalNames.contains(repPrincipalName)) { + if (principalNames == null + || principalNames.isEmpty() + || principalNames.contains(repPrincipalName)) { - resources.add(repPolicy); + resources.add(repPolicy); - log.debug("Included by principal [ {} ]", repPolicy.getPath()); - break; + log.debug("Included by principal [ {} ]", repPolicy.getPath()); + break; + } } } } @@ -317,14 +352,25 @@ public class ACLPackagerServletImpl extends SlingAllMethodsServlet { * @return true if the resource's path matches any of the include patterns */ private boolean isIncluded(final Resource resource, final List<Pattern> includePatterns) { - if (includePatterns == null || includePatterns.isEmpty()) { - return true; + if (resource == null) { + // Resource is null; so dont accept this + return false; + } else if (!resource.isResourceType("rep:ACL")) { + // ONLY accept the resource is a rep:ACL node + return false; } - for (final Pattern pattern : includePatterns) { - final Matcher matcher = pattern.matcher(resource.getPath()); - if (matcher.matches()) { - return true; + if (includePatterns == null || includePatterns.isEmpty()) { + // If patterns are empty then accept everything! + return true; + } else { + // Else check the patterns + for (final Pattern pattern : includePatterns) { + final Matcher matcher = pattern.matcher(resource.getPath()); + if (matcher.matches()) { + // Accept the resource on the first match + return true; + } } } diff --git a/bundle/src/test/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImplTest.java b/bundle/src/test/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImplTest.java index 5667bb5f7..b525811ed 100644 --- a/bundle/src/test/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImplTest.java +++ b/bundle/src/test/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImplTest.java @@ -21,6 +21,7 @@ package com.adobe.acs.commons.packaging.impl; import com.adobe.acs.commons.packaging.PackageHelper; +import com.adobe.acs.commons.util.AemCapabilityHelper; import com.day.jcr.vault.packaging.JcrPackage; import com.day.jcr.vault.packaging.JcrPackageManager; import com.day.jcr.vault.packaging.Version; @@ -63,22 +64,39 @@ public class ACLPackagerServletImplTest { static final String CONTENT_RESOURCE_PATH = "/etc/acs-commons/packages/acl-packager-test/jcr:content"; static final String CONTENT_RESOURCE_TYPE = "acs-commons/components/utilities/packager/acl-packager"; - SuccessMockResourceResolver resourceResolver = new SuccessMockResourceResolver(); + Crx2SuccessMockResourceResolver crx2ResourceResolver = new Crx2SuccessMockResourceResolver(); + OakSuccessMockResourceResolver oakResourceResolver = new OakSuccessMockResourceResolver(); + ErrorMockResourceResolver errorResourceResolver = new ErrorMockResourceResolver(); @Spy - MockResource contentResource = new MockResource(resourceResolver, CONTENT_RESOURCE_PATH, CONTENT_RESOURCE_TYPE); + MockResource crx2ContentResource = new MockResource(crx2ResourceResolver, CONTENT_RESOURCE_PATH, CONTENT_RESOURCE_TYPE); + + @Spy + MockResource crx2ConfigurationResource = new MockResource(crx2ResourceResolver, + CONTENT_RESOURCE_PATH + "/configuration", ""); + + + @Spy + MockResource oakContentResource = new MockResource(oakResourceResolver, CONTENT_RESOURCE_PATH, + CONTENT_RESOURCE_TYPE); @Spy - MockResource configurationResource = new MockResource(resourceResolver, + MockResource oakConfigurationResource = new MockResource(oakResourceResolver, CONTENT_RESOURCE_PATH + "/configuration", ""); + @Mock PackageHelper packageHelper; - @Mock JcrPackage jcrPackage; + @Mock + JcrPackage jcrPackage; + + @Mock + AemCapabilityHelper aemCapabilityHelper; - @Mock Session session; + @Mock + Session session; @InjectMocks ACLPackagerServletImpl aclPackagerServlet; @@ -95,10 +113,14 @@ public class ACLPackagerServletImplTest { ValueMap properties = new ValueMapDecorator(map); - doReturn(properties).when(configurationResource).adaptTo(ValueMap.class); + doReturn(properties).when(crx2ConfigurationResource).adaptTo(ValueMap.class); + doReturn(properties).when(oakConfigurationResource).adaptTo(ValueMap.class); - resourceResolver.addResource(contentResource); - resourceResolver.addResource(configurationResource); + crx2ResourceResolver.addResource(crx2ContentResource); + crx2ResourceResolver.addResource(crx2ConfigurationResource); + + oakResourceResolver.addResource(oakContentResource); + oakResourceResolver.addResource(oakConfigurationResource); /* PackageHelper Mocks */ when(packageHelper.getNextVersion(any(JcrPackageManager.class), any(String.class), any(String.class), @@ -111,6 +133,7 @@ public class ACLPackagerServletImplTest { when(packageHelper.getSuccessJSON(any(JcrPackage.class))).thenReturn("{\\"status\\": \\"success\\"}"); when(packageHelper.getErrorJSON(any(String.class))).thenReturn("{\\"status\\": \\"error\\"}"); when(packageHelper.getPathFilterSetPreviewJSON(any(Collection.class))).thenReturn("{\\"status\\": \\"preview\\"}"); + } @After @@ -119,7 +142,9 @@ public class ACLPackagerServletImplTest { } @Test - public void testDoPost_success() throws Exception { + public void testDoPost_crx2_success() throws Exception { + when(aemCapabilityHelper.isOak()).thenReturn(false); + final String resourcePath = "/etc/acs-commons/packages/acl-packager-test/jcr:content"; final String selectors = "package"; final String extension = "json"; @@ -128,13 +153,40 @@ public class ACLPackagerServletImplTest { MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resourcePath, selectors, extension, suffix, queryString); - request.setResourceResolver(resourceResolver); + request.setResourceResolver(crx2ResourceResolver); request.setMethod("POST"); MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); - request.setResourceResolver(resourceResolver); - request.setResource(contentResource); + request.setResourceResolver(crx2ResourceResolver); + request.setResource(crx2ContentResource); + + aclPackagerServlet.doPost(request, response); + + final JSONObject actual = new JSONObject(response.getOutput().toString()); + assertEquals("success", actual.optString("status", "error")); + } + + + @Test + public void testDoPost_oak_success() throws Exception { + when(aemCapabilityHelper.isOak()).thenReturn(true); + + final String resourcePath = "/etc/acs-commons/packages/acl-packager-test/jcr:content"; + final String selectors = "package"; + final String extension = "json"; + final String suffix = ""; + final String queryString = ""; + + MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resourcePath, selectors, + extension, suffix, queryString); + request.setResourceResolver(oakResourceResolver); + request.setMethod("POST"); + + MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); + + request.setResourceResolver(oakResourceResolver); + request.setResource(oakContentResource); aclPackagerServlet.doPost(request, response); @@ -157,8 +209,8 @@ public class ACLPackagerServletImplTest { MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); - request.setResourceResolver(resourceResolver); - request.setResource(contentResource); + request.setResourceResolver(crx2ResourceResolver); + request.setResource(crx2ContentResource); aclPackagerServlet.doPost(request, response); String tmp = response.getOutput().toString(); @@ -184,7 +236,7 @@ public class ACLPackagerServletImplTest { MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); request.setResourceResolver(errorResourceResolver); - request.setResource(contentResource); + request.setResource(crx2ContentResource); aclPackagerServlet.doPost(request, response); @@ -193,18 +245,18 @@ public class ACLPackagerServletImplTest { } - private class SuccessMockResourceResolver extends MockResourceResolver { + private class Crx2SuccessMockResourceResolver extends MockResourceResolver { final List<Resource> results; - public SuccessMockResourceResolver() { + public Crx2SuccessMockResourceResolver() { super(); results = new LinkedList<Resource>(); - results.add(new MockResource(this, "/content/dam/rep:policy", "")); - results.add(new MockResource(this, "/content/acs-commons/rep:policy", "")); - results.add(new MockResource(this, "/etc/workflow/packages/rep:policy", "")); - results.add(new MockResource(this, "/var/audit/1/2/3/rep:policy", "")); - results.add(new MockResource(this, "/home/groups/authors/rep:policy", "")); + results.add(new MockResource(this, "/content/dam/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/content/acs-commons/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/etc/workflow/packages/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/var/audit/1/2/3/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/home/groups/authors/rep:policy", "rep:ACL")); for(Resource resource : results) { this.addResource(resource); @@ -258,6 +310,71 @@ public class ACLPackagerServletImplTest { } } + private class OakSuccessMockResourceResolver extends MockResourceResolver { + final List<Resource> results; + + public OakSuccessMockResourceResolver() { + super(); + + results = new LinkedList<Resource>(); + results.add(new MockResource(this, "/content/dam/rep:policy/allow0", "")); + results.add(new MockResource(this, "/content/dam/rep:policy/allow1", "")); + results.add(new MockResource(this, "/content/acs-commons/rep:policy/deny", "")); + results.add(new MockResource(this, "/etc/workflow/packages/rep:policy/allow", "")); + results.add(new MockResource(this, "/var/audit/1/2/3/rep:policy/deny", "")); + results.add(new MockResource(this, "/home/groups/authors/rep:policy/allow", "")); + + for(Resource resource : results) { + this.addResource(resource); + } + + this.addResource(new MockResource(this, "/content/dam/rep:policy", "rep:ACL")); + this.addResource(new MockResource(this, "/content/acs-commons/rep:policy", "rep:ACL")); + this.addResource(new MockResource(this, "/etc/workflow/packages/rep:policy", "rep:ACL")); + this.addResource(new MockResource(this, "/var/audit/1/2/3/rep:policy", "rep:ACL")); + this.addResource(new MockResource(this, "/home/groups/authors/rep:policy", "rep:ACL")); + } + + @Override + public Iterable<Resource> getChildren(final Resource resource) { + return null; + } + + public Iterator<Resource> findResources(String query, String language) { + return this.results.iterator(); + } + + @Override + public void delete(final Resource resource) throws PersistenceException { + + } + + @Override + public Resource create(final Resource resource, final String s, final Map<String, Object> stringObjectMap) throws PersistenceException { + return null; + } + + @Override + public void revert() { + + } + + @Override + public void commit() throws PersistenceException { + + } + + @Override + public boolean hasChanges() { + return false; + } + + @SuppressWarnings("unchecked") + public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) { + return (AdapterType) session; + } + } + private class ErrorMockResourceResolver extends MockResourceResolver { final List<Resource> results; @@ -265,11 +382,11 @@ public class ACLPackagerServletImplTest { super(); results = new LinkedList<Resource>(); - results.add(new MockResource(this, "/content/dam/rep:policy", "")); - results.add(new MockResource(this, "/content/acs-commons/rep:policy", "")); - results.add(new MockResource(this, "/etc/workflow/packages/rep:policy", "")); - results.add(new MockResource(this, "/var/audit/1/2/3/rep:policy", "")); - results.add(new MockResource(this, "/home/groups/authors/rep:policy", "")); + results.add(new MockResource(this, "/content/dam/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/content/acs-commons/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/etc/workflow/packages/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/var/audit/1/2/3/rep:policy", "rep:ACL")); + results.add(new MockResource(this, "/home/groups/authors/rep:policy", "rep:ACL")); for(Resource resource : results) { this.addResource(resource);
['bundle/src/test/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImplTest.java', 'bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java']
{'.java': 2}
2
2
0
0
2
1,016,550
206,938
28,589
225
4,642
872
100
1
792
74
223
14
1
1
1970-01-01T00:23:42
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0