{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \\\\n\" +\n+ \"\";\n+ testRequest(HttpMethod.GET, \"/1/test-template.html\", 200, \"OK\", expected);\n+ }\n+\n @Test\n public void testRenderDirectly() throws Exception {\n TemplateEngine engine = new TestEngine(false);\n@@ -158,6 +177,5 @@ public class TemplateTest extends WebTestBase {\n handler.handle(Future.succeededFuture(Buffer.buffer(rendered)));\n }\n }\n-\n }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/templ/TemplateTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1671865,"string":"1,671,865"},"repo_tokens_count":{"kind":"number","value":369986,"string":"369,986"},"repo_lines_count":{"kind":"number","value":51775,"string":"51,775"},"repo_files_without_tests_count":{"kind":"number","value":404,"string":"404"},"changed_symbols_count":{"kind":"number","value":299,"string":"299"},"changed_tokens_count":{"kind":"number","value":72,"string":"72"},"changed_lines_count":{"kind":"number","value":13,"string":"13"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1170,"string":"1,170"},"issue_words_count":{"kind":"number","value":111,"string":"111"},"issue_tokens_count":{"kind":"number","value":244,"string":"244"},"issue_lines_count":{"kind":"number","value":41,"string":"41"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:41","string":"1970-01-01T00:26:41"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1650,"cells":{"id":{"kind":"number","value":1263,"string":"1,263"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1729/1472"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1472"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1729"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1729"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"SubRouter Mount acting as Exact Path"},"issue_body":{"kind":"string","value":"### 3.8.4\r\n\r\n* vert.x web:\r\n\r\n### Context\r\n\r\nThe handlers mounted on sub-router are ignored when the mount point is `\"/\"`. \r\n`router.mountSubRouter(\"/\", subRouter);`\r\nNote that, we can't have empty string as mount point.\r\n\r\nIt was functional until v3.8.1. With v3.8.4 it behaves as exactMatch and ending with slash.\r\n\r\nBelow table shows the difference between 3.8.1 and 3.8.4 based on the reproducer shared below:\r\n\r\n| Path | v3.8.1 | v3.8.4 |\r\n| --- | --- | --- |\r\n| /primary | Success | Resource Not Found |\r\n| /primary?query | Success | Resource Not Found |\r\n| /primary/ | Success | Success |\r\n| /primary/random | Resource Not Found | Resource Not Found |\r\n| With subrouter mounted at `/abc`|\r\n| /primary/abc | Success | Success |\r\n| /primary/abc/ | Success | Success |\r\n| /primary/abc?query | Success | Success |\r\n\r\n### Do you have a reproducer?\r\n\r\n* https://github.com/ramtech123/pocs/tree/master/vertx-subrouter-test\r\n\r\n### Steps to reproduce\r\n\r\nBy default, Vertx version is set to 3.8.4 in the reproducer. Change it to 3.8.1 to verify the behavior.\r\n\r\n1. Build and run the `RouterTestMain` given in the reproducer. Server will start listening on 8443\r\n2. Curl the given paths to observe the behavior. Ex: `curl http://localhost:8443/primary?query`\r\n\r\n### References\r\n\r\nI have gone through below issues, wondering if this change was intended?\r\n - https://github.com/vert-x3/vertx-web/issues/1435\r\n - https://github.com/vert-x3/vertx-web/issues/1441\r\n\r\n### Extra\r\n\r\nFirst two scenarios return success response in v3.8.4 also if we attach the handlers directly to the primary router instead of sub router (set `useSubRouters` flag in RouterTestServer.java to `false` to verify the behavior).\r\n\r\nHowever, raising this ticket as the behavior of sub router mounting has changed.\r\n"},"base_sha":{"kind":"string","value":"c729ef5b0afad23568758fec09b58f9514b99fc8"},"head_sha":{"kind":"string","value":"acd45048af85bbdf08f2db1163e9d81b442a1cc3"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/c729ef5b0afad23568758fec09b58f9514b99fc8...acd45048af85bbdf08f2db1163e9d81b442a1cc3"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java\nindex 9d8360619..19d777bae 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java\n@@ -51,11 +51,12 @@ public class RoutingContextWrapper extends RoutingContextImplBase {\n // just use the override\n this.mountPoint = mountPoint;\n } else {\n- if (parentMountPoint.charAt(parentMountPoint.length() - 1) == '/') {\n- // Remove the trailing slash or we won't match\n- this.mountPoint = parentMountPoint.substring(0, parentMountPoint.length() - 1) + mountPoint;\n+ // special case: when a sub router is mounting on / basically it's telling\n+ // that it wants to use the parent mount, otherwise it's extending the parent\n+ // path\n+ if (\"/\".equals(mountPoint)) {\n+ this.mountPoint = parentMountPoint;\n } else {\n- // slashes are ok, just concat\n this.mountPoint = parentMountPoint + mountPoint;\n }\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\nindex cd6bfd044..3ed96dea1 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n@@ -572,4 +572,25 @@ public class SubRouterTest extends WebTestBase {\n testRequest(HttpMethod.POST, \"/bank/order/deposit\", 200, \"OK\");\n testRequest(HttpMethod.GET, \"/bank/order/deposit\", 405, \"Method Not Allowed\");\n }\n+\n+\n+ @Test\n+ public void testMountMultiLevel() throws Exception {\n+ Router routerFirstLevel = Router.router(vertx);\n+ router.mountSubRouter(\"/primary\", routerFirstLevel);\n+\n+ Router routerSecondLevel = Router.router(vertx);\n+ routerSecondLevel.get(\"/\").handler(ctx -> {\n+ ctx.response().setStatusMessage(\"Hi\").end();\n+ });\n+ routerFirstLevel.mountSubRouter(\"/\", routerSecondLevel);\n+\n+ // Below two scenarios will fail with 3.8.4 and higher, pass with 3.8.1 and lower.\n+ testRequest(HttpMethod.GET, \"/primary\", 200, \"Hi\");\n+ testRequest(HttpMethod.GET, \"/primary?query=1\", 200, \"Hi\");\n+\n+ // Below scenarios will pass\n+ testRequest(HttpMethod.GET, \"/primary/\", 200, \"Hi\");\n+ testRequest(HttpMethod.GET, \"/primary/random\", 404, \"Not Found\");\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1671876,"string":"1,671,876"},"repo_tokens_count":{"kind":"number","value":369992,"string":"369,992"},"repo_lines_count":{"kind":"number","value":51774,"string":"51,774"},"repo_files_without_tests_count":{"kind":"number","value":404,"string":"404"},"changed_symbols_count":{"kind":"number","value":537,"string":"537"},"changed_tokens_count":{"kind":"number","value":124,"string":"124"},"changed_lines_count":{"kind":"number","value":9,"string":"9"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1781,"string":"1,781"},"issue_words_count":{"kind":"number","value":265,"string":"265"},"issue_tokens_count":{"kind":"number","value":468,"string":"468"},"issue_lines_count":{"kind":"number","value":48,"string":"48"},"issue_links_count":{"kind":"number","value":4,"string":"4"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:41","string":"1970-01-01T00:26:41"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1651,"cells":{"id":{"kind":"number","value":1264,"string":"1,264"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1724/1720"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1720"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1724"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1724"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"SockJSHandlerTest intermittent failures in CI"},"issue_body":{"kind":"string","value":"### Questions\r\n\r\nThere is an intermittent failures about `SockJSHandlerTest` in CI\r\n\r\n### Version\r\n\r\n`master` branch\r\n\r\n### Context\r\n\r\n### Exceptions found\r\n\r\n```java\r\nStarting test: SockJSHandlerTest#testCombineBinaryContinuationFramesRawWebSocket \r\nUnhandled exception \r\njava.lang.IllegalStateException: assert or failure occurred after test has completed\r\n\tat io.vertx.test.core.AsyncTestBase.handleThrowable(AsyncTestBase.java:183)\r\n\tat io.vertx.test.core.AsyncTestBase.fail(AsyncTestBase.java:422)\r\n\tat io.vertx.core.impl.AbstractContext.dispatch(AbstractContext.java:96)\r\n\tat io.vertx.core.http.impl.WebSocketImplBase.handleClosed(WebSocketImplBase.java:694)\r\n\tat io.vertx.core.http.impl.Http1xServerConnection.lambda$handleClosed$6(Http1xServerConnection.java:458)\r\n\tat io.vertx.core.impl.EventLoopContext.execute(EventLoopContext.java:73)\r\n\tat io.vertx.core.impl.DuplicatedContext.execute(DuplicatedContext.java:184)\r\n\tat io.vertx.core.impl.AbstractContext.execute(AbstractContext.java:54)\r\n\tat io.vertx.core.http.impl.Http1xServerConnection.handleClosed(Http1xServerConnection.java:458)\r\n\tat io.vertx.core.net.impl.VertxHandler.channelInactive(VertxHandler.java:136)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:389)\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:354)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)\r\n\tat io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1405)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)\r\n\tat io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:901)\r\n\tat io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:818)\r\n\tat io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)\r\n\tat io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)\r\n\tat io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:497)\r\n\tat io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\r\n\tat io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\r\n\tat io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\n```\r\n\r\n### Do you have a reproducer?\r\n\r\nhttps://travis-ci.org/github/vert-x3/vertx-web/jobs/731209417 as reference\r\n\r\n### Extra\r\n\r\n* Looks like it happens in `OpenJDK8` mostly.\r\n"},"base_sha":{"kind":"string","value":"8e6e4681df8d1262ae5a00dc6607752055ad9133"},"head_sha":{"kind":"string","value":"714d9280cf78ac0a788d5a640b2caff1aa151a9b"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/8e6e4681df8d1262ae5a00dc6607752055ad9133...714d9280cf78ac0a788d5a640b2caff1aa151a9b"},"diff":{"kind":"string","value":"diff --git a/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java b/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java\nindex db07598b9..7c3e7e86c 100644\n--- a/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java\n+++ b/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java\n@@ -62,7 +62,7 @@ public interface PebbleTemplateEngine extends TemplateEngine {\n */\n @GenIgnore\n static PebbleTemplateEngine create(Vertx vertx, PebbleEngine engine) {\n- return new PebbleTemplateEngineImpl(vertx, DEFAULT_TEMPLATE_EXTENSION, engine);\n+ return create(vertx, DEFAULT_TEMPLATE_EXTENSION, engine);\n }\n \n /**\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java\nindex 9f7eda5ba..7e13a9ca1 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java\n@@ -395,12 +395,16 @@ class SockJSSession extends SockJSSocketBase implements Shareable {\n }\n }\n \n- synchronized void handleException(Throwable t) {\n- if (exceptionHandler != null) {\n+ void handleException(Throwable t) {\n+ Handler eh;\n+ synchronized (this) {\n+ eh = exceptionHandler;\n+ }\n+ if (eh != null) {\n if (context == Vertx.currentContext()) {\n- exceptionHandler.handle(t);\n+ eh.handle(t);\n } else {\n- context.runOnContext(v -> exceptionHandler.handle(t));\n+ context.runOnContext(v -> handleException(t));\n }\n } else {\n log.error(\"Unhandled exception\", t);\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java b/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java\nindex 5400af059..7e5db09f6 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java\n@@ -73,10 +73,12 @@ public class WebTestBase extends VertxTestBase {\n @Override\n public void tearDown() throws Exception {\n if (client != null) {\n- try {\n- client.close();\n- } catch (IllegalStateException e) {\n- }\n+ CountDownLatch latch = new CountDownLatch(1);\n+ client.close((asyncResult) -> {\n+ assertTrue(asyncResult.succeeded());\n+ latch.countDown();\n+ });\n+ awaitLatch(latch);\n }\n if (server != null) {\n CountDownLatch latch = new CountDownLatch(1);"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java', 'vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1669283,"string":"1,669,283"},"repo_tokens_count":{"kind":"number","value":369360,"string":"369,360"},"repo_lines_count":{"kind":"number","value":51681,"string":"51,681"},"repo_files_without_tests_count":{"kind":"number","value":404,"string":"404"},"changed_symbols_count":{"kind":"number","value":569,"string":"569"},"changed_tokens_count":{"kind":"number","value":120,"string":"120"},"changed_lines_count":{"kind":"number","value":14,"string":"14"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":3325,"string":"3,325"},"issue_words_count":{"kind":"number","value":115,"string":"115"},"issue_tokens_count":{"kind":"number","value":661,"string":"661"},"issue_lines_count":{"kind":"number","value":56,"string":"56"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:41","string":"1970-01-01T00:26:41"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1652,"cells":{"id":{"kind":"number","value":1266,"string":"1,266"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1686/1685"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1685"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1686"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1686"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"StatusCode still remains -1 when catching a runtime exception"},"issue_body":{"kind":"string","value":"### Questions\r\n\r\nThe status code in failure handler remains -1 when catching a runtime exception\r\n\r\n### Version\r\n\r\n3.9.2, 4.0.0beta1\r\n\r\n### Do you have a reproducer?\r\n\r\ntry this example:\r\n```java\r\nRoute route1 = router.get(\"/somepath/path1/\");\r\nroute1.handler(ctx -> {\r\n // Let's say this throws a RuntimeException\r\n throw new RuntimeException(\"something happened!\");\r\n});\r\n\r\n// Define a failure handler\r\n// This will get called for any failures in the above handlers\r\nRoute route3 = router.get(\"/somepath/*\");\r\nroute3.failureHandler(failureRoutingContext -> {\r\n int statusCode = failureRoutingContext.statusCode();\r\n System.out.println(statusCode); //remains -1 here\r\n // Status code should be 500 for the RuntimeException\r\n HttpServerResponse response = failureRoutingContext.response();\r\n response.setStatusCode(statusCode).end(\"Sorry! Not today\");\r\n});\r\n```\r\n"},"base_sha":{"kind":"string","value":"f56655459e50661c8d13367193b2bf27b823702e"},"head_sha":{"kind":"string","value":"10c0ebcd54c4b448d8c5bcd27a9b9c8a1f7ca6a6"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/f56655459e50661c8d13367193b2bf27b823702e...10c0ebcd54c4b448d8c5bcd27a9b9c8a1f7ca6a6"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java\nindex 948941020..2c35e033a 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java\n@@ -16,9 +16,6 @@\n \n package io.vertx.ext.web.handler.impl;\n \n-import java.util.List;\n-import java.util.Objects;\n-\n import io.vertx.core.http.HttpHeaders;\n import io.vertx.core.http.HttpServerResponse;\n import io.vertx.core.json.JsonArray;\n@@ -28,6 +25,9 @@ import io.vertx.ext.web.RoutingContext;\n import io.vertx.ext.web.handler.ErrorHandler;\n import io.vertx.ext.web.impl.Utils;\n \n+import java.util.List;\n+import java.util.Objects;\n+\n /**\n * @author Paulo Lopes\n * @author Tim Fox\n@@ -58,48 +58,48 @@ public class ErrorHandlerImpl implements ErrorHandler {\n Throwable failure = context.failure();\n \n int errorCode = context.statusCode();\n- String errorMessage = null;\n- if (errorCode != -1) {\n- context.response().setStatusCode(errorCode);\n- errorMessage = context.response().getStatusMessage();\n- } else {\n+\n+ // force default error code\n+ if (errorCode == -1) {\n errorCode = 500;\n- if (displayExceptionDetails) {\n- errorMessage = failure.getMessage();\n- }\n- if (errorMessage == null) {\n- errorMessage = \"Internal Server Error\";\n+ }\n+\n+ response.setStatusCode(errorCode);\n+ String errorMessage = response.getStatusMessage();\n+\n+ if (displayExceptionDetails) {\n+ errorMessage = failure.getMessage();\n+ if (errorMessage != null) {\n+ // no new lines are allowed in the status message\n+ errorMessage = errorMessage.replaceAll(\"\\\\\\\\r|\\\\\\\\n\", \" \");\n+ // apply the newly desired message\n+ response.setStatusMessage(errorMessage);\n }\n- // no new lines are allowed in the status message\n- response.setStatusMessage(errorMessage.replaceAll(\"\\\\\\\\r|\\\\\\\\n\", \" \"));\n }\n \n answerWithError(context, errorCode, errorMessage);\n }\n \n- private void answerWithError(RoutingContext context, int errorCode, String errorMessage){\n- context.response().setStatusCode(errorCode);\n- if( !sendErrorResponseMIME(context, errorCode, errorMessage) &&\n- !sendErrorAcceptMIME(context, errorCode, errorMessage)\n- ){\n+ private void answerWithError(RoutingContext context, int errorCode, String errorMessage) {\n+ if (!sendErrorResponseMIME(context, errorCode, errorMessage) && !sendErrorAcceptMIME(context, errorCode, errorMessage)) {\n // fallback plain/text\n sendError(context, \"text/plain\", errorCode, errorMessage);\n }\n }\n \n- private boolean sendErrorResponseMIME(RoutingContext context, int errorCode, String errorMessage){\n+ private boolean sendErrorResponseMIME(RoutingContext context, int errorCode, String errorMessage) {\n // does the response already set the mime type?\n String mime = context.response().headers().get(HttpHeaders.CONTENT_TYPE);\n \n- if(mime == null) {\n+ if (mime == null) {\n // does the route have an acceptable content type?\n mime = context.getAcceptableContentType();\n }\n- \n+\n return mime != null && sendError(context, mime, errorCode, errorMessage);\n }\n \n- private boolean sendErrorAcceptMIME(RoutingContext context, int errorCode, String errorMessage){\n+ private boolean sendErrorAcceptMIME(RoutingContext context, int errorCode, String errorMessage) {\n // respect the client accept order\n List acceptableMimes = context.parsedHeaders().accept();\n \n@@ -120,11 +120,11 @@ public class ErrorHandlerImpl implements ErrorHandler {\n if (mime.startsWith(\"text/html\")) {\n StringBuilder stack = new StringBuilder();\n if (context.failure() != null && displayExceptionDetails) {\n- for (StackTraceElement elem: context.failure().getStackTrace()) {\n+ for (StackTraceElement elem : context.failure().getStackTrace()) {\n stack.append(\"
  • \").append(elem).append(\"
  • \");\n }\n }\n- response.putHeader(HttpHeaders.CONTENT_TYPE,\"text/html\");\n+ response.putHeader(HttpHeaders.CONTENT_TYPE, \"text/html\");\n response.end(\n errorTemplate.replace(\"{title}\", title)\n .replace(\"{errorCode}\", Integer.toString(errorCode))\n@@ -139,7 +139,7 @@ public class ErrorHandlerImpl implements ErrorHandler {\n jsonError.put(\"error\", new JsonObject().put(\"code\", errorCode).put(\"message\", errorMessage));\n if (context.failure() != null && displayExceptionDetails) {\n JsonArray stack = new JsonArray();\n- for (StackTraceElement elem: context.failure().getStackTrace()) {\n+ for (StackTraceElement elem : context.failure().getStackTrace()) {\n stack.add(elem.toString());\n }\n jsonError.put(\"stack\", stack);\n@@ -157,7 +157,7 @@ public class ErrorHandlerImpl implements ErrorHandler {\n sb.append(\": \");\n sb.append(errorMessage);\n if (context.failure() != null && displayExceptionDetails) {\n- for (StackTraceElement elem: context.failure().getStackTrace()) {\n+ for (StackTraceElement elem : context.failure().getStackTrace()) {\n sb.append(\"\\\\tat \").append(elem).append(\"\\\\n\");\n }\n }\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\nindex f11afb8f8..8dc8f729e 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n@@ -163,7 +163,11 @@ public class RoutingContextImpl extends RoutingContextImplBase {\n \n @Override\n public void fail(Throwable t) {\n- this.fail(-1, t);\n+ if (t instanceof HttpStatusException) {\n+ this.fail(((HttpStatusException) t).getStatusCode(), t);\n+ } else {\n+ this.fail(500, t);\n+ }\n }\n \n @Override\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\nindex 354ce7837..fb10dc6db 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n@@ -616,7 +616,7 @@ public class RouterTest extends WebTestBase {\n String path = \"/blah\";\n Throwable failure = new Throwable();\n router.route(path).handler(rc -> rc.fail(failure)).failureHandler(frc -> {\n- assertEquals(-1, frc.statusCode());\n+ assertEquals(500, frc.statusCode());\n assertSame(failure, frc.failure());\n frc.response().setStatusCode(500).setStatusMessage(\"Internal Server Error\").end();\n });\n@@ -627,7 +627,7 @@ public class RouterTest extends WebTestBase {\n public void testFailureWithNullThrowable() throws Exception {\n String path = \"/blah\";\n router.route(path).handler(rc -> rc.fail(null)).failureHandler(frc -> {\n- assertEquals(-1, frc.statusCode());\n+ assertEquals(500, frc.statusCode());\n assertTrue(frc.failure() instanceof NullPointerException);\n frc.response().setStatusCode(500).setStatusMessage(\"Internal Server Error\").end();\n });\n@@ -2767,4 +2767,27 @@ public class RouterTest extends WebTestBase {\n \n testRequest(HttpMethod.MKCOL, \"/\", 200, \"socks\");\n }\n+\n+ @Test\n+ public void testStatusCodeUncatchedException() throws Exception {\n+ Route route1 = router.get(\"/somepath/path1\");\n+ route1.handler(ctx -> {\n+ // Let's say this throws a RuntimeException\n+ throw new RuntimeException(\"something happened!\");\n+ });\n+\n+// Define a failure handler\n+// This will get called for any failures in the above handlers\n+ Route route3 = router.get(\"/somepath/*\");\n+ route3.failureHandler(failureRoutingContext -> {\n+ int statusCode = failureRoutingContext.statusCode();\n+ // Status code should be 500 for the RuntimeException\n+ assertEquals(500, statusCode);\n+ HttpServerResponse response = failureRoutingContext.response();\n+ response.setStatusCode(statusCode).end(\"Sorry! Not today\");\n+ });\n+\n+ testRequest(HttpMethod.GET, \"/somepath/path1\", 500, \"Internal Server Error\");\n+\n+ }\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\nindex 4b9e87aad..a6ee31031 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n@@ -310,7 +310,7 @@ public class SubRouterTest extends WebTestBase {\n });\n \n router.route(\"/subpath/*\").failureHandler(rc -> {\n- assertEquals(-1, rc.statusCode());\n+ assertEquals(500, rc.statusCode());\n assertEquals(\"Balderdash!\", rc.failure().getMessage());\n rc.response().setStatusCode(555).setStatusMessage(\"Badgers\").end();\n });\n@@ -329,7 +329,7 @@ public class SubRouterTest extends WebTestBase {\n });\n \n subRouter.route(\"/foo/*\").failureHandler(rc -> {\n- assertEquals(-1, rc.statusCode());\n+ assertEquals(500, rc.statusCode());\n assertEquals(\"Balderdash!\", rc.failure().getMessage());\n rc.response().setStatusCode(555).setStatusMessage(\"Badgers\").end();\n });"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 4}"},"changed_files_count":{"kind":"number","value":4,"string":"4"},"java_changed_files_count":{"kind":"number","value":4,"string":"4"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":4,"string":"4"},"repo_symbols_count":{"kind":"number","value":1648974,"string":"1,648,974"},"repo_tokens_count":{"kind":"number","value":364858,"string":"364,858"},"repo_lines_count":{"kind":"number","value":51080,"string":"51,080"},"repo_files_without_tests_count":{"kind":"number","value":404,"string":"404"},"changed_symbols_count":{"kind":"number","value":2837,"string":"2,837"},"changed_tokens_count":{"kind":"number","value":557,"string":"557"},"changed_lines_count":{"kind":"number","value":62,"string":"62"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":870,"string":"870"},"issue_words_count":{"kind":"number","value":98,"string":"98"},"issue_tokens_count":{"kind":"number","value":193,"string":"193"},"issue_lines_count":{"kind":"number","value":30,"string":"30"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:38","string":"1970-01-01T00:26:38"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1653,"cells":{"id":{"kind":"number","value":1246,"string":"1,246"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2066/2065"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2065"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2066"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2066"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"SecuritySchemeImpl returns null on bind call"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.1.5\r\n\r\n### Context\r\n\r\nWhen calling `RouterBuilder.securityScheme(String).bind(..)` the returned Future always return null due to a `.mapEmpty()` call.\r\n"},"base_sha":{"kind":"string","value":"5b34cadd4a24b197ca2ac625393b8cf29f25f677"},"head_sha":{"kind":"string","value":"f24d31766fda9b17c418b6403289212109d22941"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/5b34cadd4a24b197ca2ac625393b8cf29f25f677...f24d31766fda9b17c418b6403289212109d22941"},"diff":{"kind":"string","value":"diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java\nindex 2c8043fff..7df9cf046 100644\n--- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java\n+++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java\n@@ -40,7 +40,7 @@ public class SecuritySchemeImpl implements SecurityScheme {\n if (securitySchemes.containsKey(securitySchemeId)) {\n return factory.apply(securitySchemes.getJsonObject(securitySchemeId))\n .onSuccess(handler -> routerBuilder.securityHandler(securitySchemeId, handler))\n- .mapEmpty();\n+ .map(routerBuilder);\n }\n }\n return\ndiff --git a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java\nindex 80d90e15b..d11b9db9c 100644\n--- a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java\n+++ b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java\n@@ -1,11 +1,15 @@\n package io.vertx.ext.web.openapi;\n \n+import static org.assertj.core.api.Assertions.assertThat;\n+\n+import io.vertx.core.Future;\n import io.vertx.core.Vertx;\n import io.vertx.ext.web.handler.APIKeyHandler;\n import io.vertx.ext.web.handler.OAuth2AuthHandler;\n import io.vertx.junit5.Timeout;\n import io.vertx.junit5.VertxExtension;\n import io.vertx.junit5.VertxTestContext;\n+import org.assertj.core.api.Assertions;\n import org.junit.jupiter.api.Test;\n import org.junit.jupiter.api.extension.ExtendWith;\n \n@@ -68,4 +72,19 @@ public class RouterBuilderSecurityHandlerTest extends BaseRouterBuilderTest {\n }\n });\n }\n+\n+ @Test\n+ public void asyncBindHandler(Vertx vertx, VertxTestContext testContext) {\n+ RouterBuilder.create(vertx, SECURITY_TESTS)\n+ .compose(routerBuilder ->\n+ routerBuilder\n+ .securityHandler(\"oauth\")\n+ .bind(config -> Future.succeededFuture(OAuth2AuthHandler.create(vertx, null)))\n+ )\n+ .onSuccess(routerBuilder -> {\n+ testContext.verify(() -> assertThat(routerBuilder).isNotNull());\n+ testContext.completeNow();\n+ })\n+ .onFailure(testContext::failNow);\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java', 'vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1913261,"string":"1,913,261"},"repo_tokens_count":{"kind":"number","value":424136,"string":"424,136"},"repo_lines_count":{"kind":"number","value":59339,"string":"59,339"},"repo_files_without_tests_count":{"kind":"number","value":474,"string":"474"},"changed_symbols_count":{"kind":"number","value":55,"string":"55"},"changed_tokens_count":{"kind":"number","value":11,"string":"11"},"changed_lines_count":{"kind":"number","value":2,"string":"2"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":170,"string":"170"},"issue_words_count":{"kind":"number","value":19,"string":"19"},"issue_tokens_count":{"kind":"number","value":40,"string":"40"},"issue_lines_count":{"kind":"number","value":8,"string":"8"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:13","string":"1970-01-01T00:27:13"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1654,"cells":{"id":{"kind":"number","value":1268,"string":"1,268"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1492/1490"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1490"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1492"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1492"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"FormLoginHandlerImpl should return status 401 on failed authentication"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n* vert.x core: 3.8.4\r\n* vert.x web: 3.8.4\r\n\r\n### Context\r\n\r\nI was using the FormLoginHandler to perform simple form-based login. The default implementation sets the status code to 403 (\"Forbidden\") which to me indicates that the user is not **allowed** to login. I think 401 (\"Unauthorized\") is more appropriate since it \"[indicates that the request has not been applied because it lacks valid authentication credentials for the target resource](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401)\"\r\n\r\nAlso see\r\nhttps://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses\r\n\r\n### Do you have a reproducer?\r\n\r\nJust read the code at:\r\nhttps://github.com/vert-x3/vertx-web/blob/4c2ab04649c0ed306099abac1346f5fedea8c53b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java#L125\r\n\r\n### Steps to reproduce\r\n\r\n1. Add FormLoginHandler to route\r\n2. Submit wrong credentials via html form\r\n3. observe\r\n"},"base_sha":{"kind":"string","value":"70b4403c3b3a970167ebb101868ce2166ebf12d1"},"head_sha":{"kind":"string","value":"357a8678ed88283b1b3112a91ebb691e51ed23be"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/70b4403c3b3a970167ebb101868ce2166ebf12d1...357a8678ed88283b1b3112a91ebb691e51ed23be"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java\nindex 0fe34f8d6..71ed6f810 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java\n@@ -81,7 +81,7 @@ public class FormLoginHandlerImpl implements FormLoginHandler {\n public void handle(RoutingContext context) {\n HttpServerRequest req = context.request();\n if (req.method() != HttpMethod.POST) {\n- context.fail(405); // Must be a POST\n+ context.fail(new HttpStatusException(405)); // Must be a POST\n } else {\n if (!req.isExpectMultipart()) {\n throw new IllegalStateException(\"HttpServerRequest should have setExpectMultipart set to true, but it is currently set to false.\");\n@@ -91,7 +91,7 @@ public class FormLoginHandlerImpl implements FormLoginHandler {\n String password = params.get(passwordParam);\n if (username == null || password == null) {\n log.warn(\"No username or password provided in form - did you forget to include a BodyHandler?\");\n- context.fail(400);\n+ context.fail(new HttpStatusException(400));\n } else {\n Session session = context.session();\n JsonObject authInfo = new JsonObject().put(\"username\", username).put(\"password\", password);\n@@ -122,7 +122,7 @@ public class FormLoginHandlerImpl implements FormLoginHandler {\n req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);\n }\n } else {\n- context.fail(403); // Failed login\n+ context.fail(new HttpStatusException(401)); // Failed login\n }\n });\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java\nindex a0bdae237..1612a10cc 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java\n@@ -275,7 +275,7 @@ public class RedirectAuthHandlerTest extends AuthHandlerTestBase {\n req.putHeader(\"cookie\", sessionCookie.get());\n req.write(buffer);\n }, resp -> {\n- }, 403, \"Forbidden\", null);\n+ }, 401, \"Unauthorized\", null);\n testRequest(HttpMethod.GET, \"/protected/somepage\", req -> req.putHeader(\"cookie\", sessionCookie.get()), resp -> {\n String location = resp.headers().get(\"location\");\n assertNotNull(location);"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1270844,"string":"1,270,844"},"repo_tokens_count":{"kind":"number","value":283807,"string":"283,807"},"repo_lines_count":{"kind":"number","value":40228,"string":"40,228"},"repo_files_without_tests_count":{"kind":"number","value":298,"string":"298"},"changed_symbols_count":{"kind":"number","value":316,"string":"316"},"changed_tokens_count":{"kind":"number","value":67,"string":"67"},"changed_lines_count":{"kind":"number","value":6,"string":"6"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":976,"string":"976"},"issue_words_count":{"kind":"number","value":104,"string":"104"},"issue_tokens_count":{"kind":"number","value":252,"string":"252"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"issue_links_count":{"kind":"number","value":3,"string":"3"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:16","string":"1970-01-01T00:26:16"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1655,"cells":{"id":{"kind":"number","value":1261,"string":"1,261"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1765/1742"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1742"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1765"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1765"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"ResponsePredicateResult::response returns null when requiresBody is false"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n`3.9.3`\r\n\r\n### Context\r\n\r\nI have a very simple `ErrorConverter` whose `ResponsePredicateResult` is returning `null` for `response()` when `requiresBody()` is set to `false`. It works fine (valid `HttpResponse` instance) if `requiresBody()` is set to `true`.\r\n\r\nI would expect to be able to assess all response properties _except_ `body()` by having `requiresBody` set to `false`.\r\n\r\n### Do you have a reproducer?\r\n\r\n~~No, if the report doesn't point to an obvious culprit I can see if I can create one.~~\r\n\r\nhttps://github.com/pnsantos/vertx-predicate-npe-repro\r\n\r\n### Steps to reproduce\r\n\r\nThis is my error converter:\r\n```java\r\npublic class MyConverter implements ErrorConverter {\r\n\r\n @Override\r\n public Throwable apply(ResponsePredicateResult result) {\r\n int code = result.response().statusCode(); <--- result.response() is null\r\n\r\n (...)\r\n }\r\n}\r\n```\r\n\r\nAnd this is how I'm creating the response predicate:\r\n```\r\nResponsePredicate.create(ResponsePredicate.SC_SUCCESS, new MyConverter())\r\n```\r\n\r\nOn \"success\" cases everything works fine. When the predicate fails (4xx/5xx responses), and the converter is called, if `requiresBody` is set to `true` everything works as expected. However if `requiresBody` is `false` the following exception happens (line 21 is where I'm doing (`result.response().statusCode()`):\r\n```\r\njava.lang.NullPointerException\r\n at com.example.error.MyErrorConverter.apply(MyErrorConverter.java:21)\r\n at io.vertx.ext.web.client.impl.predicate.PredicateInterceptor.failOnPredicate(PredicateInterceptor.java:88)\r\n at io.vertx.ext.web.client.impl.predicate.PredicateInterceptor.handle(PredicateInterceptor.java:55)\r\n at io.vertx.ext.web.client.impl.predicate.PredicateInterceptor.handle(PredicateInterceptor.java:32)\r\n at io.vertx.ext.web.client.impl.HttpContext.next(HttpContext.java:272)\r\n at io.vertx.ext.web.client.impl.HttpContext.fire(HttpContext.java:282)\r\n at io.vertx.ext.web.client.impl.HttpContext.receiveResponse(HttpContext.java:230) \r\n at io.vertx.ext.web.client.impl.HttpContext.lambda$handleSendRequest$7(HttpContext.java:420)\r\n at io.vertx.core.impl.FutureImpl.dispatch(FutureImpl.java:105)\r\n at io.vertx.core.impl.FutureImpl.tryComplete(FutureImpl.java:150)\r\n at io.vertx.core.http.impl.HttpClientRequestImpl.handleResponse(HttpClientRequestImpl.java:391)\r\n at io.vertx.core.http.impl.HttpClientRequestBase.checkHandleResponse(HttpClientRequestBase.java:159)\r\n at io.vertx.core.http.impl.HttpClientRequestBase.handleResponse(HttpClientRequestBase.java:140)\r\n at io.vertx.core.http.impl.Http1xClientConnection.handleResponseBegin(Http1xClientConnection.java:623)\r\n at io.vertx.core.http.impl.Http1xClientConnection.handleHttpMessage(Http1xClientConnection.java:593)\r\n at io.vertx.core.http.impl.Http1xClientConnection.handleMessage(Http1xClientConnection.java:575)\r\n at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:366)\r\n at io.vertx.core.impl.EventLoopContext.execute(EventLoopContext.java:43)\r\n at io.vertx.core.impl.ContextImpl.executeFromIO(ContextImpl.java:229)\r\n at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:163)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436)\r\n at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324)\r\n at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296)\r\n at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) \r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1518)\r\n at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1267)\r\n at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1314)\r\n at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)\r\n at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)\r\n at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)\r\n at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:792)\r\n at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:475)\r\n at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378)\r\n at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\r\n at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\r\n at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n at java.lang.Thread.run(Thread.java:748)\r\n```\r\nI confirmed via logs that `result.response()` is returning `null`.\r\n\r\n### Extra\r\n\r\n```\r\nnetty: 4.1.49.Final\r\n---\r\nopenjdk version \"1.8.0_265\"\r\nOpenJDK Runtime Environment (Zulu 8.48.0.53-CA-linux64) (build 1.8.0_265-b11)\r\nOpenJDK 64-Bit Server VM (Zulu 8.48.0.53-CA-linux64) (build 25.265-b11, mixed mode)\r\n```\r\n"},"base_sha":{"kind":"string","value":"5e61e19dc35d74543b93bc7a19eb56802ac7d855"},"head_sha":{"kind":"string","value":"d4260ec69ed3228dee793a0da19d243a37a57c69"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/5e61e19dc35d74543b93bc7a19eb56802ac7d855...d4260ec69ed3228dee793a0da19d243a37a57c69"},"diff":{"kind":"string","value":"diff --git a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java\nindex a4f5afe5e..8273ea14b 100644\n--- a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java\n+++ b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java\n@@ -44,7 +44,7 @@ public class PredicateInterceptor implements Handler> {\n for (ResponsePredicate expectation : expectations) {\n ResponsePredicateResultImpl predicateResult;\n try {\n- predicateResult = (ResponsePredicateResultImpl) expectation.apply(responseCopy(resp, httpContext,null));\n+ predicateResult = (ResponsePredicateResultImpl) expectation.apply(responseCopy(resp, httpContext, null));\n } catch (Exception e) {\n httpContext.fail(e);\n return;\n@@ -52,6 +52,7 @@ public class PredicateInterceptor implements Handler> {\n if (!predicateResult.succeeded()) {\n ErrorConverter errorConverter = expectation.errorConverter();\n if (!errorConverter.requiresBody()) {\n+ predicateResult.setHttpResponse(responseCopy(resp, httpContext, null));\n failOnPredicate(httpContext, errorConverter, predicateResult);\n } else {\n resp.bodyHandler(buffer -> {\ndiff --git a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java\nindex 7e2396f6b..59052c32c 100644\n--- a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java\n+++ b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java\n@@ -1775,6 +1775,29 @@ public class WebClientTest extends WebClientTestBase {\n });\n }\n \n+ @Test\n+ public void testExpectCustomExceptionWithStatusCode() throws Exception {\n+ UUID uuid = UUID.randomUUID();\n+ int statusCode = 400;\n+\n+ ResponsePredicate predicate = ResponsePredicate.create(ResponsePredicate.SC_SUCCESS, ErrorConverter.create(result -> {\n+ int code = result.response().statusCode();\n+ return new CustomException(uuid, String.valueOf(code));\n+ }));\n+\n+ testExpectation(true, req -> req.expect(predicate), httpServerResponse -> {\n+ httpServerResponse\n+ .setStatusCode(statusCode)\n+ .end(TestUtils.randomBuffer(2048));\n+ }, ar -> {\n+ Throwable cause = ar.cause();\n+ assertThat(cause, instanceOf(CustomException.class));\n+ CustomException customException = (CustomException) cause;\n+ assertEquals(String.valueOf(statusCode), customException.getMessage());\n+ assertEquals(uuid, customException.tag);\n+ });\n+ }\n+\n @Test\n public void testExpectFunctionThrowsException() throws Exception {\n ResponsePredicate predicate = ResponsePredicate.create(r -> {"},"changed_files":{"kind":"string","value":"['vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java', 'vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1691104,"string":"1,691,104"},"repo_tokens_count":{"kind":"number","value":374258,"string":"374,258"},"repo_lines_count":{"kind":"number","value":52377,"string":"52,377"},"repo_files_without_tests_count":{"kind":"number","value":411,"string":"411"},"changed_symbols_count":{"kind":"number","value":323,"string":"323"},"changed_tokens_count":{"kind":"number","value":55,"string":"55"},"changed_lines_count":{"kind":"number","value":3,"string":"3"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":6845,"string":"6,845"},"issue_words_count":{"kind":"number","value":318,"string":"318"},"issue_tokens_count":{"kind":"number","value":1494,"string":"1,494"},"issue_lines_count":{"kind":"number","value":106,"string":"106"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":4,"string":"4"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:44","string":"1970-01-01T00:26:44"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1656,"cells":{"id":{"kind":"number","value":1253,"string":"1,253"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1978/1380"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1380"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1978"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1978"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"Race condition when using an event bus bridge hook (events handler), between socket closed event and other events"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n* vert.x core: 3.7.1 (should apply to 3.8.1, master)\r\n* vert.x web: 3.7.1 (should apply to 3.8.1, master)\r\n\r\n### Context\r\n\r\nWe started to see that some messages were not delivered to the same event bus (bridge) address. After multiple re-connections, a client can't listen anymore to some particular address as it receives nothing or receives too few messages out of all the messages sent. The server needs to be restarted.\r\n\r\nWhen an event bus bridge hook (events handler) is used, it seems like there's a race condition where io.vertx.ext.web.handler.sockjs.impl.EventBusBridgeImpl.java may call handleSocketClosed while we're still in internalHandleRegister (or unregister, sendorpub). This can happen before checkCallHook's okAction is run as we're still waiting for the hook (event handlers) to accept the event...\r\n\r\n### Do you have a reproducer?\r\n\r\nSee steps below\r\n\r\n### Steps to reproduce\r\n\r\nWe reproduced this with custom tools but I think this scenario is sufficient to reproduce it:\r\n\r\n1. ... Set an event bus bridge events handler\r\n2. ... Intercept \"REGISTER\" event and wait enough time before accepting the event\r\n3. ... Meanwhile, disconnect the client\r\n4. ... A MessageConsumer is created for the given address although socket is already closed and any message sent to this address might now land into this MessageConsumer associated to nothing\r\n\r\n### Extra\r\n\r\nShould apply to 3.8.1 and master as nothing was changed that could fix this issue in this file (EventBusBridgeImpl.java).\r\n\r\nWe fixed this internally by just checking for\r\n`if (!sockInfos.containsKey(sock)) return;`\r\nat the beginning of checkCallHook's okAction handlers.\r\n\r\nIt could probably explain https://github.com/vert-x3/vertx-web/issues/1327: the message consumer's handler references the closed socket when the race condition issue happens while a REGISTER event is being handled."},"base_sha":{"kind":"string","value":"7a8c6550ee5f4fdd9755ebfabb326765a6e52f3a"},"head_sha":{"kind":"string","value":"e321e222b2086086b8901941f79acc3a90341af2"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/7a8c6550ee5f4fdd9755ebfabb326765a6e52f3a...e321e222b2086086b8901941f79acc3a90341af2"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java\nindex 346b45b8e..51a98c417 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java\n@@ -97,8 +97,11 @@ public class EventBusBridgeImpl implements Handler {\n // On close unregister any handlers that haven't been unregistered\n registrations.forEach((key, value) -> {\n value.unregister();\n- checkCallHook(() -> new BridgeEventImpl(BridgeEventType.UNREGISTER,\n- new JsonObject().put(\"type\", \"unregister\").put(\"address\", value.address()), sock), null, null);\n+ checkCallHook(() ->\n+ new BridgeEventImpl(\n+ BridgeEventType.UNREGISTER,\n+ new JsonObject().put(\"type\", \"unregister\").put(\"address\", value.address()),\n+ sock));\n });\n \n SockInfo info = sockInfos.remove(sock);\n@@ -109,8 +112,7 @@ public class EventBusBridgeImpl implements Handler {\n }\n }\n \n- checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_CLOSED, null, sock),\n- null, null);\n+ checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_CLOSED, null, sock));\n }\n \n private void handleSocketData(SockJSSocket sock, Buffer data, Map> registrations) {\n@@ -158,19 +160,35 @@ public class EventBusBridgeImpl implements Handler {\n \n }\n \n+ private void checkCallHook(Supplier eventSupplier) {\n+ checkCallHook(eventSupplier, null, null);\n+ }\n+\n private void checkCallHook(Supplier eventSupplier, Runnable okAction, Runnable rejectAction) {\n if (bridgeEventHandler == null) {\n if (okAction != null) {\n okAction.run();\n }\n } else {\n- BridgeEventImpl event = eventSupplier.get();\n+ final BridgeEventImpl event = eventSupplier.get();\n+ final boolean before = sockInfos.containsKey(event.socket());\n bridgeEventHandler.handle(event);\n- event.future().onComplete(res -> {\n- if (res.succeeded()) {\n- if (res.result()) {\n- if (okAction != null) {\n- okAction.run();\n+ event.future()\n+ .onFailure(err -> LOG.error(\"Failure in bridge event handler\", err))\n+ .onSuccess(ok -> {\n+ if (ok) {\n+ final boolean after = sockInfos.containsKey(event.socket());\n+ if (before != after) {\n+ // even though the event check is valid, the socket info isn't valid anymore\n+ if (rejectAction != null) {\n+ rejectAction.run();\n+ } else {\n+ LOG.debug(\"SockJSSocket state change prevented send or pub\");\n+ }\n+ } else {\n+ if (okAction != null) {\n+ okAction.run();\n+ }\n }\n } else {\n if (rejectAction != null) {\n@@ -179,10 +197,7 @@ public class EventBusBridgeImpl implements Handler {\n LOG.debug(\"Bridge handler prevented send or pub\");\n }\n }\n- } else {\n- LOG.error(\"Failure in bridge event handler\", res.cause());\n- }\n- });\n+ });\n }\n }\n \n@@ -261,7 +276,7 @@ public class EventBusBridgeImpl implements Handler {\n registrations.put(address, reg);\n info.handlerCount++;\n // Notify registration completed\n- checkCallHook(() -> new BridgeEventImpl(BridgeEventType.REGISTERED, rawMsg, sock), null, null);\n+ checkCallHook(() -> new BridgeEventImpl(BridgeEventType.REGISTERED, rawMsg, sock));\n } else {\n // inbound match failed\n if (debug) {\n@@ -306,7 +321,7 @@ public class EventBusBridgeImpl implements Handler {\n if (info != null) {\n info.pingInfo.lastPing = System.currentTimeMillis();\n // Trigger an event to allow custom behavior after updating lastPing\n- checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_PING, null, sock), null, null);\n+ checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_PING, null, sock));\n }\n }\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1757323,"string":"1,757,323"},"repo_tokens_count":{"kind":"number","value":389173,"string":"389,173"},"repo_lines_count":{"kind":"number","value":54407,"string":"54,407"},"repo_files_without_tests_count":{"kind":"number","value":434,"string":"434"},"changed_symbols_count":{"kind":"number","value":2238,"string":"2,238"},"changed_tokens_count":{"kind":"number","value":476,"string":"476"},"changed_lines_count":{"kind":"number","value":47,"string":"47"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1881,"string":"1,881"},"issue_words_count":{"kind":"number","value":276,"string":"276"},"issue_tokens_count":{"kind":"number","value":416,"string":"416"},"issue_lines_count":{"kind":"number","value":33,"string":"33"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:03","string":"1970-01-01T00:27:03"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1657,"cells":{"id":{"kind":"number","value":1254,"string":"1,254"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1947/1890"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1890"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1947"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1947"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"SessionHandler doesn't set SameSite cookie attribute when destroying the session and expiring the session cookie "},"issue_body":{"kind":"string","value":"### Questions\r\n\r\nWhen the session cookie needs to be removed on session logout, the SameSite attribute is not set. \r\n\r\n### Version\r\n\r\n3.9.2\r\n\r\n### Context\r\n\r\nIf SameSite.None is set on the cookie while setting it for the duration of the session, It should also be present when the user sends a logout and the expiration of the cookie is set.\r\nThe logout can be called from different locations where the SameSite.None is needed for it to function.\r\nNow because it's not set, the cookie remains, and the session is still available.\r\n\r\n### Do you have a reproducer?\r\n\r\nIt's on line 196 in io.vertx.ext.web.handler.impl.SessionHandlerImpl. The cookie is removed when the session gets destroyed. But the additional attributes are not there.\r\n\r\nI duplicated the SessionHandlerImpl class and added the following code to get it to work. I can add a pull request, to add the cookie handling in the SessionHandlerImpl itself. \r\n\r\n```\r\n...\r\n } else {\r\n // invalidate the cookie as the session has been destroyed\r\n context.removeCookie(sessionCookieName);\r\n\r\n/* added from here*/\r\n Cookie cookie = context.getCookie(sessionCookieName);\r\n if (cookie != null) {\r\n cookie.setPath(sessionCookiePath);\r\n cookie.setSecure(sessionCookieSecure);\r\n cookie.setHttpOnly(sessionCookieHttpOnly);\r\n cookie.setSameSite(cookieSameSite);\r\n context.addCookie(cookie);\r\n }\r\n/* until here*/\r\n\r\n // if the session was regenerated in the request\r\n // the old id must also be removed\r\n if (session.isRegenerated()) {\r\n...\r\n```\r\n"},"base_sha":{"kind":"string","value":"a4eb3dbe0f2dc167f1242c03282b14e37aeb13be"},"head_sha":{"kind":"string","value":"48c3ede6747d7a65cb00478a57478b44125e59a0"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/a4eb3dbe0f2dc167f1242c03282b14e37aeb13be...48c3ede6747d7a65cb00478a57478b44125e59a0"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java\nindex 367e27de1..c9934625c 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java\n@@ -146,14 +146,16 @@ public class SessionHandlerImpl implements SessionHandler {\n *\n * @param cookie the cookie to set\n */\n- private void setCookieProperties(Cookie cookie) {\n+ private void setCookieProperties(Cookie cookie, boolean expired) {\n cookie.setPath(sessionCookiePath);\n cookie.setSecure(sessionCookieSecure);\n cookie.setHttpOnly(sessionCookieHttpOnly);\n cookie.setSameSite(cookieSameSite);\n- // set max age if user requested it - else it's a session cookie\n- if (cookieMaxAge >= 0) {\n- cookie.setMaxAge(cookieMaxAge);\n+ if (!expired) {\n+ // set max age if user requested it - else it's a session cookie\n+ if (cookieMaxAge >= 0) {\n+ cookie.setMaxAge(cookieMaxAge);\n+ }\n }\n }\n \n@@ -190,7 +192,7 @@ public class SessionHandlerImpl implements SessionHandler {\n // restore defaults\n session.setAccessed();\n cookie.setValue(session.value());\n- setCookieProperties(cookie);\n+ setCookieProperties(cookie, false);\n }\n \n // we must invalidate the old id\n@@ -234,7 +236,10 @@ public class SessionHandlerImpl implements SessionHandler {\n } else {\n if (!cookieless) {\n // invalidate the cookie as the session has been destroyed\n- context.removeCookie(sessionCookieName);\n+ final Cookie expiredCookie = context.removeCookie(sessionCookieName);\n+ if (expiredCookie != null) {\n+ setCookieProperties(expiredCookie, true);\n+ }\n }\n // if the session was regenerated in the request\n // the old id must also be removed\n@@ -450,7 +455,7 @@ public class SessionHandlerImpl implements SessionHandler {\n return cookie;\n }\n cookie = Cookie.cookie(sessionCookieName, session.value());\n- setCookieProperties(cookie);\n+ setCookieProperties(cookie, false);\n context.addCookie(cookie);\n return cookie;\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java\nindex 12bd307b3..e11505e8f 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java\n@@ -16,6 +16,7 @@\n \n package io.vertx.ext.web.handler;\n \n+import io.vertx.core.http.CookieSameSite;\n import io.vertx.core.http.HttpMethod;\n import io.vertx.ext.web.Session;\n import io.vertx.ext.web.WebTestBase;\n@@ -381,6 +382,7 @@ public abstract class SessionHandlerTestBase extends WebTestBase {\n \t\ttestRequest(HttpMethod.GET, \"/0\", req -> {\n \t\t}, resp -> {\n \t\t\tString setCookie = resp.headers().get(\"set-cookie\");\n+\t\t\tSystem.out.println(setCookie);\n \t\t\tsessionID.set(setCookie);\n \t\t}, 200, \"OK\", null);\n \t\tCountDownLatch responseReceived = new CountDownLatch(1);\n@@ -393,6 +395,38 @@ public abstract class SessionHandlerTestBase extends WebTestBase {\n \t\treturn MILLISECONDS.convert(System.nanoTime() - now, NANOSECONDS);\n \t}\n \n+ @Test\n+ public void testInvalidation() throws Exception {\n+ router.route().handler(SessionHandler.create(store).setCookieSameSite(CookieSameSite.STRICT));\n+ AtomicReference rid = new AtomicReference<>();\n+\n+ router.get(\"/0\").handler(rc -> {\n+ rid.set(rc.session());\n+ rc.session().put(\"foo\", \"foo_value\");\n+ rc.response().end();\n+ });\n+ router.get(\"/1\").handler(rc -> {\n+ rid.set(rc.session());\n+ assertEquals(\"foo_value\", rc.session().get(\"foo\"));\n+ rc.session().destroy();\n+ rc.response().end();\n+ });\n+\n+ AtomicReference sessionID = new AtomicReference<>();\n+ testRequest(HttpMethod.GET, \"/0\", req -> {\n+ }, resp -> {\n+ String setCookie = resp.headers().get(\"set-cookie\");\n+ sessionID.set(setCookie);\n+ }, 200, \"OK\", null);\n+ CountDownLatch responseReceived = new CountDownLatch(1);\n+ testRequest(HttpMethod.GET, \"/1\", req -> req.putHeader(\"cookie\", sessionID.get()), resp -> {\n+ // ensure that expired cookies still contain the the configured properties\n+ assertTrue(resp.headers().get(\"set-cookie\").contains(\"SameSite=Strict\"));\n+ responseReceived.countDown();\n+ }, 200, \"OK\", null);\n+ awaitLatch(responseReceived);\n+ }\n+\n \t@Test\n \tpublic void testSessionFixation() throws Exception {\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1749425,"string":"1,749,425"},"repo_tokens_count":{"kind":"number","value":387236,"string":"387,236"},"repo_lines_count":{"kind":"number","value":54129,"string":"54,129"},"repo_files_without_tests_count":{"kind":"number","value":428,"string":"428"},"changed_symbols_count":{"kind":"number","value":833,"string":"833"},"changed_tokens_count":{"kind":"number","value":175,"string":"175"},"changed_lines_count":{"kind":"number","value":19,"string":"19"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1663,"string":"1,663"},"issue_words_count":{"kind":"number","value":208,"string":"208"},"issue_tokens_count":{"kind":"number","value":326,"string":"326"},"issue_lines_count":{"kind":"number","value":43,"string":"43"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:00","string":"1970-01-01T00:27:00"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1658,"cells":{"id":{"kind":"number","value":1255,"string":"1,255"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1945/1933"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1933"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1945"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1945"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"CORS handling fails with \"Origin: null\" header"},"issue_body":{"kind":"string","value":"### Version\r\n\r\nWhich version(s) did you encounter this bug ?\r\n\r\n4.0.3\r\n\r\n### Context\r\n\r\nWhen issuing an HTTP request with the `Origin: null` header, the CorsHandler generates an HTTP 500 error (`CORS Rejected - Invalid origin`), even though it should allow the request to continue its normal processing.\r\n\r\nThis happens whenever one creates a CorsHandler with either https://vertx.io/docs/apidocs/io/vertx/ext/web/handler/CorsHandler.html#create-- (which should allow any origin), or with https://vertx.io/docs/apidocs/io/vertx/ext/web/handler/CorsHandler.html#create-java.lang.String- and passing the `\"*\"` pattern (which should do the same as `.create()` and allow any origin.)\r\n\r\nThe `Origin: null` header name and value is a valid origin, as per https://tools.ietf.org/html/rfc6454#section-7.1 ; the literal `null` is allowed; in that RFC it just happens to be phrased using its hex-encoded ascii values:\r\n\r\n```\r\norigin-list-or-null = %x6E %x75 %x6C %x6C / origin-list\r\n```\r\n\r\nThis particular header value is sent automatically by browsers whenever they perform a cross-origin request, and the browser has to set an \"opaque origin\", like when the URL of the page is `file://` (see https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null )\r\n\r\n### Do you have a reproducer?\r\n\r\nSort of; I noticed this issue in the https://github.com/yuzutech/kroki project; this project happens to have a publicly available instance which can demonstrate the issue; you can inspect how the CorsHandler is created, at https://github.com/yuzutech/kroki/blob/v0.12.1/server/src/main/java/io/kroki/server/Server.java#L92 \r\n\r\nTo reproduce, just issue what should be a valid HTTP request with `Origin: null`, and notice that the API reports back an HTTP 500 error:\r\n\r\n* `curl https://kroki.io/graphviz/svg/eNpLyUwvSizIUHBXqPZIzcnJ17ULzy_KSanlAgB1EAjQ`, gives you HTTP 200, and a bunch of SVG, as expected.\r\n* `curl -H 'Origin: http://localhost' https://kroki.io/graphviz/svg/eNpLyUwvSizIUHBXqPZIzcnJ17ULzy_KSanlAgB1EAjQ`, also gives you HTTP 200, and a bunch of SVG.\r\n* `curl -H 'Origin: null' https://kroki.io/graphviz/svg/eNpLyUwvSizIUHBXqPZIzcnJ17ULzy_KSanlAgB1EAjQ` gives you an HTTP 500 with the error message `Error 500: CORS Rejected - Invalid origin` (which can be traced back to vertx-web).\r\n\r\nFor that case, the stacktrace is this (reproduced in local environment):\r\n\r\n```\r\njava.lang.IllegalStateException: CORS Rejected - Invalid origin\r\n at io.vertx.ext.web.handler.impl.CorsHandlerImpl.handle(CorsHandlerImpl.java:211)\r\n at io.vertx.ext.web.handler.impl.CorsHandlerImpl.handle(CorsHandlerImpl.java:41) \r\n at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1129)\r\n at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:151)\r\n at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:133) \r\n at io.vertx.ext.web.impl.RouterImpl.handle(RouterImpl.java:55) \r\n at io.vertx.ext.web.impl.RouterImpl.handle(RouterImpl.java:37) \r\n at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:67) \r\n at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:30) \r\n at io.vertx.core.impl.EventLoopContext.emit(EventLoopContext.java:52) \r\n at io.vertx.core.impl.DuplicatedContext.emit(DuplicatedContext.java:194) \r\n at io.vertx.core.http.impl.Http1xServerConnection.handleMessage(Http1xServerConnection.java:140) \r\n at io.vertx.core.net.impl.ConnectionBase.read(ConnectionBase.java:153) \r\n at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:154) \r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) \r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) \r\n at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:93)\r\n at io.netty.handler.codec.http.websocketx.extensions.WebSocketServerExtensionHandler.channelRead(WebSocketServerExtensionHandler.java:102)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) \r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) \r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.vertx.core.http.impl.Http1xUpgradeToH2CHandler.channelRead(Http1xUpgradeToH2CHandler.java:115) \r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) \r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) \r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) \r\n at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324) \r\n at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) \r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) \r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) \r\n at io.vertx.core.http.impl.Http1xOrH2CHandler.end(Http1xOrH2CHandler.java:61)\r\n at io.vertx.core.http.impl.Http1xOrH2CHandler.channelRead(Http1xOrH2CHandler.java:38)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)\r\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)\r\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)\r\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)\r\n at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)\r\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)\r\n at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\r\n at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\r\n at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n at java.base/java.lang.Thread.run(Unknown Source)\r\n```\r\n```"},"base_sha":{"kind":"string","value":"f8e7bb17b6365b1f86f84fae0090102a48674205"},"head_sha":{"kind":"string","value":"dce68f718a20d7c985a2175219c19c1507414f11"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/f8e7bb17b6365b1f86f84fae0090102a48674205...dce68f718a20d7c985a2175219c19c1507414f11"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java\nindex f2aec90b5..5feada3f7 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java\n@@ -34,6 +34,7 @@ public final class Origin {\n private final String host;\n private final int port;\n private final String resource;\n+ private final boolean isNull;\n \n // internal\n private final String base;\n@@ -41,6 +42,21 @@ public final class Origin {\n private final String optional;\n \n private Origin(String protocol, String host, String port, String resource) {\n+\n+ if (protocol == null && host == null && port == null && resource == null) {\n+ this.protocol = null;\n+ this.host = null;\n+ this.port = -1;\n+ this.resource = null;\n+ isNull = true;\n+ this.base = null;\n+ this.BASE = null;\n+ this.optional = null;\n+ return;\n+ } else {\n+ isNull = false;\n+ }\n+\n String defaultPort;\n switch (protocol.toLowerCase()) {\n case \"ftp\":\n@@ -120,6 +136,12 @@ public final class Origin {\n \n public static Origin parse(String text) {\n \n+ if (text.length() == 4) {\n+ if (\"null\".equals(text)) {\n+ return new Origin(null, null, null, null);\n+ }\n+ }\n+\n int sep0 = text.indexOf(\"://\");\n \n if (sep0 > 0) {\n@@ -168,6 +190,12 @@ public final class Origin {\n * https://tools.ietf.org/html/rfc6454#section-7\n */\n public static boolean isValid(String text) {\n+ if (text.length() == 4) {\n+ if (\"null\".equals(text)) {\n+ return true;\n+ }\n+ }\n+\n int sep0 = text.indexOf(\"://\");\n \n if (sep0 > 0) {\n@@ -285,6 +313,11 @@ public final class Origin {\n }\n \n public boolean sameOrigin(String other) {\n+\n+ if (isNull) {\n+ return \"null\".equals(other);\n+ }\n+\n // for each char of other\n // if any base chars != other abort\n // if more chars\n@@ -332,6 +365,10 @@ public final class Origin {\n }\n \n public String encode() {\n+ if (isNull) {\n+ return \"\";\n+ }\n+\n switch (protocol) {\n case \"http\":\n return protocol + \"://\" + host + (port == 80 ? \"\" : \":\" + port);\n@@ -346,6 +383,10 @@ public final class Origin {\n \n @Override\n public String toString() {\n+ if (isNull) {\n+ return \"null\";\n+ }\n+\n return base;\n }\n \n@@ -353,6 +394,10 @@ public final class Origin {\n * An hyperlink representation of this origin. Like on web browsers.\n */\n public String href() {\n+ if (isNull) {\n+ return \"null\";\n+ }\n+\n return base + (resource == null ? \"/\" : resource);\n }\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java\nindex a6daff696..96ee929c8 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java\n@@ -495,4 +495,12 @@ public class CORSHandlerTest extends WebTestBase {\n router.route().handler(context -> context.response().end());\n testRequest(HttpMethod.GET, \"/\", req -> req.headers().add(\"origin\", \"https://www.vertx.io\"), resp -> checkHeaders(resp, \"https://www.vertx.io\", null, null, null, \"true\", null), 200, \"OK\", null);\n }\n+\n+ @Test\n+ public void testAcceptNullOrigin() throws Exception {\n+ router.route().handler(CorsHandler.create().addOrigin(\"*\"));\n+ router.route().handler(context -> context.response().end());\n+ testRequest(HttpMethod.GET, \"/\", req -> req.headers().add(\"origin\", \"null\"), resp -> checkHeaders(resp, \"*\", null, null, null), 200, \"OK\", null);\n+ }\n+\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java b/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java\nindex 1f7929557..cb72dfb48 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java\n@@ -44,4 +44,11 @@ public class OriginTest {\n assertFalse(Origin.isValid(origin));\n }\n }\n+\n+ @Test\n+ public void testNullOrigin() {\n+ Origin.parse(\"null\");\n+ assertTrue(Origin.isValid(\"null\"));\n+ }\n+\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java', 'vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1748628,"string":"1,748,628"},"repo_tokens_count":{"kind":"number","value":387026,"string":"387,026"},"repo_lines_count":{"kind":"number","value":54084,"string":"54,084"},"repo_files_without_tests_count":{"kind":"number","value":428,"string":"428"},"changed_symbols_count":{"kind":"number","value":841,"string":"841"},"changed_tokens_count":{"kind":"number","value":210,"string":"210"},"changed_lines_count":{"kind":"number","value":45,"string":"45"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":8731,"string":"8,731"},"issue_words_count":{"kind":"number","value":404,"string":"404"},"issue_tokens_count":{"kind":"number","value":1718,"string":"1,718"},"issue_lines_count":{"kind":"number","value":85,"string":"85"},"issue_links_count":{"kind":"number","value":10,"string":"10"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:00","string":"1970-01-01T00:27:00"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1659,"cells":{"id":{"kind":"number","value":1234,"string":"1,234"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2397/2315"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2315"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2397"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2397"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"TenantHandler doesn't respect the order aware sub handler"},"issue_body":{"kind":"string","value":"See: https://github.com/eclipse-vertx/vert.x/issues/4536\r\n\r\nA possible use case is to implement SSO on the same endpoint, for this the IdP info is extracted from a param, however, OAuth2Handler implements `OrderListener` and depends on this information to properly mount the callback.\r\n\r\nOn a Multi tenant environment, the order should be set to the handlers to avoid them being missed on the route."},"base_sha":{"kind":"string","value":"eae0a59cd95a68f1df51ac887b8f9631d26435ca"},"head_sha":{"kind":"string","value":"d8f87ecca44446944a090d74e7c7a555ee2009dc"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/eae0a59cd95a68f1df51ac887b8f9631d26435ca...d8f87ecca44446944a090d74e7c7a555ee2009dc"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java\nindex ccf8e8f22..d8d75c14a 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java\n@@ -18,6 +18,7 @@ package io.vertx.ext.web.handler.impl;\n import io.vertx.core.Handler;\n import io.vertx.ext.web.RoutingContext;\n import io.vertx.ext.web.handler.MultiTenantHandler;\n+import io.vertx.ext.web.impl.OrderListener;\n \n import java.util.Map;\n import java.util.Objects;\n@@ -27,7 +28,7 @@ import java.util.function.Function;\n /**\n * @author Paulo Lopes\n */\n-public class MultiTenantHandlerImpl implements MultiTenantHandler {\n+public class MultiTenantHandlerImpl implements MultiTenantHandler, OrderListener {\n \n private final Map> handlerMap = new ConcurrentHashMap<>();\n \n@@ -87,4 +88,13 @@ public class MultiTenantHandlerImpl implements MultiTenantHandler {\n ctx.next();\n }\n }\n+\n+ @Override\n+ public void onOrder(int order) {\n+ for (Handler handler : handlerMap.values()) {\n+ if (handler instanceof OrderListener) {\n+ ((OrderListener) handler).onOrder(order);\n+ }\n+ }\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":2020426,"string":"2,020,426"},"repo_tokens_count":{"kind":"number","value":448267,"string":"448,267"},"repo_lines_count":{"kind":"number","value":62389,"string":"62,389"},"repo_files_without_tests_count":{"kind":"number","value":504,"string":"504"},"changed_symbols_count":{"kind":"number","value":434,"string":"434"},"changed_tokens_count":{"kind":"number","value":88,"string":"88"},"changed_lines_count":{"kind":"number","value":12,"string":"12"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":399,"string":"399"},"issue_words_count":{"kind":"number","value":59,"string":"59"},"issue_tokens_count":{"kind":"number","value":89,"string":"89"},"issue_lines_count":{"kind":"number","value":5,"string":"5"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:59","string":"1970-01-01T00:27:59"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1660,"cells":{"id":{"kind":"number","value":1256,"string":"1,256"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1925/1919"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1919"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1925"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1925"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"Server eats exception and simply responds 500"},"issue_body":{"kind":"string","value":"### Description\r\n\r\nServer log doesn't contain any info about NPE error. I think it happens for other errors too.\r\n\r\n### Version\r\n\r\n4.0.3\r\n\r\n### Code sample\r\n\r\n```\r\n final HttpServer server = vertx\r\n .createHttpServer(\r\n new HttpServerOptions()\r\n .setLogActivity(true)\r\n );\r\n\r\n final Router router = Router.router(vertx);\r\n\r\n router\r\n .route()\r\n .handler(ResponseContentTypeHandler.create());\r\n\r\n router\r\n .get(\"/somepath\")\r\n .produces(\"text/xml\")\r\n .handler(ctx -> {\r\n final String foo = context.get(\"foo\").toString();\r\n ctx.response().end();\r\n });\r\n\r\n server\r\n .requestHandler(router)\r\n .listen(8080)\r\n .onSuccess(s -> System.out.format(\r\n \"HTTP server is listening on port %s.\",\r\n s.actualPort()));\r\n```\r\n\r\n### Log sample\r\n\r\n```\r\nHTTP server is listening on port 8080.\r\n14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096\r\n14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2\r\n14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16\r\n14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8\r\n14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.delayedQueue.ratio: 8\r\n14:06:09.550 [vert.x-eventloop-thread-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true\r\n14:06:09.550 [vert.x-eventloop-thread-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true\r\n14:06:09.551 [vert.x-eventloop-thread-1] DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@6f856194\r\n14:06:09.588 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] READ: 86B\r\n +-------------------------------------------------+\r\n | 0 1 2 3 4 5 6 7 8 9 a b c d e f |\r\n+--------+-------------------------------------------------+----------------+\r\n|00000000| 47 45 54 20 2f 73 6f 6d 65 70 61 74 68 20 48 54 |GET /somepath HT|\r\n|00000010| 54 50 2f 31 2e 31 0d 0a 48 6f 73 74 3a 20 6c 6f |TP/1.1..Host: lo|\r\n|00000020| 63 61 6c 68 6f 73 74 3a 38 30 38 30 0d 0a 55 73 |calhost:8080..Us|\r\n|00000030| 65 72 2d 41 67 65 6e 74 3a 20 63 75 72 6c 2f 37 |er-Agent: curl/7|\r\n|00000040| 2e 36 34 2e 31 0d 0a 41 63 63 65 70 74 3a 20 2a |.64.1..Accept: *|\r\n|00000050| 2f 2a 0d 0a 0d 0a |/*.... |\r\n+--------+-------------------------------------------------+----------------+\r\n14:06:09.614 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.codec.compression.ZlibCodecFactory - -Dio.netty.noJdkZlibDecoder: false\r\n14:06:09.614 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.codec.compression.ZlibCodecFactory - -Dio.netty.noJdkZlibEncoder: false\r\n14:06:09.634 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] WRITE: 103B\r\n +-------------------------------------------------+\r\n | 0 1 2 3 4 5 6 7 8 9 a b c d e f |\r\n+--------+-------------------------------------------------+----------------+\r\n|00000000| 48 54 54 50 2f 31 2e 31 20 35 30 30 20 49 6e 74 |HTTP/1.1 500 Int|\r\n|00000010| 65 72 6e 61 6c 20 53 65 72 76 65 72 20 45 72 72 |ernal Server Err|\r\n|00000020| 6f 72 0d 0a 63 6f 6e 74 65 6e 74 2d 6c 65 6e 67 |or..content-leng|\r\n|00000030| 74 68 3a 20 32 31 0d 0a 63 6f 6e 74 65 6e 74 2d |th: 21..content-|\r\n|00000040| 74 79 70 65 3a 20 74 65 78 74 2f 78 6d 6c 0d 0a |type: text/xml..|\r\n|00000050| 0d 0a 49 6e 74 65 72 6e 61 6c 20 53 65 72 76 65 |..Internal Serve|\r\n|00000060| 72 20 45 72 72 6f 72 |r Error |\r\n+--------+-------------------------------------------------+----------------+\r\n14:06:09.635 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] READ COMPLETE\r\n14:06:09.635 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] FLUSH\r\n14:06:09.637 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] READ COMPLETE\r\n14:06:09.640 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 ! R:/[0:0:0:0:0:0:0:1]:50225] INACTIVE\r\n14:06:09.640 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 ! R:/[0:0:0:0:0:0:0:1]:50225] UNREGISTERED\r\n14:06:15.228 [vert.x-eventloop-thread-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 2 thread-local buffer(s) from thread: vert.x-eventloop-thread-1\r\n```"},"base_sha":{"kind":"string","value":"123b750b7995a20302bbeff92527344454f4894e"},"head_sha":{"kind":"string","value":"1e0a374065cbdb3af9c43e953bf8833f3c226c8f"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/123b750b7995a20302bbeff92527344454f4894e...1e0a374065cbdb3af9c43e953bf8833f3c226c8f"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\nindex c7e87fce0..4432edcb6 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\n@@ -180,9 +180,6 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal {\n }\n \n private void handleInHandlerRuntimeFailure(RouterImpl router, boolean failed, Throwable t) {\n- if (LOG.isTraceEnabled()) {\n- LOG.trace(\"Throwable thrown from handler\", t);\n- }\n if (!failed) {\n if (LOG.isTraceEnabled()) {\n LOG.trace(\"Failing the routing\");\n@@ -199,6 +196,8 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal {\n \n \n protected void unhandledFailure(int statusCode, Throwable failure, RouterImpl router) {\n+ LOG.error(\"Unhandled exception in router\", failure);\n+\n int code = statusCode != -1 ?\n statusCode :\n (failure instanceof HttpException) ?\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java\nindex 79da1fc79..9fdb3e145 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java\n@@ -115,7 +115,7 @@ public class BodyHandlerTest extends WebTestBase {\n req.setChunked(true);\n req.putHeader(\"content-type\", \"text/plain;charset=ISO-8859-1\");\n byte b = str.getBytes(StandardCharsets.ISO_8859_1)[0];\n- req.write(Buffer.buffer(new byte[] { b }));\n+ req.write(Buffer.buffer(new byte[]{b}));\n }, 200, \"OK\", null);\n }\n \n@@ -315,20 +315,20 @@ public class BodyHandlerTest extends WebTestBase {\n \n @Test\n public void testFileDeleteOnLargeUpload() throws Exception {\n- String uploadsDirectory = tempUploads.newFolder().getPath();\n- router.clear();\n- router.route().handler(BodyHandler.create()\n- .setDeleteUploadedFilesOnEnd(true)\n- .setBodyLimit(10000)\n- .setUploadsDirectory(uploadsDirectory));\n- router.route().handler(ctx -> {\n- fail();\n- ctx.fail(500);\n- });\n+ String uploadsDirectory = tempUploads.newFolder().getPath();\n+ router.clear();\n+ router.route().handler(BodyHandler.create()\n+ .setDeleteUploadedFilesOnEnd(true)\n+ .setBodyLimit(10000)\n+ .setUploadsDirectory(uploadsDirectory));\n+ router.route().handler(ctx -> {\n+ fail();\n+ ctx.fail(500);\n+ });\n \n- sendFileUploadRequest(TestUtils.randomBuffer(20000), 413, \"Request Entity Too Large\");\n+ sendFileUploadRequest(TestUtils.randomBuffer(20000), 413, \"Request Entity Too Large\");\n \n- assertWaitUntil(() -> vertx.fileSystem().readDirBlocking(uploadsDirectory).isEmpty());\n+ assertWaitUntil(() -> vertx.fileSystem().readDirBlocking(uploadsDirectory).isEmpty());\n }\n \n @Test\n@@ -392,8 +392,8 @@ public class BodyHandlerTest extends WebTestBase {\n String uploadsDirectory = tempUploads.newFolder().getPath();\n router.clear();\n router.route().handler(BodyHandler.create()\n- .setDeleteUploadedFilesOnEnd(deletedUploadedFilesOnEnd)\n- .setUploadsDirectory(uploadsDirectory));\n+ .setDeleteUploadedFilesOnEnd(deletedUploadedFilesOnEnd)\n+ .setUploadsDirectory(uploadsDirectory));\n router.route().handler(requestHandler);\n \n sendFileUploadRequest(TestUtils.randomBuffer(50), statusCode, statusMessage);\n@@ -500,13 +500,13 @@ public class BodyHandlerTest extends WebTestBase {\n \n for (int i = 0; i < uploads; i++) {\n String header =\n- \"--\" + boundary + \"\\\\r\\\\n\" +\n- \"Content-Disposition: form-data; name=\\\\\"file\" + i + \"\\\\\"; filename=\\\\\"file\" + i + \"\\\\\"\\\\r\\\\n\" +\n- \"Content-Type: application/octet-stream\\\\r\\\\n\" +\n- \"Content-Transfer-Encoding: binary\\\\r\\\\n\" +\n- \"\\\\r\\\\n\";\n+ \"--\" + boundary + \"\\\\r\\\\n\" +\n+ \"Content-Disposition: form-data; name=\\\\\"file\" + i + \"\\\\\"; filename=\\\\\"file\" + i + \"\\\\\"\\\\r\\\\n\" +\n+ \"Content-Type: application/octet-stream\\\\r\\\\n\" +\n+ \"Content-Transfer-Encoding: binary\\\\r\\\\n\" +\n+ \"\\\\r\\\\n\";\n buffer.appendString(header);\n- buffer.appendBuffer(TestUtils.randomBuffer(4096*16));\n+ buffer.appendBuffer(TestUtils.randomBuffer(4096 * 16));\n buffer.appendString(\"\\\\r\\\\n\");\n }\n buffer.appendString(\"--\" + boundary + \"\\\\r\\\\n\");\n@@ -543,10 +543,10 @@ public class BodyHandlerTest extends WebTestBase {\n Buffer buffer = Buffer.buffer();\n String str =\n \"--\" + boundary + \"\\\\r\\\\n\" +\n- \"Content-Disposition: form-data; name=\\\\\"attr1\\\\\"\\\\r\\\\n\\\\r\\\\nTim\\\\r\\\\n\" +\n- \"--\" + boundary + \"\\\\r\\\\n\" +\n- \"Content-Disposition: form-data; name=\\\\\"attr2\\\\\"\\\\r\\\\n\\\\r\\\\nJulien\\\\r\\\\n\" +\n- \"--\" + boundary + \"--\\\\r\\\\n\";\n+ \"Content-Disposition: form-data; name=\\\\\"attr1\\\\\"\\\\r\\\\n\\\\r\\\\nTim\\\\r\\\\n\" +\n+ \"--\" + boundary + \"\\\\r\\\\n\" +\n+ \"Content-Disposition: form-data; name=\\\\\"attr2\\\\\"\\\\r\\\\n\\\\r\\\\nJulien\\\\r\\\\n\" +\n+ \"--\" + boundary + \"--\\\\r\\\\n\";\n buffer.appendString(str);\n req.headers().set(\"content-length\", String.valueOf(buffer.length()));\n req.headers().set(\"content-type\", \"multipart/form-data; boundary=\" + boundary);\n@@ -561,7 +561,7 @@ public class BodyHandlerTest extends WebTestBase {\n \n router.clear();\n router.route().handler(BodyHandler.create()\n- .setUploadsDirectory(uploadsDirectory));\n+ .setUploadsDirectory(uploadsDirectory));\n router.route().handler(ctx -> {\n assertNull(ctx.getBody());\n assertEquals(1, ctx.fileUploads().size());\n@@ -575,11 +575,11 @@ public class BodyHandlerTest extends WebTestBase {\n String boundary = \"dLV9Wyq26L_-JQxk6ferf-RT153LhOO\";\n Buffer buffer = Buffer.buffer();\n String header =\n- \"--\" + boundary + \"\\\\r\\\\n\" +\n- \"Content-Disposition: form-data; name=\\\\\"\" + name + \"\\\\\"; filename=\\\\\"\" + fileName + \"\\\\\"\\\\r\\\\n\" +\n- \"Content-Type: \" + contentType + \"\\\\r\\\\n\" +\n- \"Content-Transfer-Encoding: binary\\\\r\\\\n\" +\n- \"\\\\r\\\\n\";\n+ \"--\" + boundary + \"\\\\r\\\\n\" +\n+ \"Content-Disposition: form-data; name=\\\\\"\" + name + \"\\\\\"; filename=\\\\\"\" + fileName + \"\\\\\"\\\\r\\\\n\" +\n+ \"Content-Type: \" + contentType + \"\\\\r\\\\n\" +\n+ \"Content-Transfer-Encoding: binary\\\\r\\\\n\" +\n+ \"\\\\r\\\\n\";\n buffer.appendString(header);\n buffer.appendBuffer(TestUtils.randomBuffer(50));\n String footer = \"\\\\r\\\\n--\" + boundary + \"--\\\\r\\\\n\";\n@@ -591,8 +591,7 @@ public class BodyHandlerTest extends WebTestBase {\n }\n \n @Test\n- public void testNoUploadDirMultiPartFormData() throws Exception\n- {\n+ public void testNoUploadDirMultiPartFormData() throws Exception {\n String dirName = getNotCreatedTemporaryFolderName();\n router.clear();\n router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName));\n@@ -612,7 +611,7 @@ public class BodyHandlerTest extends WebTestBase {\n \n @Test\n public void testFormMultipartFormDataWithAllowedFilesUploadFalse2() throws Exception {\n- testFormMultipartFormDataWithAllowedFilesUploadFalse(false);\n+ testFormMultipartFormDataWithAllowedFilesUploadFalse(false);\n }\n \n private void testFormMultipartFormDataWithAllowedFilesUploadFalse(boolean mergeAttributes) throws Exception {\n@@ -645,7 +644,7 @@ public class BodyHandlerTest extends WebTestBase {\n Buffer buffer = Buffer.buffer();\n String boundary = \"dLV9Wyq26L_-JQxk6ferf-RT153LhOO\";\n String header =\n- \"--\" + boundary + \"\\\\r\\\\n\" +\n+ \"--\" + boundary + \"\\\\r\\\\n\" +\n \"Content-Disposition: form-data; name=\\\\\"attr1\\\\\"\\\\r\\\\n\\\\r\\\\nTim\\\\r\\\\n\" +\n \"--\" + boundary + \"\\\\r\\\\n\" +\n \"Content-Disposition: form-data; name=\\\\\"attr2\\\\\"\\\\r\\\\n\\\\r\\\\nTommaso\\\\r\\\\n\" +\n@@ -654,8 +653,8 @@ public class BodyHandlerTest extends WebTestBase {\n \"Content-Type: application/octet-stream\\\\r\\\\n\" +\n \"Content-Transfer-Encoding: binary\\\\r\\\\n\" +\n \"\\\\r\\\\n\";\n- buffer.appendString(header);\n- buffer.appendBuffer(TestUtils.randomBuffer(50));\n+ buffer.appendString(header);\n+ buffer.appendBuffer(TestUtils.randomBuffer(50));\n buffer.appendString(\"\\\\r\\\\n--\" + boundary + \"--\\\\r\\\\n\");\n req.headers().set(\"content-length\", String.valueOf(buffer.length()));\n req.headers().set(\"content-type\", \"multipart/form-data; boundary=\" + boundary);\n@@ -664,8 +663,7 @@ public class BodyHandlerTest extends WebTestBase {\n }\n \n @Test\n- public void testNoUploadDirFormURLEncoded() throws Exception\n- {\n+ public void testNoUploadDirFormURLEncoded() throws Exception {\n String dirName = getNotCreatedTemporaryFolderName();\n router.clear();\n router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName));\n@@ -676,16 +674,14 @@ public class BodyHandlerTest extends WebTestBase {\n }\n \n @Test\n- public void testBodyHandlerCreateTrueWorks() throws Exception\n- {\n+ public void testBodyHandlerCreateTrueWorks() throws Exception {\n router.clear();\n router.route().handler(BodyHandler.create(true));\n testFormURLEncoded();\n }\n \n @Test\n- public void testSetHandleFileUploads() throws Exception\n- {\n+ public void testSetHandleFileUploads() throws Exception {\n String dirName = getNotCreatedTemporaryFolderName();\n router.clear();\n \n@@ -709,8 +705,7 @@ public class BodyHandlerTest extends WebTestBase {\n }\n \n @Test\n- public void testRerouteWithHandleFileUploadsFalse() throws Exception\n- {\n+ public void testRerouteWithHandleFileUploadsFalse() throws Exception {\n String fileName = \"test.bin\";\n router.clear();\n router.route().handler(BodyHandler.create(false).setMergeFormAttributes(true));\n@@ -735,7 +730,7 @@ public class BodyHandlerTest extends WebTestBase {\n Buffer buffer = Buffer.buffer();\n String boundary = \"dLV9Wyq26L_-JQxk6ferf-RT153LhOO\";\n String header =\n- \"--\" + boundary + \"\\\\r\\\\n\" +\n+ \"--\" + boundary + \"\\\\r\\\\n\" +\n \"Content-Disposition: form-data; name=\\\\\"attr1\\\\\"\\\\r\\\\n\\\\r\\\\nTim\\\\r\\\\n\" +\n \"--\" + boundary + \"\\\\r\\\\n\" +\n \"Content-Disposition: form-data; name=\\\\\"attr2\\\\\"\\\\r\\\\n\\\\r\\\\nTommaso\\\\r\\\\n\" +\n@@ -744,8 +739,8 @@ public class BodyHandlerTest extends WebTestBase {\n \"Content-Type: application/octet-stream\\\\r\\\\n\" +\n \"Content-Transfer-Encoding: binary\\\\r\\\\n\" +\n \"\\\\r\\\\n\";\n- buffer.appendString(header);\n- buffer.appendBuffer(TestUtils.randomBuffer(50));\n+ buffer.appendString(header);\n+ buffer.appendBuffer(TestUtils.randomBuffer(50));\n buffer.appendString(\"\\\\r\\\\n--\" + boundary + \"--\\\\r\\\\n\");\n req.headers().set(\"content-length\", String.valueOf(buffer.length()));\n req.headers().set(\"content-type\", \"multipart/form-data; boundary=\" + boundary);\n@@ -754,8 +749,7 @@ public class BodyHandlerTest extends WebTestBase {\n }\n \n @Test\n- public void testBodyLimitWithHandleFileUploadsFalse() throws Exception\n- {\n+ public void testBodyLimitWithHandleFileUploadsFalse() throws Exception {\n router.clear();\n \n BodyHandler bodyHandler = BodyHandler.create(false).setBodyLimit(2048);\n@@ -768,8 +762,7 @@ public class BodyHandlerTest extends WebTestBase {\n sendFileUploadRequest(fileData, 413, \"Request Entity Too Large\");\n }\n \n- private String getNotCreatedTemporaryFolderName() throws IOException\n- {\n+ private String getNotCreatedTemporaryFolderName() throws IOException {\n File dir = tempUploads.newFolder();\n dir.delete();\n return dir.getPath();\n@@ -882,24 +875,22 @@ public class BodyHandlerTest extends WebTestBase {\n router.clear();\n router.route().handler(BodyHandler.create());\n router.route().handler(rc -> {\n- MultiMap attrs = rc.request().formAttributes();\n- assertNotNull(attrs);\n- int size = 0;\n- assertNotNull(attrs.get(\"attr1\"));\n- size += attrs.get(\"attr1\").length();\n- assertNotNull(attrs.get(\"attr2\"));\n- size += attrs.get(\"attr2\").length();\n- assertTrue(size > 2048);\n- rc.response().end();\n+ fail(\"Should not get here\");\n+ }).failureHandler(ctx -> {\n+ assertNotNull(ctx.failure());\n+ assertTrue(ctx.failure() instanceof IOException);\n+ assertEquals(\"Size exceed allowed maximum capacity\", ctx.failure().getMessage());\n+ ctx.next();\n });\n+\n testRequest(HttpMethod.POST, \"/?p1=foo\", req -> {\n Buffer buffer = Buffer.buffer();\n String boundary = \"dLV9Wyq26L_-JQxk6ferf-RT153LhOO\";\n String header =\n \"--\" + boundary + \"\\\\r\\\\n\" +\n- \"Content-Disposition: form-data; name=\\\\\"attr1\\\\\"\\\\r\\\\n\\\\r\\\\n\" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(1024).getBytes()) + \"\\\\r\\\\n\" +\n+ \"Content-Disposition: form-data; name=\\\\\"attr1\\\\\"\\\\r\\\\n\\\\r\\\\n\" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(2048).getBytes()) + \"\\\\r\\\\n\" +\n \"--\" + boundary + \"\\\\r\\\\n\" +\n- \"Content-Disposition: form-data; name=\\\\\"attr2\\\\\"\\\\r\\\\n\\\\r\\\\n\" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(1024).getBytes()) + \"\\\\r\\\\n\" +\n+ \"Content-Disposition: form-data; name=\\\\\"attr2\\\\\"\\\\r\\\\n\\\\r\\\\n\" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(2048).getBytes()) + \"\\\\r\\\\n\" +\n \"--\" + boundary + \"\\\\r\\\\n\" +\n \"Content-Disposition: form-data; name=\\\\\"\" + name + \"\\\\\"; filename=\\\\\"file\\\\\"\\\\r\\\\n\" +\n \"Content-Type: application/octet-stream\\\\r\\\\n\" +\n@@ -911,7 +902,19 @@ public class BodyHandlerTest extends WebTestBase {\n req.headers().set(\"content-length\", String.valueOf(buffer.length()));\n req.headers().set(\"content-type\", \"multipart/form-data; boundary=\" + boundary);\n req.write(buffer);\n- }, 200, \"OK\", null);\n+ }, 400, \"Bad Request\", null);\n+ }\n+\n+ @Test\n+ public void testLogExceptions() throws Exception {\n+ router.clear();\n+ router.route().handler(BodyHandler.create());\n+\n+ router.route().handler(ctx -> {\n+ throw new NullPointerException();\n+ });\n+ testRequest(HttpMethod.GET, \"/\", req -> {\n+ }, 500, \"Internal Server Error\", null);\n }\n \n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1746216,"string":"1,746,216"},"repo_tokens_count":{"kind":"number","value":386399,"string":"386,399"},"repo_lines_count":{"kind":"number","value":53997,"string":"53,997"},"repo_files_without_tests_count":{"kind":"number","value":427,"string":"427"},"changed_symbols_count":{"kind":"number","value":153,"string":"153"},"changed_tokens_count":{"kind":"number","value":33,"string":"33"},"changed_lines_count":{"kind":"number","value":5,"string":"5"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":5157,"string":"5,157"},"issue_words_count":{"kind":"number","value":521,"string":"521"},"issue_tokens_count":{"kind":"number","value":1950,"string":"1,950"},"issue_lines_count":{"kind":"number","value":83,"string":"83"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:58","string":"1970-01-01T00:26:58"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1661,"cells":{"id":{"kind":"number","value":1260,"string":"1,260"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1779/1778"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1778"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1779"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1779"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"HTTP server file upload cleanup fail to delete"},"issue_body":{"kind":"string","value":"The HTTP server file upload cleanup mechanism implemented in `BodyHandler` can fail to delete uploaded files because it does not ensure that the file upload is finished before deleting the file. Fixing this in vertx-web would bring lot of complexity and instead this has been implemented in vertx-core HTTP server file upload that will delete any stream not successfully completed.\r\n"},"base_sha":{"kind":"string","value":"7d91fc4471655c3d57bb0ef7210079cf8b483145"},"head_sha":{"kind":"string","value":"68dd64008a5312e67950bc7429a32a35b92f90ab"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/7d91fc4471655c3d57bb0ef7210079cf8b483145...68dd64008a5312e67950bc7429a32a35b92f90ab"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java b/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java\nindex bc812f747..a95a2cb30 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java\n@@ -62,5 +62,11 @@ public interface FileUpload {\n */\n String charSet();\n \n+ /**\n+ * Try to cancel the file upload.\n+ *\n+ * @return {@code true} when the upload was cancelled, {@code false} when the upload is finished and the file is available\n+ */\n+ boolean cancel();\n \n }\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\nindex 02b56382e..23457b62e 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\n@@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger;\n \n import io.netty.handler.codec.DecoderException;\n import io.netty.handler.codec.http.HttpHeaderValues;\n+import io.vertx.core.Future;\n import io.vertx.core.Handler;\n import io.vertx.core.buffer.Buffer;\n import io.vertx.core.file.FileSystem;\n@@ -190,7 +191,7 @@ public class BodyHandlerImpl implements BodyHandler {\n long size = uploadSize + upload.size();\n if (size > bodyLimit) {\n failed = true;\n- deleteFileUploads();\n+ cancelAndCleanupFileUploads();\n context.fail(413);\n return;\n }\n@@ -199,20 +200,23 @@ public class BodyHandlerImpl implements BodyHandler {\n // we actually upload to a file with a generated filename\n uploadCount.incrementAndGet();\n String uploadedFileName = new File(uploadsDir, UUID.randomUUID().toString()).getPath();\n- upload.streamToFileSystem(uploadedFileName);\n FileUploadImpl fileUpload = new FileUploadImpl(uploadedFileName, upload);\n fileUploads.add(fileUpload);\n- upload.exceptionHandler(t -> {\n- deleteFileUploads();\n- context.fail(t);\n+ Future fut = upload.streamToFileSystem(uploadedFileName);\n+ fut.onComplete(ar -> {\n+ if (fut.succeeded()) {\n+ uploadEnded();\n+ } else {\n+ cancelAndCleanupFileUploads();\n+ context.fail(ar.cause());\n+ }\n });\n- upload.endHandler(v -> uploadEnded());\n }\n });\n }\n \n context.request().exceptionHandler(t -> {\n- deleteFileUploads();\n+ cancelAndCleanupFileUploads();\n if (t instanceof DecoderException) {\n // bad request\n context.fail(400, t.getCause());\n@@ -253,7 +257,7 @@ public class BodyHandlerImpl implements BodyHandler {\n uploadSize += buff.length();\n if (bodyLimit != -1 && uploadSize > bodyLimit) {\n failed = true;\n- deleteFileUploads();\n+ cancelAndCleanupFileUploads();\n context.fail(413);\n } else {\n // multipart requests will not end up in the request body\n@@ -290,12 +294,12 @@ public class BodyHandlerImpl implements BodyHandler {\n void doEnd() {\n \n if (failed) {\n- deleteFileUploads();\n+ cancelAndCleanupFileUploads();\n return;\n }\n \n if (deleteUploadedFilesOnEnd) {\n- context.addBodyEndHandler(x -> deleteFileUploads());\n+ context.addBodyEndHandler(x -> cancelAndCleanupFileUploads());\n }\n \n HttpServerRequest req = context.request();\n@@ -309,22 +313,21 @@ public class BodyHandlerImpl implements BodyHandler {\n context.next();\n }\n \n- private void deleteFileUploads() {\n+ /**\n+ * Cancel all unfinished file upload in progress and delete all uploaded files.\n+ */\n+ private void cancelAndCleanupFileUploads() {\n if (cleanup.compareAndSet(false, true) && handleFileUploads) {\n for (FileUpload fileUpload : context.fileUploads()) {\n FileSystem fileSystem = context.vertx().fileSystem();\n- String uploadedFileName = fileUpload.uploadedFileName();\n- fileSystem.exists(uploadedFileName, existResult -> {\n- if (existResult.failed()) {\n- log.warn(\"Could not detect if uploaded file exists, not deleting: \" + uploadedFileName, existResult.cause());\n- } else if (existResult.result()) {\n- fileSystem.delete(uploadedFileName, deleteResult -> {\n- if (deleteResult.failed()) {\n- log.warn(\"Delete of uploaded file failed: \" + uploadedFileName, deleteResult.cause());\n- }\n- });\n- }\n- });\n+ if (!fileUpload.cancel()) {\n+ String uploadedFileName = fileUpload.uploadedFileName();\n+ fileSystem.delete(uploadedFileName, deleteResult -> {\n+ if (deleteResult.failed()) {\n+ log.warn(\"Delete of uploaded file failed: \" + uploadedFileName, deleteResult.cause());\n+ }\n+ });\n+ }\n }\n }\n }\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java\nindex 98d62b7c6..70c8fef42 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java\n@@ -67,4 +67,8 @@ public class FileUploadImpl implements FileUpload {\n return upload.charset();\n }\n \n+ @Override\n+ public boolean cancel() {\n+ return upload.cancelStreamToFileSystem();\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1698077,"string":"1,698,077"},"repo_tokens_count":{"kind":"number","value":375725,"string":"375,725"},"repo_lines_count":{"kind":"number","value":52586,"string":"52,586"},"repo_files_without_tests_count":{"kind":"number","value":412,"string":"412"},"changed_symbols_count":{"kind":"number","value":2487,"string":"2,487"},"changed_tokens_count":{"kind":"number","value":469,"string":"469"},"changed_lines_count":{"kind":"number","value":59,"string":"59"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":383,"string":"383"},"issue_words_count":{"kind":"number","value":60,"string":"60"},"issue_tokens_count":{"kind":"number","value":70,"string":"70"},"issue_lines_count":{"kind":"number","value":2,"string":"2"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:45","string":"1970-01-01T00:26:45"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1662,"cells":{"id":{"kind":"number","value":1259,"string":"1,259"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1815/1814"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1814"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1815"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1815"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"NPE when userAgentEnabled is set to false"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.0.0 (and in previous betas)\r\n\r\n### Context\r\n\r\nI have a SecretsClient that is based on VaultConfigStore and like that code uses SlimVaultClient to access secrets in Vault. It only uses loginWithAppRole for creating/renewing the client token.\r\n\r\nThe configuration passed thru to the SlimVaultClient includes the setting `userAgentEnabled = false`. When attempting to access the vault store, it will first attempt to get a token and it's at this point that the request fails with\r\n\r\n```\r\njava.lang.NullPointerException\r\n\tat io.vertx.ext.web.client.impl.HttpContext.handleSendRequest(HttpContext.java:469)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.execute(HttpContext.java:332)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.next(HttpContext.java:322)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.fire(HttpContext.java:289)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.sendRequest(HttpContext.java:193)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.handlePrepareRequest(HttpContext.java:404)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.execute(HttpContext.java:329)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.next(HttpContext.java:322)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.fire(HttpContext.java:289)\r\n\tat io.vertx.ext.web.client.impl.HttpContext.prepareRequest(HttpContext.java:180)\r\n\tat io.vertx.ext.web.client.impl.HttpRequestImpl.send(HttpRequestImpl.java:310)\r\n\tat io.vertx.ext.web.client.impl.HttpRequestImpl.sendJsonObject(HttpRequestImpl.java:290)\r\n\tat io.vertx.config.vault.client.SlimVaultClient.loginWithAppRole(SlimVaultClient.java:234)\r\n```\r\n\r\nIf the setting is changed to `userAgentEnabled = true` then the request proceeds OK.\r\n\r\nWhilst the bug was found in the vertx-config project, I think the error is in the processing of requests via the underlying WebClient _within_ the SlimVaultClient.\r\n\r\n```java\r\n// HttpContext line 459\r\nprivate void handleSendRequest() {\r\n if (request.headers != null) {\r\n MultiMap headers = requestOptions.getHeaders();\r\n if (headers == null) {\r\n headers = MultiMap.caseInsensitiveMultiMap();\r\n requestOptions.setHeaders(headers);\r\n }\r\n headers.addAll(request.headers);\r\n }\r\n if (contentType != null) {\r\n // !! at this point the options headers is always null when userAgentEnabled = true !!\r\n String prev = requestOptions.getHeaders().get(HttpHeaders.CONTENT_TYPE);\r\n if (prev == null) {\r\n requestOptions.addHeader(HttpHeaders.CONTENT_TYPE, contentType);\r\n } else {\r\n contentType = prev;\r\n }\r\n }\r\n```\r\n\r\n### Do you have a reproducer?\r\n\r\n```java\r\n@test fun testSlimVaultClient() {\r\n runBlocking {\r\n val client = SlimVaultClient(vertx, JsonObject()\r\n .put(\"host\", \"localhost\")\r\n .put(\"port\", 8500)\r\n .put(\"ssl\", false)\r\n .put(\"userAgentEnabled\", false))\r\n\r\n val promise = (vertx as VertxInternal).promise()\r\n\r\n println(\"Login\")\r\n client.loginWithAppRole(\"some.role\", \"some.secret\") {\r\n println(\"Handling\")\r\n if (it.failed()) {\r\n promise.fail(it.cause())\r\n } else {\r\n it.succeeded()\r\n }\r\n }\r\n\r\n println(\"Waiting\")\r\n promise.await()\r\n }\r\n}\r\n```\r\n\r\n### Steps to reproduce\r\n\r\n1. attempt to run the test above\r\n2. when `userAgentEnabled = true`, only _Login_ is printed\r\n3. when `userAgentEnabled = false`, _Login_ _Waiting_ and _Handling_ are printed\r\n\r\n### Extra\r\n\r\n* same code used to work in 4.0.0-milestone5 \r\n"},"base_sha":{"kind":"string","value":"b00221acf6a4809e87241e984a357bc5b20467b9"},"head_sha":{"kind":"string","value":"dfee825ee22a2610978565ce5f8be5fa6897dff3"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/b00221acf6a4809e87241e984a357bc5b20467b9...dfee825ee22a2610978565ce5f8be5fa6897dff3"},"diff":{"kind":"string","value":"diff --git a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java\nindex b83629198..a2c760d77 100644\n--- a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java\n+++ b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java\n@@ -79,6 +79,8 @@ public class HttpRequestImpl implements HttpRequest {\n this.options = options;\n if (options.isUserAgentEnabled()) {\n headers = HttpHeaders.set(HttpHeaders.USER_AGENT, options.getUserAgent());\n+ } else {\n+ headers = HttpHeaders.headers();\n }\n }\n \n@@ -92,7 +94,7 @@ public class HttpRequestImpl implements HttpRequest {\n this.host = other.host;\n this.timeout = other.timeout;\n this.uri = other.uri;\n- this.headers = other.headers != null ? HttpHeaders.headers().addAll(other.headers) : null;\n+ this.headers = other.headers != null ? HttpHeaders.headers().addAll(other.headers) : HttpHeaders.headers();\n this.params = other.params != null ? HttpHeaders.headers().addAll(other.params) : null;\n this.codec = other.codec;\n this.followRedirects = other.followRedirects;\ndiff --git a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java\nindex 3b0f6dabb..8f7912e44 100644\n--- a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java\n+++ b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java\n@@ -33,7 +33,6 @@ import org.junit.Test;\n import java.io.File;\n import java.io.FileNotFoundException;\n import java.net.ConnectException;\n-import java.net.URLEncoder;\n import java.nio.charset.StandardCharsets;\n import java.nio.file.Files;\n import java.util.*;\n@@ -135,6 +134,32 @@ public class WebClientTest extends WebClientTestBase {\n testRequest(client -> client.get(\"somehost\", \"somepath\"), req -> assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT)));\n }\n \n+ @Test\n+ public void testSendingJsonWithUserAgentDisabled() throws Exception {\n+ waitFor(2);\n+ server.requestHandler(req -> {\n+ assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT));\n+ try {\n+ complete();\n+ } finally {\n+ req.response().end();\n+ }\n+ });\n+ startServer();\n+\n+ JsonObject payload = new JsonObject().put(\"meaning\", 42);\n+\n+ WebClientOptions clientOptions = new WebClientOptions()\n+ .setDefaultHost(DEFAULT_HTTP_HOST)\n+ .setDefaultPort(DEFAULT_HTTP_PORT)\n+ .setUserAgentEnabled(false);\n+\n+ WebClient agentFreeClient = WebClient.create(vertx, clientOptions);\n+ HttpRequest builder = agentFreeClient.post(\"somehost\", \"somepath\");\n+ builder.sendJson(payload, onSuccess(resp -> complete()));\n+ await();\n+ }\n+\n @Test\n public void testUserAgentHeaderOverride() throws Exception {\n testRequest(client -> client.get(\"somehost\", \"somepath\").putHeader(HttpHeaders.USER_AGENT.toString(), \"smith\"), req -> assertEquals(Collections.singletonList(\"smith\"), req.headers().getAll(HttpHeaders.USER_AGENT)));"},"changed_files":{"kind":"string","value":"['vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java', 'vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1706875,"string":"1,706,875"},"repo_tokens_count":{"kind":"number","value":377581,"string":"377,581"},"repo_lines_count":{"kind":"number","value":52829,"string":"52,829"},"repo_files_without_tests_count":{"kind":"number","value":416,"string":"416"},"changed_symbols_count":{"kind":"number","value":262,"string":"262"},"changed_tokens_count":{"kind":"number","value":49,"string":"49"},"changed_lines_count":{"kind":"number","value":4,"string":"4"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":3569,"string":"3,569"},"issue_words_count":{"kind":"number","value":309,"string":"309"},"issue_tokens_count":{"kind":"number","value":753,"string":"753"},"issue_lines_count":{"kind":"number","value":92,"string":"92"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":3,"string":"3"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:47","string":"1970-01-01T00:26:47"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1663,"cells":{"id":{"kind":"number","value":1258,"string":"1,258"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1834/1825"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1825"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1834"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1834"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"RoutingContext.isFresh() returns false for IF-NONE-MATCH single value Header"},"issue_body":{"kind":"string","value":"Hi,\r\n\r\nwhile trying to use e-tag header for HTTP caching - I noticed the following behavior.\r\n\r\n### Version\r\n\r\n4.0.0\r\n\r\n### Context\r\n\r\nGiven a simple HTTP server sample using `ctx.isFresh()` method:\r\n\r\n```java\r\npackage io.vertx.reproducer;\r\n\r\nimport io.vertx.core.AbstractVerticle;\r\nimport io.vertx.core.Promise;\r\nimport io.vertx.ext.web.Router;\r\n\r\npublic class HttpServerVerticle extends AbstractVerticle {\r\n\r\n @Override\r\n public void start(Promise startPromise) throws Exception {\r\n final Router router = Router.router(vertx);\r\n\r\n router.route(\"/check/e-tag\").handler(ctx -> {\r\n ctx.etag(\"1234\");\r\n\r\n if (ctx.isFresh()) {\r\n ctx.response().setStatusCode(304).end(\"Not Modified\");\r\n } else {\r\n ctx.response().setStatusCode(200).end(\"OK\");\r\n }\r\n });\r\n\r\n vertx.createHttpServer()\r\n .requestHandler(router)\r\n .listen(8080)\r\n .onFailure(startPromise::fail)\r\n .onSuccess(server -> startPromise.complete());\r\n }\r\n\r\n}\r\n```\r\n\r\nWhen sending IF-NONE-MATCH header with value that is matching the ETag:\r\n\r\n```shell\r\n> curl -v 'http://localhost:8080/check/e-tag' -H 'IF-NONE-MATCH: \"1234\"'\r\n* Trying ::1:8080...\r\n* Connected to localhost (::1) port 8080 (#0)\r\n> GET /check/e-tag HTTP/1.1\r\n> Host: localhost:8080\r\n> User-Agent: curl/7.74.0\r\n> Accept: */*\r\n> IF-NONE-MATCH: \"1234\"\r\n> \r\n* Mark bundle as not supporting multiuse\r\n< HTTP/1.1 200 OK\r\n< etag: \"1234\"\r\n< content-length: 2\r\n< \r\n* Connection #0 to host localhost left intact\r\nOK% \r\n```\r\n\r\nI expect `ctx.isFresh()` to return `true` and my server to respond with Not Modified.\r\n\r\nInspecting the [code](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java#L171) it seems to me, that the only way an e-tag is not marked as stale is to have a `,` character in it. That might work when you send multiple values, but am I supposed to send a trailing comma for single value?\r\n\r\n```shell\r\n> curl -v 'http://localhost:8080/check/e-tag' -H 'IF-NONE-MATCH: \"1234\",'\r\n* Trying ::1:8080...\r\n* Connected to localhost (::1) port 8080 (#0)\r\n> GET /check/e-tag HTTP/1.1\r\n> Host: localhost:8080\r\n> User-Agent: curl/7.74.0\r\n> Accept: */*\r\n> IF-NONE-MATCH: \"1234\",\r\n> \r\n* Mark bundle as not supporting multiuse\r\n< HTTP/1.1 304 Not Modified\r\n< etag: \"1234\"\r\n< \r\n* Connection #0 to host localhost left intact\r\n```\r\n\r\nThis one returns the expected result.\r\n\r\nReferring to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag it seems valid to not send trailing comma. Am I missing something?\r\n\r\n### Do you have a reproducer?\r\n\r\nhttps://github.com/FrederikS/vertx-etag-none-match-reproducer\r\n"},"base_sha":{"kind":"string","value":"2c0d3e6b84bc4c30dc3a384e6e9309d3b95f324b"},"head_sha":{"kind":"string","value":"105040967214ab96d66ce29af48af4bf2ec2b4e2"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/2c0d3e6b84bc4c30dc3a384e6e9309d3b95f324b...105040967214ab96d66ce29af48af4bf2ec2b4e2"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java\nindex 2425fe96b..572f02319 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java\n@@ -161,7 +161,8 @@ public class Utils extends io.vertx.core.impl.Utils {\n int end = 0;\n int start = 0;\n \n- loop: for (int i = 0; i < noneMatch.length(); i++) {\n+ loop:\n+ for (int i = 0; i < noneMatch.length(); i++) {\n switch (noneMatch.charAt(i)) {\n case ' ':\n if (start == end) {\n@@ -183,7 +184,11 @@ public class Utils extends io.vertx.core.impl.Utils {\n }\n \n if (etagStale) {\n- return false;\n+ // the parser run out of bytes, need to check if the match is valid\n+ String match = noneMatch.substring(start, end);\n+ if (!match.equals(etag) && !match.equals(\"W/\" + etag) && !(\"W/\" + match).equals(etag)) {\n+ return false;\n+ }\n }\n }\n \n@@ -196,7 +201,7 @@ public class Utils extends io.vertx.core.impl.Utils {\n \n boolean modifiedStale = lastModified == -1 || !(lastModified <= parseRFC1123DateTime(modifiedSince));\n \n- return !modifiedStale;\n+ return !modifiedStale;\n }\n \n return true;\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\nindex 590602dae..1f3db5547 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n@@ -2904,4 +2904,25 @@ public class RouterTest extends WebTestBase {\n \n testRequest(HttpMethod.GET, \"/?u=\" + utf8 + \"&l=\" + latin1, 200, \"OK\");\n }\n+\n+ @Test\n+ public void testETag() throws Exception {\n+ router.route(\"/check/e-tag\").handler(ctx -> {\n+ ctx.etag(\"1234\");\n+\n+ if (ctx.isFresh()) {\n+ ctx.response().setStatusCode(304).end(\"Not Modified\");\n+ } else {\n+ ctx.response().setStatusCode(200).end(\"OK\");\n+ }\n+ });\n+\n+ testRequest(HttpMethod.GET, \"/check/e-tag\", req -> {\n+ req.putHeader(\"IF-NONE-MATCH\", \"\\\\\"1234\\\\\",\");\n+ }, 304, \"Not Modified\", \"\");\n+\n+ testRequest(HttpMethod.GET, \"/check/e-tag\", req -> {\n+ req.putHeader(\"IF-NONE-MATCH\", \"\\\\\"1234\\\\\"\");\n+ }, 304, \"Not Modified\", \"\");\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1707426,"string":"1,707,426"},"repo_tokens_count":{"kind":"number","value":377707,"string":"377,707"},"repo_lines_count":{"kind":"number","value":52854,"string":"52,854"},"repo_files_without_tests_count":{"kind":"number","value":416,"string":"416"},"changed_symbols_count":{"kind":"number","value":479,"string":"479"},"changed_tokens_count":{"kind":"number","value":126,"string":"126"},"changed_lines_count":{"kind":"number","value":11,"string":"11"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":2743,"string":"2,743"},"issue_words_count":{"kind":"number","value":307,"string":"307"},"issue_tokens_count":{"kind":"number","value":724,"string":"724"},"issue_lines_count":{"kind":"number","value":95,"string":"95"},"issue_links_count":{"kind":"number","value":5,"string":"5"},"issue_code_blocks_count":{"kind":"number","value":3,"string":"3"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:49","string":"1970-01-01T00:26:49"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1664,"cells":{"id":{"kind":"number","value":1236,"string":"1,236"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2300/2293"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2293"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2300"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2300"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"\"405 Method Not Allowed\" response not adding allow header"},"issue_body":{"kind":"string","value":"As per this document, https://vertx.io/docs/vertx-web/java/#_route_match_failures Vert.x-Web will signal a 405 error If a route matches the path but doesn’t match the HTTP Method, but as per Mozilla document https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 response should contain `allow` header. Is there any reason why it's not added in response?\r\n\r\nIt only adds `content-length` header\r\n\r\nVersion - 4.3.4"},"base_sha":{"kind":"string","value":"1231eab65a061c9e6f9497049b86d3a3a21394e1"},"head_sha":{"kind":"string","value":"8bcd7b50bd1a8bde897341df205121b4414e9287"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/1231eab65a061c9e6f9497049b86d3a3a21394e1...8bcd7b50bd1a8bde897341df205121b4414e9287"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\nindex c6959902b..07da73ab5 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n@@ -35,6 +35,7 @@ import io.vertx.ext.web.handler.impl.UserHolder;\n import java.nio.charset.Charset;\n import java.util.*;\n import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;\n+import java.util.stream.Collectors;\n \n import static io.vertx.ext.web.handler.impl.SessionHandlerImpl.SESSION_USER_HOLDER_KEY;\n \n@@ -158,6 +159,10 @@ public class RoutingContextImpl extends RoutingContextImplBase {\n this.response()\n .putHeader(HttpHeaderNames.CONTENT_TYPE, \"text/html; charset=utf-8\")\n .end(DEFAULT_404);\n+ } else if (this.request().method() != HttpMethod.HEAD && matchFailure == 405) {\n+ // If it's a 405 let's send a body too\n+ this.response()\n+ .putHeader(HttpHeaderNames.ALLOW, allowedMethods.stream().map(HttpMethod::name).collect(Collectors.joining(\",\"))).end();\n } else {\n this.response().end();\n }\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\nindex 58ff9d1f5..1e9860d95 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\n@@ -18,6 +18,7 @@ package io.vertx.ext.web.impl;\n \n import io.netty.handler.codec.http.HttpResponseStatus;\n import io.vertx.core.Handler;\n+import io.vertx.core.http.HttpMethod;\n import io.vertx.core.impl.logging.Logger;\n import io.vertx.core.impl.logging.LoggerFactory;\n import io.vertx.ext.web.Route;\n@@ -25,6 +26,7 @@ import io.vertx.ext.web.Router;\n import io.vertx.ext.web.RoutingContext;\n import io.vertx.ext.web.handler.HttpException;\n \n+import java.util.HashSet;\n import java.util.Iterator;\n import java.util.Set;\n import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;\n@@ -58,6 +60,8 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal {\n // internal runtime state\n private volatile long seen;\n \n+ protected Set allowedMethods = new HashSet<>();\n+\n RoutingContextImplBase(String mountPoint, Set routes, Router currentRouter) {\n this.mountPoint = mountPoint;\n this.routes = routes;\n@@ -179,6 +183,8 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal {\n }\n return true;\n } else if (matchResult == 405) {\n+ //We need to add supported methods for route in case we need to send 405 at end\n+ allowedMethods.addAll(routeState.getMethods());\n // invalid method match, means that\n // we should \"update\" the failure if not found to be invalid method\n if (this.matchFailure == 404) {\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\nindex d8eaa9b8d..fe0168e7d 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n@@ -2761,6 +2761,18 @@ public class RouterTest extends WebTestBase {\n testRequest(HttpMethod.PUT, \"/path\", HttpResponseStatus.METHOD_NOT_ALLOWED);\n }\n \n+ @Test\n+ public void testMethodNotAllowedHeader() throws Exception {\n+ router.get(\"/path\").handler(rc -> rc.response().end());\n+ router.post(\"/path\").handler(rc -> rc.response().end());\n+ router.put(\"/hello\").handler(rc -> rc.response().end());\n+ testRequest(HttpMethod.PUT, \"/path\", null, res -> {\n+ assertEquals(2, res.getHeader(\"allow\").split(\",\").length);\n+ assertTrue(res.getHeader(\"allow\").contains(\"GET\"));\n+ assertTrue(res.getHeader(\"allow\").contains(\"POST\"));\n+ }, HttpResponseStatus.METHOD_NOT_ALLOWED.code(), HttpResponseStatus.METHOD_NOT_ALLOWED.reasonPhrase(), null);\n+ }\n+\n @Test\n public void testNotAcceptableStatusCode() throws Exception {\n router.route().produces(\"text/html\").handler(rc -> rc.response().end());"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1970042,"string":"1,970,042"},"repo_tokens_count":{"kind":"number","value":437391,"string":"437,391"},"repo_lines_count":{"kind":"number","value":61089,"string":"61,089"},"repo_files_without_tests_count":{"kind":"number","value":482,"string":"482"},"changed_symbols_count":{"kind":"number","value":616,"string":"616"},"changed_tokens_count":{"kind":"number","value":132,"string":"132"},"changed_lines_count":{"kind":"number","value":11,"string":"11"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":419,"string":"419"},"issue_words_count":{"kind":"number","value":52,"string":"52"},"issue_tokens_count":{"kind":"number","value":104,"string":"104"},"issue_lines_count":{"kind":"number","value":5,"string":"5"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:47","string":"1970-01-01T00:27:47"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1665,"cells":{"id":{"kind":"number","value":1230,"string":"1,230"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2347/2319"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2319"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2347"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2319#issuecomment-1406925163"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"resolve"},"issue_title":{"kind":"string","value":"CORS headers not set on response for .* origin"},"issue_body":{"kind":"string","value":"### Version\r\n\r\nVertX 4.3.6\r\n\r\n### Context\r\n\r\nOn a HTTP-Request without `Origin` i would expect the CORS-Handler to set `Vary:Origin` and this was the case with 3.4.5. \r\nI'm not 100% sure about the CORS spec itself but considering that the Requests could be cached and looking at -> https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches it seems to me that the previous behavior was the correct one.\r\n\r\n### Do you have a reproducer?\r\n\r\nno\r\n\r\n### Steps to reproduce\r\n\r\n1. ` Router.router(vertx).route().handler(CorsHandler.create().addRelativeOrigin(\".*\").allowedMethod(GET))`\r\n2. `router.get(\"/path\").handler(rc -> rc.end(\"hello\"));`\r\n3. Call with a HttpClient asserting `ctx.assertNotNull(response.getHeaders().get(HttpHeaders.VARY))`\r\n\r\n### Extra\r\n\r\n* OpenJDK 19\r\n"},"base_sha":{"kind":"string","value":"79faa1baaa4e5292f945a56c30bfad60c3af6fb6"},"head_sha":{"kind":"string","value":"26919f07ea3510cde0c08b51255531a22e4c939b"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/79faa1baaa4e5292f945a56c30bfad60c3af6fb6...26919f07ea3510cde0c08b51255531a22e4c939b"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java\nindex 4df0ebfd5..1b938687d 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java\n@@ -234,7 +234,8 @@ public class CorsHandlerImpl implements CorsHandler {\n \n } else {\n // when it is possible to determine if only one origin is allowed, we can skip this extra caching header\n- if (!starOrigin() && !uniqueOrigin()) {\n+ // If allow credentials is set, the response cannot be '*' thus we need to vary on origin\n+ if (!(starOrigin() && !allowCredentials) && !uniqueOrigin()) {\n Utils.appendToMapIfAbsent(response.headers(), VARY, \",\", ORIGIN);\n }\n addCredentialsAndOriginHeader(response, origin);\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java\nindex 3dfe5dfc6..21c968b01 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java\n@@ -694,6 +694,30 @@ public class CORSHandlerTest extends WebTestBase {\n public void testCORSSetupStarOriginShouldNotHaveVary() throws Exception {\n // when we allow any origin, the response is not dependent on it, so we tell caches not to consider origin in\n // the cache key\n+ router\n+ .route()\n+ .handler(CorsHandler.create()\n+ .allowCredentials(false)\n+ .allowedHeader(\"Content-Type\")\n+ .allowedMethod(HttpMethod.GET)\n+ .allowedMethod(HttpMethod.POST)\n+ .allowedMethod(HttpMethod.OPTIONS)\n+ .allowedHeader(\"Access-Control-Allow-Origin\"))\n+ .handler(BodyHandler.create().setBodyLimit(1))\n+ .handler(context -> context.response().end());\n+\n+ testRequest(HttpMethod.POST, \"/\", req -> {\n+ req.headers().add(\"origin\", \"https://mydomain.org:3000\");\n+ }, resp -> {\n+ assertNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));\n+ assertNotNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));\n+ assertNull(resp.getHeader(HttpHeaders.VARY));\n+ }, 200, \"OK\", null);\n+ }\n+\n+ @Test\n+ public void testCORSSetupStarOriginWithAllowCredentialsShouldHaveVary() throws Exception {\n+ // When allow credentials is set with any origin, the response is dependent on the origin\n router\n .route()\n .handler(CorsHandler.create()\n@@ -711,7 +735,7 @@ public class CORSHandlerTest extends WebTestBase {\n }, resp -> {\n assertNotNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));\n assertNotNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));\n- assertNull(resp.getHeader(HttpHeaders.VARY));\n+ assertEquals(\"origin\", resp.getHeader(HttpHeaders.VARY));\n }, 200, \"OK\", null);\n }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1985499,"string":"1,985,499"},"repo_tokens_count":{"kind":"number","value":440889,"string":"440,889"},"repo_lines_count":{"kind":"number","value":61525,"string":"61,525"},"repo_files_without_tests_count":{"kind":"number","value":488,"string":"488"},"changed_symbols_count":{"kind":"number","value":219,"string":"219"},"changed_tokens_count":{"kind":"number","value":50,"string":"50"},"changed_lines_count":{"kind":"number","value":3,"string":"3"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":772,"string":"772"},"issue_words_count":{"kind":"number","value":90,"string":"90"},"issue_tokens_count":{"kind":"number","value":198,"string":"198"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:54","string":"1970-01-01T00:27:54"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1666,"cells":{"id":{"kind":"number","value":1267,"string":"1,267"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1639/1619"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1619"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1639"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1639"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"ApolloWS handler does not support messages sent in multiple frames"},"issue_body":{"kind":"string","value":"GraphQL Subscriptions websocket uses a handler instead of textMessageHandler resulting in lost messages since handler will be called for all binary / text / continuation frames.\r\n\r\nIn our case we should add a textMessageHandler since we want to concatenate messages when a continuation frame is received\r\n\r\nhttps://github.com/vert-x3/vertx-web/blob/13c10f88ec3b20e53950fd63ed740c9dc317f65a/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java#L71"},"base_sha":{"kind":"string","value":"129fedc24157d84dadefde44cfd186274f3fddb9"},"head_sha":{"kind":"string","value":"4eb7f7321e71f77c135311f171cd6727386eb72e"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/129fedc24157d84dadefde44cfd186274f3fddb9...4eb7f7321e71f77c135311f171cd6727386eb72e"},"diff":{"kind":"string","value":"diff --git a/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java b/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java\nindex abdd7e4ed..7394d8f96 100644\n--- a/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java\n+++ b/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java\n@@ -19,6 +19,7 @@ package io.vertx.ext.web.handler.graphql.impl;\n import graphql.ExecutionInput;\n import graphql.ExecutionResult;\n import io.vertx.core.Handler;\n+import io.vertx.core.buffer.Buffer;\n import io.vertx.core.http.ServerWebSocket;\n import io.vertx.core.impl.ContextInternal;\n import io.vertx.core.impl.logging.Logger;\n@@ -68,50 +69,52 @@ class ApolloWSConnectionHandler {\n ch.handle(serverWebSocket);\n }\n \n- serverWebSocket.handler(buffer -> {\n- JsonObject content = buffer.toJsonObject();\n- String opId = content.getString(\"id\");\n- ApolloWSMessageType type = from(content.getString(\"type\"));\n+ serverWebSocket.binaryMessageHandler(this::handleBinaryMessage);\n+ serverWebSocket.textMessageHandler(this::handleTextMessage);\n+ serverWebSocket.closeHandler(this::close);\n+ }\n \n- if (type == null) {\n- sendMessage(opId, ERROR, \"Unknown message type: \" + content.getString(\"type\"));\n- return;\n- }\n+ private void handleBinaryMessage(Buffer buffer) {\n+ handleMessage(new JsonObject(buffer));\n+ }\n \n- ApolloWSMessage message = new ApolloWSMessageImpl(serverWebSocket, type, content);\n+ private void handleTextMessage(String text) {\n+ handleMessage(new JsonObject(text));\n+ }\n \n- Handler mh = apolloWSHandler.getMessageHandler();\n- if (mh != null) {\n- mh.handle(message);\n- }\n+ private void handleMessage(JsonObject jsonObject) {\n+ String opId = jsonObject.getString(\"id\");\n+ ApolloWSMessageType type = from(jsonObject.getString(\"type\"));\n \n- switch (type) {\n- case CONNECTION_INIT:\n- connect();\n- break;\n- case CONNECTION_TERMINATE:\n- serverWebSocket.close();\n- break;\n- case START:\n- start(message);\n- break;\n- case STOP:\n- stop(opId);\n- break;\n- default:\n- sendMessage(opId, ERROR, \"Unsupported message type: \" + type);\n- break;\n- }\n- });\n+ if (type == null) {\n+ sendMessage(opId, ERROR, \"Unknown message type: \" + jsonObject.getString(\"type\"));\n+ return;\n+ }\n \n- serverWebSocket.closeHandler(v -> {\n- subscriptions.values().forEach(Subscription::cancel);\n+ ApolloWSMessage message = new ApolloWSMessageImpl(serverWebSocket, type, jsonObject);\n \n- Handler eh = apolloWSHandler.getEndHandler();\n- if (eh != null) {\n- eh.handle(serverWebSocket);\n- }\n- });\n+ Handler mh = apolloWSHandler.getMessageHandler();\n+ if (mh != null) {\n+ mh.handle(message);\n+ }\n+\n+ switch (type) {\n+ case CONNECTION_INIT:\n+ connect();\n+ break;\n+ case CONNECTION_TERMINATE:\n+ serverWebSocket.close();\n+ break;\n+ case START:\n+ start(message);\n+ break;\n+ case STOP:\n+ stop(opId);\n+ break;\n+ default:\n+ sendMessage(opId, ERROR, \"Unsupported message type: \" + type);\n+ break;\n+ }\n }\n \n private void connect() {\n@@ -250,4 +253,13 @@ class ApolloWSConnectionHandler {\n }\n serverWebSocket.writeTextMessage(message.toString());\n }\n+\n+ private void close(Void v) {\n+ subscriptions.values().forEach(Subscription::cancel);\n+\n+ Handler eh = apolloWSHandler.getEndHandler();\n+ if (eh != null) {\n+ eh.handle(serverWebSocket);\n+ }\n+ }\n }\ndiff --git a/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java b/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java\nindex d282ab59e..d09c4789d 100644\n--- a/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java\n+++ b/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java\n@@ -25,7 +25,10 @@ import graphql.schema.idl.SchemaParser;\n import graphql.schema.idl.TypeDefinitionRegistry;\n import io.vertx.core.AsyncResult;\n import io.vertx.core.Handler;\n+import io.vertx.core.buffer.Buffer;\n import io.vertx.core.http.HttpClientOptions;\n+import io.vertx.core.http.WebSocket;\n+import io.vertx.core.http.WebSocketFrame;\n import io.vertx.core.json.JsonObject;\n import io.vertx.core.net.NetClientOptions;\n import io.vertx.core.net.NetServer;\n@@ -40,6 +43,7 @@ import java.util.Map;\n import java.util.concurrent.CountDownLatch;\n import java.util.concurrent.atomic.AtomicInteger;\n import java.util.concurrent.atomic.AtomicReference;\n+import java.util.function.BiConsumer;\n import java.util.stream.IntStream;\n \n import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;\n@@ -132,8 +136,8 @@ public class ApolloWSHandlerTest extends WebTestBase {\n \n AtomicReference id = new AtomicReference<>();\n AtomicInteger counter = new AtomicInteger();\n- websocket.handler(buffer -> {\n- JsonObject obj = buffer.toJsonObject();\n+ websocket.textMessageHandler(text -> {\n+ JsonObject obj = new JsonObject(text);\n int current = counter.getAndIncrement();\n if (current >= 0 && current <= MAX_COUNT) {\n if (current == 0) {\n@@ -166,14 +170,30 @@ public class ApolloWSHandlerTest extends WebTestBase {\n \n @Test\n public void testQueryWsCall() {\n+ testQueryWsCall((webSocket, message) -> webSocket.write(message.toBuffer()));\n+ }\n+\n+ @Test\n+ public void testQueryWsCallMultipleFrames() {\n+ testQueryWsCall((webSocket, message) -> {\n+ Buffer buffer = message.toBuffer();\n+ int part = buffer.length() / 3;\n+ if (part == 0) fail(\"Cannot perform test\");\n+ webSocket.writeFrame(WebSocketFrame.binaryFrame(buffer.getBuffer(0, part), false));\n+ webSocket.writeFrame(WebSocketFrame.continuationFrame(buffer.getBuffer(part, 2 * part), false));\n+ webSocket.writeFrame(WebSocketFrame.continuationFrame(buffer.getBuffer(2 * part, buffer.length()), true));\n+ });\n+ }\n+\n+ private void testQueryWsCall(BiConsumer sender) {\n waitFor(2);\n client.webSocket(\"/graphql\", onSuccess(websocket -> {\n websocket.exceptionHandler(this::fail);\n \n AtomicReference id = new AtomicReference<>();\n AtomicInteger counter = new AtomicInteger();\n- websocket.handler(buffer -> {\n- JsonObject obj = buffer.toJsonObject();\n+ websocket.textMessageHandler(text -> {\n+ JsonObject obj = new JsonObject(text);\n int current = counter.getAndIncrement();\n if (current == 0) {\n assertTrue(id.compareAndSet(null, obj.getString(\"id\")));\n@@ -195,7 +215,7 @@ public class ApolloWSHandlerTest extends WebTestBase {\n .put(\"query\", \"query Query { staticCounter { count } }\"))\n .put(\"type\", \"start\")\n .put(\"id\", \"1\");\n- websocket.write(message.toBuffer());\n+ sender.accept(websocket, message);\n }));\n await();\n }\n@@ -224,9 +244,9 @@ public class ApolloWSHandlerTest extends WebTestBase {\n websocket.exceptionHandler(this::fail);\n \n AtomicInteger counter = new AtomicInteger(0);\n- websocket.handler(buffer -> {\n+ websocket.textMessageHandler(text -> {\n try {\n- JsonObject obj = buffer.toJsonObject();\n+ JsonObject obj = new JsonObject(text);\n \n if (counter.getAndIncrement() == 0) {\n assertEquals(ApolloWSMessageType.CONNECTION_ACK.getText(), obj.getString(\"type\"));\n@@ -261,7 +281,7 @@ public class ApolloWSHandlerTest extends WebTestBase {\n websocket.exceptionHandler(this::fail);\n \n AtomicInteger counter = new AtomicInteger();\n- websocket.handler(buffer -> {\n+ websocket.textMessageHandler(text -> {\n if (counter.getAndIncrement() == MAX_COUNT) {\n if (subscriptionRef.get() == null) {\n fail(\"Expected a live subscription\");"},"changed_files":{"kind":"string","value":"['vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java', 'vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1611540,"string":"1,611,540"},"repo_tokens_count":{"kind":"number","value":355944,"string":"355,944"},"repo_lines_count":{"kind":"number","value":49888,"string":"49,888"},"repo_files_without_tests_count":{"kind":"number","value":402,"string":"402"},"changed_symbols_count":{"kind":"number","value":2846,"string":"2,846"},"changed_tokens_count":{"kind":"number","value":568,"string":"568"},"changed_lines_count":{"kind":"number","value":88,"string":"88"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":494,"string":"494"},"issue_words_count":{"kind":"number","value":47,"string":"47"},"issue_tokens_count":{"kind":"number","value":119,"string":"119"},"issue_lines_count":{"kind":"number","value":5,"string":"5"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:32","string":"1970-01-01T00:26:32"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1667,"cells":{"id":{"kind":"number","value":1232,"string":"1,232"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2406/1935"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1935"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2406"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2406"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"Log (LoggerHandlerImpl) swallows/loses log if client closes connection."},"issue_body":{"kind":"string","value":"As discussed from: https://github.com/eclipse-vertx/vert.x/issues/3902\r\n\r\nVersion\r\n3.9.x\r\n\r\nContext\r\nLog is not logged\r\n\r\nDo you have a reproducer?\r\nNo.\r\n\r\nSteps to reproduce\r\nThis is coming from conversation here: https://groups.google.com/g/vertx/c/CZaPXYk2MA0\r\n\r\nAdd LoggerHandlerImpl to your route as early as possible. Make sure immediate is false, so that the log gets loged at the end of the request to ensure that context.addBodyEndHandler(v -> log(context, timestamp, remoteClient, version, method, uri)); is used.\r\n\r\nHave client connect and drop close the connection before response is returned."},"base_sha":{"kind":"string","value":"01794a9f52c06fb496916f3095a0174d8b57f352"},"head_sha":{"kind":"string","value":"f2e96ec91594a83c019c40d9a2c6ae45301b3f10"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/01794a9f52c06fb496916f3095a0174d8b57f352...f2e96ec91594a83c019c40d9a2c6ae45301b3f10"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java\nindex 5a5c8ca2e..a521f1500 100755\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java\n@@ -57,7 +57,6 @@ public class LoggerHandlerImpl implements LoggerHandler {\n */\n private final LoggerFormat format;\n \n- private Function customFormatter;\n private LoggerFormatter logFormatter;\n \n public LoggerHandlerImpl(boolean immediate, LoggerFormat format) {\n@@ -147,11 +146,7 @@ public class LoggerHandlerImpl implements LoggerHandler {\n break;\n case CUSTOM:\n try {\n- if (logFormatter != null) {\n- message = logFormatter.format(context, (System.currentTimeMillis() - timestamp));\n- } else {\n- message = customFormatter.apply(request);\n- }\n+ message = logFormatter.format(context, (System.currentTimeMillis() - timestamp));\n } catch (RuntimeException e) {\n // if an error happens at the user side\n // log it instead\n@@ -183,7 +178,7 @@ public class LoggerHandlerImpl implements LoggerHandler {\n if (immediate) {\n log(context, timestamp, remoteClient, version, method, uri);\n } else {\n- context.addBodyEndHandler(v -> log(context, timestamp, remoteClient, version, method, uri));\n+ context.addEndHandler(v -> log(context, timestamp, remoteClient, version, method, uri));\n }\n \n context.next();"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1751923,"string":"1,751,923"},"repo_tokens_count":{"kind":"number","value":391757,"string":"391,757"},"repo_lines_count":{"kind":"number","value":55275,"string":"55,275"},"repo_files_without_tests_count":{"kind":"number","value":443,"string":"443"},"changed_symbols_count":{"kind":"number","value":574,"string":"574"},"changed_tokens_count":{"kind":"number","value":109,"string":"109"},"changed_lines_count":{"kind":"number","value":9,"string":"9"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":605,"string":"605"},"issue_words_count":{"kind":"number","value":78,"string":"78"},"issue_tokens_count":{"kind":"number","value":146,"string":"146"},"issue_lines_count":{"kind":"number","value":17,"string":"17"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:28:00","string":"1970-01-01T00:28:00"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1668,"cells":{"id":{"kind":"number","value":1252,"string":"1,252"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1984/1983"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1983"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1984"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1984"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Pause/Resume missing in AuthorizationHandlerImpl? IllegalStateException: Request has already been read"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.1.0\r\n\r\n### Context\r\n\r\nWhen using async operations in implementations of `AuthorizationProvider.getAuthorizations` then a `BodyHandler` added after an `AuthorizationHandler` that uses that `AuthorizationProvider` (created with `AuthorizationHandler.create`) causes that requests with body may fail due to:\r\n\r\n```\r\njava.lang.IllegalStateException: Request has already been read\r\n\tat io.vertx.core.http.impl.Http1xServerRequest.checkEnded(Http1xServerRequest.java:627)\r\n\tat io.vertx.core.http.impl.Http1xServerRequest.handler(Http1xServerRequest.java:287)\r\n\tat io.vertx.ext.web.impl.HttpServerRequestWrapper.handler(HttpServerRequestWrapper.java:97)\r\n\tat io.vertx.ext.web.handler.impl.BodyHandlerImpl.handle(BodyHandlerImpl.java:85)\r\n\tat io.vertx.ext.web.handler.impl.BodyHandlerImpl.handle(BodyHandlerImpl.java:44)\r\n\tat io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1127)\r\n\tat io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:114)\r\n\tat io.vertx.ext.web.impl.RoutingContextWrapper.next(RoutingContextWrapper.java:201)\r\n\tat io.vertx.ext.web.handler.impl.AuthorizationHandlerImpl.checkOrFetchAuthorizations(AuthorizationHandlerImpl.java:79)\r\n\tat io.vertx.ext.web.handler.impl.AuthorizationHandlerImpl.lambda$checkOrFetchAuthorizations$0(AuthorizationHandlerImpl.java:99)\r\n\tat io.vertx.core.impl.future.FutureImpl$3.onSuccess(FutureImpl.java:124)\r\n```\r\n\r\nI have noticed that counter measures have been taken in `AuthenticationHandlerImpl` with this [commit]( https://github.com/vert-x3/vertx-web/commit/937d1e73bda0e90789a9ced17ec2c5a800bdbf0b#diff-5b9edb22f0e308c1a7a43e62f17550732cea30ff9215305686994ff27674975d) where `request.pause()` and `request.resume()` are utilized. Unfortunately - as implementer of an `AuthorizationProvider` I have no way of adding this functionality by myself without copying/extending `AuthorizationHandlerImpl`.\r\n"},"base_sha":{"kind":"string","value":"97917b0ad77ee80bfd6d65ca2f87b57ff3ad2d6a"},"head_sha":{"kind":"string","value":"bc9a0366a6d09477b5d701d58029bc73dd622cd2"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/97917b0ad77ee80bfd6d65ca2f87b57ff3ad2d6a...bc9a0366a6d09477b5d701d58029bc73dd622cd2"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\nindex bdb61f542..d735cf00a 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\n@@ -53,10 +53,22 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n if (routingContext.user() == null) {\n routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);\n } else {\n- // create the authorization context\n- AuthorizationContext authorizationContext = getAuthorizationContext(routingContext);\n- // check or fetch authorizations\n- checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator());\n+ // before starting any potential async operation here\n+ // pause parsing the request body. The reason is that\n+ // we don't want to loose the body or protocol upgrades\n+ // for async operations\n+ routingContext.request().pause();\n+\n+ try {\n+ // create the authorization context\n+ AuthorizationContext authorizationContext = getAuthorizationContext(routingContext);\n+ // check or fetch authorizations\n+ checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator());\n+ } catch (RuntimeException e) {\n+ // resume as the error handler may allow this request to become valid again\n+ routingContext.request().resume();\n+ routingContext.fail(e);\n+ }\n }\n }\n \n@@ -76,10 +88,14 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n */\n private void checkOrFetchAuthorizations(RoutingContext routingContext, AuthorizationContext authorizationContext, Iterator providers) {\n if (authorization.match(authorizationContext)) {\n+ // resume the processing of the request\n+ routingContext.request().resume();\n routingContext.next();\n return;\n }\n if (!providers.hasNext()) {\n+ // resume as the error handler may allow this request to become valid again\n+ routingContext.request().resume();\n routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);\n return;\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1757869,"string":"1,757,869"},"repo_tokens_count":{"kind":"number","value":389260,"string":"389,260"},"repo_lines_count":{"kind":"number","value":54421,"string":"54,421"},"repo_files_without_tests_count":{"kind":"number","value":434,"string":"434"},"changed_symbols_count":{"kind":"number","value":1268,"string":"1,268"},"changed_tokens_count":{"kind":"number","value":221,"string":"221"},"changed_lines_count":{"kind":"number","value":24,"string":"24"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1909,"string":"1,909"},"issue_words_count":{"kind":"number","value":107,"string":"107"},"issue_tokens_count":{"kind":"number","value":452,"string":"452"},"issue_lines_count":{"kind":"number","value":25,"string":"25"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:04","string":"1970-01-01T00:27:04"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1669,"cells":{"id":{"kind":"number","value":1248,"string":"1,248"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2035/1817"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1817"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2035"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2035"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"Enable loading OpenAPI YAML from classpath"},"issue_body":{"kind":"string","value":"#### Feature Description\r\n\r\nI'd like to load an OpenAPI YAML for router creation from a file that's bundled in a JAR. However, when using `getResource` to determine the URI to the bundled file, an exception is thrown:\r\n\r\n```\r\nio.vertx.ext.web.openapi.RouterBuilderException: Cannot load the spec in path file:/path/to/app.jar!/api/core_1.0.0.yaml\r\n```\r\n\r\nIdeally [RouterBuilder.create](https://vertx.io/docs/apidocs/io/vertx/ext/web/openapi/RouterBuilder.html#create-io.vertx.core.Vertx-java.lang.String-) should be adapted to be able to load any URI, even those pointing to files in the JAR.\r\n\r\n#### Contribution\r\n\r\nNot sure how much work this is. I'd think that it's something that can be implemented in a couple of minutes but maybe it needs some larger refactoring.\r\nIf it's not too much work, I'm open to get acquainted with the codebase and implement it. However I'd appreciate if someone could give me a few pointers on possible approaches."},"base_sha":{"kind":"string","value":"faff38257bcf4c9608a645ca151ae8fe56d6f920"},"head_sha":{"kind":"string","value":"51e13bbef6d7a52d7eb6019a87818163ced80ed1"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/faff38257bcf4c9608a645ca151ae8fe56d6f920...51e13bbef6d7a52d7eb6019a87818163ced80ed1"},"diff":{"kind":"string","value":"diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java\nindex c092f22bb..66cb0ebe1 100755\n--- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java\n+++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java\n@@ -375,6 +375,7 @@ public class OpenAPIHolderImpl implements OpenAPIHolder {\n try {\n switch (uri.getScheme()) {\n case \"http\":\n+ case \"https\":\n return Paths.get(uri.getPath());\n case \"file\":\n return Paths.get(uri);"},"changed_files":{"kind":"string","value":"['vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1772442,"string":"1,772,442"},"repo_tokens_count":{"kind":"number","value":392555,"string":"392,555"},"repo_lines_count":{"kind":"number","value":54835,"string":"54,835"},"repo_files_without_tests_count":{"kind":"number","value":436,"string":"436"},"changed_symbols_count":{"kind":"number","value":22,"string":"22"},"changed_tokens_count":{"kind":"number","value":5,"string":"5"},"changed_lines_count":{"kind":"number","value":1,"string":"1"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":947,"string":"947"},"issue_words_count":{"kind":"number","value":128,"string":"128"},"issue_tokens_count":{"kind":"number","value":217,"string":"217"},"issue_lines_count":{"kind":"number","value":14,"string":"14"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:10","string":"1970-01-01T00:27:10"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1670,"cells":{"id":{"kind":"number","value":1249,"string":"1,249"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2031/2030"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2030"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2031"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2031"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"HTTP/2, BodyHandler together with AuthorizationHandler - IllegalStateException Request has already been read"},"issue_body":{"kind":"string","value":"### Version\r\n\r\nvertx-web 4.1.0 - 4.2.0.Beta.1 (since this [commit](https://github.com/vert-x3/vertx-web/commit/bc9a0366a6d09477b5d701d58029bc73dd622cd2))\r\n\r\n### Context\r\n\r\n* BodyHandler together with a `AuthorizationHandler.create(RoleBasedAuthorization.create(\"operator\"))` and Http 2 requests.\r\n\r\n### Do you have a reproducer?\r\n\r\nhttps://github.com/DemonicTutor/vertx-web-aaa\r\n\r\n### Extra\r\n\r\n* OpenJDK 16\r\n"},"base_sha":{"kind":"string","value":"342982409d38e2defff1587c99c2ddcfd5c1aec3"},"head_sha":{"kind":"string","value":"24b2c593bfdc491e24a18d5a68f7785c5f6a0f31"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/342982409d38e2defff1587c99c2ddcfd5c1aec3...24b2c593bfdc491e24a18d5a68f7785c5f6a0f31"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\nindex d735cf00a..28e51519e 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\n@@ -18,6 +18,8 @@ import java.util.Iterator;\n import java.util.Objects;\n import java.util.function.BiConsumer;\n \n+import io.vertx.core.http.HttpHeaders;\n+import io.vertx.core.http.HttpServerRequest;\n import io.vertx.core.impl.logging.Logger;\n import io.vertx.core.impl.logging.LoggerFactory;\n import io.vertx.ext.auth.authorization.Authorization;\n@@ -57,16 +59,18 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n // pause parsing the request body. The reason is that\n // we don't want to loose the body or protocol upgrades\n // for async operations\n- routingContext.request().pause();\n-\n+ final boolean parseEnded = routingContext.request().isEnded();\n+ if (!parseEnded) {\n+ routingContext.request().pause();\n+ }\n try {\n // create the authorization context\n AuthorizationContext authorizationContext = getAuthorizationContext(routingContext);\n // check or fetch authorizations\n- checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator());\n+ checkOrFetchAuthorizations(routingContext, parseEnded, authorizationContext, authorizationProviders.iterator());\n } catch (RuntimeException e) {\n // resume as the error handler may allow this request to become valid again\n- routingContext.request().resume();\n+ resume(routingContext.request(), parseEnded);\n routingContext.fail(e);\n }\n }\n@@ -86,16 +90,16 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n * @param authorizationContext the current authorization context\n * @param providers the providers iterator\n */\n- private void checkOrFetchAuthorizations(RoutingContext routingContext, AuthorizationContext authorizationContext, Iterator providers) {\n+ private void checkOrFetchAuthorizations(RoutingContext routingContext, boolean parseEnded, AuthorizationContext authorizationContext, Iterator providers) {\n if (authorization.match(authorizationContext)) {\n // resume the processing of the request\n- routingContext.request().resume();\n+ resume(routingContext.request(), parseEnded);\n routingContext.next();\n return;\n }\n if (!providers.hasNext()) {\n // resume as the error handler may allow this request to become valid again\n- routingContext.request().resume();\n+ resume(routingContext.request(), parseEnded);\n routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);\n return;\n }\n@@ -112,7 +116,7 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n LOG.warn(\"An error occured getting authorization - providerId: \" + provider.getId(), authorizationResult.cause());\n // note that we don't 'record' the fact that we tried to fetch the authorization provider. therefore it will be re-fetched later-on\n }\n- checkOrFetchAuthorizations(routingContext, authorizationContext, providers);\n+ checkOrFetchAuthorizations(routingContext, parseEnded, authorizationContext, providers);\n });\n // get out right now as the callback will decide what to do next\n return;\n@@ -135,4 +139,10 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n this.authorizationProviders.add(authorizationProvider);\n return this;\n }\n+\n+ private void resume(HttpServerRequest request, final boolean parseEnded) {\n+ if (!parseEnded && !request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) {\n+ request.resume();\n+ }\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1771962,"string":"1,771,962"},"repo_tokens_count":{"kind":"number","value":392449,"string":"392,449"},"repo_lines_count":{"kind":"number","value":54825,"string":"54,825"},"repo_files_without_tests_count":{"kind":"number","value":436,"string":"436"},"changed_symbols_count":{"kind":"number","value":1551,"string":"1,551"},"changed_tokens_count":{"kind":"number","value":280,"string":"280"},"changed_lines_count":{"kind":"number","value":26,"string":"26"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":408,"string":"408"},"issue_words_count":{"kind":"number","value":33,"string":"33"},"issue_tokens_count":{"kind":"number","value":129,"string":"129"},"issue_lines_count":{"kind":"number","value":16,"string":"16"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:10","string":"1970-01-01T00:27:10"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1671,"cells":{"id":{"kind":"number","value":1245,"string":"1,245"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2124/2123"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2123"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2124"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2124"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"SessionHandler doesn't callback the handler of method flush in some cases"},"issue_body":{"kind":"string","value":"### Questions\r\n\r\nSessionHandler doesn't callback the handler of method flush in some cases, leaving some user defined actions uncomplished in the handler.\r\n\r\n### Version\r\n\r\nvertx-web 3.9.12\r\n\r\n### Context\r\n\r\nHi, we are developing website with Vert.x framework. When we tested the session feature based on the Vert.x `SessionHandler`, we find that sometimes the HTTP response has reached the browser while the session storage action is not finished.(We extended the `SessionStore` to put session into our cache server, sometime it may not act quickly) The root cause is the default logic of Vert.x `SessionHandler` is to flush session in the \"HeadersEndHandler\", and it does not ensure the response is sent after the session is flushed properly.\r\n\r\nAfter searching some issues, we find this is the expected behavior. So we decide to run the `flush` method manually and write the response after the flush action is done. But we find the `flush` method of `SessionHandlerImpl` does not always callback the `handler`. The `handler` are only called back when the session is actually stored. If the response indicates error(status code 4xx/5xx) or the session is not touched or some other cases, the session will not be actually written into the `SessionStore` and the `handler` is not called.\r\n\r\nThis is a problem for those who want to do something after the session flush procedure ends. Because in some cases, the \"end\" is never shown to the caller of `flush` method.\r\n\r\n### Do you have a reproducer?\r\n\r\nHere is a reproducer:\r\n\r\n```java\r\npublic class Demo {\r\n\r\n private static Vertx vertx = Vertx.vertx();\r\n\r\n private static int flag = 0;\r\n\r\n public static void main(String[] args) {\r\n final HttpServer httpServer = vertx.createHttpServer(new HttpServerOptions()\r\n .setIdleTimeout(10));\r\n final Router router = Router.router(vertx);\r\n final SessionHandler sessionHandler = SessionHandler.create(LocalSessionStore.create(vertx))\r\n .setSessionTimeout(10_000)\r\n .setLazySession(true);\r\n\r\n router.route().handler(sessionHandler);\r\n router.route().handler(ctx -> {\r\n System.out.println(\"get request\");\r\n\r\n final HttpServerResponse response = ctx.response();\r\n ctx.session();\r\n if ((++flag & 1) == 0) {\r\n response.setStatusCode(500);\r\n } else {\r\n response.setStatusCode(200);\r\n }\r\n\r\n sessionHandler.flush(ctx, asyncResult -> {\r\n System.out.println(\"get session flush result: \" + asyncResult.succeeded());\r\n response.putHeader(\"Content-Type\", \"text/plain\");\r\n response.end(\"Hello World!\");\r\n ctx.next();\r\n });\r\n });\r\n httpServer.requestHandler(router).listen(9999);\r\n }\r\n}\r\n```\r\n\r\nOnly the vertx-web dependency is needed for this demo.\r\n\r\n### Steps to reproduce\r\n\r\n1. run the demo above\r\n2. curl `http://localhost:9999/`\r\n\r\nI've made the server response `200` and `500` alternately. And when 200 is returned, the client will get response instantly, while when 500 should be returned, the server will hang the connection until the connection idle timed out.\r\n\r\n### Extra\r\n\r\nI'm not sure whether this is the expected behavior of `SessionHandler`. But I guess people who want to ensure the order between \"flush session\" and some \"finish action\" may be troubled by this behavior. Is it possible to fix this problem?\r\n\r\nLooking forward to your reply, and thank you very much."},"base_sha":{"kind":"string","value":"91a1b2ade0d5af86aeb38231a919a5013a33ad99"},"head_sha":{"kind":"string","value":"92fd0ac40396c9fdeff54e3c47801d22987ca5cf"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/91a1b2ade0d5af86aeb38231a919a5013a33ad99...92fd0ac40396c9fdeff54e3c47801d22987ca5cf"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java\nindex 40d6efbdc..e07b7ac85 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java\n@@ -238,6 +238,8 @@ public class SessionHandlerImpl implements SessionHandler {\n }\n });\n }\n+ } else {\n+ handler.handle(Future.failedFuture(\"Skipping session store: ignoreStatus || (currentStatusCode >= 200 && currentStatusCode < 400)\"));\n }\n } else {\n if (!cookieless) {\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java\nindex 9b9fb7112..8b4948308 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java\n@@ -16,6 +16,8 @@\n \n package io.vertx.ext.web.sstore;\n \n+import io.vertx.core.http.HttpMethod;\n+import io.vertx.ext.web.handler.SessionHandler;\n import io.vertx.ext.web.handler.SessionHandlerTestBase;\n import org.junit.Test;\n \n@@ -34,4 +36,25 @@ public class LocalSessionHandlerTest extends SessionHandlerTestBase {\n public void testRetryTimeout() throws Exception {\n assertTrue(doTestSessionRetryTimeout() < 3000);\n }\n+\n+ @Test\n+ public void test2123() throws Exception {\n+ SessionHandler sessionHandler = SessionHandler.create(LocalSessionStore.create(vertx))\n+ .setSessionTimeout(10_000)\n+ .setLazySession(true);\n+\n+ router.clear();\n+\n+ router.route().handler(sessionHandler);\n+ router.route().handler(ctx -> {\n+ ctx.session();\n+ ctx.response().setStatusCode(500);\n+ sessionHandler.flush(ctx, asyncResult -> {\n+ assertTrue(asyncResult.failed());\n+ ctx.end();\n+ });\n+ });\n+\n+ testRequest(HttpMethod.GET, \"/\", 500, \"Internal Server Error\");\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java', 'vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1906750,"string":"1,906,750"},"repo_tokens_count":{"kind":"number","value":423047,"string":"423,047"},"repo_lines_count":{"kind":"number","value":59207,"string":"59,207"},"repo_files_without_tests_count":{"kind":"number","value":462,"string":"462"},"changed_symbols_count":{"kind":"number","value":158,"string":"158"},"changed_tokens_count":{"kind":"number","value":33,"string":"33"},"changed_lines_count":{"kind":"number","value":2,"string":"2"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":3532,"string":"3,532"},"issue_words_count":{"kind":"number","value":446,"string":"446"},"issue_tokens_count":{"kind":"number","value":735,"string":"735"},"issue_lines_count":{"kind":"number","value":73,"string":"73"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:24","string":"1970-01-01T00:27:24"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1672,"cells":{"id":{"kind":"number","value":1244,"string":"1,244"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2140/2136"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2136"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2140"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2140"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"Subrouter fails if mounted on another subrouter on path with path params"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.2.4 and 4.3.0-SNAPSHOT\r\n\r\n### Context\r\n\r\nIf subrouter is NOT mounted on root router (but instead on another subrouter) and its path contains parameters, then routing fails with 404 and well-known HTML output \"Resource not found\".\r\n\r\n### Do you have a reproducer?\r\n\r\nBy modifying [SubRouterTest#testSimpleWithParams](https://github.com/vert-x3/vertx-web/blob/8d1c667a6848ed71753d4dd7d314cb8492fb09a2/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java#L460) I constructed test that fails:\r\n\r\n```\r\n @Test // Fails!\r\n public void testHierarchicalWithParams() throws Exception {\r\n\r\n Router restRouter = Router.router(vertx);\r\n Router subRouter = Router.router(vertx);\r\n\r\n subRouter.get(\"/files\").handler(ctx -> {\r\n // version is extracted from the root router\r\n assertEquals(\"1\", ctx.pathParam(\"version\"));\r\n ctx.response().end();\r\n });\r\n\r\n restRouter.mountSubRouter(\"/:version\", subRouter);\r\n\r\n router.mountSubRouter(\"/rest\", restRouter);\r\n\r\n testRequest(HttpMethod.GET, \"/rest/1/files\", 200, \"OK\");\r\n }\r\n```\r\n\r\nAnother interesting fact is that subrouter will work if it has path params too (!):\r\n\r\n```\r\n @Test // Passes\r\n public void testHierarchicalWithParamsInAllRouters() throws Exception {\r\n\r\n Router restRouter = Router.router(vertx);\r\n Router subRouter = Router.router(vertx);\r\n\r\n subRouter.get(\"/files/:id\").handler(ctx -> {\r\n // version is extracted from the root router\r\n assertEquals(\"1\", ctx.pathParam(\"version\"));\r\n // id is extracted from this router\r\n assertEquals(\"2\", ctx.pathParam(\"id\"));\r\n ctx.response().end();\r\n });\r\n\r\n restRouter.mountSubRouter(\"/:version\", subRouter);\r\n\r\n router.mountSubRouter(\"/rest\", restRouter);\r\n\r\n testRequest(HttpMethod.GET, \"/rest/1/files/2\", 200, \"OK\");\r\n }\r\n```\r\n### Steps to reproduce\r\n\r\n1. Add those tests to [SubRouterTest.java](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java)\r\n2. Run tests with `mvn -Dtest=SubRouterTest test -pl vertx-web`\r\n\r\n### Extra\r\n\r\n* OS: Ubuntu 21:10\r\n* JVM: OpenJDK 11.0.13 2021-10-19\r\n"},"base_sha":{"kind":"string","value":"8d1c667a6848ed71753d4dd7d314cb8492fb09a2"},"head_sha":{"kind":"string","value":"0a998d8f269f8c12ec4980af8d1409b340f41b17"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/8d1c667a6848ed71753d4dd7d314cb8492fb09a2...0a998d8f269f8c12ec4980af8d1409b340f41b17"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java\nindex efae8cccd..63db497d3 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java\n@@ -346,12 +346,14 @@ public class RouterImpl implements Router {\n }\n // regex\n if (ctx.matchRest != -1) {\n+ // if we're on a sub router already we need to skip the matched path\n+ int skip = ctx.mountPoint != null ? ctx.mountPoint.length() : 0;\n if (ctx.matchNormalized) {\n- return ctx.normalizedPath().substring(0, ctx.matchRest);\n+ return ctx.normalizedPath().substring(skip, skip + ctx.matchRest);\n } else {\n String path = ctx.request().path();\n if (path != null) {\n- return path.substring(0, ctx.matchRest);\n+ return path.substring(skip, skip + ctx.matchRest);\n }\n return null;\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\nindex d0e6793e9..48700238a 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n@@ -647,5 +647,55 @@ public class SubRouterTest extends WebTestBase {\n router.route(\"/level1/*\").handler(level2);\n testRequest(HttpMethod.GET, \"/level1/level2/level3\", 200, \"ok\");\n }\n+\n+ @Test\n+ public void testHierarchicalWithParams() throws Exception {\n+\n+ Router restRouter = Router.router(vertx);\n+ Router subRouter = Router.router(vertx);\n+\n+ subRouter.get(\"/files\").handler(ctx -> {\n+ // version is extracted from the root router\n+ assertEquals(\"1\", ctx.pathParam(\"version\"));\n+ ctx.response().end();\n+ });\n+\n+ restRouter.mountSubRouter(\"/:version\", subRouter);\n+\n+ router.mountSubRouter(\"/rest\", restRouter);\n+\n+ // router\n+ // /rest -> restRouter\n+ // /:version -> subRouter\n+ // /files -> OK\n+\n+ testRequest(HttpMethod.GET, \"/rest/1/files\", 200, \"OK\");\n+ }\n+\n+ @Test\n+ public void testHierarchicalWithParamsInAllRouters() throws Exception {\n+\n+ Router restRouter = Router.router(vertx);\n+ Router subRouter = Router.router(vertx);\n+\n+ subRouter.get(\"/files/:id\").handler(ctx -> {\n+ // version is extracted from the root router\n+ assertEquals(\"1\", ctx.pathParam(\"version\"));\n+ // id is extracted from this router\n+ assertEquals(\"2\", ctx.pathParam(\"id\"));\n+ ctx.response().end();\n+ });\n+\n+ restRouter.mountSubRouter(\"/:version\", subRouter);\n+\n+ router.mountSubRouter(\"/rest\", restRouter);\n+\n+ // router\n+ // /rest -> restRouter\n+ // /:version -> subRouter\n+ // /files/:id -> OK\n+\n+ testRequest(HttpMethod.GET, \"/rest/1/files/2\", 200, \"OK\");\n+ }\n }\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1907442,"string":"1,907,442"},"repo_tokens_count":{"kind":"number","value":423206,"string":"423,206"},"repo_lines_count":{"kind":"number","value":59226,"string":"59,226"},"repo_files_without_tests_count":{"kind":"number","value":462,"string":"462"},"changed_symbols_count":{"kind":"number","value":403,"string":"403"},"changed_tokens_count":{"kind":"number","value":89,"string":"89"},"changed_lines_count":{"kind":"number","value":6,"string":"6"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":2138,"string":"2,138"},"issue_words_count":{"kind":"number","value":191,"string":"191"},"issue_tokens_count":{"kind":"number","value":555,"string":"555"},"issue_lines_count":{"kind":"number","value":67,"string":"67"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:26","string":"1970-01-01T00:27:26"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1673,"cells":{"id":{"kind":"number","value":1243,"string":"1,243"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2159/2139"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2139"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2159"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2159"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"ConcurrentLRUCache shouldn't be named concurrent or LRU?"},"issue_body":{"kind":"string","value":"Hey!\r\n\r\nI happened to notice `io.vertx.ext.web.impl.ConcurrentLRUCache` class in this project. Is this still being maintained and/or used somewhere? I couldn't find any references to this class in the codebase except in the tests here, or any discussions related to this.\r\n\r\nI was about to start using this for a simple cache, but after having done cursory review, it looks like this class doesn't do what the name implies.\r\n\r\nFirst and foremost, it is based on ConcurrentHashMap which is thread-safe, but it also relies internally on ArrayDeque, which is _not_ thread-safe. There doesn't seem to be any synchronization happening either. The \"concurrent\" in name would imply that this would be thread-safe.\r\n\r\nSecond, it doesn't seem to be LRU either. If I read the code correctly, it deletes the earliest inserted item once reaching the max size, instead of the least recently used item.\r\n\r\nNot necessarily anything that needs to be done about this - just heads-up that the class name is quite confusing as it sets an expectation for something completely else.. :)"},"base_sha":{"kind":"string","value":"8ed704182b18d459bd82c8bf2dc389d1a4edd8d5"},"head_sha":{"kind":"string","value":"a6894b3407554f43db8fc07c579441e133d65ca8"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/8ed704182b18d459bd82c8bf2dc389d1a4edd8d5...a6894b3407554f43db8fc07c579441e133d65ca8"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java\ndeleted file mode 100644\nindex e4b91f050..000000000\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java\n+++ /dev/null\n@@ -1,163 +0,0 @@\n-/*\n- * Copyright 2014 Red Hat, Inc.\n- *\n- * All rights reserved. This program and the accompanying materials\n- * are made available under the terms of the Eclipse Public License v1.0\n- * and Apache License v2.0 which accompanies this distribution.\n- *\n- * The Eclipse Public License is available at\n- * http://www.eclipse.org/legal/epl-v10.html\n- *\n- * The Apache License v2.0 is available at\n- * http://www.opensource.org/licenses/apache2.0.php\n- *\n- * You may elect to redistribute this code under either of these licenses.\n- */\n-\n-package io.vertx.ext.web.impl;\n-\n-import java.util.ArrayDeque;\n-import java.util.Map;\n-import java.util.Queue;\n-import java.util.concurrent.ConcurrentHashMap;\n-import java.util.function.BiFunction;\n-\n-/**\n- * Concurrent LRU cache.\n- *\n- * Note that remove operation on this structure is SLOW! Avoid using it.\n- *\n- * @author Tim Fox\n- */\n-public class ConcurrentLRUCache extends ConcurrentHashMap {\n-\n- private int maxSize;\n- private final Queue queue = new ArrayDeque<>();\n-\n- public ConcurrentLRUCache(int maxSize) {\n- this.maxSize = maxSize;\n- checkSize();\n- }\n-\n- public ConcurrentLRUCache(int initialCapacity, int maxSize) {\n- super(initialCapacity);\n- this.maxSize = maxSize;\n- checkSize();\n- }\n-\n- public ConcurrentLRUCache(Map m, int maxSize) {\n- super(m);\n- this.maxSize = maxSize;\n- checkSize();\n- for (K k: m.keySet()) {\n- entryAdded(k);\n- }\n- checkRemoveOldest();\n- }\n-\n- public ConcurrentLRUCache(int initialCapacity, float loadFactor, int maxSize) {\n- super(initialCapacity, loadFactor);\n- this.maxSize = maxSize;\n- checkSize();\n- }\n-\n- public ConcurrentLRUCache(int initialCapacity, float loadFactor, int concurrencyLevel, int maxSize) {\n- super(initialCapacity, loadFactor, concurrencyLevel);\n- this.maxSize = maxSize;\n- checkSize();\n- }\n-\n- public void setMaxSize(int maxSize) {\n- this.maxSize = maxSize;\n- checkRemoveOldest();\n- }\n-\n- @Override\n- public V put(K key, V value) {\n- V v = super.put(key, value);\n- if (v == null) {\n- entryAdded(key);\n- }\n- checkRemoveOldest();\n- return v;\n- }\n-\n- @Override\n- public void putAll(Map m) {\n- for (K k: m.keySet()) {\n- if (!super.containsKey(k)) {\n- entryAdded(k);\n- }\n- }\n- super.putAll(m);\n- checkRemoveOldest();\n- }\n-\n- @Override\n- public V remove(Object key) {\n- V v = super.remove(key);\n- if (v != null) {\n- entryRemoved(key);\n- }\n- return v;\n- }\n-\n- @Override\n- public void clear() {\n- super.clear();\n- queue.clear();\n- }\n-\n- @Override\n- public V putIfAbsent(K key, V value) {\n- V v = super.putIfAbsent(key, value);\n- if (v == null) {\n- entryAdded(key);\n- }\n- checkRemoveOldest();\n- return v;\n- }\n-\n- @Override\n- public boolean remove(Object key, Object value) {\n- boolean removed = super.remove(key, value);\n- if (removed) {\n- entryRemoved(value);\n- }\n- return removed;\n- }\n-\n- @Override\n- public V merge(K key, V value, BiFunction remappingFunction) {\n- throw new UnsupportedOperationException();\n- }\n-\n- private void entryAdded(K k) {\n- queue.add(k);\n- }\n-\n- private void entryRemoved(Object o) {\n- if (!queue.remove(o)) {\n- throw new IllegalStateException(\"Failed to remove\");\n- }\n- }\n- \n- private void checkRemoveOldest() {\n- while (queue.size() > maxSize) {\n- K k = queue.poll();\n- if (k != null) {\n- super.remove(k);\n- }\n- }\n- }\n-\n- private void checkSize() {\n- if (maxSize < 1) {\n- throw new IllegalArgumentException(\"maxSize must be >= 1\");\n- }\n- }\n-\n- public int queueSize() {\n- return queue.size();\n- }\n-}\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java b/vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java\ndeleted file mode 100644\nindex 1ff39d68e..000000000\n--- a/vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java\n+++ /dev/null\n@@ -1,72 +0,0 @@\n-/*\n- * Copyright 2014 Red Hat, Inc.\n- *\n- * All rights reserved. This program and the accompanying materials\n- * are made available under the terms of the Eclipse Public License v1.0\n- * and Apache License v2.0 which accompanies this distribution.\n- *\n- * The Eclipse Public License is available at\n- * http://www.eclipse.org/legal/epl-v10.html\n- *\n- * The Apache License v2.0 is available at\n- * http://www.opensource.org/licenses/apache2.0.php\n- *\n- * You may elect to redistribute this code under either of these licenses.\n- */\n-\n-package io.vertx.ext.web;\n-\n-import io.vertx.ext.web.impl.ConcurrentLRUCache;\n-import org.junit.Test;\n-\n-import java.util.Map;\n-\n-import static org.junit.Assert.*;\n-\n-/**\n- * @author Tim Fox\n- */\n-public class ConcurrentLRUCacheTest extends LRUCacheTestBase {\n-\n- @Override\n- protected Map createCache() {\n- return new ConcurrentLRUCache<>(maxSize);\n- }\n-\n- @Test\n- public void testPut() {\n- super.testPut();\n- assertEquals(maxSize, ((ConcurrentLRUCache)cache).queueSize());\n- }\n-\n- @Test\n- public void testRemove() {\n- super.testRemove();\n- assertEquals(0, ((ConcurrentLRUCache)cache).queueSize());\n- }\n-\n- @Test(expected=IllegalArgumentException.class)\n- public void testCacheInvalidSize1() {\n- new ConcurrentLRUCache<>(0);\n- }\n-\n- @Test(expected=IllegalArgumentException.class)\n- public void testCacheInvalidSize2() {\n- new ConcurrentLRUCache<>(-1);\n- }\n-\n- @Test\n- public void testIncreaseMaxSize() {\n- for (int i = 0; i < maxSize; i++) {\n- cache.put(\"key\" + i, \"value\" + i);\n- }\n- assertEquals(maxSize, cache.size());\n- ConcurrentLRUCache ccache = (ConcurrentLRUCache)cache;\n- ccache.setMaxSize(maxSize + 10);\n- for (int i = maxSize; i < maxSize + 10; i++) {\n- cache.put(\"key\" + i, \"value\" + i);\n- }\n- assertEquals(maxSize + 10, cache.size());\n- }\n-\n-}"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1930111,"string":"1,930,111"},"repo_tokens_count":{"kind":"number","value":428865,"string":"428,865"},"repo_lines_count":{"kind":"number","value":59963,"string":"59,963"},"repo_files_without_tests_count":{"kind":"number","value":466,"string":"466"},"changed_symbols_count":{"kind":"number","value":3834,"string":"3,834"},"changed_tokens_count":{"kind":"number","value":925,"string":"925"},"changed_lines_count":{"kind":"number","value":163,"string":"163"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1065,"string":"1,065"},"issue_words_count":{"kind":"number","value":172,"string":"172"},"issue_tokens_count":{"kind":"number","value":221,"string":"221"},"issue_lines_count":{"kind":"number","value":11,"string":"11"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:28","string":"1970-01-01T00:27:28"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1674,"cells":{"id":{"kind":"number","value":1242,"string":"1,242"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2176/2169"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2169"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2176"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2176"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"fileUploads are un-ordered"},"issue_body":{"kind":"string","value":"### Questions\r\n\r\n`fileUploads` are stored in an `HashSet`, thus we lose the order they were sent from.\r\n\r\n### Version\r\n\r\n4.3.0-SNAPSHOT\r\n\r\n### Context\r\n\r\nI have a route which handle file uploads and it needs to retrieves the file names in the order they were sent.\r\n\r\n### Do you have a reproducer?\r\n\r\nThe `HashSet` is created here:\r\nhttps://github.com/vert-x3/vertx-web/blob/a60906bf3a88f944c47f324aa1f847b8cc367fea/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java#L538-L543\r\n\r\nCould a `LinkedHashSet` be used here instead?\r\n\r\n"},"base_sha":{"kind":"string","value":"4e2a4aca621884107ab1b0651acc76361ddb0b75"},"head_sha":{"kind":"string","value":"c1f6e93ee0ddec39f3edb92d715b20d09db6af4e"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/4e2a4aca621884107ab1b0651acc76361ddb0b75...c1f6e93ee0ddec39f3edb92d715b20d09db6af4e"},"diff":{"kind":"string","value":"diff --git a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java\nindex d8428e232..5992cc391 100644\n--- a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java\n+++ b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java\n@@ -44,7 +44,7 @@ public class OpenAPI3RequestValidationHandlerImpl extends HTTPOperationRequestVa\n this.isOptional = isOptional;\n }\n \n- private boolean existFileUpload(Set files, String name, Pattern contentType) {\n+ private boolean existFileUpload(List files, String name, Pattern contentType) {\n for (FileUpload f : files) {\n if (f.name().equals(name) && contentType.matcher(f.contentType()).matches()) return true;\n }\ndiff --git a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java\nindex 4c83a015c..4c14462ba 100644\n--- a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java\n+++ b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java\n@@ -275,7 +275,7 @@ public abstract class BaseValidationHandler implements ValidationHandler {\n return parsedParams;\n }\n \n- private boolean existFileUpload(Set files, String name, Pattern contentType) {\n+ private boolean existFileUpload(List files, String name, Pattern contentType) {\n for (FileUpload f : files) {\n if (f.name().equals(name) && contentType.matcher(f.contentType()).matches()) return true;\n }\n@@ -283,7 +283,7 @@ public abstract class BaseValidationHandler implements ValidationHandler {\n }\n \n private void validateFileUpload(RoutingContext routingContext) throws ValidationException {\n- Set fileUploads = routingContext.fileUploads();\n+ List fileUploads = routingContext.fileUploads();\n for (Map.Entry expectedFile : multipartFileRules.entrySet()) {\n if (!existFileUpload(fileUploads, expectedFile.getKey(), expectedFile.getValue()))\n throw ValidationException.ValidationExceptionFactory.generateFileNotFoundValidationException(expectedFile\ndiff --git a/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java b/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java\nindex 6b04a31e6..e408838d7 100644\n--- a/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java\n+++ b/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java\n@@ -5,7 +5,7 @@ import io.vertx.core.http.HttpHeaders;\n import io.vertx.ext.web.FileUpload;\n import io.vertx.ext.web.RoutingContext;\n \n-import java.util.Set;\n+import java.util.List;\n import java.util.function.Function;\n import java.util.regex.Pattern;\n \n@@ -40,7 +40,7 @@ public interface RequestPredicate extends Function files = rc.fileUploads();\n+ List files = rc.fileUploads();\n for (FileUpload f : files) {\n if (f.name().equals(propertyName) && contentType.matcher(f.contentType()).matches()) return success();\n }\ndiff --git a/vertx-web/src/main/java/examples/WebExamples.java b/vertx-web/src/main/java/examples/WebExamples.java\nindex 9dd9ad7f9..52c09446b 100644\n--- a/vertx-web/src/main/java/examples/WebExamples.java\n+++ b/vertx-web/src/main/java/examples/WebExamples.java\n@@ -696,7 +696,7 @@ public class WebExamples {\n \n router.post(\"/some/path/uploads\").handler(ctx -> {\n \n- Set uploads = ctx.fileUploads();\n+ List uploads = ctx.fileUploads();\n // Do something with uploads....\n \n });\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java b/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java\nindex 9af928097..2fd2b1afe 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java\n@@ -378,10 +378,10 @@ public interface RoutingContext {\n RequestBody body();\n \n /**\n- * @return a set of fileuploads (if any) for the request. The context must have first been routed to a\n+ * @return a list of {@link FileUpload} (if any) for the request. The context must have first been routed to a\n * {@link io.vertx.ext.web.handler.BodyHandler} for this to work.\n */\n- Set fileUploads();\n+ List fileUploads();\n \n /**\n * Get the session. The context must have first been routed to a {@link io.vertx.ext.web.handler.SessionHandler}\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\nindex 9a286199f..0269e9cca 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\n@@ -17,7 +17,7 @@\n package io.vertx.ext.web.handler.impl;\n \n import java.io.File;\n-import java.util.Set;\n+import java.util.List;\n import java.util.UUID;\n import java.util.concurrent.atomic.AtomicBoolean;\n import java.util.concurrent.atomic.AtomicInteger;\n@@ -210,7 +210,7 @@ public class BodyHandlerImpl implements BodyHandler {\n initBodyBuffer();\n }\n \n- Set fileUploads = context.fileUploads();\n+ List fileUploads = context.fileUploads();\n \n final String contentType = context.request().getHeader(HttpHeaders.CONTENT_TYPE);\n if (contentType == null) {\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java\nindex 819e11e39..9a2820107 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java\n@@ -133,7 +133,7 @@ public class RoutingContextDecorator implements RoutingContextInternal {\n }\n \n @Override\n- public Set fileUploads() {\n+ public List fileUploads() {\n return decoratedContext.fileUploads();\n }\n \ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\nindex 79413cb55..d7b7a1ae4 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n@@ -27,7 +27,6 @@ import io.vertx.core.impl.ContextInternal;\n import io.vertx.ext.auth.User;\n import io.vertx.ext.web.RequestBody;\n import io.vertx.ext.web.FileUpload;\n-import io.vertx.ext.web.RequestBody;\n import io.vertx.ext.web.RoutingContext;\n import io.vertx.ext.web.Session;\n import io.vertx.ext.web.handler.HttpException;\n@@ -67,7 +66,7 @@ public class RoutingContextImpl extends RoutingContextImplBase {\n private String acceptableContentType;\n private ParsableHeaderValuesContainer parsedHeaders;\n \n- private Set fileUploads;\n+ private List fileUploads;\n private Session session;\n private User user;\n \n@@ -304,8 +303,11 @@ public class RoutingContextImpl extends RoutingContextImplBase {\n }\n \n @Override\n- public Set fileUploads() {\n- return getFileUploads();\n+ public List fileUploads() {\n+ if (fileUploads == null) {\n+ fileUploads = new ArrayList<>();\n+ }\n+ return fileUploads;\n }\n \n @Override\n@@ -535,13 +537,6 @@ public class RoutingContextImpl extends RoutingContextImplBase {\n return endHandlers;\n }\n \n- private Set getFileUploads() {\n- if (fileUploads == null) {\n- fileUploads = new HashSet<>();\n- }\n- return fileUploads;\n- }\n-\n private void doFail() {\n this.iter = router.iterator();\n currentRoute = null;\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java\nindex 22dca1361..4a4bfe546 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java\n@@ -279,7 +279,7 @@ public class RoutingContextWrapper extends RoutingContextImplBase {\n }\n \n @Override\n- public Set fileUploads() {\n+ public List fileUploads() {\n return inner.fileUploads();\n }\n \ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java\nindex f49853c37..ba298bc1f 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java\n@@ -36,7 +36,7 @@ import java.io.File;\n import java.io.IOException;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n-import java.util.Set;\n+import java.util.List;\n import java.util.function.Function;\n \n /**\n@@ -247,7 +247,7 @@ public class BodyHandlerTest extends WebTestBase {\n String contentType = \"application/octet-stream\";\n Buffer fileData = TestUtils.randomBuffer(size);\n router.route().handler(rc -> {\n- Set fileUploads = rc.fileUploads();\n+ List fileUploads = rc.fileUploads();\n assertNotNull(fileUploads);\n assertEquals(1, fileUploads.size());\n FileUpload upload = fileUploads.iterator().next();\n@@ -830,7 +830,7 @@ public class BodyHandlerTest extends WebTestBase {\n String contentType = \"application/octet-stream\";\n Buffer fileData = TestUtils.randomBuffer(50);\n router.route().handler(rc -> {\n- Set fileUploads = rc.fileUploads();\n+ List fileUploads = rc.fileUploads();\n assertNotNull(fileUploads);\n assertEquals(1, fileUploads.size());\n FileUpload upload = fileUploads.iterator().next();"},"changed_files":{"kind":"string","value":"['vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java', 'vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java', 'vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java', 'vertx-web/src/main/java/examples/WebExamples.java', 'vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 10}"},"changed_files_count":{"kind":"number","value":10,"string":"10"},"java_changed_files_count":{"kind":"number","value":10,"string":"10"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":10,"string":"10"},"repo_symbols_count":{"kind":"number","value":1960389,"string":"1,960,389"},"repo_tokens_count":{"kind":"number","value":435305,"string":"435,305"},"repo_lines_count":{"kind":"number","value":60784,"string":"60,784"},"repo_files_without_tests_count":{"kind":"number","value":481,"string":"481"},"changed_symbols_count":{"kind":"number","value":1879,"string":"1,879"},"changed_tokens_count":{"kind":"number","value":441,"string":"441"},"changed_lines_count":{"kind":"number","value":41,"string":"41"},"changed_files_without_tests_count":{"kind":"number","value":9,"string":"9"},"issue_symbols_count":{"kind":"number","value":548,"string":"548"},"issue_words_count":{"kind":"number","value":63,"string":"63"},"issue_tokens_count":{"kind":"number","value":153,"string":"153"},"issue_lines_count":{"kind":"number","value":20,"string":"20"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:32","string":"1970-01-01T00:27:32"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1675,"cells":{"id":{"kind":"number","value":1241,"string":"1,241"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2186/2185"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2185"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2186"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2186"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Subrouter fails if mounted on another subrouter on path with path params"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.3.0 and 4.3.1-SNAPSHOT\r\n\r\n### Context\r\n\r\nFollow up on #2136 which still fails in some cases.\r\n\r\n### Do you have a reproducer?\r\n\r\nAdd this to [SubRouterTest](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java):\r\n\r\n```\r\n @Test // FAILS!\r\n public void testHierarchicalWithParamsSimple() throws Exception {\r\n\r\n Router restRouter = Router.router(vertx);\r\n Router productRouter = Router.router(vertx);\r\n Router instanceRouter = Router.router(vertx);\r\n\r\n router.route(\"/rest*\").subRouter(restRouter);\r\n restRouter.route(\"/product*\").subRouter(productRouter);\r\n productRouter.route(\"/:id*\").subRouter(instanceRouter);\r\n instanceRouter.get(\"/\").handler(ctx -> {\r\n // id is extracted from the root router\r\n assertEquals(\"123\", ctx.pathParam(\"id\"));\r\n ctx.response().end();\r\n });\r\n\r\n // router\r\n // /rest -> restRouter\r\n // /product -> productRouter\r\n // /:id -> instanceRouter\r\n // / -> OK\r\n\r\n testRequest(HttpMethod.GET, \"/rest/product/123\", 200, \"OK\");\r\n }\r\n```\r\n\r\nHowever, route is recognized if I add another path param to last sub-router:\r\n\r\n```\r\n @Test // succeeds\r\n public void testHierarchicalWithParamsSimpleWithDummy() throws Exception {\r\n\r\n Router restRouter = Router.router(vertx);\r\n Router productRouter = Router.router(vertx);\r\n Router instanceRouter = Router.router(vertx);\r\n\r\n router.route(\"/rest*\").subRouter(restRouter);\r\n restRouter.route(\"/product*\").subRouter(productRouter);\r\n productRouter.route(\"/:id*\").subRouter(instanceRouter);\r\n instanceRouter.get(\"/:foo\").handler(ctx -> {\r\n // id is extracted from the root router\r\n assertEquals(\"123\", ctx.pathParam(\"id\"));\r\n assertEquals(\"bar\", ctx.pathParam(\"foo\"));\r\n ctx.response().end();\r\n });\r\n\r\n // router\r\n // /rest -> restRouter\r\n // /product -> productRouter\r\n // /:id -> instanceRouter\r\n // /:foo -> OK\r\n\r\n testRequest(HttpMethod.GET, \"/rest/product/123/bar\", 200, \"OK\");\r\n }\r\n```\r\n### Steps to reproduce\r\n\r\n1. Add those tests to [SubRouterTest.java](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java)\r\n2. Run tests with `mvn -Dtest=SubRouterTest test -pl vertx-web`\r\n\r\n### Extra\r\n\r\n* OS: Ubuntu 21.10\r\n* JVM: OpenJDK 64-Bit Server VM 11.0.14.1 2022-02-08"},"base_sha":{"kind":"string","value":"f3e7c6e32632702bae3557c3da86fe8d35e23c5b"},"head_sha":{"kind":"string","value":"ab2318af9ac0cab9129a35fa4b38c5e58affe286"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/f3e7c6e32632702bae3557c3da86fe8d35e23c5b...ab2318af9ac0cab9129a35fa4b38c5e58affe286"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java\nindex b9833c6a3..7d54c0c76 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java\n@@ -1024,7 +1024,7 @@ final class RouteState {\n }\n \n context.matchRest = -1;\n- context.matchNormalized = useNormalizedPath;\n+ context.normalizedMatch = useNormalizedPath;\n \n if (m.groupCount() > 0) {\n if (!exactPath) {\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java\nindex 1fe9a7370..7f5e344fc 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java\n@@ -246,12 +246,14 @@ public class RouterImpl implements Router {\n \n @Override\n public void handleContext(RoutingContext ctx) {\n- new RoutingContextWrapper(getAndCheckRoutePath(ctx), state.getRoutes(), (RoutingContextInternal) ctx, this).next();\n+ final RoutingContextInternal ctxi = (RoutingContextInternal) ctx;\n+ new RoutingContextWrapper(getAndCheckRoutePath(ctxi), state.getRoutes(), ctxi, this).next();\n }\n \n @Override\n public void handleFailure(RoutingContext ctx) {\n- new RoutingContextWrapper(getAndCheckRoutePath(ctx), state.getRoutes(), (RoutingContextInternal) ctx, this).next();\n+ final RoutingContextInternal ctxi = (RoutingContextInternal) ctx;\n+ new RoutingContextWrapper(getAndCheckRoutePath(ctxi), state.getRoutes(), ctxi, this).next();\n }\n \n @Override\n@@ -333,8 +335,7 @@ public class RouterImpl implements Router {\n return state.getErrorHandler(statusCode);\n }\n \n- private String getAndCheckRoutePath(RoutingContext routingContext) {\n- final RoutingContextImplBase ctx = (RoutingContextImplBase) routingContext;\n+ private String getAndCheckRoutePath(RoutingContextInternal ctx) {\n final Route route = ctx.currentRoute();\n \n if (!route.isRegexPath()) {\n@@ -347,18 +348,9 @@ public class RouterImpl implements Router {\n }\n }\n // regex\n- if (ctx.matchRest != -1) {\n+ if (ctx.restIndex() != -1) {\n // if we're on a sub router already we need to skip the matched path\n- int skip = ctx.mountPoint != null ? ctx.mountPoint.length() : 0;\n- if (ctx.matchNormalized) {\n- return ctx.normalizedPath().substring(skip, skip + ctx.matchRest);\n- } else {\n- String path = ctx.request().path();\n- if (path != null) {\n- return path.substring(skip, skip + ctx.matchRest);\n- }\n- return null;\n- }\n+ return ctx.basePath();\n } else {\n // failure did not match\n throw new IllegalStateException(\"Sub routers must be mounted on paths (constant or parameterized)\");\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java\nindex c072c25ae..70d3628a7 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java\n@@ -286,6 +286,16 @@ public class RoutingContextDecorator implements RoutingContextInternal {\n decoratedContext.setSession(session);\n }\n \n+ @Override\n+ public int restIndex() {\n+ return decoratedContext.restIndex();\n+ }\n+\n+ @Override\n+ public boolean normalizedMatch() {\n+ return decoratedContext.normalizedMatch();\n+ }\n+\n @Override\n public void setUser(User user) {\n decoratedContext.setUser(user);\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\nindex f043362c7..c6959902b 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java\n@@ -108,7 +108,6 @@ public class RoutingContextImpl extends RoutingContextImplBase {\n HeaderParser.sort(HeaderParser.convertToParsedHeaderValues(acceptLanguage, ParsableLanguageValue::new)),\n new ParsableMIMEValue(contentType)\n );\n-\n }\n \n @Override\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\nindex 2a1261e0e..58ff9d1f5 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java\n@@ -54,7 +54,7 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal {\n int matchFailure;\n // the current path matched string\n int matchRest = -1;\n- boolean matchNormalized;\n+ boolean normalizedMatch;\n // internal runtime state\n private volatile long seen;\n \n@@ -78,6 +78,16 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal {\n return (seen & id) != 0;\n }\n \n+ @Override\n+ public int restIndex() {\n+ return matchRest;\n+ }\n+\n+ @Override\n+ public boolean normalizedMatch() {\n+ return normalizedMatch;\n+ }\n+\n @Override\n public synchronized RoutingContextInternal setMatchFailure(int matchFailure) {\n this.matchFailure = matchFailure;\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java\nindex 34304fed4..f5a8b6b69 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java\n@@ -84,4 +84,25 @@ public interface RoutingContextInternal extends RoutingContext {\n * @param session the session\n */\n void setSession(Session session);\n+\n+ int restIndex();\n+\n+ boolean normalizedMatch();\n+\n+ default String basePath() {\n+ // if we're on a sub router already we need to skip the matched path\n+ String mountPoint = mountPoint();\n+\n+ int skip = mountPoint != null ? mountPoint.length() : 0;\n+ if (normalizedMatch()) {\n+ return normalizedPath().substring(skip, skip + restIndex());\n+ } else {\n+ String path = request().path();\n+ if (path != null) {\n+ return path.substring(skip, skip + restIndex());\n+ }\n+ return null;\n+ }\n+\n+ };\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\nindex 4d66c6b2c..6d32d22e4 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java\n@@ -690,5 +690,55 @@ public class SubRouterTest extends WebTestBase {\n \n testRequest(HttpMethod.GET, \"/rest/1/files/2\", 200, \"OK\");\n }\n-}\n \n+ @Test\n+ public void testHierarchicalWithParamsSimple() throws Exception {\n+\n+ Router restRouter = Router.router(vertx);\n+ Router productRouter = Router.router(vertx);\n+ Router instanceRouter = Router.router(vertx);\n+\n+ router.route(\"/rest*\").subRouter(restRouter);\n+ restRouter.route(\"/product*\").subRouter(productRouter);\n+ productRouter.route(\"/:id*\").subRouter(instanceRouter);\n+ instanceRouter.get(\"/\").handler(ctx -> {\n+ // id is extracted from the root router\n+ assertEquals(\"123\", ctx.pathParam(\"id\"));\n+ ctx.response().end();\n+ });\n+\n+ // router\n+ // /rest -> restRouter\n+ // /product -> productRouter\n+ // /:id -> instanceRouter\n+ // / -> OK\n+\n+ testRequest(HttpMethod.GET, \"/rest/product/123\", 200, \"OK\");\n+ }\n+\n+ @Test\n+ public void testHierarchicalWithParamsSimpleWithDummy() throws Exception {\n+\n+ Router restRouter = Router.router(vertx);\n+ Router productRouter = Router.router(vertx);\n+ Router instanceRouter = Router.router(vertx);\n+\n+ router.route(\"/rest*\").subRouter(restRouter);\n+ restRouter.route(\"/product*\").subRouter(productRouter);\n+ productRouter.route(\"/:id*\").subRouter(instanceRouter);\n+ instanceRouter.get(\"/:foo\").handler(ctx -> {\n+ // id is extracted from the root router\n+ assertEquals(\"123\", ctx.pathParam(\"id\"));\n+ assertEquals(\"bar\", ctx.pathParam(\"foo\"));\n+ ctx.response().end();\n+ });\n+\n+ // router\n+ // /rest -> restRouter\n+ // /product -> productRouter\n+ // /:id -> instanceRouter\n+ // /:foo -> OK\n+\n+ testRequest(HttpMethod.GET, \"/rest/product/123/bar\", 200, \"OK\");\n+ }\n+}"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java', 'vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 7}"},"changed_files_count":{"kind":"number","value":7,"string":"7"},"java_changed_files_count":{"kind":"number","value":7,"string":"7"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":7,"string":"7"},"repo_symbols_count":{"kind":"number","value":1965720,"string":"1,965,720"},"repo_tokens_count":{"kind":"number","value":436450,"string":"436,450"},"repo_lines_count":{"kind":"number","value":60969,"string":"60,969"},"repo_files_without_tests_count":{"kind":"number","value":482,"string":"482"},"changed_symbols_count":{"kind":"number","value":2332,"string":"2,332"},"changed_tokens_count":{"kind":"number","value":517,"string":"517"},"changed_lines_count":{"kind":"number","value":68,"string":"68"},"changed_files_without_tests_count":{"kind":"number","value":6,"string":"6"},"issue_symbols_count":{"kind":"number","value":2445,"string":"2,445"},"issue_words_count":{"kind":"number","value":203,"string":"203"},"issue_tokens_count":{"kind":"number","value":613,"string":"613"},"issue_lines_count":{"kind":"number","value":77,"string":"77"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:33","string":"1970-01-01T00:27:33"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1676,"cells":{"id":{"kind":"number","value":1270,"string":"1,270"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1432/1429"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1429"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1432"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1432"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"StaticHandlerImpl uses a shared DateFormat across threads causing issues with date parsing in header values"},"issue_body":{"kind":"string","value":"Continuing on this curious issue in Quarkus https://github.com/quarkusio/quarkus/issues/4627, apart from the fix done yesterday here https://github.com/vert-x3/vertx-web/issues/1423, it would be really odd that Firefox (that too the latest version) would send incorrect values for a header like `If-Modified-Since`. The user attached the browser's request header screenshots here https://github.com/quarkusio/quarkus/issues/4627#issuecomment-543247193 and they show that Firefox is sending the right header values. So looking back into the code in `StaticHandlerImpl`, I think what's happening is multiple requests (across threads) are being handled by it and it uses a single instance of `DateFormat` to parse the header value. The `DateFormat` (`java.text.SimpleDateFormat`) is created once for that handler and stored as a member variable. The javadoc of `SimpleDateFormat` states:\r\n```\r\n* Date formats are not synchronized.\r\n * It is recommended to create separate format instances for each thread.\r\n * If multiple threads access a format concurrently, it must be synchronized\r\n * externally.\r\n```\r\nSo what seems to be happening in that issue that is that its running into a race condition due to multiple threads using the same DateFormatter.\r\nI think the implementation in this `StaticHandlerImpl` should either create the DateFormat as and when needed or maybe have a `ThreadLocal`."},"base_sha":{"kind":"string","value":"32f6a489e9e53431a7051a6151977940150cb931"},"head_sha":{"kind":"string","value":"7eae93b1dce3d6c916e85b8372b1eece8a3a9e7e"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/32f6a489e9e53431a7051a6151977940150cb931...7eae93b1dce3d6c916e85b8372b1eece8a3a9e7e"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java\nindex a76a6513e..282e8e99a 100755\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java\n@@ -27,9 +27,6 @@ import io.vertx.ext.web.handler.LoggerHandler;\n import io.vertx.ext.web.RoutingContext;\n import io.vertx.ext.web.impl.Utils;\n \n-import java.text.DateFormat;\n-import java.util.Date;\n-\n /** # Logger\n *\n * Logger for request. There are 3 formats included:\n@@ -48,10 +45,6 @@ public class LoggerHandlerImpl implements LoggerHandler {\n \n private final io.vertx.core.logging.Logger logger = LoggerFactory.getLogger(this.getClass());\n \n- /** The Date formatter (UTC JS compatible format)\n- */\n- private final DateFormat dateTimeFormat = Utils.createRFC1123DateTimeFormatter();\n-\n /** log before request or after\n */\n private final boolean immediate;\n@@ -119,7 +112,7 @@ public class LoggerHandlerImpl implements LoggerHandler {\n \n message = String.format(\"%s - - [%s] \\\\\"%s %s %s\\\\\" %d %d \\\\\"%s\\\\\" \\\\\"%s\\\\\"\",\n remoteClient,\n- dateTimeFormat.format(new Date(timestamp)),\n+ Utils.formatRFC1123DateTime(timestamp),\n method,\n uri,\n versionFormatted,\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java\nindex b85df7d5c..14e34dd26 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java\n@@ -34,8 +34,6 @@ import io.vertx.ext.web.impl.Utils;\n \n import java.io.File;\n import java.nio.charset.Charset;\n-import java.text.DateFormat;\n-import java.text.ParseException;\n import java.util.*;\n import java.util.concurrent.Callable;\n import java.util.regex.Matcher;\n@@ -54,7 +52,6 @@ public class StaticHandlerImpl implements StaticHandler {\n \n private static final Logger log = LoggerFactory.getLogger(StaticHandlerImpl.class);\n \n- private final DateFormat dateTimeFormatter = Utils.createRFC1123DateTimeFormatter();\n private String webRoot = DEFAULT_WEB_ROOT;\n private long maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS; // One day\n private boolean directoryListing = DEFAULT_DIRECTORY_LISTING;\n@@ -112,7 +109,7 @@ public class StaticHandlerImpl implements StaticHandler {\n // We use cache-control and last-modified\n // We *do not use* etags and expires (since they do the same thing - redundant)\n Utils.addToMapIfAbsent(headers, \"cache-control\", \"public, max-age=\" + maxAgeSeconds);\n- Utils.addToMapIfAbsent(headers, \"last-modified\", dateTimeFormatter.format(props.lastModifiedTime()));\n+ Utils.addToMapIfAbsent(headers, \"last-modified\", Utils.formatRFC1123DateTime(props.lastModifiedTime()));\n // We send the vary header (for intermediate caches)\n // (assumes that most will turn on compression when using static handler)\n if (sendVaryHeader && request.headers().contains(\"accept-encoding\")) {\n@@ -121,7 +118,7 @@ public class StaticHandlerImpl implements StaticHandler {\n }\n \n // date header is mandatory\n- headers.set(\"date\", dateTimeFormatter.format(new Date()));\n+ headers.set(\"date\", Utils.formatRFC1123DateTime(System.currentTimeMillis()));\n }\n \n @Override\n@@ -742,14 +739,8 @@ public class StaticHandlerImpl implements StaticHandler {\n // Not a conditional request\n return false;\n }\n- Date ifModifiedSinceDate;\n- try {\n- ifModifiedSinceDate = dateTimeFormatter.parse(ifModifiedSince);\n- } catch (ParseException e) {\n- // Behave like the header is not present\n- return false;\n- }\n- boolean modifiedSince = Utils.secondsFactor(props.lastModifiedTime()) > ifModifiedSinceDate.getTime();\n+ long ifModifiedSinceDate = Utils.parseRFC1123DateTime(ifModifiedSince);\n+ boolean modifiedSince = Utils.secondsFactor(props.lastModifiedTime()) > ifModifiedSinceDate;\n return !modifiedSince;\n }\n \ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java\nindex 47ff09536..c2dff873a 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java\n@@ -32,6 +32,12 @@ import java.nio.charset.Charset;\n import java.nio.charset.StandardCharsets;\n import java.text.DateFormat;\n import java.text.SimpleDateFormat;\n+import java.time.Instant;\n+import java.time.LocalDateTime;\n+import java.time.ZoneId;\n+import java.time.ZoneOffset;\n+import java.time.format.DateTimeFormatter;\n+import java.time.format.DateTimeParseException;\n import java.util.Locale;\n import java.util.TimeZone;\n \n@@ -91,10 +97,19 @@ public class Utils extends io.vertx.core.impl.Utils {\n }\n }\n \n- public static DateFormat createRFC1123DateTimeFormatter() {\n- DateFormat dtf = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss zzz\", Locale.ENGLISH);\n- dtf.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n- return dtf;\n+ private static final ZoneId ZONE_GMT = ZoneId.of(\"GMT\");\n+\n+ public static String formatRFC1123DateTime(final long time) {\n+ return DateTimeFormatter.RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(time).atZone(ZONE_GMT));\n+ }\n+\n+ public static long parseRFC1123DateTime(final String header) {\n+ try {\n+ return header == null || header.isEmpty() ? -1 :\n+ LocalDateTime.parse(header, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant(ZoneOffset.UTC).toEpochMilli();\n+ } catch (DateTimeParseException ex) {\n+ return -1;\n+ }\n }\n \n public static String pathOffset(String path, RoutingContext context) {\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java\nindex 7a2d3dd07..710fa3e14 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java\n@@ -22,7 +22,6 @@ import io.vertx.ext.web.impl.Utils;\n import io.vertx.ext.web.WebTestBase;\n import org.junit.Test;\n \n-import java.text.DateFormat;\n import java.util.*;\n \n /**\n@@ -137,8 +136,8 @@ public class CookieHandlerTest extends WebTestBase {\n int startPos = encoded.indexOf(\"Expires=\");\n int endPos = encoded.indexOf(';', startPos);\n String expiresDate = encoded.substring(startPos + 8, endPos);\n- Date d = dateTimeFormat.parse(expiresDate);\n- assertTrue(d.getTime() - now >= maxAge);\n+ long d = Utils.parseRFC1123DateTime(expiresDate);\n+ assertTrue(d - now >= maxAge);\n \n cookie.setMaxAge(Long.MIN_VALUE);\n cookie.setSecure(true);\n@@ -146,6 +145,4 @@ public class CookieHandlerTest extends WebTestBase {\n cookie.setHttpOnly(true);\n assertEquals(\"foo=bar; Path=/somepath; Domain=foo.com; Secure; HTTPOnly\", cookie.encode());\n }\n-\n- private final DateFormat dateTimeFormat = Utils.createRFC1123DateTimeFormatter();\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java\nindex 375d48ee5..2134a80dd 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java\n@@ -19,13 +19,11 @@ package io.vertx.ext.web.handler;\n import io.vertx.core.http.HttpMethod;\n import io.vertx.ext.web.Session;\n import io.vertx.ext.web.WebTestBase;\n-import io.vertx.ext.web.impl.Utils;\n import io.vertx.ext.web.sstore.AbstractSession;\n import io.vertx.ext.web.sstore.LocalSessionStore;\n import io.vertx.ext.web.sstore.SessionStore;\n import org.junit.Test;\n \n-import java.text.DateFormat;\n import java.util.Objects;\n import java.util.concurrent.CompletableFuture;\n import java.util.concurrent.CountDownLatch;\n@@ -360,8 +358,6 @@ public abstract class SessionHandlerTestBase extends WebTestBase {\n \t\t\t\tresp -> assertNull(resp.headers().get(\"set-cookie\")), 200, \"OK\", null);\n \t}\n \n-\tprivate final DateFormat dateTimeFormatter = Utils.createRFC1123DateTimeFormatter();\n-\n \tprotected long doTestSessionRetryTimeout() throws Exception {\n \t\trouter.route().handler(SessionHandler.create(store));\n \t\tAtomicReference rid = new AtomicReference<>();\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java\nindex da95bbee3..e10672e45 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java\n@@ -16,7 +16,6 @@\n \n package io.vertx.ext.web.handler;\n \n-import io.vertx.core.Handler;\n import io.vertx.core.http.*;\n import io.vertx.core.json.JsonArray;\n import io.vertx.core.net.PemKeyCertOptions;\n@@ -29,7 +28,6 @@ import org.junit.Test;\n \n import java.io.File;\n import java.nio.file.Files;\n-import java.text.DateFormat;\n import java.util.*;\n import java.util.concurrent.CountDownLatch;\n import java.util.concurrent.atomic.AtomicReference;\n@@ -40,8 +38,6 @@ import java.util.function.BiConsumer;\n */\n public class StaticHandlerTest extends WebTestBase {\n \n- private final DateFormat dateTimeFormatter = Utils.createRFC1123DateTimeFormatter();\n-\n protected StaticHandler stat;\n \n @Override\n@@ -307,7 +303,7 @@ public class StaticHandlerTest extends WebTestBase {\n \n @Test\n public void testCacheGetNew() throws Exception {\n- testCacheReturnFromCache((lastModified, req) -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(toDateTime(lastModified) - 1)), 200, \"OK\", \"Other page\");\n+ testCacheReturnFromCache((lastModified, req) -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(toDateTime(lastModified) - 1)), 200, \"OK\", \"Other page\");\n }\n \n @Test\n@@ -442,7 +438,7 @@ public class StaticHandlerTest extends WebTestBase {\n String lastModified = res.headers().get(\"last-modified\");\n assertEquals(modified, toDateTime(lastModified));\n }, 200, \"OK\", \"File system page\");\n- testRequest(HttpMethod.GET, \"/fspage.html\", req -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(modified)), null, 304, \"Not Modified\", null);\n+ testRequest(HttpMethod.GET, \"/fspage.html\", req -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(modified)), null, 304, \"Not Modified\", null);\n }\n \n @Test\n@@ -458,7 +454,7 @@ public class StaticHandlerTest extends WebTestBase {\n resource.setLastModified(modified + 1000);\n }, 200, \"OK\", \"File system page\");\n // But it should still return not modified as the entry is cached\n- testRequest(HttpMethod.GET, \"/fspage.html\", req -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(modified)), null, 304, \"Not Modified\", null);\n+ testRequest(HttpMethod.GET, \"/fspage.html\", req -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(modified)), null, 304, \"Not Modified\", null);\n }\n \n @Test\n@@ -481,7 +477,7 @@ public class StaticHandlerTest extends WebTestBase {\n }, 200, \"OK\", html);\n // But it should return a new entry as the entry is now old\n Thread.sleep(cacheEntryTimeout + 1);\n- testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(modified)), res -> {\n+ testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(modified)), res -> {\n String lastModified = res.headers().get(\"last-modified\");\n assertEquals(modified + 1000, toDateTime(lastModified));\n }, 200, \"OK\", html);\n@@ -489,7 +485,7 @@ public class StaticHandlerTest extends WebTestBase {\n // 304 must still work when cacheEntry.isOutOfDate() == true, https://github.com/vert-x3/vertx-web/issues/726\n Thread.sleep(cacheEntryTimeout + 1);\n \n- testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(modified + 1000)), 304, \"Not Modified\", null);\n+ testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(modified + 1000)), 304, \"Not Modified\", null);\n }\n \n @Test\n@@ -506,10 +502,10 @@ public class StaticHandlerTest extends WebTestBase {\n stat.setCacheEntryTimeout(3600 * 1000);\n \n long modified = Utils.secondsFactor(pageFile.lastModified());\n- testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(modified)), null, 304, \"Not Modified\", null);\n+ testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(modified)), null, 304, \"Not Modified\", null);\n pageFile.delete();\n testRequest(HttpMethod.GET, page, 404, \"Not Found\");\n- testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", dateTimeFormatter.format(modified)), null, 404, \"Not Found\", null);\n+ testRequest(HttpMethod.GET, page, req -> req.putHeader(\"if-modified-since\", Utils.formatRFC1123DateTime(modified)), null, 404, \"Not Found\", null);\n \n }\n \n@@ -855,8 +851,7 @@ public class StaticHandlerTest extends WebTestBase {\n \n private long toDateTime(String header) {\n try {\n- Date date = dateTimeFormatter.parse(header);\n- return date.getTime();\n+ return Utils.parseRFC1123DateTime(header);\n } catch (Exception e) {\n fail(e.getMessage());\n return -1;"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 6}"},"changed_files_count":{"kind":"number","value":6,"string":"6"},"java_changed_files_count":{"kind":"number","value":6,"string":"6"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":6,"string":"6"},"repo_symbols_count":{"kind":"number","value":1211345,"string":"1,211,345"},"repo_tokens_count":{"kind":"number","value":271625,"string":"271,625"},"repo_lines_count":{"kind":"number","value":38526,"string":"38,526"},"repo_files_without_tests_count":{"kind":"number","value":292,"string":"292"},"changed_symbols_count":{"kind":"number","value":2339,"string":"2,339"},"changed_tokens_count":{"kind":"number","value":482,"string":"482"},"changed_lines_count":{"kind":"number","value":49,"string":"49"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":1389,"string":"1,389"},"issue_words_count":{"kind":"number","value":194,"string":"194"},"issue_tokens_count":{"kind":"number","value":298,"string":"298"},"issue_lines_count":{"kind":"number","value":9,"string":"9"},"issue_links_count":{"kind":"number","value":3,"string":"3"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:11","string":"1970-01-01T00:26:11"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1677,"cells":{"id":{"kind":"number","value":1250,"string":"1,250"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1998/1996"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1996"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1998"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1998"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Hosted OpenAPI document relative `$ref` values replaced with absolute file paths"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.1.0\r\n\r\n### Context\r\n\r\nWhen hosting an OpenAPI document using `io.vertx.ext.web.openapi.RouterBuilder` with `io.vertx.ext.web.openapi.RouterBuilderOptions#setContractEndpoint`, the hosted document has absolute paths in `$ref` attribute values. It appears the relative references (i.e. to `#/components/...`) were replaced for the purposes of validation. However, the relative paths should still be present in the hosted document returned from HTTP GET at `/openapi` (or whatever the contract endpoint is configured to be).\r\n\r\n### Do you have a reproducer?\r\n\r\nNot yet, but I can put something together if necessary. \r\n\r\n### Extra\r\n\r\nN/A\r\n"},"base_sha":{"kind":"string","value":"bb945a87766b61f2c5e62690305406a811cd9e55"},"head_sha":{"kind":"string","value":"d427e10d3a696ace43360000ed8b2c1cdfee6777"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/bb945a87766b61f2c5e62690305406a811cd9e55...d427e10d3a696ace43360000ed8b2c1cdfee6777"},"diff":{"kind":"string","value":"diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java\nindex f227a422c..c092f22bb 100755\n--- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java\n+++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java\n@@ -76,7 +76,7 @@ public class OpenAPIHolderImpl implements OpenAPIHolder {\n })\n .compose(openapi -> {\n absolutePaths.put(initialScope, openapi); // Circular refs hell!\n- openapiRoot = openapi;\n+ openapiRoot = openapi.copy();\n return walkAndSolve(openapi, initialScope).map(openapi);\n })\n .compose(openapi -> {\ndiff --git a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java\nindex b799caacb..2b92e6e9f 100755\n--- a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java\n+++ b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java\n@@ -224,6 +224,20 @@ public class OpenAPIHolderTest {\n \"src/test/resources/yaml/valid/local_refs.yaml#/components/schemas/Simple\"\n ).toString());\n \n+ // Verify the OpenAPI object stored by the OpenAPIHolder retains local refs.\n+ assertThat(loader.getOpenAPI())\n+ .extracting(JsonPointer.create()\n+ .append(\"paths\")\n+ .append(\"/simple\")\n+ .append(\"post\")\n+ .append(\"requestBody\")\n+ .append(\"content\")\n+ .append(\"multipart/form-data\")\n+ .append(\"schema\")\n+ .append(\"$ref\")\n+ )\n+ .isEqualTo(\"#/components/schemas/Simple\");\n+\n assertThat(loader)\n .hasCached(resolveAbsoluteURIFromFS(\"src/test/resources/yaml/valid/refs/Simple.yaml\"));\n \n@@ -645,7 +659,7 @@ public class OpenAPIHolderTest {\n )).append(Arrays.asList(\n \"paths\", \"/test8\", \"post\", \"requestBody\", \"content\", \"application/json\", \"schema\"\n ));\n- JsonObject resolved = (JsonObject) schemaPointer.query(loader.getOpenAPI(),\n+ JsonObject resolved = (JsonObject) schemaPointer.query(l.result(),\n new JsonPointerIteratorWithLoader(loader));\n \n Map additionalSchemasToRegister = new HashMap<>();"},"changed_files":{"kind":"string","value":"['vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java', 'vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1763022,"string":"1,763,022"},"repo_tokens_count":{"kind":"number","value":390341,"string":"390,341"},"repo_lines_count":{"kind":"number","value":54569,"string":"54,569"},"repo_files_without_tests_count":{"kind":"number","value":436,"string":"436"},"changed_symbols_count":{"kind":"number","value":70,"string":"70"},"changed_tokens_count":{"kind":"number","value":17,"string":"17"},"changed_lines_count":{"kind":"number","value":2,"string":"2"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":653,"string":"653"},"issue_words_count":{"kind":"number","value":85,"string":"85"},"issue_tokens_count":{"kind":"number","value":142,"string":"142"},"issue_lines_count":{"kind":"number","value":16,"string":"16"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:06","string":"1970-01-01T00:27:06"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1678,"cells":{"id":{"kind":"number","value":1273,"string":"1,273"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/986/943"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/943"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/986"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/986"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"ParsableHeaderValue::parameter does not call ensureHeaderProcessed"},"issue_body":{"kind":"string","value":"`ParsableHeaderValue::parameter` does not call `ensureHeaderProcessed`. Because of this, the function will return `null` even though there is a parameter.\r\n\r\nSame goes for `parameters`\r\n\r\nWorkaround is to call `value` first"},"base_sha":{"kind":"string","value":"b1af8b3be4081a4a956853c5aa8c8a15685be6d2"},"head_sha":{"kind":"string","value":"9a3e485bf68656793363d36e7aaaf52bbe1d1fa4"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/b1af8b3be4081a4a956853c5aa8c8a15685be6d2...9a3e485bf68656793363d36e7aaaf52bbe1d1fa4"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java\nindex 596d7071e..b46cdfd77 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java\n@@ -54,10 +54,12 @@ public class ParsableHeaderValue implements ParsedHeaderValue {\n }\n \n public String parameter(String key) {\n+ ensureHeaderProcessed();\n return parameter.get(key);\n }\n \n public Map parameters() {\n+ ensureHeaderProcessed();\n return Collections.unmodifiableMap(parameter);\n }\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":926962,"string":"926,962"},"repo_tokens_count":{"kind":"number","value":209607,"string":"209,607"},"repo_lines_count":{"kind":"number","value":29639,"string":"29,639"},"repo_files_without_tests_count":{"kind":"number","value":223,"string":"223"},"changed_symbols_count":{"kind":"number","value":59,"string":"59"},"changed_tokens_count":{"kind":"number","value":10,"string":"10"},"changed_lines_count":{"kind":"number","value":2,"string":"2"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":223,"string":"223"},"issue_words_count":{"kind":"number","value":29,"string":"29"},"issue_tokens_count":{"kind":"number","value":50,"string":"50"},"issue_lines_count":{"kind":"number","value":5,"string":"5"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:32","string":"1970-01-01T00:25:32"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1679,"cells":{"id":{"kind":"number","value":1240,"string":"1,240"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2187/2182"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2182"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2187"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2187"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Upgrading to 4.3.0 fails at the router Creation"},"issue_body":{"kind":"string","value":"I just upgraded to 4.3.0 from 4.2.7 and now the router creation fails with Cannot add [SECURITY_POLICY] handler to route with [BODY] handler at index 0.\r\n\r\njava.lang.IllegalStateException: Cannot add [SECURITY_POLICY] handler to route with [BODY] handler at index 0\r\n\tat io.vertx.ext.web.impl.RouteState.addContextHandler(RouteState.java:546)\r\n\tat io.vertx.ext.web.impl.RouteImpl.handler(RouteImpl.java:143)\r\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1511)\r\n\tat io.vertx.ext.web.openapi.impl.OpenAPI3RouterBuilderImpl.createRouter(OpenAPI3RouterBuilderImpl.java:268)\r\n\r\nHere is a projecto to reproduce the error, in the pom file you can swap from 4.2.7 and 4.3.0\r\n\r\nhttps://github.com/yazalulloa/vertx-openapi-changes-4.3.0\r\n\r\nEdit:\r\n\r\nAfter reading the changes in https://vertx.io/blog/whats-new-in-vert-x-4-3/#vertx-web I reordered the handlers according to the documentation:\r\n\r\n1 - PLATFORM: plat­form han­dlers (LoggerHandler, FaviconHandler, etc.)\r\n2 - SECURITY_POLICY: HTTP Se­cu­rity poli­cies (CSPHandler, CorsHandler, etc.)\r\n3 - BODY: Body pars­ing (BodyHandler)\r\n4 - AUTHENTICATION: Authn (JWTAuthHandler, APIKeyHandler, WebauthnHandler, etc.)\r\n5 - INPUT_TRUST: Input ver­i­fi­ca­tion (CSRFHandler)\r\n6 - AUTHORIZATION: Authz (AuthorizationHandler)\r\n\r\nBut it still fails with Cannot add [PLATFORM] handler to route with [BODY] handler at index 0"},"base_sha":{"kind":"string","value":"553c190b657a928af84fb5ffba0c6d3bfa70feba"},"head_sha":{"kind":"string","value":"101f13f33b847ad8c70e47fbd889546c420103df"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/553c190b657a928af84fb5ffba0c6d3bfa70feba...101f13f33b847ad8c70e47fbd889546c420103df"},"diff":{"kind":"string","value":"diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java\nindex fc1395d2a..ffadb3128 100644\n--- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java\n+++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java\n@@ -79,9 +79,15 @@ public interface RouterBuilder {\n *\n * @param bodyHandler\n * @return self\n+ *\n+ * @deprecated Use {@link #rootHandler(Handler)} instead. The order matters, so adding the body handler should\n+ * happen after any {@code PLATFORM} or {@code SECURITY_POLICY} handler(s).\n */\n @Fluent\n- RouterBuilder bodyHandler(@Nullable BodyHandler bodyHandler);\n+ @Deprecated\n+ default RouterBuilder bodyHandler(@Nullable BodyHandler bodyHandler) {\n+ return rootHandler(bodyHandler);\n+ }\n \n /**\n * Add global handler to be applied prior to {@link Router} being generated.
    \ndiff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java\nindex 6b3f3bb43..6e8c648c2 100644\n--- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java\n+++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java\n@@ -51,23 +51,21 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder {\n };\n }\n \n- private Vertx vertx;\n- private OpenAPIHolder openapi;\n+ private final Vertx vertx;\n+ private final OpenAPIHolder openapi;\n private RouterBuilderOptions options;\n- private Map operations;\n- private BodyHandler bodyHandler;\n- private AuthenticationHandlersStore securityHandlers;\n- private List> globalHandlers;\n+ private final Map operations;\n+ private final AuthenticationHandlersStore securityHandlers;\n+ private final List> globalHandlers;\n private Function serviceExtraPayloadMapper;\n- private SchemaRouter schemaRouter;\n- private OpenAPI3SchemaParser schemaParser;\n- private OpenAPI3ValidationHandlerGenerator validationHandlerGenerator;\n+ private final SchemaRouter schemaRouter;\n+ private final OpenAPI3SchemaParser schemaParser;\n+ private final OpenAPI3ValidationHandlerGenerator validationHandlerGenerator;\n \n public OpenAPI3RouterBuilderImpl(Vertx vertx, HttpClient client, OpenAPIHolderImpl spec, OpenAPILoaderOptions options) {\n this.vertx = vertx;\n this.openapi = spec;\n this.options = new RouterBuilderOptions();\n- this.bodyHandler = BodyHandler.create();\n this.globalHandlers = new ArrayList<>();\n this.schemaRouter = SchemaRouter.create(vertx, client, vertx.fileSystem(), options.toSchemaRouterOptions());\n this.schemaParser = OpenAPI3SchemaParser.create(schemaRouter);\n@@ -75,7 +73,7 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder {\n this.schemaParser.withStringFormatValidator(\"binary\", v -> true);\n this.validationHandlerGenerator = new OpenAPI3ValidationHandlerGenerator(spec, schemaParser);\n \n- spec.getAbsolutePaths().forEach((u, jo) -> schemaRouter.addJson(u, jo));\n+ spec.getAbsolutePaths().forEach(schemaRouter::addJson);\n \n // Load default generators\n this.validationHandlerGenerator\n@@ -181,12 +179,6 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder {\n return this.operations.get(operationId);\n }\n \n- @Override\n- public RouterBuilder bodyHandler(BodyHandler bodyHandler) {\n- this.bodyHandler = bodyHandler;\n- return this;\n- }\n-\n @Override\n public RouterBuilder rootHandler(Handler rootHandler) {\n this.globalHandlers.add(rootHandler);\n@@ -262,8 +254,9 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder {\n public Router createRouter() {\n Router router = Router.router(vertx);\n Route globalRoute = router.route();\n- if (bodyHandler != null) {\n- globalRoute.handler(bodyHandler);\n+ if (globalHandlers.isEmpty()) {\n+ // TODO: this is very opinionated\n+ globalRoute.handler(BodyHandler.create());\n }\n globalHandlers.forEach(globalRoute::handler);\n \ndiff --git a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java\nindex 2ce74cca8..89c87d624 100644\n--- a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java\n+++ b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java\n@@ -14,8 +14,7 @@ import io.vertx.core.json.JsonObject;\n import io.vertx.ext.web.Route;\n import io.vertx.ext.web.Router;\n import io.vertx.ext.web.RoutingContext;\n-import io.vertx.ext.web.handler.BodyHandler;\n-import io.vertx.ext.web.handler.StaticHandler;\n+import io.vertx.ext.web.handler.*;\n import io.vertx.ext.web.multipart.MultipartForm;\n import io.vertx.ext.web.validation.BodyProcessorException;\n import io.vertx.ext.web.validation.ParameterProcessorException;\n@@ -156,7 +155,6 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n RouterBuilder routerBuilder = routerBuilderAsyncResult.result();\n routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n- routerBuilder.bodyHandler(null);\n \n Router router = routerBuilder.createRouter();\n \n@@ -205,15 +203,15 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n Checkpoint checkpoint = testContext.checkpoint();\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n+ routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n \n- routerBuilder.operation(\"listPets\").handler(routingContext ->\n- routingContext\n- .response()\n- .setStatusCode(200)\n- .end()\n- );\n- }).onComplete(h ->\n+ routerBuilder.operation(\"listPets\").handler(routingContext ->\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .end()\n+ );\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.GET, \"/pets\")\n .expect(statusCode(200))\n .send(testContext, checkpoint)\n@@ -225,18 +223,18 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n Checkpoint checkpoint = testContext.checkpoint();\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n+ routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n \n- routerBuilder\n- .operation(\"listPets\")\n- .handler(routingContext -> routingContext.fail(null))\n- .failureHandler(routingContext -> routingContext\n- .response()\n- .setStatusCode(500)\n- .setStatusMessage(\"ERROR\")\n- .end()\n- );\n- }).onComplete(h ->\n+ routerBuilder\n+ .operation(\"listPets\")\n+ .handler(routingContext -> routingContext.fail(null))\n+ .failureHandler(routingContext -> routingContext\n+ .response()\n+ .setStatusCode(500)\n+ .setStatusMessage(\"ERROR\")\n+ .end()\n+ );\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.GET, \"/pets\")\n .expect(statusCode(500), statusMessage(\"ERROR\"))\n .send(testContext, checkpoint)\n@@ -248,30 +246,30 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n Checkpoint checkpoint = testContext.checkpoint();\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n+ routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n \n- routerBuilder\n- .operation(\"listPets\")\n- .handler(routingContext ->\n- routingContext.put(\"message\", \"A\").next()\n- )\n- .handler(routingContext -> {\n- routingContext.put(\"message\", routingContext.get(\"message\") + \"B\");\n- routingContext.fail(500);\n- });\n- routerBuilder\n- .operation(\"listPets\")\n- .failureHandler(routingContext ->\n- routingContext.put(\"message\", routingContext.get(\"message\") + \"E\").next()\n- )\n- .failureHandler(routingContext ->\n- routingContext\n- .response()\n- .setStatusCode(500)\n- .setStatusMessage(routingContext.get(\"message\"))\n- .end()\n- );\n- }).onComplete(h ->\n+ routerBuilder\n+ .operation(\"listPets\")\n+ .handler(routingContext ->\n+ routingContext.put(\"message\", \"A\").next()\n+ )\n+ .handler(routingContext -> {\n+ routingContext.put(\"message\", routingContext.get(\"message\") + \"B\");\n+ routingContext.fail(500);\n+ });\n+ routerBuilder\n+ .operation(\"listPets\")\n+ .failureHandler(routingContext ->\n+ routingContext.put(\"message\", routingContext.get(\"message\") + \"E\").next()\n+ )\n+ .failureHandler(routingContext ->\n+ routingContext\n+ .response()\n+ .setStatusCode(500)\n+ .setStatusMessage(routingContext.get(\"message\"))\n+ .end()\n+ );\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.GET, \"/pets\")\n .expect(statusCode(500), statusMessage(\"ABE\"))\n .send(testContext, checkpoint)\n@@ -287,29 +285,29 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n Checkpoint checkpoint = testContext.checkpoint(4);\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/path_matching_order.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n+ routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n \n- routerBuilder\n- .operation(\"searchPets\")\n- .handler(routingContext -> {\n- routingContext.response().setStatusMessage(\"searchPets\").end();\n- });\n- routerBuilder\n- .operation(\"searchPetsInShop\")\n- .handler(routingContext -> {\n- routingContext.response().setStatusMessage(\"searchPetsInShop\").end();\n- });\n- routerBuilder\n- .operation(\"addPet\")\n- .handler(routingContext -> {\n- routingContext.response().setStatusMessage(\"addPet\").end();\n- });\n+ routerBuilder\n+ .operation(\"searchPets\")\n+ .handler(routingContext -> {\n+ routingContext.response().setStatusMessage(\"searchPets\").end();\n+ });\n+ routerBuilder\n+ .operation(\"searchPetsInShop\")\n+ .handler(routingContext -> {\n+ routingContext.response().setStatusMessage(\"searchPetsInShop\").end();\n+ });\n+ routerBuilder\n+ .operation(\"addPet\")\n+ .handler(routingContext -> {\n+ routingContext.response().setStatusMessage(\"addPet\").end();\n+ });\n routerBuilder\n .operation(\"addPetToShop\")\n .handler(routingContext -> {\n routingContext.response().setStatusMessage(\"addPetToShop\").end();\n });\n- }).onComplete(h -> {\n+ }).onComplete(h -> {\n testRequest(client, HttpMethod.POST, \"/pets/wolfie\")\n .expect(statusCode(200), statusMessage(\"addPet\"))\n .sendJson(new JsonObject(), testContext, checkpoint);\n@@ -334,13 +332,13 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n Checkpoint checkpoint = testContext.checkpoint();\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(\n- new RouterBuilderOptions()\n- .setRequireSecurityHandlers(false)\n- .setMountNotImplementedHandler(true)\n- );\n- routerBuilder.operation(\"showPetById\").handler(RoutingContext::next);\n- }).onComplete(h ->\n+ routerBuilder.setOptions(\n+ new RouterBuilderOptions()\n+ .setRequireSecurityHandlers(false)\n+ .setMountNotImplementedHandler(true)\n+ );\n+ routerBuilder.operation(\"showPetById\").handler(RoutingContext::next);\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.GET, \"/pets\")\n .expect(statusCode(501), statusMessage(\"Not Implemented\"))\n .send(testContext, checkpoint)\n@@ -353,15 +351,15 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(\n- new RouterBuilderOptions()\n- .setRequireSecurityHandlers(false)\n- .setMountNotImplementedHandler(true)\n- );\n+ routerBuilder.setOptions(\n+ new RouterBuilderOptions()\n+ .setRequireSecurityHandlers(false)\n+ .setMountNotImplementedHandler(true)\n+ );\n \n- routerBuilder.operation(\"deletePets\").handler(RoutingContext::next);\n- routerBuilder.operation(\"createPets\").handler(RoutingContext::next);\n- }).onComplete(rc ->\n+ routerBuilder.operation(\"deletePets\").handler(RoutingContext::next);\n+ routerBuilder.operation(\"createPets\").handler(RoutingContext::next);\n+ }).onComplete(rc ->\n testRequest(client, HttpMethod.GET, \"/pets\")\n .expect(statusCode(405), statusMessage(\"Method Not Allowed\"))\n .expect(resp ->\n@@ -375,23 +373,23 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n public void addGlobalHandlersTest(Vertx vertx, VertxTestContext testContext) {\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false));\n-\n- routerBuilder.rootHandler(rc -> {\n- rc.response().putHeader(\"header-from-global-handler\", \"some dummy data\");\n- rc.next();\n- }).rootHandler(rc -> {\n- rc.response().putHeader(\"header-from-global-handler\", \"some more dummy data\");\n- rc.next();\n- });\n+ routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false));\n+\n+ routerBuilder.rootHandler(rc -> {\n+ rc.response().putHeader(\"header-from-global-handler\", \"some dummy data\");\n+ rc.next();\n+ }).rootHandler(rc -> {\n+ rc.response().putHeader(\"header-from-global-handler\", \"some more dummy data\");\n+ rc.next();\n+ });\n \n- routerBuilder.operation(\"listPets\").handler(routingContext -> routingContext\n- .response()\n- .setStatusCode(200)\n- .setStatusMessage(\"OK\")\n- .end()\n- );\n- }).onComplete(h ->\n+ routerBuilder.operation(\"listPets\").handler(routingContext -> routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .setStatusMessage(\"OK\")\n+ .end()\n+ );\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.GET, \"/pets\")\n .expect(statusCode(200))\n .expect(responseHeader(\"header-from-global-handler\", \"some more dummy data\"))\n@@ -405,22 +403,22 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setOperationModelKey(\n- \"fooBarKey\"));\n+ routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setOperationModelKey(\n+ \"fooBarKey\"));\n \n- routerBuilder.operation(\"listPets\").handler(routingContext -> {\n- JsonObject operation = routingContext.get(\"fooBarKey\");\n+ routerBuilder.operation(\"listPets\").handler(routingContext -> {\n+ JsonObject operation = routingContext.get(\"fooBarKey\");\n \n- routingContext\n- .response()\n- .setStatusCode(200)\n- .setStatusMessage(operation.getString(\"operationId\"))\n- .end();\n- });\n- }).onComplete(h ->\n- testRequest(client, HttpMethod.GET, \"/pets\")\n- .expect(statusCode(200), statusMessage(\"listPets\"))\n- .send(testContext, checkpoint)\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .setStatusMessage(operation.getString(\"operationId\"))\n+ .end();\n+ });\n+ }).onComplete(h ->\n+ testRequest(client, HttpMethod.GET, \"/pets\")\n+ .expect(statusCode(200), statusMessage(\"listPets\"))\n+ .send(testContext, checkpoint)\n );\n }\n \n@@ -430,24 +428,24 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/produces_consumes_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false));\n+ routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false));\n \n- routerBuilder.operation(\"consumesTest\").handler(routingContext -> {\n- RequestParameters params = routingContext.get(\"parsedParameters\");\n- if (params.body() != null && params.body().isJsonObject()) {\n- routingContext\n- .response()\n- .setStatusCode(200)\n- .putHeader(\"Content-Type\", \"application/json\")\n- .end(params.body().getJsonObject().encode());\n- } else {\n- routingContext\n- .response()\n+ routerBuilder.operation(\"consumesTest\").handler(routingContext -> {\n+ RequestParameters params = routingContext.get(\"parsedParameters\");\n+ if (params.body() != null && params.body().isJsonObject()) {\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .putHeader(\"Content-Type\", \"application/json\")\n+ .end(params.body().getJsonObject().encode());\n+ } else {\n+ routingContext\n+ .response()\n .setStatusCode(200)\n .end();\n }\n });\n- }).onComplete(h -> {\n+ }).onComplete(h -> {\n JsonObject obj = new JsonObject().put(\"name\", \"francesco\");\n testRequest(client, HttpMethod.POST, \"/consumesTest\")\n .expect(statusCode(200))\n@@ -481,19 +479,19 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/produces_consumes_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false));\n+ routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false));\n \n- routerBuilder.operation(\"producesTest\").handler(routingContext -> {\n- if (((RequestParameters) routingContext.get(\"parsedParameters\")).queryParameter(\"fail\").getBoolean())\n- routingContext\n- .response()\n- .putHeader(\"content-type\", \"text/plain\")\n- .setStatusCode(500)\n- .end(\"Hate it\");\n- else\n- routingContext.response().setStatusCode(200).end(\"{}\"); // ResponseContentTypeHandler does the job for me\n- });\n- }).onComplete(h -> {\n+ routerBuilder.operation(\"producesTest\").handler(routingContext -> {\n+ if (((RequestParameters) routingContext.get(\"parsedParameters\")).queryParameter(\"fail\").getBoolean())\n+ routingContext\n+ .response()\n+ .putHeader(\"content-type\", \"text/plain\")\n+ .setStatusCode(500)\n+ .end(\"Hate it\");\n+ else\n+ routingContext.response().setStatusCode(200).end(\"{}\"); // ResponseContentTypeHandler does the job for me\n+ });\n+ }).onComplete(h -> {\n String acceptableContentTypes = String.join(\", \", \"application/json\", \"text/plain\");\n testRequest(client, HttpMethod.GET, \"/producesTest\")\n .with(requestHeader(\"Accept\", acceptableContentTypes))\n@@ -522,7 +520,7 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n routingContext.response().setStatusMessage(params.pathParameter(\"id\").getInteger().toString()).end();\n });\n \n- testContext.completeNow();\n+ testContext.completeNow();\n }).onComplete(h -> {\n testRequest(client, HttpMethod.GET, \"/product/special\")\n .expect(statusCode(200), statusMessage(\"special\"))\n@@ -539,21 +537,21 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n+ routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n \n- routerBuilder.operation(\"encodedParamTest\").handler(routingContext -> {\n- RequestParameters params = routingContext.get(\"parsedParameters\");\n- assertThat(params.pathParameter(\"p1\").toString()).isEqualTo(\"a:b\");\n- assertThat(params.queryParameter(\"p2\").toString()).isEqualTo(\"a:b\");\n- routingContext\n- .response()\n- .setStatusCode(200)\n- .setStatusMessage(params.pathParameter(\"p1\").toString())\n- .end();\n- });\n+ routerBuilder.operation(\"encodedParamTest\").handler(routingContext -> {\n+ RequestParameters params = routingContext.get(\"parsedParameters\");\n+ assertThat(params.pathParameter(\"p1\").toString()).isEqualTo(\"a:b\");\n+ assertThat(params.queryParameter(\"p2\").toString()).isEqualTo(\"a:b\");\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .setStatusMessage(params.pathParameter(\"p1\").toString())\n+ .end();\n+ });\n \n testContext.completeNow();\n- }).onComplete(h ->\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.GET, \"/foo/a%3Ab?p2=a%3Ab\")\n .expect(statusCode(200), statusMessage(\"a:b\"))\n .send(testContext, checkpoint)\n@@ -572,7 +570,7 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n BodyHandler bodyHandler = BodyHandler.create(\"my-uploads\");\n \n- routerBuilder.bodyHandler(bodyHandler);\n+ routerBuilder.rootHandler(bodyHandler);\n \n routerBuilder.operation(\"upload\").handler(routingContext -> routingContext.response().setStatusCode(201).end());\n \n@@ -595,23 +593,23 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n \n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/shared_request_body.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n+ routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);\n \n- final Handler handler = routingContext -> {\n- RequestParameters params = routingContext.get(\"parsedParameters\");\n- RequestParameter body = params.body();\n- JsonObject jsonBody = body.getJsonObject();\n- routingContext\n- .response()\n- .setStatusCode(200)\n- .setStatusMessage(\"OK\")\n- .putHeader(\"Content-Type\", \"application/json\")\n- .end(jsonBody.toBuffer());\n- };\n+ final Handler handler = routingContext -> {\n+ RequestParameters params = routingContext.get(\"parsedParameters\");\n+ RequestParameter body = params.body();\n+ JsonObject jsonBody = body.getJsonObject();\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .setStatusMessage(\"OK\")\n+ .putHeader(\"Content-Type\", \"application/json\")\n+ .end(jsonBody.toBuffer());\n+ };\n \n- routerBuilder.operation(\"thisWayWorks\").handler(handler);\n- routerBuilder.operation(\"thisWayBroken\").handler(handler);\n- }).onComplete(h -> {\n+ routerBuilder.operation(\"thisWayWorks\").handler(handler);\n+ routerBuilder.operation(\"thisWayBroken\").handler(handler);\n+ }).onComplete(h -> {\n JsonObject obj = new JsonObject().put(\"id\", \"aaa\").put(\"name\", \"bla\");\n testRequest(client, HttpMethod.POST, \"/v1/working\")\n .expect(statusCode(200))\n@@ -628,44 +626,44 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n public void pathResolverShouldNotCreateRegex(Vertx vertx, VertxTestContext testContext) {\n RouterBuilder.create(vertx, \"src/test/resources/specs/produces_consumes_test.yaml\",\n testContext.succeeding(routerBuilder -> {\n- routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false));\n+ routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false));\n \n- routerBuilder.operation(\"consumesTest\").handler(routingContext ->\n- routingContext\n- .response()\n- .setStatusCode(200)\n- .setStatusMessage(\"OK\")\n- );\n+ routerBuilder.operation(\"consumesTest\").handler(routingContext ->\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .setStatusMessage(\"OK\")\n+ );\n \n- testContext.verify(() ->\n+ testContext.verify(() ->\n assertThat(routerBuilder.createRouter().getRoutes())\n .extracting(Route::getPath)\n .anyMatch(\"/consumesTest\"::equals)\n );\n \n testContext.completeNow();\n- }));\n+ }));\n }\n \n @Test\n public void testJsonEmptyBody(Vertx vertx, VertxTestContext testContext) {\n loadBuilderAndStartServer(vertx, \"src/test/resources/specs/router_builder_test.yaml\", testContext,\n routerBuilder -> {\n- routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setMountNotImplementedHandler(false));\n+ routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setMountNotImplementedHandler(false));\n \n- routerBuilder.operation(\"jsonEmptyBody\").handler(routingContext -> {\n- RequestParameters params = routingContext.get(\"parsedParameters\");\n- RequestParameter body = params.body();\n- routingContext\n- .response()\n- .setStatusCode(200)\n- .setStatusMessage(\"OK\")\n- .putHeader(\"Content-Type\", \"application/json\")\n- .end(new JsonObject().put(\"bodyEmpty\", body == null).toBuffer());\n- });\n+ routerBuilder.operation(\"jsonEmptyBody\").handler(routingContext -> {\n+ RequestParameters params = routingContext.get(\"parsedParameters\");\n+ RequestParameter body = params.body();\n+ routingContext\n+ .response()\n+ .setStatusCode(200)\n+ .setStatusMessage(\"OK\")\n+ .putHeader(\"Content-Type\", \"application/json\")\n+ .end(new JsonObject().put(\"bodyEmpty\", body == null).toBuffer());\n+ });\n \n testContext.completeNow();\n- }).onComplete(h ->\n+ }).onComplete(h ->\n testRequest(client, HttpMethod.POST, \"/jsonBody/empty\")\n .expect(statusCode(200), jsonBodyResponse(new JsonObject().put(\"bodyEmpty\", true)))\n .send(testContext)\n@@ -1547,4 +1545,44 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest {\n });\n }\n \n+ @Test\n+ public void testProperOrderOfHandlers(Vertx vertx, VertxTestContext testContext) {\n+ loadBuilderAndStartServer(vertx, VALIDATION_SPEC, testContext, routerBuilder -> {\n+\n+ routerBuilder.rootHandler(LoggerHandler.create(true, LoggerHandler.DEFAULT_FORMAT));\n+ routerBuilder.rootHandler(TimeoutHandler.create(180000));\n+ routerBuilder.rootHandler(CorsHandler.create(\"*\"));\n+ routerBuilder.rootHandler(BodyHandler.create().setBodyLimit(40000000).setDeleteUploadedFilesOnEnd(true).setHandleFileUploads(true));\n+\n+ routerBuilder\n+ .operation(\"listPets\")\n+ .handler(routingContext -> routingContext.response().setStatusMessage(\"ok\").end());\n+ }).onComplete(h ->\n+ testRequest(client, HttpMethod.GET, \"/pets\")\n+ .expect(statusCode(200), statusMessage(\"ok\"))\n+ .send(testContext)\n+ );\n+ }\n+\n+ @Test\n+ public void testIncorrectOrderOfHandlers(Vertx vertx, VertxTestContext testContext) {\n+\n+ RouterBuilder.create(vertx, VALIDATION_SPEC, testContext.succeeding(routerBuilder -> {\n+ routerBuilder.rootHandler(BodyHandler.create().setBodyLimit(40000000).setDeleteUploadedFilesOnEnd(true).setHandleFileUploads(true));\n+ routerBuilder.rootHandler(LoggerHandler.create(true, LoggerHandler.DEFAULT_FORMAT));\n+ routerBuilder.rootHandler(TimeoutHandler.create(180000));\n+ routerBuilder.rootHandler(CorsHandler.create(\"*\"));\n+\n+ routerBuilder\n+ .operation(\"listPets\")\n+ .handler(routingContext -> routingContext.response().setStatusMessage(\"ok\").end());\n+\n+ try {\n+ routerBuilder.createRouter();\n+ testContext.failNow(\"Should not reach here\");\n+ } catch (IllegalStateException ise) {\n+ testContext.completeNow();\n+ }\n+ }));\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java', 'vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java', 'vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1966252,"string":"1,966,252"},"repo_tokens_count":{"kind":"number","value":436577,"string":"436,577"},"repo_lines_count":{"kind":"number","value":61001,"string":"61,001"},"repo_files_without_tests_count":{"kind":"number","value":482,"string":"482"},"changed_symbols_count":{"kind":"number","value":1762,"string":"1,762"},"changed_tokens_count":{"kind":"number","value":365,"string":"365"},"changed_lines_count":{"kind":"number","value":39,"string":"39"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":1371,"string":"1,371"},"issue_words_count":{"kind":"number","value":141,"string":"141"},"issue_tokens_count":{"kind":"number","value":371,"string":"371"},"issue_lines_count":{"kind":"number","value":24,"string":"24"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:33","string":"1970-01-01T00:27:33"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1680,"cells":{"id":{"kind":"number","value":1271,"string":"1,271"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1245/983"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/983"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1245"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1245"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"*/* produces does not limit AcceptableContentType based on Accept header"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n* vert.x core: 3.6.0-SNAPSHOT\r\n* vert.x web: 3.6.0-SNAPSHOT\r\n\r\n### Context\r\n\r\nWhen a route can produce `*/*` and the client specifies a specific content type via the Accept header, AcceptableContentType returns `*/*` instead of the client specified content type. To figure out what the client is requesting, you have to examine the parsed Accept header yourself.\r\n\r\n### Steps to reproduce\r\n\r\nSample code:\r\n\r\n```\r\npublic static void main(String[] args) {\r\n Vertx vertx = Vertx.vertx();\r\n HttpServer server = vertx.createHttpServer();\r\n Router router = Router.router(vertx);\r\n\r\n router.route().produces(\"*/*\").handler(routingContext -> {\r\n HttpServerResponse response = routingContext.response();\r\n\r\n response.end(\"Accept headers are:\" +\r\n routingContext.parsedHeaders().accept().stream().map(ParsedHeaderValue::rawValue).collect(Collectors.toList()) +\r\n \"\\\\nAcceptable Content Type is \" +\r\n routingContext.getAcceptableContentType());\r\n });\r\n\r\n server.requestHandler(router).listen(8080);\r\n }\r\n```\r\n\r\nStart up above server.\r\n```\r\ncurl -H \"Accept: application/json\" localhost:8080\r\nAccept headers are:[application/json]\r\nAcceptable Content Type is */*\r\n```\r\n\r\nI would expect Acceptable Content Type to be `application/json`"},"base_sha":{"kind":"string","value":"9147d85ad6b300f6b75cd56907f594043797003c"},"head_sha":{"kind":"string","value":"d152aaf0aa21a99bc456adc733f992d759c8b483"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/9147d85ad6b300f6b75cd56907f594043797003c...d152aaf0aa21a99bc456adc733f992d759c8b483"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java b/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java\nindex 54e1a1777..b54d8171b 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java\n@@ -1,11 +1,11 @@\n package io.vertx.ext.web;\n \n-import java.util.Collection;\n-import java.util.List;\n-\n import io.vertx.codegen.annotations.GenIgnore;\n import io.vertx.codegen.annotations.VertxGen;\n \n+import java.util.Collection;\n+import java.util.List;\n+\n /**\n * A container with the request's headers that are meaningful enough to be parsed\n * Contains:\n@@ -54,5 +54,5 @@ public interface ParsedHeaderValues {\n * @return The first header that matched, otherwise empty if none matched\n */\n @GenIgnore\n- T findBestUserAcceptedIn(List accepted, Collection in);\n+ MIMEHeader findBestUserAcceptedIn(List accepted, Collection in);\n }\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java\nindex a9c528c06..1ae8bf71a 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java\n@@ -1,13 +1,13 @@\n package io.vertx.ext.web.impl;\n \n-import java.util.Collection;\n-import java.util.List;\n-\n import io.vertx.ext.web.LanguageHeader;\n import io.vertx.ext.web.MIMEHeader;\n import io.vertx.ext.web.ParsedHeaderValue;\n import io.vertx.ext.web.ParsedHeaderValues;\n \n+import java.util.Collection;\n+import java.util.List;\n+\n public class ParsableHeaderValuesContainer implements ParsedHeaderValues {\n \n private List accept;\n@@ -48,11 +48,14 @@ public class ParsableHeaderValuesContainer implements ParsedHeaderValues {\n }\n \n @Override\n- public T findBestUserAcceptedIn(List userAccepted, Collection in) {\n- for (T acceptableType: userAccepted) {\n- T acceptedType = acceptableType.findMatchedBy(in);\n- if(acceptedType != null){\n- return acceptedType;\n+ public MIMEHeader findBestUserAcceptedIn(List userAccepted, Collection in) {\n+ for (MIMEHeader acceptableType: userAccepted) {\n+ MIMEHeader acceptedType = acceptableType.findMatchedBy(in);\n+ if (acceptedType != null) {\n+ if (\"*\".equals(acceptedType.subComponent()) || \"*\".equals(acceptedType.component()))\n+ return acceptableType;\n+ else\n+ return acceptedType;\n }\n }\n return null;\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\nindex 9019767d1..b469388ae 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java\n@@ -1088,6 +1088,33 @@ public class RouterTest extends WebTestBase {\n testRequestWithAccepts(HttpMethod.GET, \"/foo\", \"application/*\", 404, \"Not Found\");\n }\n \n+ @Test\n+ public void testProducesSubtypeWildcardAcceptTextPlain() throws Exception {\n+ router.route().produces(\"text/*\").handler(rc -> {\n+ rc.response().setStatusMessage(rc.getAcceptableContentType());\n+ rc.response().end();\n+ });\n+ testRequestWithAccepts(HttpMethod.GET, \"/foo\", \"text/plain\", 200, \"text/plain\");\n+ }\n+\n+ @Test\n+ public void testProducesComponentWildcardAcceptTextPlain() throws Exception {\n+ router.route().produces(\"*/plain\").handler(rc -> {\n+ rc.response().setStatusMessage(rc.getAcceptableContentType());\n+ rc.response().end();\n+ });\n+ testRequestWithAccepts(HttpMethod.GET, \"/foo\", \"text/plain\", 200, \"text/plain\");\n+ }\n+\n+ @Test\n+ public void testProducesAllWildcard() throws Exception {\n+ router.route().produces(\"*/*\").handler(rc -> {\n+ rc.response().setStatusMessage(rc.getAcceptableContentType());\n+ rc.response().end();\n+ });\n+ testRequestWithAccepts(HttpMethod.GET, \"/foo\", \"text/plain\", 200, \"text/plain\");\n+ }\n+\n @Test\n public void testProducesTopLevelTypeWildcard() throws Exception {\n router.route().produces(\"application/json\").handler(rc -> {"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java', 'vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1117662,"string":"1,117,662"},"repo_tokens_count":{"kind":"number","value":250532,"string":"250,532"},"repo_lines_count":{"kind":"number","value":35342,"string":"35,342"},"repo_files_without_tests_count":{"kind":"number","value":278,"string":"278"},"changed_symbols_count":{"kind":"number","value":1114,"string":"1,114"},"changed_tokens_count":{"kind":"number","value":243,"string":"243"},"changed_lines_count":{"kind":"number","value":27,"string":"27"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":1285,"string":"1,285"},"issue_words_count":{"kind":"number","value":134,"string":"134"},"issue_tokens_count":{"kind":"number","value":286,"string":"286"},"issue_lines_count":{"kind":"number","value":40,"string":"40"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:55","string":"1970-01-01T00:25:55"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1681,"cells":{"id":{"kind":"number","value":1233,"string":"1,233"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2399/2388"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2388"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2399"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2399"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"ParsableMIMEValue - component() and subComponent() do not ensure the header is parsed"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.3.7\r\n\r\n### Context\r\n\r\nThe `io.vertx.ext.web.impl.ParsableMIMEValue.component()` and `io.vertx.ext.web.impl.ParsableMIMEValue.subComponent()` methods do not call the `ensureHeaderProcessed()` method. As a result, these methods may return `null`.\r\n\r\nA workaround exists: first call any other method that triggers parsing, e.g. `io.vertx.ext.web.impl.ParsableHeaderValue.value()`.\r\n\r\nThere is also `io.vertx.ext.web.impl.ParsableHeaderValue.forceParse()` but that's an implementation class, i.e. not part of the public API.\r\n"},"base_sha":{"kind":"string","value":"6ab7e72204338712bc1303bce252a9982721917b"},"head_sha":{"kind":"string","value":"ec366d0056ea438e1aac497a4e66e128678ddf6f"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/6ab7e72204338712bc1303bce252a9982721917b...ec366d0056ea438e1aac497a4e66e128678ddf6f"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java\nindex 01d24ed2f..dda7d80c9 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java\n@@ -17,11 +17,13 @@ public class ParsableMIMEValue extends ParsableHeaderValue implements MIMEHeader\n \n @Override\n public String component() {\n+ ensureHeaderProcessed();\n return component;\n }\n \n @Override\n public String subComponent() {\n+ ensureHeaderProcessed();\n return subComponent;\n }\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":2020811,"string":"2,020,811"},"repo_tokens_count":{"kind":"number","value":448355,"string":"448,355"},"repo_lines_count":{"kind":"number","value":62401,"string":"62,401"},"repo_files_without_tests_count":{"kind":"number","value":504,"string":"504"},"changed_symbols_count":{"kind":"number","value":59,"string":"59"},"changed_tokens_count":{"kind":"number","value":10,"string":"10"},"changed_lines_count":{"kind":"number","value":2,"string":"2"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":539,"string":"539"},"issue_words_count":{"kind":"number","value":53,"string":"53"},"issue_tokens_count":{"kind":"number","value":129,"string":"129"},"issue_lines_count":{"kind":"number","value":12,"string":"12"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:59","string":"1970-01-01T00:27:59"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1682,"cells":{"id":{"kind":"number","value":1247,"string":"1,247"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2064/2063"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2063"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2064"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2064"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"AuthorizationHandlerImpl: hanging requests - ctx.fail() is never called at denied request with all authorizations already cached in session"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.1.1\r\n\r\n### Context\r\n\r\nWhen `AuthorizationHandlerImpl` handles a denied request for a user with an active session where all authorizations are already fetched from all providers (at a previous request of the same user session) then `ctx.fail(...)` is never called, which causes the request to hang.\r\n\r\n### Steps to reproduce\r\n\r\n_With sessions/session-cookies enabled:_\r\n\r\n1. Try to access an forbidden ressource -> forbidden is returned\r\n2. Try to access an forbidden ressource again -> the request hangs\r\n\r\n"},"base_sha":{"kind":"string","value":"ca67bd5de22f27d4389310c2fde293f9df161a94"},"head_sha":{"kind":"string","value":"fad10340e34ffce9cdf34841f81301255ad0251c"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/ca67bd5de22f27d4389310c2fde293f9df161a94...fad10340e34ffce9cdf34841f81301255ad0251c"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\nindex 10d4a1b04..e794cea21 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java\n@@ -44,11 +44,13 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n \n private final Authorization authorization;\n private final Collection authorizationProviders;\n+ private final Collection authorizationProviderIds;\n private BiConsumer variableHandler;\n \n public AuthorizationHandlerImpl(Authorization authorization) {\n this.authorization = Objects.requireNonNull(authorization);\n this.authorizationProviders = new ArrayList<>();\n+ this.authorizationProviderIds = new ArrayList<>();\n }\n \n @Override\n@@ -105,7 +107,7 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n \n final User user = ctx.user();\n \n- if (user == null || !providers.hasNext()) {\n+ if (user == null || !providers.hasNext() || allAuthorizationsFetched(user)) {\n // resume as the error handler may allow this request to become valid again\n resume(ctx.request(), parseEnded);\n ctx.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);\n@@ -135,8 +137,8 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n @Override\n public AuthorizationHandler addAuthorizationProvider(AuthorizationProvider authorizationProvider) {\n Objects.requireNonNull(authorizationProvider);\n-\n this.authorizationProviders.add(authorizationProvider);\n+ this.authorizationProviderIds.add(authorizationProvider.getId());\n return this;\n }\n \n@@ -145,4 +147,17 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler {\n request.resume();\n }\n }\n+\n+ /**\n+ * Returns true when the authorizations of all available\n+ * providers have been loaded for the given user which may have happened in a\n+ * previous request of the current user session.\n+ *\n+ * @param user\n+ * @return true when the authorizations of all available\n+ * providers have been loaded for the user\n+ */\n+ private boolean allAuthorizationsFetched(final User user) {\n+ return user.authorizations().getProviderIds().containsAll(authorizationProviderIds);\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1913013,"string":"1,913,013"},"repo_tokens_count":{"kind":"number","value":424082,"string":"424,082"},"repo_lines_count":{"kind":"number","value":59336,"string":"59,336"},"repo_files_without_tests_count":{"kind":"number","value":474,"string":"474"},"changed_symbols_count":{"kind":"number","value":855,"string":"855"},"changed_tokens_count":{"kind":"number","value":181,"string":"181"},"changed_lines_count":{"kind":"number","value":19,"string":"19"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":524,"string":"524"},"issue_words_count":{"kind":"number","value":77,"string":"77"},"issue_tokens_count":{"kind":"number","value":110,"string":"110"},"issue_lines_count":{"kind":"number","value":16,"string":"16"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:13","string":"1970-01-01T00:27:13"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1683,"cells":{"id":{"kind":"number","value":1231,"string":"1,231"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2413/2219"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2219"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2413"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2413"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"OAuth2AuthHandler.withScope returns new instance rather than updating current instance"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.3.1\r\n\r\n### Context\r\n\r\nI upgraded from 4.0.0. There were a few changes I needed to make, which went fine. But when testing OAuth with Webex, I got a message saying I was passing an invalid scope. I checked the URL, and no scope was being passed although I called `withScope()`\r\n\r\nInvestigating further, I found OAuth2AuthImpl.withScope() and .withScopes both return a new instance rather than the current instance https://github.com/vert-x3/vertx-web/blob/4.3.1/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java#L240. Other fluent methods return the same instance.\r\n\r\n### Do you have a reproducer?\r\n\r\nI don't have a reproducer that calls an external provider because Webex APIs only work with a paid account But you can review by looking at the example in the documentation, https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/main/java/examples/WebExamples.java#L1386. From what I've stepped through in my code, this won't work as expected, because on line 1402 it will pass a scope to add. But the method called doesn't update the current `oauth2` instance, instead is creates a new instance of the class and returns that. If you can debug the code, you should see at line 1405 `oauth2` does not have the scopes passed in line 1402. In order for the example to work, it would need to be changed to be `oauth2 = oauth2.withScope(\"profile\");`.\r\n\r\n### Steps to reproduce\r\n\r\n1. If you can debug the example, you will see it calls `withScope()` at line 1402\r\n2. After the method has been called, the `oauth2` instance at line 1405 won't have any scopes.\r\n\r\n### Extra\r\n\r\nI'm not sure which is your preferred solution. I can work around it by reassigning my OAuth2AuthHandler. I just want to make sure the code I have is best for the future and that the documentation and code align.\r\n"},"base_sha":{"kind":"string","value":"62c838ebe99883d38606e9eef3dcbec3025ae9db"},"head_sha":{"kind":"string","value":"70efdb09de560528968a88750c47e0f1ef914b6a"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/62c838ebe99883d38606e9eef3dcbec3025ae9db...70efdb09de560528968a88750c47e0f1ef914b6a"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java\nindex 9af0816ac..70cc1172c 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java\n@@ -32,7 +32,8 @@ import java.util.List;\n public interface JWTAuthHandler extends AuthenticationHandler {\n \n /**\n- * Create a JWT auth handler\n+ * Create a JWT auth handler. When no scopes are explicit declared, the default scopes will be looked up from the\n+ * route metadata.\n *\n * @param authProvider the auth provider to use\n * @return the auth handler\n@@ -42,7 +43,8 @@ public interface JWTAuthHandler extends AuthenticationHandler {\n }\n \n /**\n- * Create a JWT auth handler\n+ * Create a JWT auth handler. When no scopes are explicit declared, the default scopes will be looked up from the\n+ * route metadata.\n *\n * @param authProvider the auth provider to use\n * @return the auth handler\n@@ -52,32 +54,31 @@ public interface JWTAuthHandler extends AuthenticationHandler {\n }\n \n /**\n- * Return a new instance with the internal state copied from the caller but the scopes delimiter set\n- * to be unique to the instance.\n+ * Set the scope delimiter. By default this is a space character.\n *\n * @param delimiter scope delimiter.\n- * @return new instance of this interface.\n+ * @return fluent self.\n */\n @Fluent\n JWTAuthHandler scopeDelimiter(String delimiter);\n \n /**\n * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token\n- * request are unique to the instance.\n+ * request are unique to the instance. When scopes are applied to the handler, the default scopes from the route\n+ * metadata will be ignored.\n *\n * @param scope scope.\n * @return new instance of this interface.\n */\n- @Fluent\n JWTAuthHandler withScope(String scope);\n \n /**\n * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token\n- * request are unique to the instance.\n+ * request are unique to the instance. When scopes are applied to the handler, the default scopes from the route\n+ * metadata will be ignored.\n *\n * @param scopes scopes.\n * @return new instance of this interface.\n */\n- @Fluent\n JWTAuthHandler withScopes(List scopes);\n }\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java\nindex 5b9f1df31..2f8439444 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java\n@@ -35,11 +35,14 @@ import java.util.List;\n public interface OAuth2AuthHandler extends AuthenticationHandler {\n \n /**\n- * Create a OAuth2 auth handler with host pinning\n+ * Create a OAuth2 auth handler with host pinning. When no scopes are explicit declared, the default scopes will be\n+ * looked up from the route metadata under the key {@code scopes} which can either be a single {@link String} or a\n+ * {@link List}.\n *\n * @param vertx the vertx instance\n * @param authProvider the auth provider to use\n- * @param callbackURL the callback URL you entered in your provider admin console, usually it should be something like: `https://myserver:8888/callback`\n+ * @param callbackURL the callback URL you entered in your provider admin console, usually it should be something\n+ * like: {@code https://myserver:8888/callback}\n * @return the auth handler\n */\n static OAuth2AuthHandler create(Vertx vertx, OAuth2Auth authProvider, String callbackURL) {\n@@ -50,9 +53,10 @@ public interface OAuth2AuthHandler extends AuthenticationHandler {\n }\n \n /**\n- * Create a OAuth2 auth handler without host pinning.\n- * Most providers will not look to the redirect url but always redirect to\n- * the preconfigured callback. So this factory does not provide a callback url.\n+ * Create a OAuth2 auth handler without host pinning.Most providers will not look to the redirect url but always\n+ * redirect to the preconfigured callback. So this factory does not provide a callback url. When no scopes are\n+ * explicit declared, the default scopes will be looked up from the route metadata under the key {@code scopes}\n+ * which can either be a single {@link String} or a {@link List}.\n *\n * @param vertx the vertx instance\n * @param authProvider the auth provider to use\n@@ -72,8 +76,9 @@ public interface OAuth2AuthHandler extends AuthenticationHandler {\n OAuth2AuthHandler extraParams(JsonObject extraParams);\n \n /**\n- * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token\n- * request are unique to the instance.\n+ * Return a new instance with the internal state copied from the caller but the scopes to be requested during\n+ * a token request are unique to the instance. When scopes are applied to the handler, the default scopes from the\n+ * route metadata will be ignored.\n *\n * @param scope scope.\n * @return new instance of this interface.\n@@ -82,8 +87,9 @@ public interface OAuth2AuthHandler extends AuthenticationHandler {\n OAuth2AuthHandler withScope(String scope);\n \n /**\n- * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token\n- * request are unique to the instance.\n+ * Return a new instance with the internal state copied from the caller but the scopes to be requested during\n+ * a token request are unique to the instance. When scopes are applied to the handler, the default scopes from the\n+ * route metadata will be ignored.\n *\n * @param scopes scopes.\n * @return new instance of this interface.\n@@ -98,9 +104,14 @@ public interface OAuth2AuthHandler extends AuthenticationHandler {\n *\n *
      \n *
    • login will force the user to enter their credentials on that request, negating single-sign on.
    • \n- *
    • none is the opposite - it will ensure that the user isn't presented with any interactive prompt whatsoever. If the request can't be completed silently via single-sign on, the Microsoft identity platform endpoint will return an interaction_required error.
    • \n- *
    • consent will trigger the OAuth consent dialog after the user signs in, asking the user to grant permissions to the app.
    • \n- *
    • select_account will interrupt single sign-on providing account selection experience listing all the accounts either in session or any remembered account or an option to choose to use a different account altogether.
    • \n+ *
    • none is the opposite - it will ensure that the user isn't presented with any interactive prompt\n+ * whatsoever. If the request can't be completed silently via single-sign on, the Microsoft identity platform\n+ * endpoint will return an interaction_required error.
    • \n+ *
    • consent will trigger the OAuth consent dialog after the user signs in, asking the user to grant\n+ * permissions to the app.
    • \n+ *
    • select_account will interrupt single sign-on providing account selection experience listing all the\n+ * accounts either in session or any remembered account or an option to choose to use a different account\n+ * altogether.
    • \n *
    • \n *
    \n *\n@@ -125,7 +136,7 @@ public interface OAuth2AuthHandler extends AuthenticationHandler {\n \n /**\n * add the callback handler to a given route.\n- * @param route a given route e.g.: `/callback`\n+ * @param route a given route e.g.: {@code /callback}\n * @return self\n */\n @Fluent\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java\nindex a3f47bacd..5550c8501 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java\n@@ -29,7 +29,9 @@ import io.vertx.ext.web.handler.JWTAuthHandler;\n import io.vertx.ext.web.impl.RoutingContextInternal;\n \n import java.util.ArrayList;\n+import java.util.Collections;\n import java.util.List;\n+import java.util.Objects;\n import java.util.stream.Collectors;\n import java.util.stream.Stream;\n \n@@ -39,17 +41,19 @@ import java.util.stream.Stream;\n public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler implements JWTAuthHandler, ScopedAuthentication {\n \n private final List scopes;\n- private final String delimiter;\n+ private String delimiter;\n \n public JWTAuthHandlerImpl(JWTAuth authProvider, String realm) {\n super(authProvider, Type.BEARER, realm);\n- scopes = new ArrayList<>();\n+ scopes = Collections.emptyList();\n this.delimiter = \" \";\n }\n \n private JWTAuthHandlerImpl(JWTAuthHandlerImpl base, List scopes, String delimiter) {\n super(base.authProvider, Type.BEARER, base.realm);\n+ Objects.requireNonNull(scopes, \"scopes cannot be null\");\n this.scopes = scopes;\n+ Objects.requireNonNull(delimiter, \"delimiter cannot be null\");\n this.delimiter = delimiter;\n }\n \n@@ -88,6 +92,7 @@ public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler implem\n \n @Override\n public JWTAuthHandler withScope(String scope) {\n+ Objects.requireNonNull(scope, \"scope cannot be null\");\n List updatedScopes = new ArrayList<>(this.scopes);\n updatedScopes.add(scope);\n return new JWTAuthHandlerImpl(this, updatedScopes, delimiter);\n@@ -95,12 +100,15 @@ public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler implem\n \n @Override\n public JWTAuthHandler withScopes(List scopes) {\n+ Objects.requireNonNull(scopes, \"scopes cannot be null\");\n return new JWTAuthHandlerImpl(this, scopes, delimiter);\n }\n \n @Override\n- public JWTAuthHandler scopeDelimiter(String delimeter) {\n- return new JWTAuthHandlerImpl(this, scopes, delimeter);\n+ public JWTAuthHandler scopeDelimiter(String delimiter) {\n+ Objects.requireNonNull(delimiter, \"delimiter cannot be null\");\n+ this.delimiter = delimiter;\n+ return this;\n }\n \n /**\n@@ -115,6 +123,8 @@ public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler implem\n return;\n }\n // the user is authenticated, however the user may not have all the required scopes\n+ final List scopes = getScopesOrSearchMetadata(this.scopes, ctx);\n+\n if (scopes.size() > 0) {\n final JsonObject jwt = user.get(\"accessToken\");\n if (jwt == null) {\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\nindex 0fc83daf2..62c8bfc7f 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\n@@ -61,7 +61,6 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n private final MessageDigest sha256;\n \n private final List scopes;\n- private final boolean openId;\n private JsonObject extraParams;\n private String prompt;\n private int pkce = -1;\n@@ -92,8 +91,7 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n this.callbackURL = null;\n }\n // scopes are empty by default\n- this.scopes = new ArrayList<>();\n- this.openId = false;\n+ this.scopes = Collections.emptyList();\n }\n \n private OAuth2AuthHandlerImpl(OAuth2AuthHandlerImpl base, List scopes) {\n@@ -117,8 +115,8 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n this.callback = base.callback;\n this.order = base.order;\n // apply the new scopes\n+ Objects.requireNonNull(scopes, \"scopes cannot be null\");\n this.scopes = scopes;\n- this.openId = scopes != null && scopes.contains(\"openid\");\n }\n \n @Override\n@@ -150,13 +148,15 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n // the redirect is processed as a failure to abort the chain\n String redirectUri = context.request().uri();\n try {\n- return Future.failedFuture(new HttpException(302, authURI(context.session(), redirectUri)));\n+ return Future.failedFuture(new HttpException(302, authURI(context, redirectUri)));\n } catch (IllegalStateException e) {\n return Future.failedFuture(e);\n }\n }\n } else {\n // continue\n+ final List scopes = getScopesOrSearchMetadata(this.scopes, context);\n+\n final Credentials credentials =\n scopes.size() > 0 ? new TokenCredentials(token).setScopes(scopes) : new TokenCredentials(token);\n \n@@ -170,12 +170,14 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n });\n }\n \n- private String authURI(Session session, String redirectURL) {\n+ private String authURI(RoutingContext context, String redirectURL) {\n \n String state = null;\n String codeVerifier = null;\n String loginHint = null;\n \n+ final Session session = context.session();\n+\n if (session == null) {\n if (pkce > 0) {\n // we can only handle PKCE with a session\n@@ -224,6 +226,8 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n config.setRedirectUri(callbackURL.href());\n }\n \n+ final List scopes = getScopesOrSearchMetadata(this.scopes, context);\n+\n if (scopes.size() > 0) {\n config.setScopes(scopes);\n }\n@@ -248,6 +252,8 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n \n @Override\n public OAuth2AuthHandler withScope(String scope) {\n+ Objects.requireNonNull(scope, \"scope cannot be null\");\n+\n List updatedScopes = new ArrayList<>(this.scopes);\n updatedScopes.add(scope);\n return new OAuth2AuthHandlerImpl(this, updatedScopes);\n@@ -255,6 +261,7 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n \n @Override\n public OAuth2AuthHandler withScopes(List scopes) {\n+ Objects.requireNonNull(scopes, \"scopes cannot be null\");\n return new OAuth2AuthHandlerImpl(this, scopes);\n }\n \n@@ -329,7 +336,9 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n @Override\n public void postAuthentication(RoutingContext ctx) {\n // the user is authenticated, however the user may not have all the required scopes\n- if (scopes != null && scopes.size() > 0) {\n+ final List scopes = getScopesOrSearchMetadata(this.scopes, ctx);\n+\n+ if (scopes.size() > 0) {\n final User user = ctx.user().get();\n if (user == null) {\n // bad state\n@@ -338,22 +347,26 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n }\n \n if (user.principal().containsKey(\"scope\")) {\n- final String scopes = user.principal().getString(\"scope\");\n- if (scopes != null) {\n+ final String userScopes = user.principal().getString(\"scope\");\n+ if (userScopes != null) {\n // user principal contains scope, a basic assertion is required to ensure that\n // the scopes present match the required ones\n- for (String scope : this.scopes) {\n+\n+ // check if openid is active\n+ final boolean openId = userScopes.contains(\"openid\");\n+\n+ for (String scope : scopes) {\n // do not assert openid scopes if openid is active\n if (openId && OPENID_SCOPES.contains(scope)) {\n continue;\n }\n \n- int idx = scopes.indexOf(scope);\n+ int idx = userScopes.indexOf(scope);\n if (idx != -1) {\n // match, but is it valid?\n if (\n- (idx != 0 && scopes.charAt(idx -1) != ' ') ||\n- (idx + scope.length() != scopes.length() && scopes.charAt(idx + scope.length()) != ' ')) {\n+ (idx != 0 && userScopes.charAt(idx -1) != ' ') ||\n+ (idx + scope.length() != userScopes.length() && userScopes.charAt(idx + scope.length()) != ' ')) {\n // invalid scope assignment\n ctx.fail(403, new IllegalStateException(\"principal scope != handler scopes\"));\n return;\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java\nindex 853a74634..cf03a03ee 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java\n@@ -1,13 +1,18 @@\n package io.vertx.ext.web.handler.impl;\n \n+import io.vertx.ext.web.Route;\n+import io.vertx.ext.web.RoutingContext;\n import io.vertx.ext.web.handler.AuthenticationHandler;\n \n+import java.util.Collections;\n import java.util.List;\n+import java.util.Map;\n \n /**\n * Internal interface for scope aware Authentication handlers.\n- * @author Paulo Lopes\n+ *\n * @param \n+ * @author Paulo Lopes\n */\n public interface ScopedAuthentication {\n \n@@ -28,4 +33,39 @@ public interface ScopedAuthentication {\n * @return new instance of this interface.\n */\n SELF withScopes(List scopes);\n+\n+ /**\n+ * Return the list of scopes provided as the 1st argument, unless the list is empty. In this case, the list of scopes\n+ * is obtained from the routing context metadata if possible. In case the metadata is not available, the list of\n+ * scopes is always an empty list.\n+ */\n+ default List getScopesOrSearchMetadata(List scopes, RoutingContext ctx) {\n+ if (!scopes.isEmpty()) {\n+ return scopes;\n+ }\n+\n+ final Route currentRoute = ctx.currentRoute();\n+\n+ if (currentRoute == null) {\n+ return Collections.emptyList();\n+ }\n+\n+ final Object value = currentRoute\n+ .metadata()\n+ .get(\"scopes\");\n+\n+ if (value == null) {\n+ return Collections.emptyList();\n+ }\n+\n+ if (value instanceof List) {\n+ return (List) value;\n+ }\n+\n+ if (value instanceof String) {\n+ return Collections.singletonList((String) value);\n+ }\n+\n+ throw new IllegalStateException(\"Invalid type for scopes metadata: \" + value.getClass().getName());\n+ }\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java\nindex 33069c484..fd688fa8d 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java\n@@ -160,4 +160,50 @@ public class JWTAuthHandlerTest extends WebTestBase {\n \n testRequest(HttpMethod.GET, \"/\", req -> req.putHeader(\"Authorization\", \"Bearer \" + authProvider.generateToken(payloadB)), 200, \"OK\", null);\n }\n+\n+ @Test\n+ public void testLoginWithScopesFromMetadata() throws Exception {\n+\n+ router.route()\n+ .putMetadata(\"scopes\", Arrays.asList(\"a\", \"b\"))\n+ .handler(JWTAuthHandler.create(authProvider))\n+ .handler(RoutingContext::end);\n+\n+ // Payload as String list\n+ final JsonObject payloadA = new JsonObject()\n+ .put(\"sub\", \"Paulo\")\n+ .put(\"scope\", String.join(\" \", Arrays.asList(\"a\", \"b\")));\n+\n+ testRequest(HttpMethod.GET, \"/\", req -> req.putHeader(\"Authorization\", \"Bearer \" + authProvider.generateToken(payloadA)), 200, \"OK\", null);\n+\n+ // Payload as Array\n+ final JsonObject payloadB = new JsonObject()\n+ .put(\"sub\", \"Paulo\")\n+ .put(\"scope\", new JsonArray().add(\"a\").add(\"b\"));\n+\n+ testRequest(HttpMethod.GET, \"/\", req -> req.putHeader(\"Authorization\", \"Bearer \" + authProvider.generateToken(payloadB)), 200, \"OK\", null);\n+ }\n+\n+ @Test\n+ public void testLoginWithScopesFromMetadataSingle() throws Exception {\n+\n+ router.route()\n+ .putMetadata(\"scopes\", \"a\")\n+ .handler(JWTAuthHandler.create(authProvider))\n+ .handler(RoutingContext::end);\n+\n+ // Payload as String list\n+ final JsonObject payloadA = new JsonObject()\n+ .put(\"sub\", \"Paulo\")\n+ .put(\"scope\", \"a\");\n+\n+ testRequest(HttpMethod.GET, \"/\", req -> req.putHeader(\"Authorization\", \"Bearer \" + authProvider.generateToken(payloadA)), 200, \"OK\", null);\n+\n+ // Payload as Array\n+ final JsonObject payloadB = new JsonObject()\n+ .put(\"sub\", \"Paulo\")\n+ .put(\"scope\", new JsonArray().add(\"a\"));\n+\n+ testRequest(HttpMethod.GET, \"/\", req -> req.putHeader(\"Authorization\", \"Bearer \" + authProvider.generateToken(payloadB)), 200, \"OK\", null);\n+ }\n }\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java\nindex 443350172..5db674edf 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java\n@@ -241,6 +241,130 @@ public class OAuth2AuthHandlerTest extends WebTestBase {\n server.close();\n }\n \n+ @Test\n+ public void testAuthCodeFlowWithScopesFromMetadata() throws Exception {\n+\n+ // lets mock an oauth2 server using code auth code flow\n+ OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()\n+ .setClientId(\"client-id\")\n+ .setClientSecret(\"client-secret\")\n+ .setSite(\"http://localhost:10000\"));\n+\n+ final CountDownLatch latch = new CountDownLatch(1);\n+\n+ HttpServer server = vertx.createHttpServer().requestHandler(req -> {\n+ if (req.method() == HttpMethod.POST && \"/oauth/token\".equals(req.path())) {\n+ req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader(\"Content-Type\", \"application/json\").end(fixture.encode()));\n+ } else if (req.method() == HttpMethod.POST && \"/oauth/revoke\".equals(req.path())) {\n+ req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end());\n+ } else {\n+ req.response().setStatusCode(400).end();\n+ }\n+ });\n+\n+ server.listen(10000).onComplete(ready -> {\n+ if (ready.failed()) {\n+ throw new RuntimeException(ready.cause());\n+ }\n+ // ready\n+ latch.countDown();\n+ });\n+\n+ latch.await();\n+\n+ // create a oauth2 handler on our domain to the callback: \"http://localhost:8080/callback\"\n+ OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler\n+ .create(vertx, oauth2, \"http://localhost:8080/callback\");\n+\n+ // setup the callback handler for receiving the callback\n+ oauth2Handler.setupCallback(router.route(\"/callback\"));\n+\n+ // protect everything under /protected\n+ router.route(\"/protected/*\")\n+ .putMetadata(\"scopes\", \"read\")\n+ .handler(oauth2Handler);\n+ // mount some handler under the protected zone\n+ router.route(\"/protected/somepage\").handler(rc -> {\n+ assertNotNull(rc.user().get());\n+ rc.response().end(\"Welcome to the protected resource!\");\n+ });\n+\n+\n+ testRequest(HttpMethod.GET, \"/protected/somepage\", null, resp -> {\n+ // in this case we should get a redirect\n+ redirectURL = resp.getHeader(\"Location\");\n+ assertNotNull(redirectURL);\n+ }, 302, \"Found\", null);\n+\n+ // fake the redirect\n+ testRequest(HttpMethod.GET, \"/callback?state=/protected/somepage&code=1\", null, resp -> {\n+ }, 200, \"OK\", \"Welcome to the protected resource!\");\n+\n+ server.close();\n+ }\n+\n+ @Test\n+ public void testAuthCodeFlowWithScopesFromMetadataNoMatch() throws Exception {\n+\n+ // lets mock an oauth2 server using code auth code flow\n+ OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()\n+ .setClientId(\"client-id\")\n+ .setClientSecret(\"client-secret\")\n+ .setSite(\"http://localhost:10000\"));\n+\n+ final CountDownLatch latch = new CountDownLatch(1);\n+\n+ HttpServer server = vertx.createHttpServer().requestHandler(req -> {\n+ if (req.method() == HttpMethod.POST && \"/oauth/token\".equals(req.path())) {\n+ req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader(\"Content-Type\", \"application/json\").end(fixture.encode()));\n+ } else if (req.method() == HttpMethod.POST && \"/oauth/revoke\".equals(req.path())) {\n+ req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end());\n+ } else {\n+ req.response().setStatusCode(400).end();\n+ }\n+ });\n+\n+ server.listen(10000).onComplete(ready -> {\n+ if (ready.failed()) {\n+ throw new RuntimeException(ready.cause());\n+ }\n+ // ready\n+ latch.countDown();\n+ });\n+\n+ latch.await();\n+\n+ // create a oauth2 handler on our domain to the callback: \"http://localhost:8080/callback\"\n+ OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler\n+ .create(vertx, oauth2, \"http://localhost:8080/callback\");\n+\n+ // setup the callback handler for receiving the callback\n+ oauth2Handler.setupCallback(router.route(\"/callback\"));\n+\n+ // protect everything under /protected\n+ router.route(\"/protected/*\")\n+ .putMetadata(\"scopes\", \"delete\")\n+ .handler(oauth2Handler);\n+ // mount some handler under the protected zone\n+ router.route(\"/protected/somepage\").handler(rc -> {\n+ assertNotNull(rc.user().get());\n+ rc.response().end(\"Welcome to the protected resource!\");\n+ });\n+\n+\n+ testRequest(HttpMethod.GET, \"/protected/somepage\", null, resp -> {\n+ // in this case we should get a redirect\n+ redirectURL = resp.getHeader(\"Location\");\n+ assertNotNull(redirectURL);\n+ }, 302, \"Found\", null);\n+\n+ // fake the redirect\n+ testRequest(HttpMethod.GET, \"/callback?state=/protected/somepage&code=1\", null, resp -> {\n+ }, 403, \"Forbidden\", null);\n+\n+ server.close();\n+ }\n+\n @Test\n public void testAuthCodeFlowBypass() throws Exception {\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 7}"},"changed_files_count":{"kind":"number","value":7,"string":"7"},"java_changed_files_count":{"kind":"number","value":7,"string":"7"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":7,"string":"7"},"repo_symbols_count":{"kind":"number","value":1755892,"string":"1,755,892"},"repo_tokens_count":{"kind":"number","value":392675,"string":"392,675"},"repo_lines_count":{"kind":"number","value":55397,"string":"55,397"},"repo_files_without_tests_count":{"kind":"number","value":443,"string":"443"},"changed_symbols_count":{"kind":"number","value":8764,"string":"8,764"},"changed_tokens_count":{"kind":"number","value":1916,"string":"1,916"},"changed_lines_count":{"kind":"number","value":155,"string":"155"},"changed_files_without_tests_count":{"kind":"number","value":5,"string":"5"},"issue_symbols_count":{"kind":"number","value":1838,"string":"1,838"},"issue_words_count":{"kind":"number","value":279,"string":"279"},"issue_tokens_count":{"kind":"number","value":458,"string":"458"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:28:00","string":"1970-01-01T00:28:00"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1684,"cells":{"id":{"kind":"number","value":1272,"string":"1,272"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1046/1044"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1044"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1046"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1046"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"OAuth handler should not redirect the callback route"},"issue_body":{"kind":"string","value":"when the oauth handle is set to protect everything e.g.: `router.route().handler(...` it always covers the `callback` handler and this will enter an infinite loop of redirects to the oauth provider and back. This needs to be whitelisted."},"base_sha":{"kind":"string","value":"19cfcfa8c421a207c430a8f3f3e301b0b2ffcb62"},"head_sha":{"kind":"string","value":"0140c6910f3c5c599eee1827d57b921fbfe687ba"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/19cfcfa8c421a207c430a8f3f3e301b0b2ffcb62...0140c6910f3c5c599eee1827d57b921fbfe687ba"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\nindex 414f08356..fb18a2b86 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\n@@ -23,6 +23,8 @@ import io.vertx.core.http.HttpHeaders;\n import io.vertx.core.http.HttpMethod;\n import io.vertx.core.json.JsonArray;\n import io.vertx.core.json.JsonObject;\n+import io.vertx.core.logging.Logger;\n+import io.vertx.core.logging.LoggerFactory;\n import io.vertx.ext.auth.AuthProvider;\n import io.vertx.ext.auth.oauth2.OAuth2Auth;\n import io.vertx.ext.web.Route;\n@@ -43,6 +45,8 @@ import static io.vertx.ext.auth.oauth2.OAuth2FlowType.AUTH_CODE;\n */\n public class OAuth2AuthHandlerImpl extends AuthorizationAuthHandler implements OAuth2AuthHandler {\n \n+ private static final Logger log = LoggerFactory.getLogger(OAuth2AuthHandlerImpl.class);\n+\n /**\n * This is a verification step, it can abort the instantiation by\n * throwing a RuntimeException\n@@ -116,8 +120,22 @@ public class OAuth2AuthHandlerImpl extends AuthorizationAuthHandler implements O\n handler.handle(Future.failedFuture(\"callback route is not configured.\"));\n return;\n }\n- // the redirect is processed as a failure to abort the chain\n- handler.handle(Future.failedFuture(new HttpStatusException(302, authURI(context.request().uri()))));\n+ // when this handle is mounted as a catch all, the callback route must be configured before,\n+ // as it would shade the callback route. When a request matches the callback path and has the\n+ // method GET the exceptional case should not redirect to the oauth2 server as it would become\n+ // an infinite redirect loop. In this case an exception must be raised.\n+ if (\n+ context.request().method() == HttpMethod.GET &&\n+ context.normalisedPath().equals(callback.getPath())) {\n+\n+ if (log.isWarnEnabled()) {\n+ log.warn(\"The callback route is shaded by the OAuth2AuthHandler, ensure the callback route is added BEFORE the OAuth2AuthHandler route!\");\n+ }\n+ handler.handle(Future.failedFuture(new HttpStatusException(500, \"Infinite redirect loop [oauth2 callback]\")));\n+ } else {\n+ // the redirect is processed as a failure to abort the chain\n+ handler.handle(Future.failedFuture(new HttpStatusException(302, authURI(context.request().uri()))));\n+ }\n } else {\n // attempt to decode the token and handle it as a user\n ((OAuth2Auth) authProvider).decodeToken(token, decodeToken -> {\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java\nindex 68ae3631b..71e2256ef 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java\n@@ -109,6 +109,82 @@ public class OAuth2AuthHandlerTest extends WebTestBase {\n server.close();\n }\n \n+ @Test\n+ public void testAuthCodeFlowBadSetup() throws Exception {\n+\n+ // lets mock a oauth2 server using code auth code flow\n+ OAuth2Auth oauth2 = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, new OAuth2ClientOptions()\n+ .setClientID(\"client-id\")\n+ .setClientSecret(\"client-secret\")\n+ .setSite(\"http://localhost:10000\"));\n+\n+ final CountDownLatch latch = new CountDownLatch(1);\n+\n+ HttpServer server = vertx.createHttpServer().requestHandler(req -> {\n+ if (req.method() == HttpMethod.POST && \"/oauth/token\".equals(req.path())) {\n+ req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader(\"Content-Type\", \"application/json\").end(fixture.encode()));\n+ } else if (req.method() == HttpMethod.POST && \"/oauth/revoke\".equals(req.path())) {\n+ req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end());\n+ } else {\n+ req.response().setStatusCode(400).end();\n+ }\n+ }).listen(10000, ready -> {\n+ if (ready.failed()) {\n+ throw new RuntimeException(ready.cause());\n+ }\n+ // ready\n+ latch.countDown();\n+ });\n+\n+ latch.await();\n+\n+ // protect everything. This has the bad sideffect that it will also shade the callback route which is computed\n+ // after this handler, the proper way to fix this would be create the route before\n+ router.route().handler(OAuth2AuthHandler.create(oauth2, \"http://localhost:8080/callback\").setupCallback(router.route()));\n+ // mount some handler under the protected zone\n+ router.route(\"/protected/somepage\").handler(rc -> {\n+ assertNotNull(rc.user());\n+ rc.response().end(\"Welcome to the protected resource!\");\n+ });\n+\n+\n+ testRequest(HttpMethod.GET, \"/protected/somepage\", null, resp -> {\n+ // in this case we should get a redirect\n+ redirectURL = resp.getHeader(\"Location\");\n+ assertNotNull(redirectURL);\n+ }, 302, \"Found\", null);\n+\n+ // fake the redirect\n+ testRequest(HttpMethod.GET, \"/callback?state=/protected/somepage&code=1\", null, resp -> {\n+ }, 500, \"Internal Server Error\", \"Internal Server Error\");\n+\n+ // second attempt with proper config\n+ router.clear();\n+\n+ // protect everything.\n+ OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler.create(oauth2, \"http://localhost:8080/callback\").setupCallback(router.route());\n+ // now the callback is registered before as it should\n+ router.route().handler(oauth2Handler);\n+ // mount some handler under the protected zone\n+ router.route(\"/protected/somepage\").handler(rc -> {\n+ assertNotNull(rc.user());\n+ rc.response().end(\"Welcome to the protected resource!\");\n+ });\n+\n+\n+ testRequest(HttpMethod.GET, \"/protected/somepage\", null, resp -> {\n+ // in this case we should get a redirect\n+ redirectURL = resp.getHeader(\"Location\");\n+ assertNotNull(redirectURL);\n+ }, 302, \"Found\", null);\n+\n+ // fake the redirect\n+ testRequest(HttpMethod.GET, \"/callback?state=/protected/somepage&code=1\", null, resp -> {\n+ }, 200, \"OK\", \"Welcome to the protected resource!\");\n+\n+ server.close();\n+ }\n+\n @Test\n public void testPasswordFlow() throws Exception {\n "},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":989166,"string":"989,166"},"repo_tokens_count":{"kind":"number","value":222491,"string":"222,491"},"repo_lines_count":{"kind":"number","value":31395,"string":"31,395"},"repo_files_without_tests_count":{"kind":"number","value":246,"string":"246"},"changed_symbols_count":{"kind":"number","value":1426,"string":"1,426"},"changed_tokens_count":{"kind":"number","value":274,"string":"274"},"changed_lines_count":{"kind":"number","value":22,"string":"22"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":237,"string":"237"},"issue_words_count":{"kind":"number","value":37,"string":"37"},"issue_tokens_count":{"kind":"number","value":51,"string":"51"},"issue_lines_count":{"kind":"number","value":1,"string":"1"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:41","string":"1970-01-01T00:25:41"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1685,"cells":{"id":{"kind":"number","value":1237,"string":"1,237"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2287/2282"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2282"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2287"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2287"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"BodyHandler Requires TRANSFER-ENCODING to react"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.3.4 \r\n\r\n### Context\r\n\r\nhttps://netty.io/news/2022/09/08/4-1-81-Final.html\r\n\r\n> Connection related headers in HTTP/2 frames are now rejected, in compliance with the specification \r\n\r\nIt is no longer allowed to set TRANSFER-ENCODING chunked on HTTP2 connections but we are currently doing this to allow BodyHandlerImpl to propagate the Body for us in RoutingContext.\r\n\r\n### Reproducer\r\n\r\nhttps://github.com/DemonicTutor/vertx-434-issues\r\nhttps://github.com/DemonicTutor/vertx-434-issues/blob/main/src/test/java/com/noenv/vertx434issues/UploadTest.java\r\n\r\n### Extra\r\n\r\n* openJdk 19\r\n"},"base_sha":{"kind":"string","value":"9736694b3b65a3fda3afbb82d98aa601f13822a8"},"head_sha":{"kind":"string","value":"bca6a416ee852b4c50f3203e6278efa13735cf55"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/9736694b3b65a3fda3afbb82d98aa601f13822a8...bca6a416ee852b4c50f3203e6278efa13735cf55"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\nindex 0269e9cca..2e674a2ef 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java\n@@ -87,8 +87,11 @@ public class BodyHandlerImpl implements BodyHandler {\n // or `content-length` headers set.\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n final long parsedContentLength = parseContentLengthHeader(request);\n+ // http2 never transmits a `transfer-encoding` as frames are chunks.\n+ final boolean hasTransferEncoding =\n+ request.version() == HttpVersion.HTTP_2 || request.headers().contains(HttpHeaders.TRANSFER_ENCODING);\n \n- if (!request.headers().contains(HttpHeaders.TRANSFER_ENCODING) && parsedContentLength == -1) {\n+ if (!hasTransferEncoding && parsedContentLength == -1) {\n // there is no \"body\", so we can skip this handler\n context.next();\n return;\ndiff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\nindex b85d3b15a..a88e50284 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java\n@@ -30,6 +30,7 @@ import io.vertx.ext.auth.VertxContextPRNG;\n import io.vertx.ext.auth.authentication.Credentials;\n import io.vertx.ext.auth.authentication.TokenCredentials;\n import io.vertx.ext.auth.oauth2.OAuth2Auth;\n+import io.vertx.ext.auth.oauth2.OAuth2FlowType;\n import io.vertx.ext.auth.oauth2.Oauth2Credentials;\n import io.vertx.ext.web.Route;\n import io.vertx.ext.web.RoutingContext;\n@@ -434,6 +435,7 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler\n }\n \n final Oauth2Credentials credentials = new Oauth2Credentials()\n+ .setFlow(OAuth2FlowType.AUTH_CODE)\n .setCode(code);\n \n // the state that was passed to the IdP server. The state can be"},"changed_files":{"kind":"string","value":"['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1970649,"string":"1,970,649"},"repo_tokens_count":{"kind":"number","value":437522,"string":"437,522"},"repo_lines_count":{"kind":"number","value":61100,"string":"61,100"},"repo_files_without_tests_count":{"kind":"number","value":482,"string":"482"},"changed_symbols_count":{"kind":"number","value":487,"string":"487"},"changed_tokens_count":{"kind":"number","value":110,"string":"110"},"changed_lines_count":{"kind":"number","value":7,"string":"7"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":597,"string":"597"},"issue_words_count":{"kind":"number","value":59,"string":"59"},"issue_tokens_count":{"kind":"number","value":158,"string":"158"},"issue_lines_count":{"kind":"number","value":21,"string":"21"},"issue_links_count":{"kind":"number","value":3,"string":"3"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:46","string":"1970-01-01T00:27:46"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1686,"cells":{"id":{"kind":"number","value":1239,"string":"1,239"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/2213/2196"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/2196"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2213"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/2213"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"SSL not set for secure Request"},"issue_body":{"kind":"string","value":"### Questions\r\nI'm currently encountering a strange bug. I'm not entirely sure whether its me, or whether something odd is happening in the vertx Code. \r\nI'm adding a secure cookie to a WebClientSession and then try to request a page from a server. \r\nHowever, the cookie is not added to the request, since the request does not set the ssl flag. \r\nI think I've found the problematic code in line 220 of HttpRequestImpl:\r\n```java\r\n if (ssl != null && ssl != client.options.isSsl()) {\r\n requestOptions\r\n .setSsl(ssl);\r\n }\r\n```\r\nThese lines will not set the ssl flag in the requestOptions if both the client.opentions.isSsl() and ssl are true. since the ssl flag on this is set to true before the line. I'm not sure, but I got the impression, that this should either be an `||` comparison, or something else is going on here. \r\n\r\n### Version\r\n\r\n4.3.1, the same code worked with 4.2.7\r\n\r\n### Context\r\n\r\nI had a test that tried to use a new session with an existing cookie but the cookie was not loaded, since the cookie was secure, but the request claimed to not have the ssl flag set.\r\n\r\n### Do you have a reproducer?\r\n\r\nSomewhat:\r\nhttps://github.com/tpfau/vertx_issue\r\n\r\nBy packaging the project you can see, that the Cookiestore gets a request for a non-ssl cookie, while the client options are set to be ssl. \r\n\r\n### Steps to reproduce\r\n\r\nRun the Tests of the reproducer, this should show that the cookiestore gets a request for a non-ssl cookie while it should get one for an ssl cookie. \r\n\r\n"},"base_sha":{"kind":"string","value":"c6aeabfae673afe2097ab799129b3dc21632d065"},"head_sha":{"kind":"string","value":"0375b9b78dc5cb496e64e26e403481551292f661"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/c6aeabfae673afe2097ab799129b3dc21632d065...0375b9b78dc5cb496e64e26e403481551292f661"},"diff":{"kind":"string","value":"diff --git a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java\nindex 34313458b..da9290138 100644\n--- a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java\n+++ b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java\n@@ -217,7 +217,10 @@ public class HttpRequestImpl implements HttpRequest {\n .setHost(host)\n .setPort(port)\n .setURI(uri);\n- if (ssl != null && ssl != client.options.isSsl()) {\n+ // if the user specified SSL we always enforce it\n+ // even if the client has a default, because the default\n+ // may have been used previously to compute the request options\n+ if (ssl != null) {\n requestOptions\n .setSsl(ssl);\n }"},"changed_files":{"kind":"string","value":"['vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1970063,"string":"1,970,063"},"repo_tokens_count":{"kind":"number","value":437405,"string":"437,405"},"repo_lines_count":{"kind":"number","value":61125,"string":"61,125"},"repo_files_without_tests_count":{"kind":"number","value":482,"string":"482"},"changed_symbols_count":{"kind":"number","value":276,"string":"276"},"changed_tokens_count":{"kind":"number","value":63,"string":"63"},"changed_lines_count":{"kind":"number","value":5,"string":"5"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1518,"string":"1,518"},"issue_words_count":{"kind":"number","value":256,"string":"256"},"issue_tokens_count":{"kind":"number","value":362,"string":"362"},"issue_lines_count":{"kind":"number","value":33,"string":"33"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:35","string":"1970-01-01T00:27:35"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1687,"cells":{"id":{"kind":"number","value":1257,"string":"1,257"},"text_id":{"kind":"string","value":"vert-x3/vertx-web/1852/1830"},"repo_owner":{"kind":"string","value":"vert-x3"},"repo_name":{"kind":"string","value":"vertx-web"},"issue_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/issues/1830"},"pull_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1852"},"comment_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/pull/1852"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"SockJS websocket connections initially fail when combined with clustered infinispan-backed sessions"},"issue_body":{"kind":"string","value":"### Version\r\n\r\n4.0.0.Beta3 - 4.0.0\r\n\r\nVersion 3.X.Y, 4.0.0.Beta1 and 4.0.0.Beta2 are not effected.\r\n\r\n### Context\r\n\r\nSince vert.x stack version 4.0.0.Beta3 SockJS websocket connections are not established\r\nfor load-balanced verticles until the same verticle processes the initial sockjs \"/info\" request and the websocket upgrade.\r\nAfter the first successful websocket upgrade the problem vanishes.\r\nThis only occurs in combination with clustered sessions handled by an infinispan cluster manager and forced websocket connections.\r\n\r\nI have not found the root cause for this problem.\r\n\r\n### Do you have a reproducer?\r\n\r\nYes, it also includes a more detailed analysis of the problem:\r\n[vertx-4-infinispan-ws-sockjs-reproducer](https://github.com/trho/vertx-4-infinispan-ws-sockjs-reproducer)\r\n\r\n### Steps to reproduce\r\n\r\nSee [vertx-4-infinispan-ws-sockjs-reproducer](https://github.com/trho/vertx-4-infinispan-ws-sockjs-reproducer)\r\n\r\n### Extra\r\n\r\nOS version, JVM version:\r\nMacOS 10.15.7, AdoptOpenJDK 11 (build 11.0.9.1+1)\r\n"},"base_sha":{"kind":"string","value":"6c50bbde8119e6f3d104f47e2a1472b95e962706"},"head_sha":{"kind":"string","value":"5c0dc3722174379c4bf594b8add03e0436d52ce1"},"diff_url":{"kind":"string","value":"https://github.com/vert-x3/vertx-web/compare/6c50bbde8119e6f3d104f47e2a1472b95e962706...5c0dc3722174379c4bf594b8add03e0436d52ce1"},"diff":{"kind":"string","value":"diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java\nindex f3be81d40..f42f2013b 100644\n--- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java\n+++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java\n@@ -72,17 +72,15 @@ public abstract class AuthenticationHandlerImpl {\n if (res.failed()) {\n- // resume as the error handler may allow this request to become valid again\n- if (!parseEnded) {\n- ctx.request().resume();\n- }\n+ resume(request, parseEnded);\n processException(ctx, res.cause());\n return;\n }\n@@ -98,9 +96,7 @@ public abstract class AuthenticationHandlerImpl minLength) {\n+ // before starting any potential async operation here\n+ // pause parsing the request body. The reason is that\n+ // we don't want to loose the body or protocol upgrades\n+ // for async operations\n+ final boolean parseEnded = request.isEnded();\n+ if (!parseEnded) {\n+ request.pause();\n+ }\n // we passed the OWASP min length requirements\n getSession(context.vertx(), sessionID, res -> {\n+ if (!parseEnded && !request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) {\n+ request.resume();\n+ }\n if (res.succeeded()) {\n Session session = res.result();\n if (session != null) {\ndiff --git a/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java\nindex 400414af8..2e430f731 100644\n--- a/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java\n+++ b/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java\n@@ -175,4 +175,21 @@ public class ClusteredSessionHandlerTest extends SessionHandlerTestBase {\n long val = doTestSessionRetryTimeout();\n assertTrue(String.valueOf(val), val >= 3000 && val < 5000);\n }\n+\n+ @Test\n+ public void testDelayedLookupWithRequestUpgrade() {\n+ String sessionCookieName = \"session\";\n+ router.route().handler(SessionHandler.create(store).setSessionCookieName(sessionCookieName).setMinLength(0));\n+ router.route().handler(rc -> {\n+ rc.request().toWebSocket(onSuccess(serverWebSocket -> serverWebSocket.textMessageHandler(msg -> {\n+ assertEquals(\"foo\", msg);\n+ testComplete();\n+ })));\n+ });\n+ WebSocketConnectOptions options = new WebSocketConnectOptions()\n+ .setURI(\"/\")\n+ .addHeader(\"cookie\", sessionCookieName + \"=\" + TestUtils.randomAlphaString(32));\n+ client.webSocket(options, onSuccess(ws -> ws.writeTextMessage(\"foo\")));\n+ await();\n+ }\n }"},"changed_files":{"kind":"string","value":"['vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1711255,"string":"1,711,255"},"repo_tokens_count":{"kind":"number","value":378609,"string":"378,609"},"repo_lines_count":{"kind":"number","value":52958,"string":"52,958"},"repo_files_without_tests_count":{"kind":"number","value":417,"string":"417"},"changed_symbols_count":{"kind":"number","value":2311,"string":"2,311"},"changed_tokens_count":{"kind":"number","value":447,"string":"447"},"changed_lines_count":{"kind":"number","value":53,"string":"53"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":1023,"string":"1,023"},"issue_words_count":{"kind":"number","value":116,"string":"116"},"issue_tokens_count":{"kind":"number","value":287,"string":"287"},"issue_lines_count":{"kind":"number","value":29,"string":"29"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:51","string":"1970-01-01T00:26:51"},"repo_stars":{"kind":"number","value":1049,"string":"1,049"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1688,"cells":{"id":{"kind":"number","value":1342,"string":"1,342"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-openfeign/202/189"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-openfeign"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/issues/189"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/pull/202"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/pull/202"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"Properly handle Pageable.unpaged() in PageableSpringEncoder"},"issue_body":{"kind":"string","value":"Version `2.1.1.RELEASE` introduced support for Spring's `Pageable` (#26). However the associated Encoder (`PageableSpringEncoder`) crashes when faced with `Pageable.unpaged()`, since the latter throws an `UnsupportedOperationException` on `Pageable.getPageNumber(int)`. This will lead to the very unspecific error:\r\n\r\n`feign.codec.EncodeException: null`\r\n\r\nPossible enhancements:\r\n- Improve error handling in the above case or\r\n- Translate `Pageable.unpaged()` to a query with page number 0 and page size `Integer.MAX_VALUE` since this is close to an \"unpaged\" result"},"base_sha":{"kind":"string","value":"eda905684de1007c7a65b378487b264b07b3da06"},"head_sha":{"kind":"string","value":"ead4c47fcb42dc36106c2ceaf573fcfb97e2e28e"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/compare/eda905684de1007c7a65b378487b264b07b3da06...ead4c47fcb42dc36106c2ceaf573fcfb97e2e28e"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java\nindex ddf631bb..4461f36b 100644\n--- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java\n+++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java\n@@ -81,8 +81,12 @@ public class PageableSpringEncoder implements Encoder {\n \t\tif (supports(object)) {\n \t\t\tif (object instanceof Pageable) {\n \t\t\t\tPageable pageable = (Pageable) object;\n-\t\t\t\ttemplate.query(pageParameter, pageable.getPageNumber() + \"\");\n-\t\t\t\ttemplate.query(sizeParameter, pageable.getPageSize() + \"\");\n+\n+\t\t\t\tif (pageable.isPaged()) {\n+\t\t\t\t\ttemplate.query(pageParameter, pageable.getPageNumber() + \"\");\n+\t\t\t\t\ttemplate.query(sizeParameter, pageable.getPageSize() + \"\");\n+\t\t\t\t}\n+\n \t\t\t\tif (pageable.getSort() != null) {\n \t\t\t\t\tapplySort(template, pageable.getSort());\n \t\t\t\t}\ndiff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java\nindex c3916507..cf94ec7c 100644\n--- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java\n+++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java\n@@ -64,13 +64,12 @@ public class PageableEncoderTests {\n \t\tencoder.encode(createPageAndSortRequest(), null, request);\n \n \t\t// Request queries shall contain three entries\n-\t\tassertThat(request.queries().size()).isEqualTo(3);\n+\t\tassertThat(request.queries()).hasSize(3);\n \t\t// Request page shall contain page\n \t\tassertThat(request.queries().get(\"page\")).contains(String.valueOf(PAGE));\n \t\t// Request size shall contain size\n-\t\tassertThat(request.queries().get(\"size\")).contains(String.valueOf(SIZE));\n-\t\t// Request sort size shall contain sort entries\n-\t\tassertThat(request.queries().get(\"sort\").size()).isEqualTo(2);\n+\t\tassertThat(request.queries().get(\"size\")).contains(String.valueOf(SIZE));\t// Request sort size shall contain sort entries\n+\t\tassertThat(request.queries().get(\"sort\")).hasSize(2);\n \t}\n \n \tprivate Pageable createPageAndSortRequest() {\n@@ -87,9 +86,8 @@ public class PageableEncoderTests {\n \t\t// Request page shall contain page\n \t\tassertThat(request.queries().get(\"page\")).contains(String.valueOf(PAGE));\n \t\t// Request size shall contain size\n-\t\tassertThat(request.queries().get(\"size\")).contains(String.valueOf(SIZE));\n-\t\t// Request sort size shall contain sort entries\n-\t\tassertThat(request.queries().containsKey(\"sort\")).isEqualTo(false);\n+\t\tassertThat(request.queries().get(\"size\")).contains(String.valueOf(SIZE));\t\t// Request sort size shall contain sort entries\n+\t\tassertThat(request.queries()).doesNotContainKey(\"sort\");\n \t}\n \n \tprivate Pageable createPageAndRequest() {\n@@ -106,11 +104,22 @@ public class PageableEncoderTests {\n \t\t// Request queries shall contain three entries\n \t\tassertThat(request.queries().size()).isEqualTo(1);\n \t\t// Request sort size shall contain sort entries\n-\t\tassertThat(request.queries().get(\"sort\").size()).isEqualTo(2);\n+\t\tassertThat(request.queries().get(\"sort\")).hasSize(2);\n \t}\n \n \tprivate Sort createSort() {\n \t\treturn Sort.by(SORT_1, SORT_2).ascending();\n \t}\n \n+\t@Test\n+\tpublic void testUnpagedRequest() {\n+\t\tEncoder encoder = this.context.getInstance(\"foo\", Encoder.class);\n+\t\tassertThat(encoder).isNotNull();\n+\t\tRequestTemplate request = new RequestTemplate();\n+\n+\t\tencoder.encode(Pageable.unpaged(), null, request);\n+\t\t// Request queries shall contain three entries\n+\t\tassertThat(request.queries()).isEmpty();\n+\t}\n+\n }"},"changed_files":{"kind":"string","value":"['spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java', 'spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":181316,"string":"181,316"},"repo_tokens_count":{"kind":"number","value":38885,"string":"38,885"},"repo_lines_count":{"kind":"number","value":5790,"string":"5,790"},"repo_files_without_tests_count":{"kind":"number","value":49,"string":"49"},"changed_symbols_count":{"kind":"number","value":307,"string":"307"},"changed_tokens_count":{"kind":"number","value":62,"string":"62"},"changed_lines_count":{"kind":"number","value":8,"string":"8"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":567,"string":"567"},"issue_words_count":{"kind":"number","value":69,"string":"69"},"issue_tokens_count":{"kind":"number","value":129,"string":"129"},"issue_lines_count":{"kind":"number","value":7,"string":"7"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:04","string":"1970-01-01T00:26:04"},"repo_stars":{"kind":"number","value":1041,"string":"1,041"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 869956, 'CSS': 34264, 'Ruby': 481}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1689,"cells":{"id":{"kind":"number","value":1341,"string":"1,341"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-openfeign/843/842"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-openfeign"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/issues/842"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/pull/843"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/pull/843#issuecomment-1453933064"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"SpringQueryMap is ignored when used with Pageable "},"issue_body":{"kind":"string","value":"`@SpringQueryMap` is ignored when method includes `Pageable`\r\n\r\n`Page list(@SpringQueryMap Pojo pojo, Pageable pageable)`\r\n\r\nthis has been introduced in version 3.1.6 by https://github.com/spring-cloud/spring-cloud-openfeign/issues/753\r\n\r\n`paramIndex` is set always to Pageable causing `PageableSpringQueryMapEncoder` to ignore `@SpringQueryMap`\r\n"},"base_sha":{"kind":"string","value":"471c5c5cb11cf6d24dc49f0d4d94f003fc5b6c89"},"head_sha":{"kind":"string","value":"5bc28fa1dd47be69c1269b6bf013e42bc6b27ff2"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-openfeign/compare/471c5c5cb11cf6d24dc49f0d4d94f003fc5b6c89...5bc28fa1dd47be69c1269b6bf013e42bc6b27ff2"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java\nindex 430bb44c..746cec5c 100644\n--- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java\n+++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java\n@@ -34,12 +34,14 @@ import feign.Contract;\n import feign.Feign;\n import feign.MethodMetadata;\n import feign.Param;\n+import feign.QueryMap;\n import feign.Request;\n import org.apache.commons.logging.Log;\n import org.apache.commons.logging.LogFactory;\n \n import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;\n import org.springframework.cloud.openfeign.CollectionFormat;\n+import org.springframework.cloud.openfeign.SpringQueryMap;\n import org.springframework.cloud.openfeign.annotation.CookieValueParameterProcessor;\n import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor;\n import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor;\n@@ -67,6 +69,7 @@ import org.springframework.util.Assert;\n import org.springframework.util.StringUtils;\n import org.springframework.web.bind.annotation.RequestMapping;\n import org.springframework.web.bind.annotation.RequestMethod;\n+import org.springframework.web.bind.annotation.RequestParam;\n \n import static feign.Util.checkState;\n import static feign.Util.emptyToNull;\n@@ -158,7 +161,7 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource\n \n \tprivate static TypeDescriptor getElementTypeDescriptor(TypeDescriptor typeDescriptor) {\n \t\tTypeDescriptor elementTypeDescriptor = typeDescriptor.getElementTypeDescriptor();\n-\t\t// that means it's not a collection but it is iterable, gh-135\n+\t\t// that means it's not a collection, but it is iterable, gh-135\n \t\tif (elementTypeDescriptor == null && Iterable.class.isAssignableFrom(typeDescriptor.getType())) {\n \t\t\tResolvableType type = typeDescriptor.getResolvableType().as(Iterable.class).getGeneric(0);\n \t\t\tif (type.resolve() == null) {\n@@ -268,8 +271,12 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource\n \n \t\ttry {\n \t\t\tif (Pageable.class.isAssignableFrom(data.method().getParameterTypes()[paramIndex])) {\n-\t\t\t\tdata.queryMapIndex(paramIndex);\n-\t\t\t\treturn false;\n+\t\t\t\t// do not set a Pageable as QueryMap if there's an actual QueryMap param\n+\t\t\t\t// present\n+\t\t\t\tif (!queryMapParamPresent(data)) {\n+\t\t\t\t\tdata.queryMapIndex(paramIndex);\n+\t\t\t\t\treturn false;\n+\t\t\t\t}\n \t\t\t}\n \t\t}\n \t\tcatch (NoClassDefFoundError ignored) {\n@@ -304,6 +311,20 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource\n \t\treturn isHttpAnnotation;\n \t}\n \n+\tprivate boolean queryMapParamPresent(MethodMetadata data) {\n+\t\tAnnotation[][] paramsAnnotations = data.method().getParameterAnnotations();\n+\t\tfor (int i = 0; i < paramsAnnotations.length; i++) {\n+\t\t\tAnnotation[] paramAnnotations = paramsAnnotations[i];\n+\t\t\tClass parameterType = data.method().getParameterTypes()[i];\n+\t\t\tif (Arrays.stream(paramAnnotations).anyMatch(\n+\t\t\t\t\tannotation -> Map.class.isAssignableFrom(parameterType) && annotation instanceof RequestParam\n+\t\t\t\t\t\t\t|| annotation instanceof SpringQueryMap || annotation instanceof QueryMap)) {\n+\t\t\t\treturn true;\n+\t\t\t}\n+\t\t}\n+\t\treturn false;\n+\t}\n+\n \tprivate void parseProduces(MethodMetadata md, Method method, RequestMapping annotation) {\n \t\tString[] serverProduces = annotation.produces();\n \t\tString clientAccepts = serverProduces.length == 0 ? null : emptyToNull(serverProduces[0]);\ndiff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java\nindex 919e85c8..e43983d4 100644\n--- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java\n+++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java\n@@ -117,7 +117,7 @@ class SpringMvcContractTests {\n \t\t\t\tMethod isNamePresent = ReflectionUtils.findMethod(parameters[0].getClass(), \"isNamePresent\");\n \t\t\t\treturn Boolean.TRUE.equals(isNamePresent.invoke(parameters[0]));\n \t\t\t}\n-\t\t\tcatch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {\n+\t\t\tcatch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignored) {\n \t\t\t}\n \t\t}\n \t\treturn false;\n@@ -631,10 +631,20 @@ class SpringMvcContractTests {\n \tvoid shouldNotFailWhenBothPageableAndRequestBodyParamsInPostRequest() {\n \t\tList data = contract.parseAndValidateMetadata(TestTemplate_PageablePost.class);\n \n-\t\tassertThat(data.get(0).queryMapIndex().intValue()).isEqualTo(0);\n-\t\tassertThat(data.get(0).bodyIndex().intValue()).isEqualTo(1);\n-\t\tassertThat(data.get(1).queryMapIndex().intValue()).isEqualTo(1);\n-\t\tassertThat(data.get(1).bodyIndex().intValue()).isEqualTo(0);\n+\t\tassertThat(data.get(0).queryMapIndex()).isEqualTo(0);\n+\t\tassertThat(data.get(0).bodyIndex()).isEqualTo(1);\n+\t\tassertThat(data.get(1).queryMapIndex()).isEqualTo(1);\n+\t\tassertThat(data.get(1).bodyIndex()).isEqualTo(0);\n+\t}\n+\n+\t@Test\n+\tvoid shouldSetPageableAsBodyWhenQueryMapParamPresent() {\n+\t\tList data = contract.parseAndValidateMetadata(TestTemplate_PageablePostWithQueryMap.class);\n+\n+\t\tassertThat(data.get(0).queryMapIndex()).isEqualTo(0);\n+\t\tassertThat(data.get(0).bodyIndex()).isEqualTo(1);\n+\t\tassertThat(data.get(1).queryMapIndex()).isEqualTo(1);\n+\t\tassertThat(data.get(1).bodyIndex()).isEqualTo(0);\n \t}\n \n \tprivate ConversionService getConversionService() {\n@@ -838,7 +848,7 @@ class SpringMvcContractTests {\n \n \t}\n \n-\tpublic interface TestTemplate_PageablePost {\n+\tinterface TestTemplate_PageablePost {\n \n \t\t@PostMapping\n \t\tPage getPage(Pageable pageable, @RequestBody String body);\n@@ -848,6 +858,16 @@ class SpringMvcContractTests {\n \n \t}\n \n+\tinterface TestTemplate_PageablePostWithQueryMap {\n+\n+\t\t@PostMapping\n+\t\tPage getPage(@SpringQueryMap TestObject pojo, Pageable pageable);\n+\n+\t\t@PostMapping\n+\t\tPage getPage(Pageable pageable, @SpringQueryMap TestObject pojo);\n+\n+\t}\n+\n \t@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)\n \tpublic class TestObject {\n "},"changed_files":{"kind":"string","value":"['spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java', 'spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":315256,"string":"315,256"},"repo_tokens_count":{"kind":"number","value":67084,"string":"67,084"},"repo_lines_count":{"kind":"number","value":9243,"string":"9,243"},"repo_files_without_tests_count":{"kind":"number","value":83,"string":"83"},"changed_symbols_count":{"kind":"number","value":1143,"string":"1,143"},"changed_tokens_count":{"kind":"number","value":253,"string":"253"},"changed_lines_count":{"kind":"number","value":27,"string":"27"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":352,"string":"352"},"issue_words_count":{"kind":"number","value":33,"string":"33"},"issue_tokens_count":{"kind":"number","value":93,"string":"93"},"issue_lines_count":{"kind":"number","value":8,"string":"8"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:57","string":"1970-01-01T00:27:57"},"repo_stars":{"kind":"number","value":1041,"string":"1,041"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 869956, 'CSS': 34264, 'Ruby': 481}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1690,"cells":{"id":{"kind":"number","value":659,"string":"659"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/1236/1235"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/1235"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1236"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1236"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Providing long deployment property values hangs"},"issue_body":{"kind":"string","value":"Trying to set a property and if the value is too long it seems to hang - saw this from both shell and UI\r\n\r\n```\r\ndataflow:>stream deploy --name ticktock --properties \"app.log.foo=FOOOOOOOOOOOBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\"\r\n```\r\n\r\ndoesn't complete in a reasonable time."},"base_sha":{"kind":"string","value":"e80994edc2f36881ac9e12941a46e82e26e41c39"},"head_sha":{"kind":"string","value":"ff2de24b4a61193237143284979fa7298b8cf696"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/e80994edc2f36881ac9e12941a46e82e26e41c39...ff2de24b4a61193237143284979fa7298b8cf696"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java b/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java\nindex 5ecc255e4..1494b4c2f 100644\n--- a/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java\n+++ b/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java\n@@ -46,11 +46,6 @@ public final class DeploymentPropertiesUtils {\n \t\t// prevent instantiation\n \t}\n \n-\t/**\n-\t * Pattern used for parsing a String of comma-delimited key=value pairs.\n-\t */\n-\tprivate static final Pattern DEPLOYMENT_PROPERTIES_PATTERN = Pattern.compile(\"(?:,{0,1}\\\\\\\\s*)((\\\\\\\\.*(\\\\\\\\w|\\\\\\\\*|-)+)+)(\\\\\\\\s*=\\\\\\\\s*)\");\n-\n \t/**\n \t * Pattern used for parsing a String of command-line arguments.\n \t */\n@@ -61,40 +56,40 @@ public final class DeploymentPropertiesUtils {\n \t * {@code app.[appname].[key]} or {@code deployer.[appname].[key]}.\n \t * Values may themselves contain commas, since the split points will be based upon the key pattern.\n \t *\n-\t *\n-\t * Logic of this pattern to find boundaries of valid key=value pairs is:\n-\t * 1. (?:,{0,1}\\\\s*) is a non-capturing group which takes characters before a key.\n-\t * Needed so that capturing groups later will capture key boundaries correctly.\n-\t * 2. ((\\\\.*(\\\\w|\\\\*|-)+)+) is a capturing group finding an actual key. There is a recursive\n-\t * capturing groups inside of it as we assume key is formed from dots and words and\n-\t * we capture those as many time as needed. We get groups 1, 2 and 3 but we only use 1.\n-\t * 3. (\\\\s*=\\\\s*) here we find boundary of '=' which may have empty characters around it.\n-\t * This becomes capturing group 4.\n-\t * 4. Now we know where is key with group 1 and start of value with group 4.\n-\t * 5. Now we can start to do matching. Need to match one ahead so that we\n-\t * know where next key possible is as that is then end of previous value.\n-\t * 6. Lastly we have one pair left which is a same case if we only have\n-\t * one pair to parse.\n+\t * Logic of parsing key/value pairs from a string is based on few rules and assumptions\n+\t * 1. keys will not have commas or equals.\n+\t * 2. First raw split is done by commas which will need to be fixed later\n+\t * if value is a comma-delimited list.\n \t *\n \t * @param s the string to parse\n \t * @return the Map of parsed key value pairs\n \t */\n \tpublic static Map parse(String s) {\n \t\tMap deploymentProperties = new HashMap();\n-\t\tif (!StringUtils.isEmpty(s)) {\n-\t\t\tint start = 0;\n-\t\t\tint end = 0;\n-\t\t\tMatcher matcher = DEPLOYMENT_PROPERTIES_PATTERN.matcher(s);\n-\t\t\twhile (matcher.find()) {\n-\t\t\t\tif (end > 0) {\n-\t\t\t\t\t// we don't know first value position until we've found second match\n-\t\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), deploymentProperties);\n-\t\t\t\t}\n-\t\t\t\tstart = matcher.start(1);\n-\t\t\t\tend = matcher.end(4);\n+\t\tArrayList pairs = new ArrayList<>();\n+\n+\t\t// get raw candidates as simple comma split\n+\t\tString[] candidates = StringUtils.commaDelimitedListToStringArray(s);\n+\t\tfor (int i = 0; i < candidates.length; i++) {\n+\t\t\tif (i > 0 && !candidates[i].contains(\"=\")) {\n+\t\t\t\t// we don't have '=' so this has to be latter parts of\n+\t\t\t\t// a comma delimited value, append it to previously added\n+\t\t\t\t// key/value pair.\n+\t\t\t\t// we skip first as we would not have anything to append to. this\n+\t\t\t\t// would happen if dep prop string is malformed and first given\n+\t\t\t\t// key/value pair is not actually a key/value.\n+\t\t\t\tpairs.set(pairs.size()-1, pairs.get(pairs.size()-1) + \",\" + candidates[i]);\n+\t\t\t}\n+\t\t\telse {\n+\t\t\t\t// we have a key/value pair having '=', or malformed first pair\n+\t\t\t\tpairs.add(candidates[i]);\n \t\t\t}\n-\t\t\t// last match, we still have one left.\n-\t\t\taddKeyValuePairAsProperty(s.substring(start), deploymentProperties);\n+\t\t}\n+\n+\t\t// add what we got, addKeyValuePairAsProperty\n+\t\t// handles rest as trimming, etc\n+\t\tfor (String pair : pairs) {\n+\t\t\taddKeyValuePairAsProperty(pair, deploymentProperties);\n \t\t}\n \t\treturn deploymentProperties;\n \t}\ndiff --git a/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java b/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java\nindex 7e3a0b42e..24eaa0db7 100644\n--- a/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java\n+++ b/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java\n@@ -83,6 +83,22 @@ public class DeploymentPropertiesUtilsTests {\n \t\tprops = DeploymentPropertiesUtils.parse(\"invalidkeyvalue1,foo=bar,invalidkeyvalue2\");\n \t\tassertThat(props.size(), is(1));\n \t\tassertThat(props, hasEntry(\"foo\", \"bar,invalidkeyvalue2\"));\n+\n+\t\tprops = DeploymentPropertiesUtils.parse(\"foo.bar1=jee1,jee2,jee3,foo.bar2=jee4,jee5,jee6\");\n+\t\tassertThat(props, hasEntry(\"foo.bar1\", \"jee1,jee2,jee3\"));\n+\t\tassertThat(props, hasEntry(\"foo.bar2\", \"jee4,jee5,jee6\"));\n+\n+\t\tprops = DeploymentPropertiesUtils.parse(\"foo.bar1=xxx=1,foo.bar2=xxx=2\");\n+\t\tassertThat(props, hasEntry(\"foo.bar1\", \"xxx=1\"));\n+\t\tassertThat(props, hasEntry(\"foo.bar2\", \"xxx=2\"));\n+\t}\n+\n+\t@Test\n+\tpublic void testLongDeploymentPropertyValues() {\n+\t\tMap props = DeploymentPropertiesUtils.parse(\"app.foo.bar=FoooooooooooooooooooooBar,app.foo.bar2=FoooooooooooooooooooooBar\");\n+\t\tassertThat(props, hasEntry(\"app.foo.bar\", \"FoooooooooooooooooooooBar\"));\n+\t\tprops = DeploymentPropertiesUtils.parse(\"app.foo.bar=FooooooooooooooooooooooooooooooooooooooooooooooooooooBar\");\n+\t\tassertThat(props, hasEntry(\"app.foo.bar\", \"FooooooooooooooooooooooooooooooooooooooooooooooooooooBar\"));\n \t}\n \n \t@Test"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java', 'spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1041670,"string":"1,041,670"},"repo_tokens_count":{"kind":"number","value":222165,"string":"222,165"},"repo_lines_count":{"kind":"number","value":30555,"string":"30,555"},"repo_files_without_tests_count":{"kind":"number","value":327,"string":"327"},"changed_symbols_count":{"kind":"number","value":2979,"string":"2,979"},"changed_tokens_count":{"kind":"number","value":771,"string":"771"},"changed_lines_count":{"kind":"number","value":59,"string":"59"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":287,"string":"287"},"issue_words_count":{"kind":"number","value":38,"string":"38"},"issue_tokens_count":{"kind":"number","value":69,"string":"69"},"issue_lines_count":{"kind":"number","value":7,"string":"7"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:49","string":"1970-01-01T00:24:49"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1691,"cells":{"id":{"kind":"number","value":648,"string":"648"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/2358/2353"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/2353"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/2358"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/2358"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"Streams definitions search is broken"},"issue_body":{"kind":"string","value":"_From @oodamien on August 3, 2018 20:52_\n\nhttps://github.com/spring-cloud/spring-cloud-dataflow/commit/4cb9d85ff2d78d239df3b1b8541514e4780f4a84#diff-1b8ed5096382d31ece0a8397f1eb4cf2R135\r\n\r\nThe search parameter has changed.\n\n_Copied from original issue: spring-cloud/spring-cloud-dataflow-ui#875_"},"base_sha":{"kind":"string","value":"042f28df7d5caf291bfb1831215f36398a7719b3"},"head_sha":{"kind":"string","value":"3010f9607f1d728fe4cfa3886dd25105fa26b84a"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/042f28df7d5caf291bfb1831215f36398a7719b3...3010f9607f1d728fe4cfa3886dd25105fa26b84a"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java\nindex 576c92897..bf2e1296f 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java\n@@ -132,14 +132,14 @@ public class StreamDefinitionController {\n \t *\n \t * @param pageable Pagination information\n \t * @param assembler assembler for {@link StreamDefinition}\n-\t * @param searchName optional findByNameLike parameter\n+\t * @param search optional findByNameLike parameter\n \t * @return list of stream definitions\n \t */\n \t@RequestMapping(value = \"\", method = RequestMethod.GET)\n \t@ResponseStatus(HttpStatus.OK)\n \tpublic PagedResources list(Pageable pageable,\n-\t\t\t@RequestParam(required = false) String searchName, PagedResourcesAssembler assembler) {\n-\t\tPage streamDefinitions = this.streamService.findDefinitionByNameLike(pageable, searchName);\n+\t\t\t@RequestParam(required = false) String search, PagedResourcesAssembler assembler) {\n+\t\tPage streamDefinitions = this.streamService.findDefinitionByNameLike(pageable, search);\n \t\treturn assembler.toResource(streamDefinitions, new Assembler(streamDefinitions));\n \t}\n \ndiff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java\nindex 346e769ad..9fc29dab6 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java\n@@ -100,10 +100,10 @@ public interface StreamService {\n \n \t/**\n \t * Find stream definitions where the findByNameLike parameter\n-\t * @param searchName the findByNameLike parameter to use\n+\t * @param search the findByNameLike parameter to use\n \t * @return Page of stream definitions\n \t */\n-\tPage findDefinitionByNameLike(Pageable pageable, String searchName);\n+\tPage findDefinitionByNameLike(Pageable pageable, String search);\n \n \t/**\n \t * Find a stream definition by name.\ndiff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java\nindex c0abe89e3..3f8b2ddc9 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java\n@@ -213,10 +213,10 @@ public abstract class AbstractStreamService implements StreamService {\n \t}\n \n \t@Override\n-\tpublic Page findDefinitionByNameLike(Pageable pageable, String searchName) {\n+\tpublic Page findDefinitionByNameLike(Pageable pageable, String search) {\n \t\tPage streamDefinitions;\n-\t\tif (searchName != null) {\n-\t\t\tfinal SearchPageable searchPageable = new SearchPageable(pageable, searchName);\n+\t\tif (search != null) {\n+\t\t\tfinal SearchPageable searchPageable = new SearchPageable(pageable, search);\n \t\t\tsearchPageable.addColumns(\"DEFINITION_NAME\", \"DEFINITION\");\n \t\t\tstreamDefinitions = streamDefinitionRepository.findByNameLike(searchPageable);\n \t\t\tlong count = streamDefinitions.getContent().size();"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":1442279,"string":"1,442,279"},"repo_tokens_count":{"kind":"number","value":307734,"string":"307,734"},"repo_lines_count":{"kind":"number","value":41542,"string":"41,542"},"repo_files_without_tests_count":{"kind":"number","value":410,"string":"410"},"changed_symbols_count":{"kind":"number","value":1241,"string":"1,241"},"changed_tokens_count":{"kind":"number","value":260,"string":"260"},"changed_lines_count":{"kind":"number","value":16,"string":"16"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":295,"string":"295"},"issue_words_count":{"kind":"number","value":18,"string":"18"},"issue_tokens_count":{"kind":"number","value":109,"string":"109"},"issue_lines_count":{"kind":"number","value":7,"string":"7"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:33","string":"1970-01-01T00:25:33"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1692,"cells":{"id":{"kind":"number","value":664,"string":"664"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/562/560"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/560"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/562"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/562"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"module info doesn't work for Docker apps"},"issue_body":{"kind":"string","value":"If I do `module info sink:log` I get the following exception -\n\n```\ndataflow:>module list\n╔══════╤═════════╤════╤════╗\n║source│processor│sink│task║\n╠══════╪═════════╪════╪════╣\n║time │ │log │ ║\n╚══════╧═════════╧════╧════╝\n\ndataflow:>module info sink:log\nCommand failed org.springframework.cloud.dataflow.rest.client.DataFlowClientException: Exception trying to list configuration properties for module Docker Resource [docker:springcloudstream/log-sink-rabbit]\n\nException trying to list configuration properties for module Docker Resource [docker:springcloudstream/log-sink-rabbit]\n\norg.springframework.cloud.dataflow.rest.client.DataFlowClientException: Exception trying to list configuration properties for module Docker Resource [docker:springcloudstream/log-sink-rabbit]\n\n at org.springframework.cloud.dataflow.rest.client.VndErrorResponseErrorHandler.handleError(VndErrorResponseErrorHandler.java:52)\n at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)\n at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)\n at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)\n at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:264)\n at org.springframework.cloud.dataflow.rest.client.ModuleTemplate.info(ModuleTemplate.java:84)\n at org.springframework.cloud.dataflow.shell.command.ModuleCommands.info(ModuleCommands.java:100)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:497)\n at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)\n at org.springframework.shell.core.SimpleExecutionStrategy.invoke(SimpleExecutionStrategy.java:64)\n at org.springframework.shell.core.SimpleExecutionStrategy.execute(SimpleExecutionStrategy.java:57)\n at org.springframework.shell.core.AbstractShell.executeCommand(AbstractShell.java:130)\n at org.springframework.shell.core.JLineShell.promptLoop(JLineShell.java:533)\n at org.springframework.shell.core.JLineShell.run(JLineShell.java:179)\n at java.lang.Thread.run(Thread.java:745)\n```\n"},"base_sha":{"kind":"string","value":"d20999bbf76b7d82b86b2d332e305e8b12e24b94"},"head_sha":{"kind":"string","value":"746f5ec294f0338908cd572816117af6afae46b9"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/d20999bbf76b7d82b86b2d332e305e8b12e24b94...746f5ec294f0338908cd572816117af6afae46b9"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java\nindex fb8524b49..94da34645 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java\n@@ -114,10 +114,13 @@ public class ModuleController {\n \t\tDetailedModuleRegistrationResource result = new DetailedModuleRegistrationResource(moduleAssembler.toResource(registration));\n \t\tResource resource = registration.getResource();\n \n-\t\tList properties = metadataResolver.listProperties(resource);\n-\t\tfor (ConfigurationMetadataProperty property : properties) {\n-\t\t\tresult.addOption(property);\n-\t\t}\n+\t\t//TODO: Docker URIs will throw an exception, need another way to get the properties for them\n+\t\ttry {\n+\t\t\tList properties = metadataResolver.listProperties(resource);\n+\t\t\tfor (ConfigurationMetadataProperty property : properties) {\n+\t\t\t\tresult.addOption(property);\n+\t\t\t}\n+\t\t} catch (Exception ignore) {}\n \t\treturn result;\n \t}\n "},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":670638,"string":"670,638"},"repo_tokens_count":{"kind":"number","value":142603,"string":"142,603"},"repo_lines_count":{"kind":"number","value":20007,"string":"20,007"},"repo_files_without_tests_count":{"kind":"number","value":206,"string":"206"},"changed_symbols_count":{"kind":"number","value":531,"string":"531"},"changed_tokens_count":{"kind":"number","value":105,"string":"105"},"changed_lines_count":{"kind":"number","value":11,"string":"11"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":2351,"string":"2,351"},"issue_words_count":{"kind":"number","value":102,"string":"102"},"issue_tokens_count":{"kind":"number","value":521,"string":"521"},"issue_lines_count":{"kind":"number","value":37,"string":"37"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:21","string":"1970-01-01T00:24:21"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1693,"cells":{"id":{"kind":"number","value":658,"string":"658"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/1349/1241"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/1241"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1349"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1349"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"Step Execution Count incorrect when same job is executed multiple times"},"issue_body":{"kind":"string","value":"When executing a batch job (with same job name) multiple times the step execution count for for all instances are the same. i.e. if a job has 3 steps, the step execution count for the first run will be 3. The next time its run the step count for the current run and previous run will be 6.\n\nSteps to reproduce. Execute a batch job(task) and then rerun it. Then go to the shell and execute a job execution list."},"base_sha":{"kind":"string","value":"15a17aec39efb159698cdf12eba1956feb536d81"},"head_sha":{"kind":"string","value":"f98b8a2e9d3860605686ce3a18e728779f8e582a"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/15a17aec39efb159698cdf12eba1956feb536d81...f98b8a2e9d3860605686ce3a18e728779f8e582a"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java\nindex 9644bd213..91c521b15 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright 2016 the original author or authors.\n+ * Copyright 2016-2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n@@ -26,6 +26,7 @@ import org.slf4j.LoggerFactory;\n import org.springframework.batch.admin.service.JobService;\n import org.springframework.batch.core.JobExecution;\n import org.springframework.batch.core.JobInstance;\n+import org.springframework.batch.core.Step;\n import org.springframework.batch.core.StepExecution;\n import org.springframework.batch.core.launch.JobExecutionNotRunningException;\n import org.springframework.batch.core.launch.NoSuchJobException;\n@@ -52,6 +53,7 @@ import org.springframework.util.Assert;\n * @author Glenn Renfro.\n * @author Gunnar Hillert\n * @author Mark Fisher\n+ * @author Ilayaperumal Gopinathan\n */\n public class DefaultTaskJobService implements TaskJobService {\n \n@@ -91,8 +93,14 @@ public class DefaultTaskJobService implements TaskJobService {\n \t\t\t\tjobService.listJobExecutions(pageable.getOffset(),\n \t\t\t\tpageable.getPageSize()));\n \t\tfor (JobExecution jobExecution : jobExecutions){\n-\t\t\tjobExecution.addStepExecutions(\n-\t\t\t\t\tnew ArrayList(jobService.getStepExecutions(jobExecution.getId())));\n+\t\t\tCollection stepExecutions = jobService.getStepExecutions(jobExecution.getId());\n+\t\t\tList validStepExecutions = new ArrayList<>();\n+\t\t\tfor (StepExecution stepExecution: stepExecutions) {\n+\t\t\t\tif (stepExecution.getId() != null) {\n+\t\t\t\t\tvalidStepExecutions.add(stepExecution);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tjobExecution.addStepExecutions(validStepExecutions);\n \t\t}\n \n \t\treturn getTaskJobExecutionsForList(jobExecutions);"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1100289,"string":"1,100,289"},"repo_tokens_count":{"kind":"number","value":234991,"string":"234,991"},"repo_lines_count":{"kind":"number","value":32267,"string":"32,267"},"repo_files_without_tests_count":{"kind":"number","value":339,"string":"339"},"changed_symbols_count":{"kind":"number","value":690,"string":"690"},"changed_tokens_count":{"kind":"number","value":156,"string":"156"},"changed_lines_count":{"kind":"number","value":14,"string":"14"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":416,"string":"416"},"issue_words_count":{"kind":"number","value":80,"string":"80"},"issue_tokens_count":{"kind":"number","value":102,"string":"102"},"issue_lines_count":{"kind":"number","value":3,"string":"3"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:52","string":"1970-01-01T00:24:52"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1694,"cells":{"id":{"kind":"number","value":663,"string":"663"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/564/563"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/563"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/564"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/564"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"NPE when module info doesn't exist"},"issue_body":{"kind":"string","value":"For the command `module info type:name` and if the app doesn't exist, then NPE is thrown.\n\n```\ndataflow:>module info processor:test\nCommand failed java.lang.NullPointerException\njava.lang.NullPointerException\n at org.springframework.cloud.dataflow.shell.command.ModuleCommands.info(ModuleCommands.java:101)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:483)\n at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)\n at org.springframework.shell.core.SimpleExecutionStrategy.invoke(SimpleExecutionStrategy.java:64)\n at org.springframework.shell.core.SimpleExecutionStrategy.execute(SimpleExecutionStrategy.java:57)\n at org.springframework.shell.core.AbstractShell.executeCommand(AbstractShell.java:130)\n at org.springframework.shell.core.JLineShell.promptLoop(JLineShell.java:533)\n at org.springframework.shell.core.JLineShell.run(JLineShell.java:179)\n at java.lang.Thread.run(Thread.java:745)\n```\n"},"base_sha":{"kind":"string","value":"746f5ec294f0338908cd572816117af6afae46b9"},"head_sha":{"kind":"string","value":"119f173daba7f3bd176e4a77d5069745b416ec35"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/746f5ec294f0338908cd572816117af6afae46b9...119f173daba7f3bd176e4a77d5069745b416ec35"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java b/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java\nindex 3f507c9d3..868f7282d 100644\n--- a/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java\n+++ b/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java\n@@ -98,36 +98,41 @@ public class ModuleCommands implements CommandMarker, ResourceLoaderAware {\n \t\t\t\t\thelp = \"name of the module to query in the form of 'type:name'\")\n \t\t\tQualifiedModuleName module) {\n \t\tDetailedModuleRegistrationResource info = moduleOperations().info(module.name, module.type);\n-\t\tList options = info.getOptions();\n \t\tList result = new ArrayList<>();\n-\t\tresult.add(String.format(\"Information about %s module '%s':\", module.type, module.name));\n+\t\tif (info != null) {\n+\t\t\tList options = info.getOptions();\n+\t\t\tresult.add(String.format(\"Information about %s module '%s':\", module.type, module.name));\n \n-\t\tresult.add(String.format(\"Resource URI: %s\", info.getUri()));\n+\t\t\tresult.add(String.format(\"Resource URI: %s\", info.getUri()));\n \n-\t\tif (info.getShortDescription() != null) {\n-\t\t\tresult.add(info.getShortDescription());\n-\t\t}\n-\t\tif (options == null) {\n-\t\t\tresult.add(\"Module options metadata is not available\");\n-\t\t}\n-\t\telse {\n-\t\t\tTableModelBuilder modelBuilder = new TableModelBuilder<>();\n-\t\t\tmodelBuilder.addRow()\n-\t\t\t\t\t.addValue(\"Option Name\")\n-\t\t\t\t\t.addValue(\"Description\")\n-\t\t\t\t\t.addValue(\"Default\")\n-\t\t\t\t\t.addValue(\"Type\");\n-\t\t\tfor (ConfigurationMetadataProperty option : options) {\n+\t\t\tif (info.getShortDescription() != null) {\n+\t\t\t\tresult.add(info.getShortDescription());\n+\t\t\t}\n+\t\t\tif (options == null) {\n+\t\t\t\tresult.add(\"Module options metadata is not available\");\n+\t\t\t}\n+\t\t\telse {\n+\t\t\t\tTableModelBuilder modelBuilder = new TableModelBuilder<>();\n \t\t\t\tmodelBuilder.addRow()\n-\t\t\t\t\t\t.addValue(option.getId())\n-\t\t\t\t\t\t.addValue(option.getDescription() == null ? \"\" : option.getDescription())\n-\t\t\t\t\t\t.addValue(prettyPrintDefaultValue(option))\n-\t\t\t\t\t\t.addValue(option.getType() == null ? \"\" : option.getType());\n+\t\t\t\t\t\t.addValue(\"Option Name\")\n+\t\t\t\t\t\t.addValue(\"Description\")\n+\t\t\t\t\t\t.addValue(\"Default\")\n+\t\t\t\t\t\t.addValue(\"Type\");\n+\t\t\t\tfor (ConfigurationMetadataProperty option : options) {\n+\t\t\t\t\tmodelBuilder.addRow()\n+\t\t\t\t\t\t\t.addValue(option.getId())\n+\t\t\t\t\t\t\t.addValue(option.getDescription() == null ? \"\" : option.getDescription())\n+\t\t\t\t\t\t\t.addValue(prettyPrintDefaultValue(option))\n+\t\t\t\t\t\t\t.addValue(option.getType() == null ? \"\" : option.getType());\n+\t\t\t\t}\n+\t\t\t\tTableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build()))\n+\t\t\t\t\t\t.on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30))\n+\t\t\t\t\t\t.and();\n+\t\t\t\tresult.add(builder.build());\n \t\t\t}\n-\t\t\tTableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build()))\n-\t\t\t\t\t.on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30))\n-\t\t\t\t\t.and();\n-\t\t\tresult.add(builder.build());\n+\t\t}\n+\t\telse {\n+\t\t\tresult.add(String.format(\"Module info is not available for %s:%s\", module.type, module.name));\n \t\t}\n \t\treturn result;\n \t}\ndiff --git a/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java b/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java\nindex 89021a4b9..8305078a7 100644\n--- a/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java\n+++ b/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java\n@@ -98,7 +98,13 @@ public class ModuleCommandsTests {\n \t\t\t\tassertThat(model.getValue(row, col), Matchers.is(expected[row][col]));\r\n \t\t\t}\r\n \t\t}\r\n- \t}\r\n+\t}\r\n+\r\n+\t@Test\r\n+\tpublic void testUnknownModule() {\r\n+\t\tList result = moduleCommands.info(new ModuleCommands.QualifiedModuleName(\"unknown\", ArtifactType.processor));\r\n+\t\tassertEquals((String) result.get(0), \"Module info is not available for processor:unknown\");\r\n+\t}\r\n \r\n \t@Test\r\n \tpublic void register() {\r"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java', 'spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":670777,"string":"670,777"},"repo_tokens_count":{"kind":"number","value":142638,"string":"142,638"},"repo_lines_count":{"kind":"number","value":20010,"string":"20,010"},"repo_files_without_tests_count":{"kind":"number","value":206,"string":"206"},"changed_symbols_count":{"kind":"number","value":2491,"string":"2,491"},"changed_tokens_count":{"kind":"number","value":528,"string":"528"},"changed_lines_count":{"kind":"number","value":55,"string":"55"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1198,"string":"1,198"},"issue_words_count":{"kind":"number","value":50,"string":"50"},"issue_tokens_count":{"kind":"number","value":245,"string":"245"},"issue_lines_count":{"kind":"number","value":20,"string":"20"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:21","string":"1970-01-01T00:24:21"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1695,"cells":{"id":{"kind":"number","value":662,"string":"662"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/1067/923"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/923"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1067"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1067"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Stream parser permits unbalanced quotes"},"issue_body":{"kind":"string","value":"You can create tasks such as: \n\n```\n`timestamp --format=\"asddd`\n```"},"base_sha":{"kind":"string","value":"60bb7939d53231a3d18a94b40c9dca4d3dad4aae"},"head_sha":{"kind":"string","value":"9dd230c3006585320b0b78ab19a59770ae68f011"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/60bb7939d53231a3d18a94b40c9dca4d3dad4aae...9dd230c3006585320b0b78ab19a59770ae68f011"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java b/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java\nindex 524a33da2..b3c9b1581 100644\n--- a/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java\n+++ b/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java\n@@ -25,6 +25,7 @@ import org.springframework.util.Assert;\n * Lex some input data into a stream of tokens that can then then be parsed.\n *\n * @author Andy Clement\n+ * @author Eric Bottard\n */\n class Tokenizer {\n \n@@ -272,7 +273,13 @@ class Tokenizer {\n \t\t}\n \t\twhile (!isArgValueIdentifierTerminator(toProcess[pos], quoteOpen));\n \t\tchar[] subarray = null;\n-\t\tif (quoteClosedCount < 2 && sameQuotes(start, pos - 1)) {\n+\t\tif (quoteInUse != null && quoteInUse == '\"' && quoteClosedCount == 0 ) {\n+\t\t\tthrow new ParseException(expressionString, start,\n+\t\t\t\tDSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING);\n+\t\t} else if (quoteInUse != null && quoteInUse == '\\\\'' && quoteClosedCount == 0) {\n+\t\t\tthrow new ParseException(expressionString, start,\n+\t\t\t\tDSLMessage.NON_TERMINATING_QUOTED_STRING);\n+\t\t} else if (quoteClosedCount == 1 && sameQuotes(start, pos - 1)) {\n \t\t\ttokens.add(new Token(TokenKind.LITERAL_STRING,\n \t\t\t\t\tsubArray(start, pos), start, pos));\n \t\t}\ndiff --git a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java\nindex d56e43f63..e85ba0279 100644\n--- a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java\n+++ b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java\n@@ -25,9 +25,7 @@ import static org.junit.Assert.fail;\n import java.util.List;\n import java.util.Properties;\n \n-import org.junit.Rule;\n import org.junit.Test;\n-import org.junit.rules.ExpectedException;\n \n /**\n * Parse streams and verify either the correct abstract syntax tree is produced or the current exception comes out.\n@@ -36,12 +34,10 @@ import org.junit.rules.ExpectedException;\n * @author David Turanski\n * @author Ilayaperumal Gopinathan\n * @author Mark Fisher\n+ * @author Eric Bottard\n */\n public class StreamParserTests {\n \n-\t@Rule\n-\tpublic ExpectedException thrown = ExpectedException.none();\n-\n \tprivate StreamNode sn;\n \n \n@@ -243,6 +239,16 @@ public class StreamParserTests {\n \t\tassertEquals(\"new StringBuilder(payload).reverse()\", props.get(\"expression\"));\n \t}\n \n+\t@Test\n+\tpublic void testUnbalancedSingleQuotes() {\n+\t\tcheckForParseError(\"foo | bar --expression='select foo\", DSLMessage.NON_TERMINATING_QUOTED_STRING, 23);\n+\t}\n+\n+\t@Test\n+\tpublic void testUnbalancedDoubleQuotes() {\n+\t\tcheckForParseError(\"foo | bar --expression=\\\\\"select foo\", DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 23);\n+\t}\n+\n \t@Test\n \tpublic void appArguments_xd1613() {\n \t\tStreamNode ast = null;\n@@ -534,20 +540,4 @@ public class StreamParserTests {\n \t\t\t}\n \t\t}\n \t}\n-\n-\tprivate void checkForParseError(String name, String stream, DSLMessage msg, int pos, String... inserts) {\n-\t\ttry {\n-\t\t\tStreamNode sn = parse(name, stream);\n-\t\t\tfail(\"expected to fail but parsed \" + sn.stringify());\n-\t\t}\n-\t\tcatch (ParseException e) {\n-\t\t\tassertEquals(msg, e.getMessageCode());\n-\t\t\tassertEquals(pos, e.getPosition());\n-\t\t\tif (inserts != null) {\n-\t\t\t\tfor (int i = 0; i < inserts.length; i++) {\n-\t\t\t\t\tassertEquals(inserts[i], e.getInserts()[i]);\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t}\n }\ndiff --git a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java\nindex bf21be4de..77492e872 100644\n--- a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java\n+++ b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java\n@@ -32,6 +32,7 @@ import org.junit.rules.ExpectedException;\n * @author Andy Clement\n * @author David Turanski\n * @author Michael Minella\n+ * @author Eric Bottard\n */\n public class TaskParserTests {\n \n@@ -246,6 +247,18 @@ public class TaskParserTests {\n \t\tassertEquals(appNode.getArgumentsAsProperties().get(\"expression\"), \"payload.replace(\\\\\"abc\\\\\", '')\");\n \t}\n \n+\t@Test\n+\tpublic void testUnbalancedSingleQuotes() {\n+\t\tcheckForParseError(\"timestamp --format='YYYY\", DSLMessage.NON_TERMINATING_QUOTED_STRING, 19);\n+\t}\n+\n+\t@Test\n+\tpublic void testUnbalancedDoubleQuotes() {\n+\t\tcheckForParseError(\"timestamp --format=\\\\\"YYYY\", DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 19);\n+\t}\n+\n+\n+\n \tAppNode parse(String taskDefinition) {\n \t\treturn new TaskParser(taskDefinition).parse();\n \t}\n@@ -281,4 +294,4 @@ public class TaskParserTests {\n \t\t\t}\n \t\t}\n \t}\n-}\n\\\\ No newline at end of file\n+}"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java', 'spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java', 'spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":846280,"string":"846,280"},"repo_tokens_count":{"kind":"number","value":177655,"string":"177,655"},"repo_lines_count":{"kind":"number","value":24594,"string":"24,594"},"repo_files_without_tests_count":{"kind":"number","value":284,"string":"284"},"changed_symbols_count":{"kind":"number","value":524,"string":"524"},"changed_tokens_count":{"kind":"number","value":144,"string":"144"},"changed_lines_count":{"kind":"number","value":9,"string":"9"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":67,"string":"67"},"issue_words_count":{"kind":"number","value":10,"string":"10"},"issue_tokens_count":{"kind":"number","value":19,"string":"19"},"issue_lines_count":{"kind":"number","value":5,"string":"5"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:41","string":"1970-01-01T00:24:41"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1696,"cells":{"id":{"kind":"number","value":661,"string":"661"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/1118/1070"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/1070"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1118"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/1118"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"REST: Retrieving non-existing app details should return a 404"},"issue_body":{"kind":"string","value":"The issue is in class `AppRegistryController#DetailedAppRegistrationResource`\r\n\r\nWhen executing a **GET** `/apps/{type}/{name}` a `200` HTTP Status is returned.\r\n\r\nBut it should produce a `404`.\r\n\r\nWe need to ensure that when making this minor **breaking change** that the shell and web UI are working."},"base_sha":{"kind":"string","value":"1131305790f5cea7d6d6ace57e171c2a6997f595"},"head_sha":{"kind":"string","value":"56472c0d1da7632e0acba9584a53bdf4e9eea048"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/1131305790f5cea7d6d6ace57e171c2a6997f595...56472c0d1da7632e0acba9584a53bdf4e9eea048"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java\nindex 092e4e259..51dd91e31 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java\n@@ -109,7 +109,7 @@ public class AppRegistryController {\n \t\t\t@PathVariable(\"name\") String name) {\n \t\tAppRegistration registration = appRegistry.find(name, type);\n \t\tif (registration == null) {\n-\t\t\treturn null;\n+\t\t\tthrow new NoSuchAppRegistrationException(name, type);\n \t\t}\n \t\tDetailedAppRegistrationResource result = new DetailedAppRegistrationResource(assembler.toResource(registration));\n \t\tResource resource = registration.getResource();\ndiff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java\nindex 011c55384..25add9adf 100644\n--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java\n+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright 2016 the original author or authors.\n+ * Copyright 2016-2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n@@ -124,6 +124,13 @@ public class AppRegistryControllerTests {\n \t\t.andExpect(status().isOk()).andExpect(jsonPath(\"content\", hasSize(4)));\n \t}\n \n+\t@Test\n+\tpublic void testFindNonExistentApp() throws Exception {\n+\t\tmockMvc.perform(\n+\t\t\t\tget(\"/apps/source/foo\").accept(MediaType.APPLICATION_JSON)).andDo(print())\n+\t\t\t\t.andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString().contains(\"NoSuchAppRegistrationException\");\n+\t}\n+\n \t@Test\n \tpublic void testRegisterAndListApplications() throws Exception {\n \t\tmockMvc.perform(\ndiff --git a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java\nindex 2f7de5d9a..8a6b984e9 100644\n--- a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java\n+++ b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java\n@@ -101,39 +101,44 @@ public class AppRegistryCommands implements CommandMarker, ResourceLoaderAware {\n \t\t\t\t\tkey = {\"\", \"id\"},\n \t\t\t\t\thelp = \"id of the application to query in the form of 'type:name'\")\n \t\t\tQualifiedApplicationName application) {\n-\t\tDetailedAppRegistrationResource info = appRegistryOperations().info(application.name, application.type);\n \t\tList result = new ArrayList<>();\n-\t\tif (info != null) {\n-\t\t\tList options = info.getOptions();\n-\t\t\tresult.add(String.format(\"Information about %s application '%s':\", application.type, application.name));\n-\t\t\tresult.add(String.format(\"Resource URI: %s\", info.getUri()));\n-\t\t\tif (info.getShortDescription() != null) {\n-\t\t\t\tresult.add(info.getShortDescription());\n-\t\t\t}\n-\t\t\tif (options == null) {\n-\t\t\t\tresult.add(\"Application options metadata is not available\");\n-\t\t\t}\n-\t\t\telse {\n-\t\t\t\tTableModelBuilder modelBuilder = new TableModelBuilder<>();\n-\t\t\t\tmodelBuilder.addRow()\n-\t\t\t\t\t\t.addValue(\"Option Name\")\n-\t\t\t\t\t\t.addValue(\"Description\")\n-\t\t\t\t\t\t.addValue(\"Default\")\n-\t\t\t\t\t\t.addValue(\"Type\");\n-\t\t\t\tfor (ConfigurationMetadataProperty option : options) {\n+\t\ttry {\n+\t\t\tDetailedAppRegistrationResource info = appRegistryOperations().info(application.name, application.type);\n+\t\t\tif (info != null) {\n+\t\t\t\tList options = info.getOptions();\n+\t\t\t\tresult.add(String.format(\"Information about %s application '%s':\", application.type, application.name));\n+\t\t\t\tresult.add(String.format(\"Resource URI: %s\", info.getUri()));\n+\t\t\t\tif (info.getShortDescription() != null) {\n+\t\t\t\t\tresult.add(info.getShortDescription());\n+\t\t\t\t}\n+\t\t\t\tif (options == null) {\n+\t\t\t\t\tresult.add(\"Application options metadata is not available\");\n+\t\t\t\t}\n+\t\t\t\telse {\n+\t\t\t\t\tTableModelBuilder modelBuilder = new TableModelBuilder<>();\n \t\t\t\t\tmodelBuilder.addRow()\n-\t\t\t\t\t\t\t.addValue(option.getId())\n-\t\t\t\t\t\t\t.addValue(option.getDescription() == null ? \"\" : option.getDescription())\n-\t\t\t\t\t\t\t.addValue(prettyPrintDefaultValue(option))\n-\t\t\t\t\t\t\t.addValue(option.getType() == null ? \"\" : option.getType());\n+\t\t\t\t\t\t\t.addValue(\"Option Name\")\n+\t\t\t\t\t\t\t.addValue(\"Description\")\n+\t\t\t\t\t\t\t.addValue(\"Default\")\n+\t\t\t\t\t\t\t.addValue(\"Type\");\n+\t\t\t\t\tfor (ConfigurationMetadataProperty option : options) {\n+\t\t\t\t\t\tmodelBuilder.addRow()\n+\t\t\t\t\t\t\t\t.addValue(option.getId())\n+\t\t\t\t\t\t\t\t.addValue(option.getDescription() == null ? \"\" : option.getDescription())\n+\t\t\t\t\t\t\t\t.addValue(prettyPrintDefaultValue(option))\n+\t\t\t\t\t\t\t\t.addValue(option.getType() == null ? \"\" : option.getType());\n+\t\t\t\t\t}\n+\t\t\t\t\tTableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build()))\n+\t\t\t\t\t\t\t.on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30))\n+\t\t\t\t\t\t\t.and();\n+\t\t\t\t\tresult.add(builder.build());\n \t\t\t\t}\n-\t\t\t\tTableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build()))\n-\t\t\t\t\t\t.on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30))\n-\t\t\t\t\t\t.and();\n-\t\t\t\tresult.add(builder.build());\n+\t\t\t}\n+\t\t\telse {\n+\t\t\t\tresult.add(String.format(\"Application info is not available for %s:%s\", application.type, application.name));\n \t\t\t}\n \t\t}\n-\t\telse {\n+\t\tcatch (Exception e) {\n \t\t\tresult.add(String.format(\"Application info is not available for %s:%s\", application.type, application.name));\n \t\t}\n \t\treturn result;"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java', 'spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 3}"},"changed_files_count":{"kind":"number","value":3,"string":"3"},"java_changed_files_count":{"kind":"number","value":3,"string":"3"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":3,"string":"3"},"repo_symbols_count":{"kind":"number","value":856660,"string":"856,660"},"repo_tokens_count":{"kind":"number","value":179835,"string":"179,835"},"repo_lines_count":{"kind":"number","value":24861,"string":"24,861"},"repo_files_without_tests_count":{"kind":"number","value":286,"string":"286"},"changed_symbols_count":{"kind":"number","value":2959,"string":"2,959"},"changed_tokens_count":{"kind":"number","value":602,"string":"602"},"changed_lines_count":{"kind":"number","value":63,"string":"63"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":302,"string":"302"},"issue_words_count":{"kind":"number","value":42,"string":"42"},"issue_tokens_count":{"kind":"number","value":69,"string":"69"},"issue_lines_count":{"kind":"number","value":7,"string":"7"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:44","string":"1970-01-01T00:24:44"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1697,"cells":{"id":{"kind":"number","value":643,"string":"643"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/3549/3546"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/3546"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/3549"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/3549"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"SCDF fails to start with Scheduling disabled"},"issue_body":{"kind":"string","value":"As a user, when deploying SCDF to CF without Scheduling (i.e., `SPRING_CLOUD_DATAFLOW_FEATURES_SCHEDULES_ENABLED=false`), I get the following error on `master` and on `2.3 M2`.\r\n\r\n```\r\n2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT ***************************\r\n 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT APPLICATION FAILED TO START\r\n 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT ***************************\r\n 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT Description:\r\n 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT Parameter 8 of method deleteTaskService in org.springframework.cloud.dataflow.server.config.features.TaskConfiguration required a bean of type 'org.springframework.cloud.dataflow.server.service.SchedulerService' that could not be found.\r\n```\r\n\r\nThe same error also appeared when deploying `master` on K8s, but it could have been due to a corrupted/unstable image."},"base_sha":{"kind":"string","value":"e466301ea38e0ab8ac8cba564214769fd97b9807"},"head_sha":{"kind":"string","value":"7431604333d48d74f26ab8219308b02dd99c8e88"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/e466301ea38e0ab8ac8cba564214769fd97b9807...7431604333d48d74f26ab8219308b02dd99c8e88"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java b/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java\nindex 13752c791..e2f7dd354 100644\n--- a/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java\n+++ b/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java\n@@ -32,11 +32,15 @@ import org.junit.Rule;\n import org.mockito.ArgumentMatchers;\n \n import org.springframework.cloud.dataflow.core.ApplicationType;\n+import org.springframework.cloud.dataflow.core.Launcher;\n+import org.springframework.cloud.dataflow.core.TaskPlatform;\n import org.springframework.cloud.dataflow.server.controller.TaskSchedulerController;\n import org.springframework.cloud.dataflow.server.service.SchedulerService;\n import org.springframework.cloud.dataflow.server.single.LocalDataflowResource;\n import org.springframework.cloud.deployer.spi.app.AppDeployer;\n import org.springframework.cloud.deployer.spi.scheduler.ScheduleInfo;\n+import org.springframework.cloud.deployer.spi.scheduler.ScheduleRequest;\n+import org.springframework.cloud.deployer.spi.scheduler.Scheduler;\n import org.springframework.cloud.skipper.domain.AboutResource;\n import org.springframework.cloud.skipper.domain.Dependency;\n import org.springframework.cloud.skipper.domain.Deployer;\n@@ -129,7 +133,9 @@ public abstract class BaseDocumentation {\n \t\tthis.dataSource = springDataflowServer.getWebApplicationContext().getBean(DataSource.class);\n \t\tTaskSchedulerController controller = this.springDataflowServer.getWebApplicationContext().getBean(TaskSchedulerController.class);\n \t\tReflectionTestUtils.setField(controller, \"schedulerService\", schedulerService());\n-\n+\t\tTaskPlatform taskPlatform = this.springDataflowServer.getWebApplicationContext().getBean(TaskPlatform.class);\n+\t\tLauncher launcher = taskPlatform.getLaunchers().stream().filter(launcherToFilter -> launcherToFilter.getName().equals(\"default\")).findFirst().get();\n+\t\tReflectionTestUtils.setField(launcher, \"scheduler\", localTestScheduler());\n \t}\n \n \t/**\n@@ -271,17 +277,41 @@ public abstract class BaseDocumentation {\n \t\t\tpublic ScheduleInfo getSchedule(String scheduleName) {\n \t\t\t\treturn null;\n \t\t\t}\n+\t\t};\n+\t}\n+\n+\tprivate List getSampleList() {\n+\t\tList result = new ArrayList<>();\n+\t\tScheduleInfo scheduleInfo = new ScheduleInfo();\n+\t\tscheduleInfo.setScheduleName(\"FOO\");\n+\t\tscheduleInfo.setTaskDefinitionName(\"BAR\");\n+\t\tMap props = new HashMap<>(1);\n+\t\tprops.put(\"scheduler.AAA.spring.cloud.scheduler.cron.expression\", \"00 41 17 ? * *\");\n+\t\tscheduleInfo.setScheduleProperties(props);\n+\t\tresult.add(scheduleInfo);\n+\t\treturn result;\n+\t}\n+\n+\tpublic Scheduler localTestScheduler() {\n+\t\treturn new Scheduler() {\n+\t\t\t@Override\n+\t\t\tpublic void schedule(ScheduleRequest scheduleRequest) {\n+\t\t\t\tthrow new UnsupportedOperationException(\"Interface is not implemented for schedule method.\");\n+\t\t\t}\n \n-\t\t\tprivate List getSampleList() {\n-\t\t\t\tList result = new ArrayList<>();\n-\t\t\t\tScheduleInfo scheduleInfo = new ScheduleInfo();\n-\t\t\t\tscheduleInfo.setScheduleName(\"FOO\");\n-\t\t\t\tscheduleInfo.setTaskDefinitionName(\"BAR\");\n-\t\t\t\tMap props = new HashMap<>(1);\n-\t\t\t\tprops.put(\"scheduler.AAA.spring.cloud.scheduler.cron.expression\", \"00 41 17 ? * *\");\n-\t\t\t\tscheduleInfo.setScheduleProperties(props);\n-\t\t\t\tresult.add(scheduleInfo);\n-\t\t\t\treturn result;\n+\t\t\t@Override\n+\t\t\tpublic void unschedule(String scheduleName) {\n+\t\t\t\tthrow new UnsupportedOperationException(\"Interface is not implemented for unschedule method.\");\n+\t\t\t}\n+\n+\t\t\t@Override\n+\t\t\tpublic List list(String taskDefinitionName) {\n+\t\t\t\tthrow new UnsupportedOperationException(\"Interface is not implemented for list method.\");\n+\t\t\t}\n+\n+\t\t\t@Override\n+\t\t\tpublic List list() {\n+\t\t\t\treturn getSampleList();\n \t\t\t}\n \t\t};\n \t}\ndiff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java\nindex 079e86d18..956148484 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java\n@@ -15,9 +15,7 @@\n */\n package org.springframework.cloud.dataflow.server.config.features;\n \n-import java.util.Collections;\n import java.util.List;\n-import java.util.Map;\n \n import javax.sql.DataSource;\n \n@@ -61,15 +59,12 @@ import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskJobServ\n import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskSaveService;\n import org.springframework.cloud.dataflow.server.service.impl.TaskAppDeploymentRequestCreator;\n import org.springframework.cloud.dataflow.server.service.impl.TaskConfigurationProperties;\n-import org.springframework.cloud.deployer.spi.scheduler.ScheduleInfo;\n import org.springframework.cloud.deployer.spi.scheduler.Scheduler;\n import org.springframework.cloud.task.repository.TaskExplorer;\n import org.springframework.cloud.task.repository.TaskRepository;\n import org.springframework.context.annotation.Bean;\n import org.springframework.context.annotation.Configuration;\n import org.springframework.context.annotation.Profile;\n-import org.springframework.data.domain.Page;\n-import org.springframework.data.domain.Pageable;\n import org.springframework.data.map.repository.config.EnableMapRepositories;\n import org.springframework.lang.Nullable;\n import org.springframework.transaction.PlatformTransactionManager;\n@@ -97,6 +92,9 @@ public class TaskConfiguration {\n \t@Autowired\n \tDataSourceProperties dataSourceProperties;\n \n+\t@Autowired(required = false)\n+\tSchedulerService schedulerService;\n+\n \t@Value(\"${spring.cloud.dataflow.server.uri:}\")\n \tprivate String dataflowServerUri;\n \n@@ -130,55 +128,6 @@ public class TaskConfiguration {\n \t\treturn taskPlatform;\n \t}\n \n-\t/**\n-\t * The default profile is active when no other profiles are active. This is configured so\n-\t * that several tests will pass without having to explicitly enable the local profile.\n-\t * @return a no-op {@link SchedulerService}\n-\t */\n-\t@Profile({ \"local\", \"default\" })\n-\t@Bean\n-\tpublic SchedulerService schedulerService() {\n-\t\treturn new SchedulerService() {\n-\t\t\t@Override\n-\t\t\tpublic void schedule(String scheduleName, String taskDefinitionName, Map taskProperties, List commandLineArgs) {\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic void unschedule(String scheduleName) {\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic void unscheduleForTaskDefinition(String taskDefinitionName) {\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic List list(Pageable pageable, String taskDefinitionName) {\n-\t\t\t\treturn null;\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic Page list(Pageable pageable) {\n-\t\t\t\treturn null;\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic List list(String taskDefinitionName) {\n-\t\t\t\treturn Collections.emptyList();\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic List list() {\n-\t\t\t\treturn Collections.emptyList();\n-\t\t\t}\n-\n-\t\t\t@Override\n-\t\t\tpublic ScheduleInfo getSchedule(String scheduleName) {\n-\t\t\t\treturn null;\n-\t\t\t}\n-\t\t};\n-\t}\n-\n-\n \t@Bean\n \tpublic TaskExecutionInfoService taskDefinitionRetriever(AppRegistryService registry,\n \t\t\tTaskExplorer taskExplorer, TaskDefinitionRepository taskDefinitionRepository,\n@@ -194,15 +143,14 @@ public class TaskConfiguration {\n \t\t\tAuditRecordService auditRecordService,\n \t\t\tDataflowTaskExecutionDao dataflowTaskExecutionDao,\n \t\t\tDataflowJobExecutionDao dataflowJobExecutionDao,\n-\t\t\tDataflowTaskExecutionMetadataDao dataflowTaskExecutionMetadataDao,\n-\t\t\tSchedulerService schedulerService) {\n+\t\t\tDataflowTaskExecutionMetadataDao dataflowTaskExecutionMetadataDao) {\n \t\treturn new DefaultTaskDeleteService(taskExplorer, launcherRepository, taskDefinitionRepository,\n \t\t\t\ttaskDeploymentRepository,\n \t\t\t\tauditRecordService,\n \t\t\t\tdataflowTaskExecutionDao,\n \t\t\t\tdataflowJobExecutionDao,\n \t\t\t\tdataflowTaskExecutionMetadataDao,\n-\t\t\t\tschedulerService);\n+\t\t\t\tthis.schedulerService);\n \t}\n \n \t@Bean\ndiff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java\nindex bb3d6907e..6c5c8f489 100644\n--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java\n+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java\n@@ -114,7 +114,6 @@ public class DefaultTaskDeleteService implements TaskDeleteService {\n \t\tAssert.notNull(dataflowTaskExecutionDao, \"DataflowTaskExecutionDao must not be null\");\n \t\tAssert.notNull(dataflowJobExecutionDao, \"DataflowJobExecutionDao must not be null\");\n \t\tAssert.notNull(dataflowTaskExecutionMetadataDao, \"DataflowTaskExecutionMetadataDao must not be null\");\n-\t\tAssert.notNull(schedulerService, \"SchedulerService must not be null\");\n \t\tthis.taskExplorer = taskExplorer;\n \t\tthis.launcherRepository = launcherRepository;\n \t\tthis.taskDefinitionRepository = taskDefinitionRepository;\n@@ -324,7 +323,9 @@ public class DefaultTaskDeleteService implements TaskDeleteService {\n \n \tprivate void deleteTaskDefinition(TaskDefinition taskDefinition) {\n \t\tTaskParser taskParser = new TaskParser(taskDefinition.getName(), taskDefinition.getDslText(), true, true);\n-\t\tschedulerService.unscheduleForTaskDefinition(taskDefinition.getTaskName());\n+\t\tif (this.schedulerService != null) {\n+\t\t\tschedulerService.unscheduleForTaskDefinition(taskDefinition.getTaskName());\n+\t\t}\n \t\tTaskNode taskNode = taskParser.parse();\n \t\t// if composed-task-runner definition then destroy all child tasks associated with it.\n \t\tif (taskNode.isComposed()) {\ndiff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java\nindex 420a90488..468ae9aab 100644\n--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java\n+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java\n@@ -45,6 +45,7 @@ import org.springframework.cloud.dataflow.server.DockerValidatorProperties;\n import org.springframework.cloud.dataflow.server.config.VersionInfoProperties;\n import org.springframework.cloud.dataflow.server.config.apps.CommonApplicationProperties;\n import org.springframework.cloud.dataflow.server.config.features.FeaturesProperties;\n+import org.springframework.cloud.dataflow.server.config.features.SchedulerConfiguration;\n import org.springframework.cloud.dataflow.server.job.LauncherRepository;\n import org.springframework.cloud.dataflow.server.repository.DataflowJobExecutionDao;\n import org.springframework.cloud.dataflow.server.repository.DataflowTaskExecutionDao;\n@@ -82,6 +83,7 @@ import org.springframework.cloud.task.repository.support.SimpleTaskRepository;\n import org.springframework.cloud.task.repository.support.TaskExecutionDaoFactoryBean;\n import org.springframework.context.ApplicationContext;\n import org.springframework.context.annotation.Bean;\n+import org.springframework.context.annotation.Conditional;\n import org.springframework.context.annotation.Configuration;\n import org.springframework.context.annotation.Import;\n import org.springframework.core.io.Resource;\n@@ -104,6 +106,7 @@ import static org.mockito.Mockito.when;\n * @author Glenn Renfro\n * @author David Turanski\n * @author Gunnar Hillert\n+ * @author Ilayaperumal Gopinathan\n */\n @Configuration\n @EnableSpringDataWebSupport\n@@ -234,7 +237,7 @@ public class TaskServiceDependencies extends WebMvcConfigurationSupport {\n \t\t\tDataflowTaskExecutionDao dataflowTaskExecutionDao,\n \t\t\tDataflowJobExecutionDao dataflowJobExecutionDao,\n \t\t\tDataflowTaskExecutionMetadataDao dataflowTaskExecutionMetadataDao,\n-\t\t\tSchedulerService schedulerService) {\n+\t\t\t@Autowired(required = false) SchedulerService schedulerService) {\n \n \t\treturn new DefaultTaskDeleteService(taskExplorer, launcherRepository, taskDefinitionRepository,\n \t\t\t\ttaskDeploymentRepository,\n@@ -296,6 +299,7 @@ public class TaskServiceDependencies extends WebMvcConfigurationSupport {\n \t}\n \n \t@Bean\n+\t@Conditional({ SchedulerConfiguration.SchedulerConfigurationPropertyChecker.class })\n \tpublic SchedulerService schedulerService(CommonApplicationProperties commonApplicationProperties,\n \t\t\t\t\t\t\t\t\t\t\t TaskPlatform taskPlatform, TaskDefinitionRepository taskDefinitionRepository,\n \t\t\t\t\t\t\t\t\t\t\t AppRegistryService registry, ResourceLoader resourceLoader,\ndiff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java\nindex 4fbdd7abb..df558a59f 100644\n--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java\n+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java\n@@ -78,7 +78,8 @@ import static org.mockito.Mockito.when;\n \t\t\"spring.cloud.dataflow.applicationProperties.task.globalkey=globalvalue\",\n \t\t\"spring.cloud.dataflow.applicationProperties.stream.globalstreamkey=nothere\",\n \t\t\"spring.main.allow-bean-definition-overriding=true\",\n-\t\t\"spring.cloud.dataflow.task.scheduler-task-launcher-url=https://test.test\"})\n+\t\t\"spring.cloud.dataflow.task.scheduler-task-launcher-url=https://test.test\",\n+\t\t\"spring.cloud.dataflow.features.schedules-enabled=true\"})\n @EnableConfigurationProperties({ CommonApplicationProperties.class, TaskConfigurationProperties.class, DockerValidatorProperties.class})\n @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)\n @AutoConfigureTestDatabase(replace = Replace.ANY)"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java', 'spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 5}"},"changed_files_count":{"kind":"number","value":5,"string":"5"},"java_changed_files_count":{"kind":"number","value":5,"string":"5"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":5,"string":"5"},"repo_symbols_count":{"kind":"number","value":1971577,"string":"1,971,577"},"repo_tokens_count":{"kind":"number","value":425151,"string":"425,151"},"repo_lines_count":{"kind":"number","value":56411,"string":"56,411"},"repo_files_without_tests_count":{"kind":"number","value":533,"string":"533"},"changed_symbols_count":{"kind":"number","value":2050,"string":"2,050"},"changed_tokens_count":{"kind":"number","value":434,"string":"434"},"changed_lines_count":{"kind":"number","value":67,"string":"67"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":906,"string":"906"},"issue_words_count":{"kind":"number","value":85,"string":"85"},"issue_tokens_count":{"kind":"number","value":281,"string":"281"},"issue_lines_count":{"kind":"number","value":11,"string":"11"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:11","string":"1970-01-01T00:26:11"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1698,"cells":{"id":{"kind":"number","value":644,"string":"644"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/3274/3264"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/3264"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/3274"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/3274"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"NPE when registering the app without the app resolution schema"},"issue_body":{"kind":"string","value":"As a user, I copied the following app registration command from the [Microsite](https://dataflow.spring.io/docs/recipes/polyglot/processor/), but it failed with an NPE.\r\n\r\nregister:\r\n```\r\napp register --type processor --name python-processor --uri springcloud/polyglot-python-processor:0.1\r\n```\r\n\r\nerror:\r\n```\r\n2019-06-04 22:03:20.278 ERROR 1 --- [nio-8080-exec-9] o.s.c.d.s.c.RestControllerAdvice : Caught exception while handling a request │\r\n│ │\r\n│ java.lang.NullPointerException: null │\r\n│ at org.springframework.cloud.dataflow.registry.support.AppResourceCommon.getResource(AppResourceCommon.java:154) │\r\n│ at org.springframework.cloud.dataflow.registry.service.DefaultAppRegistryService.getResourceVersion(DefaultAppRegistryService.java:266)\r\n```\r\n\r\n1) We need to add `docker:` schema in the microsite instructions\r\n2) Handle the NPE gracefully"},"base_sha":{"kind":"string","value":"ba7570c9443f58ca5784a5f4960841d6ed98a9d6"},"head_sha":{"kind":"string","value":"64bb806f267a325f7e513b710d4a608489171816"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/ba7570c9443f58ca5784a5f4960841d6ed98a9d6...64bb806f267a325f7e513b710d4a608489171816"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java b/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java\nindex 4c5cc44ea..85a42e2ff 100644\n--- a/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java\n+++ b/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java\n@@ -151,7 +151,12 @@ public class AppResourceCommon {\n \tpublic Resource getResource(String resourceUri) {\n \t\tAssert.isTrue(StringUtils.hasText(resourceUri), \"Resource URI must not be empty\");\n \t\ttry {\n-\t\t\tString scheme = new URI(resourceUri).getScheme().toLowerCase();\n+\t\t\tString scheme = new URI(resourceUri).getScheme();\n+\t\t\tif (scheme == null) {\n+\t\t\t\tthrow new IllegalArgumentException(\"Invalid URI schema for resource: \" + resourceUri\n+\t\t\t\t\t\t+ \" Expected URI schema prefix like file://, http:// or classpath:// but got none\");\n+\t\t\t}\n+\t\t\tscheme = scheme.toLowerCase();\n \t\t\tAssert.notNull(scheme, \"a scheme (prefix) is required\");\n \n \t\t\tswitch (scheme) {\ndiff --git a/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java b/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java\nindex c1d8e565f..6d4e87412 100644\n--- a/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java\n+++ b/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java\n@@ -70,6 +70,19 @@ public class AppResourceCommonTests {\n \t\t}\n \t}\n \n+\t@Test\n+\tpublic void testInvalidUriSchema() {\n+\t\ttry {\n+\t\t\tappResourceCommon.getResource(\"springcloud/polyglot-python-processor:0.1\");\n+\t\t\tfail(\"Excepted IllegalArgumentException for an invalid URI schema prefix\");\n+\t\t}\n+\t\tcatch (IllegalArgumentException iae) {\n+\t\t\tassertThat(iae.getMessage().equals(\"Invalid URI schema for resource: \" +\n+\t\t\t\t\t\"springcloud/polyglot-python-processor:0.1 Expected URI schema prefix like file://, \" +\n+\t\t\t\t\t\"http:// or classpath:// but got none\"));\n+\t\t}\n+\t}\n+\n \t@Test\n \tpublic void testDefaultResource() {\n \t\tString classpathUri = \"classpath:AppRegistryTests-importAll.properties\";"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java', 'spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 2}"},"changed_files_count":{"kind":"number","value":2,"string":"2"},"java_changed_files_count":{"kind":"number","value":2,"string":"2"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":2,"string":"2"},"repo_symbols_count":{"kind":"number","value":1807312,"string":"1,807,312"},"repo_tokens_count":{"kind":"number","value":390577,"string":"390,577"},"repo_lines_count":{"kind":"number","value":52140,"string":"52,140"},"repo_files_without_tests_count":{"kind":"number","value":503,"string":"503"},"changed_symbols_count":{"kind":"number","value":370,"string":"370"},"changed_tokens_count":{"kind":"number","value":82,"string":"82"},"changed_lines_count":{"kind":"number","value":7,"string":"7"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1265,"string":"1,265"},"issue_words_count":{"kind":"number","value":77,"string":"77"},"issue_tokens_count":{"kind":"number","value":213,"string":"213"},"issue_lines_count":{"kind":"number","value":18,"string":"18"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:59","string":"1970-01-01T00:25:59"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1699,"cells":{"id":{"kind":"number","value":646,"string":"646"},"text_id":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow/2509/2508"},"repo_owner":{"kind":"string","value":"spring-cloud"},"repo_name":{"kind":"string","value":"spring-cloud-dataflow"},"issue_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/issues/2508"},"pull_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/2509"},"comment_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/pull/2509"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"app info cmd throws exception for `app info `"},"issue_body":{"kind":"string","value":"Description:\r\n```\r\ndataflow:>app info source:http\r\nCommand failed java.lang.IllegalArgumentException: The options [:] and [--name && --type] are mutually exclusive and one of these should be specified to uniquely identify the application\r\n```\r\n\r\nRelease versions:\r\nLatest master, 1.7.0.RC1\r\n\r\n"},"base_sha":{"kind":"string","value":"26ebafe6c0c44d059c79b582aa2805b4cb71f864"},"head_sha":{"kind":"string","value":"6fab2419dcc3bed5e470dd8e92444278d0288345"},"diff_url":{"kind":"string","value":"https://github.com/spring-cloud/spring-cloud-dataflow/compare/26ebafe6c0c44d059c79b582aa2805b4cb71f864...6fab2419dcc3bed5e470dd8e92444278d0288345"},"diff":{"kind":"string","value":"diff --git a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java\nindex 72c867037..0b3cf45be 100644\n--- a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java\n+++ b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java\n@@ -88,8 +88,7 @@ public class ClassicAppRegistryCommands extends AbstractAppRegistryCommands impl\n \tpublic List info(\n \t\t\t@CliOption(key = { \"\", \"id\" },\n \t\t\t\t\thelp = \"id of the application to query in the form of 'type:name'\") QualifiedApplicationName application,\n-\t\t\t@CliOption(key = { \"\",\n-\t\t\t\t\t\"name\" }, help = \"name of the application to query\") String applicationName,\n+\t\t\t@CliOption(key = { \"\", \"name\" }, help = \"name of the application to query\") String applicationName,\n \t\t\t@CliOption(key = {\n \t\t\t\t\t\"type\" }, help = \"type of the application to query\") ApplicationType applicationType,\n \t\t\t@CliOption(key = { \"exhaustive\" }, help = \"return all metadata, including common Spring Boot properties\",\n@@ -142,7 +141,7 @@ public class ClassicAppRegistryCommands extends AbstractAppRegistryCommands impl\n \n \tprivate boolean assertAppInfoOptions(QualifiedApplicationName application, String name, ApplicationType type) {\n \t\tif (application != null && StringUtils.hasText(application.name) && application.type != null) {\n-\t\t\treturn !(StringUtils.hasText(name) || (type != null));\n+\t\t\treturn type == null;\n \t\t}\n \t\telse {\n \t\t\treturn (StringUtils.hasText(name) && type != null);"},"changed_files":{"kind":"string","value":"['spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 1}"},"changed_files_count":{"kind":"number","value":1,"string":"1"},"java_changed_files_count":{"kind":"number","value":1,"string":"1"},"kt_changed_files_count":{"kind":"number","value":0,"string":"0"},"py_changed_files_count":{"kind":"number","value":0,"string":"0"},"code_changed_files_count":{"kind":"number","value":1,"string":"1"},"repo_symbols_count":{"kind":"number","value":1555448,"string":"1,555,448"},"repo_tokens_count":{"kind":"number","value":331474,"string":"331,474"},"repo_lines_count":{"kind":"number","value":44779,"string":"44,779"},"repo_files_without_tests_count":{"kind":"number","value":445,"string":"445"},"changed_symbols_count":{"kind":"number","value":297,"string":"297"},"changed_tokens_count":{"kind":"number","value":76,"string":"76"},"changed_lines_count":{"kind":"number","value":5,"string":"5"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":306,"string":"306"},"issue_words_count":{"kind":"number","value":36,"string":"36"},"issue_tokens_count":{"kind":"number","value":69,"string":"69"},"issue_lines_count":{"kind":"number","value":10,"string":"10"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:39","string":"1970-01-01T00:25:39"},"repo_stars":{"kind":"number","value":1007,"string":"1,007"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":16,"numItemsPerPage":100,"numTotalItems":2522,"offset":1600,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzgwNzE4OSwic3ViIjoiL2RhdGFzZXRzL0pldEJyYWlucy1SZXNlYXJjaC9sY2EtYnVnLWxvY2FsaXphdGlvbiIsImV4cCI6MTc1NzgxMDc4OSwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.QZFpNL39yd8YypZeoXDx1QgZ3yoNrhMJDnEN3fWWFkofCFJkRmnx_wHq3L_b0yavw-xtI1YfnJeNkCMHrO58AQ","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    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
    9,883
    clickhouse/clickhouse-java/1070/1069
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/1069
    https://github.com/ClickHouse/clickhouse-java/pull/1070
    https://github.com/ClickHouse/clickhouse-java/pull/1070
    1
    fixes
    BasicAuthentication Support
    Is basic authentication supported in the most recent version of the clickhouse JDBC drivers? (`clickhouse-jdbc-0.3.2-patch11` is my version). I found an older PR saying that everyone got switched over https://github.com/ClickHouse/clickhouse-jdbc/issues/522, but looks like it may not be true in the most revent version. I tried using the `custom_http_headers` property to set my own auth header, but the client complains about double auth because https://github.com/ClickHouse/clickhouse-jdbc/blob/f285b73d45597e29cf36dff4daf4cb4f9f53453a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnection.java#L166 this method is still always attempting to add the `X-Clickhouse` user and password methods. I can't find anywhere in the codebase that ever attempts to set an accessToken based method. Am I missing a way to properly configure the client to use a `BasicAuth` header?
    4077e59b845f7d8f95a221dbedea233dbc04b8c8
    12b95acc6af2a0bc8770a1b68a4855b822233d70
    https://github.com/clickhouse/clickhouse-java/compare/4077e59b845f7d8f95a221dbedea233dbc04b8c8...12b95acc6af2a0bc8770a1b68a4855b822233d70
    diff --git a/clickhouse-client/src/test/java/com/clickhouse/client/BaseIntegrationTest.java b/clickhouse-client/src/test/java/com/clickhouse/client/BaseIntegrationTest.java index 578825d3..7a4e8fd4 100644 --- a/clickhouse-client/src/test/java/com/clickhouse/client/BaseIntegrationTest.java +++ b/clickhouse-client/src/test/java/com/clickhouse/client/BaseIntegrationTest.java @@ -19,6 +19,10 @@ public abstract class BaseIntegrationTest { return ClickHouseServerForTest.getClickHouseNode(protocol, true, ClickHouseNode.builder().build()); } + protected ClickHouseNode getSecureServer(ClickHouseProtocol protocol, ClickHouseNode base) { + return ClickHouseServerForTest.getClickHouseNode(protocol, true, base); + } + protected ClickHouseNode getServer(ClickHouseProtocol protocol) { return ClickHouseServerForTest.getClickHouseNode(protocol, false, ClickHouseNode.builder().build()); } diff --git a/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java b/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java index bf9e3897..9c4e616f 100644 --- a/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java +++ b/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java @@ -101,12 +101,14 @@ public abstract class ClientIntegrationTest extends BaseIntegrationTest { return builder; } - protected ClickHouseClient getClient() { - return initClient(ClickHouseClient.builder()).nodeSelector(ClickHouseNodeSelector.of(getProtocol())).build(); + protected ClickHouseClient getClient(ClickHouseConfig... configs) { + return initClient(ClickHouseClient.builder()).config(new ClickHouseConfig(configs)) + .nodeSelector(ClickHouseNodeSelector.of(getProtocol())).build(); } - protected ClickHouseClient getSecureClient() { + protected ClickHouseClient getSecureClient(ClickHouseConfig... configs) { return initClient(ClickHouseClient.builder()) + .config(new ClickHouseConfig(configs)) .nodeSelector(ClickHouseNodeSelector.of(getProtocol())) .option(ClickHouseClientOption.SSL, true) .option(ClickHouseClientOption.SSL_MODE, ClickHouseSslMode.STRICT) @@ -117,14 +119,22 @@ public abstract class ClientIntegrationTest extends BaseIntegrationTest { .build(); } - protected ClickHouseNode getServer() { - return getServer(getProtocol()); + protected ClickHouseNode getSecureServer(ClickHouseNode base) { + return getSecureServer(getProtocol(), base); } protected ClickHouseNode getSecureServer() { return getSecureServer(getProtocol()); } + protected ClickHouseNode getServer(ClickHouseNode base) { + return getServer(getProtocol(), base); + } + + protected ClickHouseNode getServer() { + return getServer(getProtocol()); + } + @DataProvider(name = "compressionMatrix") protected Object[][] getCompressionMatrix() { ClickHouseFormat[] formats = new ClickHouseFormat[] { @@ -1402,7 +1412,11 @@ public abstract class ClientIntegrationTest extends BaseIntegrationTest { request.query("drop temporary table if exists my_temp_table").execute().get(); request.query("create temporary table my_temp_table(a Int8)").execute().get(); request.query("insert into my_temp_table values(2)").execute().get(); - request.write().table("my_temp_table").data(new ByteArrayInputStream(new byte[] { 3 })).execute().get(); + try (ClickHouseResponse resp = request.write().table("my_temp_table") + .data(new ByteArrayInputStream(new byte[] { 3 })).executeAndWait()) { + // ignore + } + int count = 0; try (ClickHouseResponse resp = request.format(ClickHouseFormat.RowBinaryWithNamesAndTypes) .query("select * from my_temp_table order by a").execute().get()) { diff --git a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnection.java b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnection.java index 9917f124..ce9aae26 100644 --- a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnection.java +++ b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnection.java @@ -9,6 +9,7 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Map.Entry; @@ -158,39 +159,52 @@ public abstract class ClickHouseHttpConnection implements AutoCloseable { protected static Map<String, String> createDefaultHeaders(ClickHouseConfig config, ClickHouseNode server) { Map<String, String> map = new LinkedHashMap<>(); + boolean hasAuthorizationHeader = false; // add customer headers - map.putAll(ClickHouseOption.toKeyValuePairs(config.getStrOption(ClickHouseHttpOption.CUSTOM_HEADERS))); - map.put("Accept", "*/*"); + for (Entry<String, String> header : ClickHouseOption + .toKeyValuePairs(config.getStrOption(ClickHouseHttpOption.CUSTOM_HEADERS)).entrySet()) { + String name = header.getKey().toLowerCase(Locale.ROOT); + String value = header.getValue(); + if (value == null) { + continue; + } + if ("authorization".equals(name)) { + hasAuthorizationHeader = true; + } + map.put(name, value); + } + + map.put("accept", "*/*"); if (!config.getBoolOption(ClickHouseHttpOption.KEEP_ALIVE)) { - map.put("Connection", "Close"); + map.put("connection", "Close"); } - map.put("User-Agent", config.getClientName()); + map.put("user-agent", config.getClientName()); ClickHouseCredentials credentials = server.getCredentials(config); if (credentials.useAccessToken()) { // TODO check if auth-scheme is available and supported - map.put("Authorization", credentials.getAccessToken()); - } else { - map.put("X-ClickHouse-User", credentials.getUserName()); + map.put("authorization", credentials.getAccessToken()); + } else if (!hasAuthorizationHeader) { + map.put("x-clickhouse-user", credentials.getUserName()); if (config.isSsl() && !ClickHouseChecker.isNullOrEmpty(config.getSslCert())) { - map.put("X-ClickHouse-SSL-Certificate-Auth", "on"); + map.put("x-clickhouse-ssl-certificate-auth", "on"); } else if (!ClickHouseChecker.isNullOrEmpty(credentials.getPassword())) { - map.put("X-ClickHouse-Key", credentials.getPassword()); + map.put("x-clickhouse-key", credentials.getPassword()); } } String database = server.getDatabase(config); if (!ClickHouseChecker.isNullOrEmpty(database)) { - map.put("X-ClickHouse-Database", database); + map.put("x-clickhouse-database", database); } // Also, you can use the ‘default_format’ URL parameter - map.put("X-ClickHouse-Format", config.getFormat().name()); + map.put("x-clickhouse-format", config.getFormat().name()); if (config.isResponseCompressed()) { - map.put("Accept-Encoding", config.getResponseCompressAlgorithm().encoding()); + map.put("accept-encoding", config.getResponseCompressAlgorithm().encoding()); } if (config.isRequestCompressed() && config.getRequestCompressAlgorithm() != ClickHouseCompression.LZ4) { - map.put("Content-Encoding", config.getRequestCompressAlgorithm().encoding()); + map.put("content-encoding", config.getRequestCompressAlgorithm().encoding()); } return map; } @@ -251,10 +265,12 @@ public abstract class ClickHouseHttpConnection implements AutoCloseable { Map<String, String> merged = new LinkedHashMap<>(); merged.putAll(defaultHeaders); for (Entry<String, String> header : requestHeaders.entrySet()) { - if (header.getValue() == null) { - merged.remove(header.getKey()); + String name = header.getKey().toLowerCase(Locale.ROOT); + String value = header.getValue(); + if (value == null) { + merged.remove(name); } else { - merged.put(header.getKey(), header.getValue()); + merged.put(name, value); } } return merged; diff --git a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java index ac06e19a..a3c18ec5 100644 --- a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java +++ b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java @@ -6,9 +6,12 @@ import java.util.concurrent.ExecutorService; import com.clickhouse.client.ClickHouseNode; import com.clickhouse.client.ClickHouseRequest; -public abstract class ClickHouseHttpConnectionFactory { +public final class ClickHouseHttpConnectionFactory { public static ClickHouseHttpConnection createConnection(ClickHouseNode server, ClickHouseRequest<?> request, ExecutorService executor) throws IOException { return new HttpUrlConnectionImpl(server, request, executor); } + + private ClickHouseHttpConnectionFactory() { + } } diff --git a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/HttpUrlConnectionImpl.java b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/HttpUrlConnectionImpl.java index fd293590..ca9bb9fa 100644 --- a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/HttpUrlConnectionImpl.java +++ b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/HttpUrlConnectionImpl.java @@ -45,11 +45,11 @@ import javax.net.ssl.SSLContext; public class HttpUrlConnectionImpl extends ClickHouseHttpConnection { private static final Logger log = LoggerFactory.getLogger(HttpUrlConnectionImpl.class); - private static final byte[] HEADER_CONTENT_DISPOSITION = "Content-Disposition: form-data; name=\\"" + private static final byte[] HEADER_CONTENT_DISPOSITION = "content-disposition: form-data; name=\\"" .getBytes(StandardCharsets.US_ASCII); - private static final byte[] HEADER_OCTET_STREAM = "Content-Type: application/octet-stream\\r\\n" + private static final byte[] HEADER_OCTET_STREAM = "content-type: application/octet-stream\\r\\n" .getBytes(StandardCharsets.US_ASCII); - private static final byte[] HEADER_BINARY_ENCODING = "Content-Transfer-Encoding: binary\\r\\n\\r\\n" + private static final byte[] HEADER_BINARY_ENCODING = "content-transfer-encoding: binary\\r\\n\\r\\n" .getBytes(StandardCharsets.US_ASCII); private static final byte[] DOUBLE_DASH = new byte[] { '-', '-' }; @@ -217,14 +217,14 @@ public class HttpUrlConnectionImpl extends ClickHouseHttpConnection { protected ClickHouseHttpResponse post(String sql, ClickHouseInputStream data, List<ClickHouseExternalTable> tables, String url, Map<String, String> headers, ClickHouseConfig config, Runnable postCloseAction) throws IOException { - Charset charset = StandardCharsets.US_ASCII; + Charset ascii = StandardCharsets.US_ASCII; byte[] boundary = null; if (tables != null && !tables.isEmpty()) { String uuid = UUID.randomUUID().toString(); - conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=".concat(uuid)); - boundary = uuid.getBytes(charset); + conn.setRequestProperty("content-type", "multipart/form-data; boundary=".concat(uuid)); + boundary = uuid.getBytes(ascii); } else { - conn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); + conn.setRequestProperty("content-type", "text/plain; charset=UTF-8"); } setHeaders(conn, headers); @@ -241,7 +241,8 @@ public class HttpUrlConnectionImpl extends ClickHouseHttpConnection { : (hasInput ? ClickHouseClient.getAsyncRequestOutputStream(config, conn.getOutputStream(), null) // latch::countDown) : ClickHouseClient.getRequestOutputStream(c, conn.getOutputStream(), null))) { - byte[] sqlBytes = hasFile ? new byte[0] : sql.getBytes(StandardCharsets.UTF_8); + Charset utf8 = StandardCharsets.UTF_8; + byte[] sqlBytes = hasFile ? new byte[0] : sql.getBytes(utf8); if (boundary != null) { out.writeBytes(LINE_PREFIX); out.writeBytes(boundary); @@ -250,7 +251,7 @@ public class HttpUrlConnectionImpl extends ClickHouseHttpConnection { out.writeBytes(SUFFIX_QUERY); out.writeBytes(sqlBytes); for (ClickHouseExternalTable t : tables) { - byte[] tableName = t.getName().getBytes(StandardCharsets.UTF_8); + byte[] tableName = t.getName().getBytes(utf8); for (int i = 0; i < 3; i++) { out.writeBytes(LINE_PREFIX); out.writeBytes(boundary); @@ -259,10 +260,10 @@ public class HttpUrlConnectionImpl extends ClickHouseHttpConnection { out.writeBytes(tableName); if (i == 0) { out.writeBytes(SUFFIX_FORMAT); - out.writeBytes(t.getFormat().name().getBytes(charset)); + out.writeBytes(t.getFormat().name().getBytes(ascii)); } else if (i == 1) { out.writeBytes(SUFFIX_STRUCTURE); - out.writeBytes(t.getStructure().getBytes(StandardCharsets.UTF_8)); + out.writeBytes(t.getStructure().getBytes(utf8)); } else { out.writeBytes(SUFFIX_FILENAME); out.writeBytes(tableName); diff --git a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/config/ClickHouseHttpOption.java b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/config/ClickHouseHttpOption.java index cbc7d931..1d7d81e8 100644 --- a/clickhouse-http-client/src/main/java/com/clickhouse/client/http/config/ClickHouseHttpOption.java +++ b/clickhouse-http-client/src/main/java/com/clickhouse/client/http/config/ClickHouseHttpOption.java @@ -19,7 +19,9 @@ public enum ClickHouseHttpOption implements ClickHouseOption { */ CUSTOM_HEADERS("custom_http_headers", "", "Custom HTTP headers."), /** - * Custom HTTP query parameters. + * Custom HTTP query parameters. Consider + * {@link com.clickhouse.client.config.ClickHouseClientOption#CUSTOM_SETTINGS} + * if you don't want your implementation ties to http protocol. */ CUSTOM_PARAMS("custom_http_params", "", "Custom HTTP query parameters."), /** diff --git a/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java b/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java index 024be20e..9bd6d54b 100644 --- a/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java +++ b/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java @@ -8,7 +8,7 @@ import com.clickhouse.client.ClickHouseRequest; import com.clickhouse.client.http.config.ClickHouseHttpOption; import com.clickhouse.client.http.config.HttpConnectionProvider; -public abstract class ClickHouseHttpConnectionFactory { +public final class ClickHouseHttpConnectionFactory { public static ClickHouseHttpConnection createConnection(ClickHouseNode server, ClickHouseRequest<?> request, ExecutorService executor) throws IOException { HttpConnectionProvider provider = request.getConfig().getOption(ClickHouseHttpOption.CONNECTION_PROVIDER, @@ -24,4 +24,7 @@ public abstract class ClickHouseHttpConnectionFactory { return new HttpUrlConnectionImpl(server, request, executor); } } + + private ClickHouseHttpConnectionFactory() { + } } diff --git a/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/HttpClientConnectionImpl.java b/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/HttpClientConnectionImpl.java index f0a5d94f..9bafbe1d 100644 --- a/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/HttpClientConnectionImpl.java +++ b/clickhouse-http-client/src/main/java11/com/clickhouse/client/http/HttpClientConnectionImpl.java @@ -41,6 +41,7 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpClient.Redirect; import java.net.http.HttpClient.Version; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; @@ -77,6 +78,23 @@ public class HttpClientConnectionImpl extends ClickHouseHttpConnection { private static final Logger log = LoggerFactory.getLogger(HttpClientConnectionImpl.class); + private static final byte[] HEADER_CONTENT_DISPOSITION = "content-disposition: form-data; name=\\"" + .getBytes(StandardCharsets.US_ASCII); + private static final byte[] HEADER_OCTET_STREAM = "content-type: application/octet-stream\\r\\n" + .getBytes(StandardCharsets.US_ASCII); + private static final byte[] HEADER_BINARY_ENCODING = "content-transfer-encoding: binary\\r\\n\\r\\n" + .getBytes(StandardCharsets.US_ASCII); + + private static final byte[] DOUBLE_DASH = new byte[] { '-', '-' }; + private static final byte[] END_OF_NAME = new byte[] { '"', '\\r', '\\n' }; + private static final byte[] LINE_PREFIX = new byte[] { '\\r', '\\n', '-', '-' }; + private static final byte[] LINE_SUFFIX = new byte[] { '\\r', '\\n' }; + + private static final byte[] SUFFIX_QUERY = "query\\"\\r\\n\\r\\n".getBytes(StandardCharsets.US_ASCII); + private static final byte[] SUFFIX_FORMAT = "_format\\"\\r\\n\\r\\n".getBytes(StandardCharsets.US_ASCII); + private static final byte[] SUFFIX_STRUCTURE = "_structure\\"\\r\\n\\r\\n".getBytes(StandardCharsets.US_ASCII); + private static final byte[] SUFFIX_FILENAME = "\\"; filename=\\"".getBytes(StandardCharsets.US_ASCII); + private final HttpClient httpClient; private final HttpRequest pingRequest; @@ -205,55 +223,68 @@ public class HttpClientConnectionImpl extends ClickHouseHttpConnection { responseInfo -> new ClickHouseResponseHandler(config.getMaxQueuedBuffers(), config.getSocketTimeout())); } - private ClickHouseHttpResponse postStream(ClickHouseConfig config, HttpRequest.Builder reqBuilder, String boundary, + private ClickHouseHttpResponse postStream(ClickHouseConfig config, HttpRequest.Builder reqBuilder, byte[] boundary, String sql, ClickHouseInputStream data, List<ClickHouseExternalTable> tables, Runnable postAction) throws IOException { + Charset ascii = StandardCharsets.US_ASCII; + ClickHouseConfig c = config; final boolean hasFile = data != null && data.getUnderlyingFile().isAvailable(); - ClickHousePipedOutputStream stream = ClickHouseDataStreamFactory.getInstance().createPipedOutputStream(config, + + ClickHousePipedOutputStream stream = ClickHouseDataStreamFactory.getInstance().createPipedOutputStream(c, null); reqBuilder.POST(HttpRequest.BodyPublishers.ofInputStream(stream::getInputStream)); - // running in async is necessary to avoid deadlock of the piped stream CompletableFuture<HttpResponse<InputStream>> f = postRequest(reqBuilder.build()); - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) { - if (boundary != null) { - String line = "\\r\\n--" + boundary + "\\r\\n"; - writer.write(line); - writer.write("Content-Disposition: form-data; name=\\"query\\"\\r\\n\\r\\n"); - writer.write(sql); + try (ClickHouseOutputStream out = stream) { + Charset utf8 = StandardCharsets.UTF_8; + byte[] sqlBytes = hasFile ? new byte[0] : sql.getBytes(utf8); + + if (boundary != null) { + out.writeBytes(LINE_PREFIX); + out.writeBytes(boundary); + out.writeBytes(LINE_SUFFIX); + out.writeBytes(HEADER_CONTENT_DISPOSITION); + out.writeBytes(SUFFIX_QUERY); + out.writeBytes(sqlBytes); for (ClickHouseExternalTable t : tables) { - String tableName = t.getName(); - StringBuilder builder = new StringBuilder(); - builder.append(line).append("Content-Disposition: form-data; name=\\"").append(tableName) - .append("_format\\"\\r\\n\\r\\n").append(t.getFormat().name()); - builder.append(line).append("Content-Disposition: form-data; name=\\"").append(tableName) - .append("_structure\\"\\r\\n\\r\\n").append(t.getStructure()); - builder.append(line).append("Content-Disposition: form-data; name=\\"").append(tableName) - .append("\\"; filename=\\"").append(tableName).append("\\"\\r\\n") - .append("Content-Type: application/octet-stream\\r\\n") - .append("Content-Transfer-Encoding: binary\\r\\n\\r\\n"); - writer.write(builder.toString()); - writer.flush(); - - ClickHouseInputStream.pipe(t.getContent(), stream, config.getWriteBufferSize()); + byte[] tableName = t.getName().getBytes(utf8); + for (int i = 0; i < 3; i++) { + out.writeBytes(LINE_PREFIX); + out.writeBytes(boundary); + out.writeBytes(LINE_SUFFIX); + out.writeBytes(HEADER_CONTENT_DISPOSITION); + out.writeBytes(tableName); + if (i == 0) { + out.writeBytes(SUFFIX_FORMAT); + out.writeBytes(t.getFormat().name().getBytes(ascii)); + } else if (i == 1) { + out.writeBytes(SUFFIX_STRUCTURE); + out.writeBytes(t.getStructure().getBytes(utf8)); + } else { + out.writeBytes(SUFFIX_FILENAME); + out.writeBytes(tableName); + out.writeBytes(END_OF_NAME); + break; + } + } + out.writeBytes(HEADER_OCTET_STREAM); + out.writeBytes(HEADER_BINARY_ENCODING); + ClickHouseInputStream.pipe(t.getContent(), out, c.getWriteBufferSize()); } - writer.write("\\r\\n--" + boundary + "--\\r\\n"); - writer.flush(); + out.writeBytes(LINE_PREFIX); + out.writeBytes(boundary); + out.writeBytes(DOUBLE_DASH); + out.writeBytes(LINE_SUFFIX); } else { - if (!hasFile) { - writer.write(sql); - writer.flush(); - } - - if (data.available() > 0) { + out.writeBytes(sqlBytes); + if (data != null && data.available() > 0) { // append \\n - if (!hasFile && sql.charAt(sql.length() - 1) != '\\n') { - stream.write(10); + if (sqlBytes.length > 0 && sqlBytes[sqlBytes.length - 1] != (byte) '\\n') { + out.write(10); } - - ClickHouseInputStream.pipe(data, stream, config.getWriteBufferSize()); + ClickHouseInputStream.pipe(data, out, c.getWriteBufferSize()); } } } @@ -303,12 +334,13 @@ public class HttpClientConnectionImpl extends ClickHouseHttpConnection { HttpRequest.Builder reqBuilder = HttpRequest.newBuilder() .uri(URI.create(ClickHouseChecker.isNullOrEmpty(url) ? this.url : url)) .timeout(Duration.ofMillis(c.getSocketTimeout())); - String boundary = null; + byte[] boundary = null; if (tables != null && !tables.isEmpty()) { - boundary = UUID.randomUUID().toString(); - reqBuilder.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); + String uuid = UUID.randomUUID().toString(); + reqBuilder.setHeader("content-type", "multipart/form-data; boundary=" + uuid); + boundary = uuid.getBytes(StandardCharsets.US_ASCII); } else { - reqBuilder.setHeader("Content-Type", "text/plain; charset=UTF-8"); + reqBuilder.setHeader("content-type", "text/plain; charset=UTF-8"); } headers = mergeHeaders(headers); diff --git a/clickhouse-http-client/src/test/java/com/clickhouse/client/http/ClickHouseHttpClientTest.java b/clickhouse-http-client/src/test/java/com/clickhouse/client/http/ClickHouseHttpClientTest.java index c915196d..c50cd83f 100644 --- a/clickhouse-http-client/src/test/java/com/clickhouse/client/http/ClickHouseHttpClientTest.java +++ b/clickhouse-http-client/src/test/java/com/clickhouse/client/http/ClickHouseHttpClientTest.java @@ -3,6 +3,7 @@ package com.clickhouse.client.http; import java.util.UUID; import com.clickhouse.client.ClickHouseClient; +import com.clickhouse.client.ClickHouseConfig; import com.clickhouse.client.ClickHouseCredentials; import com.clickhouse.client.ClickHouseFormat; import com.clickhouse.client.ClickHouseNode; @@ -35,6 +36,36 @@ public class ClickHouseHttpClientTest extends ClientIntegrationTest { return ClickHouseHttpClient.class; } + @Test(groups = "integration") + public void testAuthentication() throws Exception { + String sql = "select currentUser()"; + try (ClickHouseClient client = getClient( + new ClickHouseConfig(null, ClickHouseCredentials.fromUserAndPassword("dba", "dba"), null, null)); + ClickHouseResponse response = client + .connect(getServer()) + // .option(ClickHouseHttpOption.CUSTOM_PARAMS, "user=dba,password=incorrect") + .query(sql).executeAndWait()) { + Assert.assertEquals(response.firstRecord().getValue(0).asString(), "dba"); + } + + try (ClickHouseClient client = getClient(); + ClickHouseResponse response = client + .connect(getServer()) + .option(ClickHouseHttpOption.CUSTOM_HEADERS, "Authorization=Basic ZGJhOmRiYQ==") + // .option(ClickHouseHttpOption.CUSTOM_PARAMS, "user=dba,password=incorrect") + .query(sql).executeAndWait()) { + Assert.assertEquals(response.firstRecord().getValue(0).asString(), "dba"); + } + + try (ClickHouseClient client = getClient(); + ClickHouseResponse response = client + .connect(getServer(ClickHouseNode + .of("http://localhost?custom_http_headers=aUthorization%3DBasic%20ZGJhOmRiYQ%3D%3D"))) + .query(sql).executeAndWait()) { + Assert.assertEquals(response.firstRecord().getValue(0).asString(), "dba"); + } + } + @Test(groups = "integration") @Override public void testSession() throws Exception {
    ['clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnection.java', 'clickhouse-http-client/src/main/java/com/clickhouse/client/http/HttpUrlConnectionImpl.java', 'clickhouse-http-client/src/test/java/com/clickhouse/client/http/ClickHouseHttpClientTest.java', 'clickhouse-http-client/src/main/java/com/clickhouse/client/http/config/ClickHouseHttpOption.java', 'clickhouse-http-client/src/main/java11/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java', 'clickhouse-client/src/test/java/com/clickhouse/client/BaseIntegrationTest.java', 'clickhouse-http-client/src/main/java/com/clickhouse/client/http/ClickHouseHttpConnectionFactory.java', 'clickhouse-http-client/src/main/java11/com/clickhouse/client/http/HttpClientConnectionImpl.java', 'clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java']
    {'.java': 9}
    9
    9
    0
    0
    9
    2,583,913
    538,949
    76,365
    333
    11,700
    2,194
    195
    6
    913
    109
    220
    7
    2
    0
    1970-01-01T00:27:42
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,888
    clickhouse/clickhouse-java/940/920
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/920
    https://github.com/ClickHouse/clickhouse-java/pull/940
    https://github.com/ClickHouse/clickhouse-java/pull/940
    1
    closes
    Multiple values insert prepared statement
    [QUESTION] about multiple values in prepared statement. Probably, after this [COMMIT](https://github.com/ClickHouse/clickhouse-jdbc/commit/09cd66e564966d76d72f996754dbf8311bf1b49d) between **patch5** and **patch6** and later versions. I can't anymore use multiple values in prepared statement, like `PreparedStatement stmt = Connection#prepareStatement("insert into table values(?,?), (?,?)");` only `PreparedStatement stmt = Connection#prepareStatement("insert into table values(?,?)");` and then insert values for each row separated by `stmt.addBatch()` Is it final change or, maybe some options are needed to be turned on? Under the hood detail. `values (?,?), (?,?)` is not properly parsed and it doesn't see `ClickHouseSqlStatement.KEYWORD_VALUES_START` (values start position index in sql). Here in the [CODE](https://github.com/ClickHouse/clickhouse-jdbc/blob/1d6257c51a1d5db0a4732441fc3c1c7dba7b5316/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java#L601) returns null which cause NPE later in code. For `values (?,?)` all worked correctly.
    44a1986ba59705fd1254af9705c315d5853e91c8
    7db110ff8cf708c59121adcbb8a7684fd74f87ec
    https://github.com/clickhouse/clickhouse-java/compare/44a1986ba59705fd1254af9705c315d5853e91c8...7db110ff8cf708c59121adcbb8a7684fd74f87ec
    diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java index ebef724b..3df1afb6 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java @@ -615,14 +615,17 @@ public class ClickHouseConnectionImpl extends JdbcWrapper implements ClickHouseC !parsedStmt.containsKeyword("SELECT") && parsedStmt.hasValues() && (!parsedStmt.hasFormat() || clientRequest.getFormat().name().equals(parsedStmt.getFormat()))) { String query = parsedStmt.getSQL(); - int startIndex = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_START); - int endIndex = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_END); - boolean useStream = true; - for (int i = startIndex + 1; i < endIndex; i++) { - char ch = query.charAt(i); - if (ch != '?' && ch != ',' && !Character.isWhitespace(ch)) { - useStream = false; - break; + boolean useStream = false; + Integer startIndex = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_START); + if (startIndex != null) { + useStream = true; + int endIndex = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_END); + for (int i = startIndex + 1; i < endIndex; i++) { + char ch = query.charAt(i); + if (ch != '?' && ch != ',' && !Character.isWhitespace(ch)) { + useStream = false; + break; + } } } diff --git a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java index 025b67ad..2f496ff9 100644 --- a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java +++ b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java @@ -1,8 +1,10 @@ package com.clickhouse.jdbc; import java.io.ByteArrayInputStream; +import java.math.BigDecimal; import java.net.Inet4Address; import java.net.Inet6Address; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.BatchUpdateException; import java.sql.Connection; @@ -1257,4 +1259,46 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { Assert.assertFalse(rs.next()); } } + + @Test(groups = "integration") + public void testInsertWithMultipleValues() throws Exception { + try (ClickHouseConnection conn = newConnection(new Properties()); + Statement s = conn.createStatement()) { + s.execute("drop table if exists test_insert_with_multiple_values; " + + "CREATE TABLE test_insert_with_multiple_values(a Int32, b Nullable(String)) ENGINE=Memory"); + try (PreparedStatement ps = conn.prepareStatement( + "INSERT INTO test_insert_with_multiple_values values(?, ?), (2 , ? ), ( ? , '') , (?,?) ,( ? ,? )")) { + ps.setInt(1, 1); + ps.setNull(2, Types.VARCHAR); + ps.setObject(3, "er"); + ps.setInt(4, 3); + ps.setInt(5, 4); + ps.setURL(6, new URL("http://some.host")); + ps.setInt(7, 5); + ps.setString(8, null); + ps.executeUpdate(); + } + + try (ResultSet rs = s.executeQuery("select * from test_insert_with_multiple_values order by a")) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getByte(1), (byte) 1); + Assert.assertEquals(rs.getObject(2), null); + Assert.assertTrue(rs.wasNull()); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getBigDecimal(1), BigDecimal.valueOf(2L)); + Assert.assertEquals(rs.getString(2), "er"); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getString(1), "3"); + Assert.assertEquals(rs.getObject(2), ""); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getShort(1), (short) 4); + Assert.assertEquals(rs.getURL(2), new URL("http://some.host")); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getObject(1), Integer.valueOf(5)); + Assert.assertEquals(rs.getString(2), null); + Assert.assertTrue(rs.wasNull()); + Assert.assertFalse(rs.next()); + } + } + } }
    ['clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    2,375,543
    497,493
    71,031
    324
    1,201
    216
    19
    1
    1,111
    108
    289
    17
    2
    0
    1970-01-01T00:27:33
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,889
    clickhouse/clickhouse-java/901/889
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/889
    https://github.com/ClickHouse/clickhouse-java/pull/901
    https://github.com/ClickHouse/clickhouse-java/pull/901
    1
    closes
    ClickHouseColumn bug when parsing a tuple type
    Hi. There is a bug or unexpected behavior in ClickHouseColumn when parsing a tuple type: `ClickHouseColumn.parse("col_name Tuple(s String, i Int64)")` is throwing the following exception: ``` java.lang.IllegalArgumentException: Unknown data type: s String ``` My use case retrieves the types with a `DESCRIBE TABLE` query and parsing them via `ClickHouseColumn.parse`.
    b76a2eefb97802eefe02f7cae83c591d285610d3
    2c7bf7773bfc09dd3708c63623c90d14fd97084f
    https://github.com/clickhouse/clickhouse-java/compare/b76a2eefb97802eefe02f7cae83c591d285610d3...2c7bf7773bfc09dd3708c63623c90d14fd97084f
    diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseColumn.java b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseColumn.java index 34011606..aac9dc41 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseColumn.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseColumn.java @@ -321,16 +321,18 @@ public final class ClickHouseColumn implements Serializable { StringBuilder sb = new StringBuilder(); i = ClickHouseUtils.readNameOrQuotedString(args, i, len, sb); String modifier = sb.toString(); + String normalizedModifier = modifier.toUpperCase(); sb.setLength(0); boolean startsWithNot = false; - if ("not".equalsIgnoreCase(modifier)) { + if ("NOT".equals(normalizedModifier)) { startsWithNot = true; i = ClickHouseUtils.readNameOrQuotedString(args, i, len, sb); modifier = sb.toString(); + normalizedModifier = modifier.toUpperCase(); sb.setLength(0); } - if ("null".equalsIgnoreCase(modifier)) { + if ("NULL".equals(normalizedModifier)) { if (nullable) { throw new IllegalArgumentException("Nullable and NULL cannot be used together"); } @@ -339,14 +341,14 @@ public final class ClickHouseColumn implements Serializable { break; } else if (startsWithNot) { throw new IllegalArgumentException("Expect keyword NULL after NOT"); - } else if ("alias".equalsIgnoreCase(modifier) || "codec".equalsIgnoreCase(modifier) - || "default".equalsIgnoreCase(modifier) || "materialized".equalsIgnoreCase(modifier) - || "ttl".equalsIgnoreCase(modifier)) { // stop words + } else if ("ALIAS".equals(normalizedModifier) || "CODEC".equals(normalizedModifier) + || "DEFAULT".equals(normalizedModifier) || "MATERIALIZED".equals(normalizedModifier) + || "TTL".equals(normalizedModifier)) { // stop words i = ClickHouseUtils.skipContentsUntil(args, i, len, ',') - 1; break; } else { if ((name == null || name.isEmpty()) - && !ClickHouseDataType.mayStartWith(builder.toString())) { + && !ClickHouseDataType.mayStartWith(builder.toString(), normalizedModifier)) { return readColumn(args, i - modifier.length(), len, builder.toString(), list); } else { builder.append(' '); diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseDataType.java b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseDataType.java index bf17c071..38de0871 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseDataType.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseDataType.java @@ -181,19 +181,25 @@ public enum ClickHouseDataType { } /** - * Checks if any alias uses the given prefix. + * Checks if any alias uses the given prefixes. * - * @param prefix prefix to check - * @return true if any alias using the given prefix; false otherwise + * @param prefixes prefixes to check + * @return true if any alias using the given prefixes; false otherwise */ - public static boolean mayStartWith(String prefix) { - if (prefix == null || prefix.isEmpty()) { + public static boolean mayStartWith(String... prefixes) { + if (prefixes == null || prefixes.length == 0) { return false; } - prefix = prefix.toUpperCase(); + StringBuilder builder = new StringBuilder(); + for (int i = 0, len = prefixes.length; i < len; i++) { + builder.append(prefixes[i].toUpperCase()).append(' '); + } + String prefix = builder.toString(); + builder.setLength(builder.length() - 1); + String typeName = builder.toString(); for (String alias : allAliases) { - if (alias.startsWith(prefix)) { + if (alias.startsWith(prefix) || alias.equals(typeName)) { return true; } } diff --git a/clickhouse-client/src/test/java/com/clickhouse/client/ClickHouseColumnTest.java b/clickhouse-client/src/test/java/com/clickhouse/client/ClickHouseColumnTest.java index 1e041d4e..ecdea072 100644 --- a/clickhouse-client/src/test/java/com/clickhouse/client/ClickHouseColumnTest.java +++ b/clickhouse-client/src/test/java/com/clickhouse/client/ClickHouseColumnTest.java @@ -17,6 +17,14 @@ public class ClickHouseColumnTest { @DataProvider(name = "objectTypesProvider") private Object[][] getObjectTypes() { return new Object[][] { + { "Tuple(not NChar Large Object)" }, + { "nchar Large Object" }, + { "Tuple(int Int32)" }, + { "a Tuple(i Int32)" }, + { "b Tuple(i1 Int32)" }, + { "Tuple(i Int32)" }, + { "Tuple(i1 Int32)" }, + { "Tuple(i Int32, a Array(Int32), m Map(LowCardinality(String), Int32))" }, { "Int8" }, { "TINYINT SIGNED" }, { "k1 Int8" }, { "k1 TINYINT SIGNED" }, { "k1 Nullable(Int8)" }, { "k1 Nullable( Int8 )" }, { "k1 TINYINT SIGNED null" },
    ['clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseDataType.java', 'clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseColumn.java', 'clickhouse-client/src/test/java/com/clickhouse/client/ClickHouseColumnTest.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    2,244,194
    470,925
    67,358
    308
    2,249
    415
    34
    2
    380
    49
    83
    10
    0
    1
    1970-01-01T00:27:30
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,890
    clickhouse/clickhouse-java/658/657
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/657
    https://github.com/ClickHouse/clickhouse-java/pull/658
    https://github.com/ClickHouse/clickhouse-java/pull/658
    1
    fixes
    Incorrect value returned from getAutoCommit
    Since transactions are implicitly enabled for new connections (they are not supported at all), the `getAutoCommit` should return true.
    339453f5173dd7a064051d31876c81baad38decd
    5ca9485fe76bce8e5e8cb4effcaa74b4ffc5a089
    https://github.com/clickhouse/clickhouse-java/compare/339453f5173dd7a064051d31876c81baad38decd...5ca9485fe76bce8e5e8cb4effcaa74b4ffc5a089
    diff --git a/clickhouse-jdbc/src/main/java/ru/yandex/clickhouse/ClickHouseConnectionImpl.java b/clickhouse-jdbc/src/main/java/ru/yandex/clickhouse/ClickHouseConnectionImpl.java index 6ec960ca..0b498c6a 100644 --- a/clickhouse-jdbc/src/main/java/ru/yandex/clickhouse/ClickHouseConnectionImpl.java +++ b/clickhouse-jdbc/src/main/java/ru/yandex/clickhouse/ClickHouseConnectionImpl.java @@ -214,7 +214,7 @@ public class ClickHouseConnectionImpl implements ClickHouseConnection { @Override public boolean getAutoCommit() throws SQLException { - return false; + return true; } @Override
    ['clickhouse-jdbc/src/main/java/ru/yandex/clickhouse/ClickHouseConnectionImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    586,216
    121,413
    17,745
    101
    44
    8
    2
    1
    134
    19
    26
    1
    0
    0
    1970-01-01T00:27:00
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,891
    clickhouse/clickhouse-java/540/462
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/462
    https://github.com/ClickHouse/clickhouse-java/pull/540
    https://github.com/ClickHouse/clickhouse-java/pull/540
    1
    fix
    NoHttpResponseException while intensive inserts
    Hi! I catch an error using sendStream in RowBinary format intensive queries(1M rows in batch every 3 second) One batch inserts in ~10-15 seconds. Clickhouse machine cpu usage is about 25%. It appears after 5 minutes of job start. I tried to catch problematic batch and insert in separately. Everything was fine. clickouse-jdbc 0.2.4 #https://github.com/ClickHouse/ClickHouse/issues/11766 Sample of usage ``` try (ClickHouseStatement statement = clickHouseDataSource.getConnection().createStatement()) { statement.write().send(QUERY_INSERT, batch, ClickHouseFormat.RowBinary); ``` Simple schema ``` CREATE TABLE IF NOT EXISTS t1 ( timestamp DateTime, sid FixedString(10), url1 String, url2 String, importMonth UInt32 default toYYYYMM(now()), sidHash UInt32 DEFAULT xxHash32(sid), url1Domain String DEFAULT domainWithoutWWW(url1) ) ENGINE = MergeTree PARTITION BY (importMonth) ORDER BY (sidHash); ``` Timeouts config ``` clickHouseDataSource.getProperties().setSessionTimeout(600_000L); clickHouseDataSource.getProperties().setConnectionTimeout(600_000); clickHouseDataSource.getProperties().setSocketTimeout(600_000); clickHouseDataSource.getProperties().setDataTransferTimeout(600_000); clickHouseDataSource.getProperties().setKeepAliveTimeout(600_000); ``` Exception ``` Caused by: org.apache.http.NoHttpResponseException: server:8123 failed to respond at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141) at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56) at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259) at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163) at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157) at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108) at ru.yandex.clickhouse.ClickHouseStatementImpl.sendStream(ClickHouseStatementImpl.java:849) ... 13 common frames omitted ``` Error in clickhouse log ``` 2020.06.18 15:10:11.079888 [ 966 ] {c2912eff-d759-4b1b-80b3-151e5a96196a} <Error> executeQuery: Code: 23, e.displayText() = DB::Exception: Cannot read from istream at offset 22020096 (version 20.4.4.18 (official build)) (from server:53702) (in query: INSERT INTO tabl1(timestamp,sid,url1,url2) FORMAT RowBinary ), Stack trace (when copying this message, always include the lines below): 0. Poco::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int) @ 0x104191d0 in /usr/bin/clickhouse 1. DB::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int) @ 0x8fff8ad in /usr/bin/clickhouse 2. ? @ 0x90db204 in /usr/bin/clickhouse 3. DB::CompressedReadBufferBase::readCompressedData(unsigned long&, unsigned long&) @ 0xcdf7dce in /usr/bin/clickhouse 4. DB::CompressedReadBuffer::nextImpl() @ 0xcdf616b in /usr/bin/clickhouse 5. DB::ConcatReadBuffer::nextImpl() @ 0x90e8912 in /usr/bin/clickhouse 6. DB::ConcatReadBuffer::nextImpl() @ 0x90e8912 in /usr/bin/clickhouse 7. DB::ReadBuffer::readStrict(char*, unsigned long) @ 0x903b525 in /usr/bin/clickhouse 8. DB::DataTypeString::deserializeBinary(DB::IColumn&, DB::ReadBuffer&) const @ 0xcf3ade5 in /usr/bin/clickhouse 9. DB::BinaryRowInputFormat::readRow(std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, DB::RowReadExtension&) @ 0xdb683af in /usr/bin/clickhouse 10. DB::IRowInputFormat::generate() @ 0xdb5d151 in /usr/bin/clickhouse 11. DB::ISource::work() @ 0xdaf3d8b in /usr/bin/clickhouse 12. DB::InputStreamFromInputFormat::readImpl() @ 0xdab99fd in /usr/bin/clickhouse 13. DB::IBlockInputStream::read() @ 0xce4825d in /usr/bin/clickhouse 14. DB::AddingDefaultsBlockInputStream::readImpl() @ 0xce3896b in /usr/bin/clickhouse 15. DB::IBlockInputStream::read() @ 0xce4825d in /usr/bin/clickhouse 16. DB::InputStreamFromASTInsertQuery::readImpl() @ 0xd1cbc39 in /usr/bin/clickhouse 17. DB::IBlockInputStream::read() @ 0xce4825d in /usr/bin/clickhouse 18. DB::copyData(DB::IBlockInputStream&, DB::IBlockOutputStream&, std::__1::atomic<bool>*) @ 0xce7717e in /usr/bin/clickhouse 19. DB::executeQuery(DB::ReadBuffer&, DB::WriteBuffer&, bool, DB::Context&, std::__1::function<void (std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) @ 0xd54d5ab in /usr/bin/clickhouse 20. DB::HTTPHandler::processQuery(Poco::Net::HTTPServerRequest&, HTMLForm&, Poco::Net::HTTPServerResponse&, DB::HTTPHandler::Output&) @ 0x90e47fc in /usr/bin/clickhouse 21. DB::HTTPHandler::handleRequest(Poco::Net::HTTPServerRequest&, Poco::Net::HTTPServerResponse&) @ 0x90e8256 in /usr/bin/clickhouse 22. Poco::Net::HTTPServerConnection::run() @ 0x102c9b83 in /usr/bin/clickhouse 23. Poco::Net::TCPServerConnection::start() @ 0x10304f4b in /usr/bin/clickhouse 24. Poco::Net::TCPServerDispatcher::run() @ 0x103053db in /usr/bin/clickhouse 25. Poco::PooledThread::run() @ 0x104b2fa6 in /usr/bin/clickhouse 26. Poco::ThreadImpl::runnableEntry(void*) @ 0x104ae260 in /usr/bin/clickhouse 27. start_thread @ 0x7fa3 in /lib/x86_64-linux-gnu/libpthread-2.28.so 28. __clone @ 0xf94cf in /lib/x86_64-linux-gnu/libc-2.28.so 2020.06.18 15:10:11.080144 [ 966 ] {} <Error> DynamicQueryHandler: Code: 23, e.displayText() = DB::Exception: Cannot read from istream at offset 22020096, Stack trace (when copying this message, always include the lines below): 0. Poco::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int) @ 0x104191d0 in /usr/bin/clickhouse 1. DB::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int) @ 0x8fff8ad in /usr/bin/clickhouse 2. ? @ 0x90db204 in /usr/bin/clickhouse 3. DB::CompressedReadBufferBase::readCompressedData(unsigned long&, unsigned long&) @ 0xcdf7dce in /usr/bin/clickhouse 4. DB::CompressedReadBuffer::nextImpl() @ 0xcdf616b in /usr/bin/clickhouse 5. DB::ConcatReadBuffer::nextImpl() @ 0x90e8912 in /usr/bin/clickhouse 6. DB::ConcatReadBuffer::nextImpl() @ 0x90e8912 in /usr/bin/clickhouse 7. DB::ReadBuffer::readStrict(char*, unsigned long) @ 0x903b525 in /usr/bin/clickhouse 8. DB::DataTypeString::deserializeBinary(DB::IColumn&, DB::ReadBuffer&) const @ 0xcf3ade5 in /usr/bin/clickhouse 9. DB::BinaryRowInputFormat::readRow(std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, DB::RowReadExtension&) @ 0xdb683af in /usr/bin/clickhouse 10. DB::IRowInputFormat::generate() @ 0xdb5d151 in /usr/bin/clickhouse 11. DB::ISource::work() @ 0xdaf3d8b in /usr/bin/clickhouse 12. DB::InputStreamFromInputFormat::readImpl() @ 0xdab99fd in /usr/bin/clickhouse 13. DB::IBlockInputStream::read() @ 0xce4825d in /usr/bin/clickhouse 14. DB::AddingDefaultsBlockInputStream::readImpl() @ 0xce3896b in /usr/bin/clickhouse 15. DB::IBlockInputStream::read() @ 0xce4825d in /usr/bin/clickhouse 16. DB::InputStreamFromASTInsertQuery::readImpl() @ 0xd1cbc39 in /usr/bin/clickhouse 17. DB::IBlockInputStream::read() @ 0xce4825d in /usr/bin/clickhouse 18. DB::copyData(DB::IBlockInputStream&, DB::IBlockOutputStream&, std::__1::atomic<bool>*) @ 0xce7717e in /usr/bin/clickhouse 19. DB::executeQuery(DB::ReadBuffer&, DB::WriteBuffer&, bool, DB::Context&, std::__1::function<void (std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) @ 0xd54d5ab in /usr/bin/clickhouse 20. DB::HTTPHandler::processQuery(Poco::Net::HTTPServerRequest&, HTMLForm&, Poco::Net::HTTPServerResponse&, DB::HTTPHandler::Output&) @ 0x90e47fc in /usr/bin/clickhouse 21. DB::HTTPHandler::handleRequest(Poco::Net::HTTPServerRequest&, Poco::Net::HTTPServerResponse&) @ 0x90e8256 in /usr/bin/clickhouse 22. Poco::Net::HTTPServerConnection::run() @ 0x102c9b83 in /usr/bin/clickhouse 23. Poco::Net::TCPServerConnection::start() @ 0x10304f4b in /usr/bin/clickhouse 24. Poco::Net::TCPServerDispatcher::run() @ 0x103053db in /usr/bin/clickhouse 25. Poco::PooledThread::run() @ 0x104b2fa6 in /usr/bin/clickhouse 26. Poco::ThreadImpl::runnableEntry(void*) @ 0x104ae260 in /usr/bin/clickhouse 27. start_thread @ 0x7fa3 in /lib/x86_64-linux-gnu/libpthread-2.28.so 28. __clone @ 0xf94cf in /lib/x86_64-linux-gnu/libc-2.28.so (version 20.4.4.18 (official build)) ```
    8e68aa489d21fcb4a0f4d48c05028f804f048169
    f90acb005c077b4b82dbb6d6d92d64930cef4d4d
    https://github.com/clickhouse/clickhouse-java/compare/8e68aa489d21fcb4a0f4d48c05028f804f048169...f90acb005c077b4b82dbb6d6d92d64930cef4d4d
    diff --git a/src/main/java/ru/yandex/clickhouse/settings/ClickHouseConnectionSettings.java b/src/main/java/ru/yandex/clickhouse/settings/ClickHouseConnectionSettings.java index 202574fe..6928a340 100644 --- a/src/main/java/ru/yandex/clickhouse/settings/ClickHouseConnectionSettings.java +++ b/src/main/java/ru/yandex/clickhouse/settings/ClickHouseConnectionSettings.java @@ -27,6 +27,7 @@ public enum ClickHouseConnectionSettings implements DriverPropertyCreator { + " ClickHouse rejects request execution if its time exceeds max_execution_time"), + @Deprecated KEEP_ALIVE_TIMEOUT("keepAliveTimeout", 30 * 1000, ""), /** @@ -35,6 +36,7 @@ public enum ClickHouseConnectionSettings implements DriverPropertyCreator { TIME_TO_LIVE_MILLIS("timeToLiveMillis", 60 * 1000, ""), DEFAULT_MAX_PER_ROUTE("defaultMaxPerRoute", 500, ""), MAX_TOTAL("maxTotal", 10000, ""), + MAX_RETRIES("maxRetries", 3, "Maximum retries(default to 3) for idempotent operation. Set 0 to disable retry."), /** * additional diff --git a/src/main/java/ru/yandex/clickhouse/settings/ClickHouseProperties.java b/src/main/java/ru/yandex/clickhouse/settings/ClickHouseProperties.java index b368917e..6c01b194 100644 --- a/src/main/java/ru/yandex/clickhouse/settings/ClickHouseProperties.java +++ b/src/main/java/ru/yandex/clickhouse/settings/ClickHouseProperties.java @@ -22,6 +22,7 @@ public class ClickHouseProperties { private int timeToLiveMillis; private int defaultMaxPerRoute; private int maxTotal; + private int maxRetries; private String host; private int port; private boolean usePathAsDb; @@ -113,6 +114,7 @@ public class ClickHouseProperties { this.timeToLiveMillis = (Integer)getSetting(info, ClickHouseConnectionSettings.TIME_TO_LIVE_MILLIS); this.defaultMaxPerRoute = (Integer)getSetting(info, ClickHouseConnectionSettings.DEFAULT_MAX_PER_ROUTE); this.maxTotal = (Integer)getSetting(info, ClickHouseConnectionSettings.MAX_TOTAL); + this.maxRetries = (Integer)getSetting(info, ClickHouseConnectionSettings.MAX_RETRIES); this.maxCompressBufferSize = (Integer) getSetting(info, ClickHouseConnectionSettings.MAX_COMPRESS_BUFFER_SIZE); this.ssl = (Boolean) getSetting(info, ClickHouseConnectionSettings.SSL); this.sslRootCertificate = (String) getSetting(info, ClickHouseConnectionSettings.SSL_ROOT_CERTIFICATE); @@ -179,6 +181,7 @@ public class ClickHouseProperties { ret.put(ClickHouseConnectionSettings.TIME_TO_LIVE_MILLIS.getKey(), String.valueOf(timeToLiveMillis)); ret.put(ClickHouseConnectionSettings.DEFAULT_MAX_PER_ROUTE.getKey(), String.valueOf(defaultMaxPerRoute)); ret.put(ClickHouseConnectionSettings.MAX_TOTAL.getKey(), String.valueOf(maxTotal)); + ret.put(ClickHouseConnectionSettings.MAX_RETRIES.getKey(), String.valueOf(maxRetries)); ret.put(ClickHouseConnectionSettings.MAX_COMPRESS_BUFFER_SIZE.getKey(), String.valueOf(maxCompressBufferSize)); ret.put(ClickHouseConnectionSettings.SSL.getKey(), String.valueOf(ssl)); ret.put(ClickHouseConnectionSettings.SSL_ROOT_CERTIFICATE.getKey(), String.valueOf(sslRootCertificate)); @@ -248,6 +251,7 @@ public class ClickHouseProperties { setTimeToLiveMillis(properties.timeToLiveMillis); setDefaultMaxPerRoute(properties.defaultMaxPerRoute); setMaxTotal(properties.maxTotal); + setMaxRetries(properties.maxRetries); setMaxCompressBufferSize(properties.maxCompressBufferSize); setSsl(properties.ssl); setSslRootCertificate(properties.sslRootCertificate); @@ -594,6 +598,14 @@ public class ClickHouseProperties { this.maxTotal = maxTotal; } + public int getMaxRetries() { + return maxRetries; + } + + public void setMaxRetries(int maxRetries) { + this.maxRetries = maxRetries; + } + public int getMaxCompressBufferSize() { return maxCompressBufferSize; } diff --git a/src/main/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilder.java b/src/main/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilder.java index 59e89314..66bc9980 100644 --- a/src/main/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilder.java +++ b/src/main/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilder.java @@ -27,20 +27,19 @@ import javax.net.ssl.TrustManagerFactory; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HeaderElementIterator; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; +import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; @@ -50,11 +49,10 @@ import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicHeaderElementIterator; -import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import ru.yandex.clickhouse.settings.ClickHouseProperties; @@ -71,16 +69,32 @@ public class ClickHouseHttpClientBuilder { public CloseableHttpClient buildClient() throws Exception { return HttpClientBuilder.create() .setConnectionManager(getConnectionManager()) + .setRetryHandler(getRequestRetryHandler()) .setConnectionReuseStrategy(getConnectionReuseStrategy()) .setDefaultConnectionConfig(getConnectionConfig()) .setDefaultRequestConfig(getRequestConfig()) .setDefaultHeaders(getDefaultHeaders()) .setDefaultCredentialsProvider(getDefaultCredentialsProvider()) - .disableContentCompression() // gzip здесь ни к чему. Используется lz4 при compress=1 + .disableContentCompression() // gzip is not needed. Use lz4 when compress=1 .disableRedirectHandling() .build(); } + private HttpRequestRetryHandler getRequestRetryHandler() { + final int maxRetries = properties.getMaxRetries(); + return new DefaultHttpRequestRetryHandler(maxRetries, false) { + @Override + public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { + if (executionCount > maxRetries || context == null + || !Boolean.TRUE.equals(context.getAttribute("is_idempotent"))) { + return false; + } + + return (exception instanceof NoHttpResponseException) || super.retryRequest(exception, executionCount, context); + } + }; + } + public static HttpClientContext createClientContext(ClickHouseProperties props) { if (props == null || !isConfigurationValidForAuth(props)) @@ -155,29 +169,6 @@ public class ClickHouseHttpClientBuilder { return headers; } - private ConnectionKeepAliveStrategy createKeepAliveStrategy() { - return new ConnectionKeepAliveStrategy() { - @Override - public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) { - // in case of errors keep-alive not always works. close connection just in case - if (httpResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { - return -1; - } - HeaderElementIterator it = new BasicHeaderElementIterator( - httpResponse.headerIterator(HTTP.CONN_DIRECTIVE)); - while (it.hasNext()) { - HeaderElement he = it.nextElement(); - String param = he.getName(); - //String value = he.getValue(); - if (param != null && param.equalsIgnoreCase(HTTP.CONN_KEEP_ALIVE)) { - return properties.getKeepAliveTimeout(); - } - } - return -1; - } - }; - } - private SSLContext getSSLContext() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { SSLContext ctx = SSLContext.getInstance("TLS"); diff --git a/src/test/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilderTest.java b/src/test/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilderTest.java index e7cc8802..e7eee897 100644 --- a/src/test/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilderTest.java +++ b/src/test/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilderTest.java @@ -1,8 +1,12 @@ package ru.yandex.clickhouse.util; import org.apache.http.HttpHost; +import org.apache.http.NoHttpResponseException; import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.HttpHostConnectException; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -141,7 +145,72 @@ public class ClickHouseHttpClientBuilderTest { null, null, "baz", "Basic ZGVmYXVsdDpiYXo=" // default:baz }, }; + } + + private static WireMockServer newServer() { + WireMockServer server = new WireMockServer( + WireMockConfiguration.wireMockConfig().dynamicPort()); + server.start(); + server.stubFor(WireMock.post(WireMock.urlPathMatching("/*")) + .willReturn(WireMock.aResponse().withStatus(200).withHeader("Connection", "Keep-Alive") + .withHeader("Content-Type", "text/plain; charset=UTF-8") + .withHeader("Transfer-Encoding", "chunked").withHeader("Keep-Alive", "timeout=3") + .withBody("OK.........................").withFixedDelay(2))); + return server; + } + private static void shutDownServerWithDelay(final WireMockServer server, final long delayMs) { + new Thread() { + public void run() { + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + server.shutdownServer(); + server.stop(); + } + }.start(); } + // @Test(dependsOnMethods = { "testWithRetry" }, expectedExceptions = { NoHttpResponseException.class }) + public void testWithoutRetry() throws Exception { + final WireMockServer server = newServer(); + + ClickHouseProperties props = new ClickHouseProperties(); + props.setMaxRetries(0); + ClickHouseHttpClientBuilder builder = new ClickHouseHttpClientBuilder(props); + CloseableHttpClient client = builder.buildClient(); + HttpPost post = new HttpPost("http://localhost:" + server.port() + "/?db=system&query=select%201"); + + shutDownServerWithDelay(server, 100); + + try { + client.execute(post); + } finally { + client.close(); + } + } + + // @Test(expectedExceptions = { HttpHostConnectException.class }) + public void testWithRetry() throws Exception { + final WireMockServer server = newServer(); + + ClickHouseProperties props = new ClickHouseProperties(); + // props.setMaxRetries(3); + ClickHouseHttpClientBuilder builder = new ClickHouseHttpClientBuilder(props); + CloseableHttpClient client = builder.buildClient(); + HttpContext context = new BasicHttpContext(); + context.setAttribute("is_idempotent", Boolean.TRUE); + HttpPost post = new HttpPost("http://localhost:" + server.port() + "/?db=system&query=select%202"); + + shutDownServerWithDelay(server, 100); + + try { + client.execute(post, context); + } finally { + client.close(); + } + } }
    ['src/test/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilderTest.java', 'src/main/java/ru/yandex/clickhouse/util/ClickHouseHttpClientBuilder.java', 'src/main/java/ru/yandex/clickhouse/settings/ClickHouseConnectionSettings.java', 'src/main/java/ru/yandex/clickhouse/settings/ClickHouseProperties.java']
    {'.java': 4}
    4
    4
    0
    0
    4
    437,607
    90,987
    13,597
    69
    3,050
    557
    63
    3
    9,958
    698
    2,975
    131
    1
    5
    1970-01-01T00:26:50
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,882
    clickhouse/clickhouse-java/1082/1072
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/1072
    https://github.com/ClickHouse/clickhouse-java/pull/1082
    https://github.com/ClickHouse/clickhouse-java/pull/1082
    1
    fixes
    File data insert using CSVWithNames is failing since v0.3.2-patch10
    We are using ClickHouse JDBC driver to import CSV files that include a header line with column names. Here is the JRuby code that we use https://github.com/rsim/mondrian-olap/blob/master/spec/rake_tasks.rb#L377-L380 ```ruby conn.jdbc_connection.createStatement.write. query("INSERT INTO #{table_name}(#{columns_string})"). format(Java::com.clickhouse.client.ClickHouseFormat::CSVWithNames). data(file_path).send ``` It was working until the version v0.3.2-patch9 but since the version v0.3.2-patch10 it is failing with: ``` Java::JavaUtilConcurrent::CompletionException: com.clickhouse.client.ClickHouseException: Code: 27. DB::ParsingException: Cannot parse input: expected ',' before: 'id,the_date,the_day,the_month,the_year,day_of_month,week_of_year,month_of_year,quarter\\n1,2010-01-01 02:00:00,Friday,January,2010,1,0,1,Q1\\n2,2010-01-02 02:00:00,': Row 1: Column 0, name: id, type: Int32, ERROR: text "id,the_dat" is not like Int32 : While executing ParallelParsingBlockInputFormat: (at row 1) . (CANNOT_PARSE_INPUT_ASSERTION_FAILED) (version 22.1.4.1) , server ClickHouseNode [uri=http://localhost:8123/mondrian_test]com.clickhouse.client.ClickHouseClientBuilder$Agent.handle(com/clickhouse/client/ClickHouseClientBuilder.java:181) com.clickhouse.client.ClickHouseClientBuilder$Agent.send(com/clickhouse/client/ClickHouseClientBuilder.java:204) com.clickhouse.client.ClickHouseClientBuilder$Agent.execute(com/clickhouse/client/ClickHouseClientBuilder.java:234) com.clickhouse.client.ClickHouseRequest$Mutation.execute(com/clickhouse/client/ClickHouseRequest.java:241) com.clickhouse.client.ClickHouseRequest$Mutation.send(com/clickhouse/client/ClickHouseRequest.java:292) java.lang.reflect.Method.invoke(java/lang/reflect/Method.java:498) ``` It seems that now the CSV format (without the header line) is used instead of CSVWithNames and it complains about the first file line with column headers. I was browsing the changes between patch9 and patch10 but couldn't identify so far which change could be causing this.
    94a5e7c2921047bfe907fbdf6aea2feaed3c2417
    fe4e199876c89df9d99bf08e0ef9f9c50d2814b8
    https://github.com/clickhouse/clickhouse-java/compare/94a5e7c2921047bfe907fbdf6aea2feaed3c2417...fe4e199876c89df9d99bf08e0ef9f9c50d2814b8
    diff --git a/clickhouse-cli-client/src/main/java/com/clickhouse/client/cli/ClickHouseCommandLine.java b/clickhouse-cli-client/src/main/java/com/clickhouse/client/cli/ClickHouseCommandLine.java index 5565b2aa..c4835963 100644 --- a/clickhouse-cli-client/src/main/java/com/clickhouse/client/cli/ClickHouseCommandLine.java +++ b/clickhouse-cli-client/src/main/java/com/clickhouse/client/cli/ClickHouseCommandLine.java @@ -124,7 +124,9 @@ public class ClickHouseCommandLine implements AutoCloseable { process = null; } - cache.put(command, value); + if (value) { // no negative cache + cache.put(command, value); + } } return Boolean.TRUE.equals(value); diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseRequest.java b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseRequest.java index 4a3caf04..62428bff 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseRequest.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseRequest.java @@ -196,7 +196,7 @@ public class ClickHouseRequest<SelfT extends ClickHouseRequest<SelfT>> implement final ClickHouseRequest<?> self = this; final ClickHouseFile wrappedFile = ClickHouseFile.of(file, compression, 0, null); - if (wrappedFile.hasFormat()) { + if (wrappedFile.hasFormat() && getFormat().defaultInputFormat() != wrappedFile.getFormat()) { format(wrappedFile.getFormat()); } this.input = changeProperty(PROP_DATA, this.input, ClickHouseDeferredValue diff --git a/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java b/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java index 0e2f42b8..c4a0f8f3 100644 --- a/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java +++ b/clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java @@ -1403,7 +1403,7 @@ public abstract class ClientIntegrationTest extends BaseIntegrationTest { } @Test(groups = { "integration" }) - public void testInsertWithCustomFormat() throws ClickHouseException { + public void testInsertWithCustomFormat1() throws ClickHouseException, IOException { ClickHouseNode server = getServer(); sendAndWait(server, "drop table if exists test_custom_input_format", "create table test_custom_input_format(i Int8, f String)engine=Memory"); @@ -1415,18 +1415,30 @@ public abstract class ClientIntegrationTest extends BaseIntegrationTest { } try (ClickHouseResponse response = request.write().format(ClickHouseFormat.CSVWithNames) .table("test_custom_input_format") - .data(o -> o.writeBytes("i,f\\n2,CSVWithNames".getBytes())).executeAndWait()) { + .data(o -> o.writeBytes("i,f\\n2,CSVWithNames\\n3,CSVWithNames".getBytes(StandardCharsets.US_ASCII))) + .executeAndWait()) { + // ignore + } + + Path temp = Files.createTempFile("data", ".csv"); + Assert.assertEquals(Files.size(temp), 0L); + Files.write(temp, "i,f\\n4,CSVWithNames\\n5,CSVWithNames\\n".getBytes(StandardCharsets.US_ASCII)); + Assert.assertTrue(Files.size(temp) > 0L); + try (ClickHouseResponse response = request.write().format(ClickHouseFormat.CSVWithNames) + .table("test_custom_input_format") + .data(temp.toFile().getAbsolutePath()).executeAndWait()) { // ignore } + try (ClickHouseResponse response = request.query("select * from test_custom_input_format order by i") .executeAndWait()) { int count = 0; for (ClickHouseRecord r : response.records()) { Assert.assertEquals(r.getValue(0).asInteger(), count + 1); - Assert.assertEquals(r.getValue(1).asString(), count == 0 ? "RowBinary" : "CSVWithNames"); + Assert.assertEquals(r.getValue(1).asString(), count < 1 ? "RowBinary" : "CSVWithNames"); count++; } - Assert.assertEquals(count, 2); + Assert.assertEquals(count, 5); } } } @@ -1481,9 +1493,10 @@ public abstract class ClientIntegrationTest extends BaseIntegrationTest { try (ClickHouseClient client = getClient()) { ClickHouseRequest<?> request = client.connect(server).format(ClickHouseFormat.RowBinary) .session(sessionId); - request.query("drop temporary table if exists my_temp_table").executeAndWait(); - request.query("create temporary table my_temp_table(a Int8)").executeAndWait(); - request.query("insert into my_temp_table values(2)").executeAndWait(); + execute(request, "drop temporary table if exists my_temp_table"); + execute(request, "create temporary table my_temp_table(a Int8)"); + execute(request, "insert into my_temp_table values(2)"); + try (ClickHouseResponse resp = request.write().table("my_temp_table") .data(new ByteArrayInputStream(new byte[] { 3 })).executeAndWait()) { // ignore
    ['clickhouse-cli-client/src/main/java/com/clickhouse/client/cli/ClickHouseCommandLine.java', 'clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseRequest.java', 'clickhouse-client/src/test/java/com/clickhouse/client/ClientIntegrationTest.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    2,642,550
    550,548
    78,098
    354
    295
    59
    6
    2
    2,073
    149
    528
    27
    2
    2
    1970-01-01T00:27:42
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,886
    clickhouse/clickhouse-java/981/977
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/977
    https://github.com/ClickHouse/clickhouse-java/pull/981
    https://github.com/ClickHouse/clickhouse-java/pull/981
    1
    fix
    Question about emptyBatchError
    Currently, I use Flink JDBC + CK Driver to write data to clickhouse in real time, and there is a high probability of encountering the following errors , So maybe we can support writing empty batch ? ``` Caused by: java.lang.RuntimeException: Writing records to JDBC failed. at org.apache.flink.connector.jdbc.internal.JdbcBatchingOutputFormat.checkFlushException(JdbcBatchingOutputFormat.java:154) at org.apache.flink.connector.jdbc.internal.JdbcBatchingOutputFormat.writeRecord(JdbcBatchingOutputFormat.java:160) at org.apache.flink.streaming.api.functions.sink.OutputFormatSinkFunction.invoke(OutputFormatSinkFunction.java:87) at org.apache.flink.streaming.api.functions.sink.SinkFunction.invoke(SinkFunction.java:49) at org.apache.flink.table.runtime.operators.sink.SinkOperator.processElement(SinkOperator.java:73) at org.apache.flink.streaming.runtime.tasks.ChainingOutput.pushToOperator(ChainingOutput.java:113) at org.apache.flink.streaming.runtime.tasks.ChainingOutput.collect(ChainingOutput.java:94) at org.apache.flink.streaming.runtime.tasks.ChainingOutput.collect(ChainingOutput.java:40) at org.apache.flink.streaming.runtime.tasks.SourceOperatorStreamTask$AsyncDataOutputToOutput.emitRecord(SourceOperatorStreamTask.java:163) at org.apache.flink.streaming.api.operators.source.SourceOutputWithWatermarks.collect(SourceOutputWithWatermarks.java:110) at org.apache.flink.streaming.api.operators.source.SourceOutputWithWatermarks.collect(SourceOutputWithWatermarks.java:101) at org.apache.flink.connector.file.src.impl.FileSourceRecordEmitter.emitRecord(FileSourceRecordEmitter.java:45) at org.apache.flink.connector.file.src.impl.FileSourceRecordEmitter.emitRecord(FileSourceRecordEmitter.java:35) at org.apache.flink.connector.base.source.reader.SourceReaderBase.pollNext(SourceReaderBase.java:128) at org.apache.flink.streaming.api.operators.SourceOperator.emitNext(SourceOperator.java:275) at org.apache.flink.streaming.runtime.io.StreamTaskSourceInput.emitNext(StreamTaskSourceInput.java:67) at org.apache.flink.streaming.runtime.io.StreamOneInputProcessor.processInput(StreamOneInputProcessor.java:65) at org.apache.flink.streaming.runtime.tasks.StreamTask.processInput(StreamTask.java:398) at org.apache.flink.streaming.runtime.tasks.mailbox.MailboxProcessor.runMailboxLoop(MailboxProcessor.java:191) at org.apache.flink.streaming.runtime.tasks.StreamTask.runMailboxLoop(StreamTask.java:619) at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:583) at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:758) at org.apache.flink.runtime.taskmanager.Task.run(Task.java:573) at java.lang.Thread.run(Thread.java:748) Caused by: java.io.IOException: java.sql.SQLException: Please call addBatch method at least once before batch execution at org.apache.flink.connector.jdbc.internal.JdbcBatchingOutputFormat.flush(JdbcBatchingOutputFormat.java:190) at org.apache.flink.connector.jdbc.internal.JdbcBatchingOutputFormat.lambda$open$0(JdbcBatchingOutputFormat.java:128) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ... 1 more Caused by: java.sql.SQLException: Please call addBatch method at least once before batch execution at com.clickhouse.jdbc.SqlExceptionUtils.clientError(SqlExceptionUtils.java:43) at com.clickhouse.jdbc.SqlExceptionUtils.emptyBatchError(SqlExceptionUtils.java:111) at com.clickhouse.jdbc.internal.InputBasedPreparedStatement.executeAny(InputBasedPreparedStatement.java:95) at com.clickhouse.jdbc.internal.AbstractPreparedStatement.executeLargeBatch(AbstractPreparedStatement.java:85) at com.clickhouse.jdbc.internal.ClickHouseStatementImpl.executeBatch(ClickHouseStatementImpl.java:568) at org.apache.flink.connector.jdbc.statement.FieldNamedPreparedStatementImpl.executeBatch(FieldNamedPreparedStatementImpl.java:65) at org.apache.flink.connector.jdbc.internal.executor.TableSimpleStatementExecutor.executeBatch(TableSimpleStatementExecutor.java:64) at org.apache.flink.connector.jdbc.internal.executor.TableBufferedStatementExecutor.executeBatch(TableBufferedStatementExecutor.java:64) at org.apache.flink.connector.jdbc.internal.JdbcBatchingOutputFormat.attemptFlush(JdbcBatchingOutputFormat.java:216) at org.apache.flink.connector.jdbc.internal.JdbcBatchingOutputFormat.flush(JdbcBatchingOutputFormat.java:184) ... 8 more ```
    e59bd468c1e1b049d84a0a8183758740735e8e9a
    844b2b8013b3af7f51e2fa66f8335b50f47cc157
    https://github.com/clickhouse/clickhouse-java/compare/e59bd468c1e1b049d84a0a8183758740735e8e9a...844b2b8013b3af7f51e2fa66f8335b50f47cc157
    diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/SqlExceptionUtils.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/SqlExceptionUtils.java index da5b824b..25b3ffe3 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/SqlExceptionUtils.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/SqlExceptionUtils.java @@ -107,10 +107,6 @@ public final class SqlExceptionUtils { return new BatchUpdateException("Unexpected error", SQL_STATE_SQL_ERROR, 0, updateCounts, cause); } - public static SQLException emptyBatchError() { - return clientError("Please call addBatch method at least once before batch execution"); - } - public static BatchUpdateException queryInBatchError(int[] updateCounts) { return new BatchUpdateException("Query is not allow in batch update", SQL_STATE_CLIENT_ERROR, updateCounts); } diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java index bae6de91..be75aa33 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java @@ -220,7 +220,7 @@ public class ClickHouseConnectionImpl extends JdbcWrapper implements ClickHouseC autoCommit = !jdbcConf.isJdbcCompliant() || jdbcConf.isAutoCommit(); ClickHouseNode node = connInfo.getServer(); - log.debug("Connecting to node: %s", node); + log.debug("Connecting to: %s", node); jvmTimeZone = TimeZone.getDefault(); diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java index 2b64d85c..94de8e5e 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java @@ -25,6 +25,7 @@ import com.clickhouse.client.ClickHouseResponseSummary; import com.clickhouse.client.ClickHouseSerializer; import com.clickhouse.client.ClickHouseUtils; import com.clickhouse.client.ClickHouseValue; +import com.clickhouse.client.ClickHouseValues; import com.clickhouse.client.config.ClickHouseClientOption; import com.clickhouse.client.config.ClickHouseConfigChangeListener; import com.clickhouse.client.config.ClickHouseOption; @@ -588,7 +589,7 @@ public class ClickHouseStatementImpl extends JdbcWrapper public long[] executeLargeBatch() throws SQLException { ensureOpen(); if (batchStmts.isEmpty()) { - throw SqlExceptionUtils.emptyBatchError(); + return ClickHouseValues.EMPTY_LONG_ARRAY; } boolean continueOnError = getConnection().getJdbcConfig().isContinueBatchOnError(); diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/InputBasedPreparedStatement.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/InputBasedPreparedStatement.java index 28c09b80..fd676de9 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/InputBasedPreparedStatement.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/InputBasedPreparedStatement.java @@ -94,7 +94,7 @@ public class InputBasedPreparedStatement extends AbstractPreparedStatement imple boolean continueOnError = false; if (asBatch) { if (counter < 1) { - throw SqlExceptionUtils.emptyBatchError(); + return ClickHouseValues.EMPTY_LONG_ARRAY; } continueOnError = getConnection().getJdbcConfig().isContinueBatchOnError(); } else { diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/SqlBasedPreparedStatement.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/SqlBasedPreparedStatement.java index 8958f95d..664f999e 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/SqlBasedPreparedStatement.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/SqlBasedPreparedStatement.java @@ -122,7 +122,7 @@ public class SqlBasedPreparedStatement extends AbstractPreparedStatement impleme boolean continueOnError = false; if (asBatch) { if (counter < 1) { - throw SqlExceptionUtils.emptyBatchError(); + return ClickHouseValues.EMPTY_LONG_ARRAY; } continueOnError = getConnection().getJdbcConfig().isContinueBatchOnError(); } else { diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/TableBasedPreparedStatement.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/TableBasedPreparedStatement.java index c389b589..e86c94e2 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/TableBasedPreparedStatement.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/TableBasedPreparedStatement.java @@ -19,6 +19,7 @@ import java.util.Set; import com.clickhouse.client.ClickHouseRequest; import com.clickhouse.client.ClickHouseResponse; import com.clickhouse.client.ClickHouseUtils; +import com.clickhouse.client.ClickHouseValues; import com.clickhouse.client.data.ClickHouseExternalTable; import com.clickhouse.client.logging.Logger; import com.clickhouse.client.logging.LoggerFactory; @@ -75,7 +76,7 @@ public class TableBasedPreparedStatement extends AbstractPreparedStatement imple boolean continueOnError = false; if (asBatch) { if (batch.isEmpty()) { - throw SqlExceptionUtils.emptyBatchError(); + return ClickHouseValues.EMPTY_LONG_ARRAY; } continueOnError = getConnection().getJdbcConfig().isContinueBatchOnError(); } else { diff --git a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java index 2a811b79..c131e052 100644 --- a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java +++ b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java @@ -778,15 +778,22 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { public void testBatchQuery() throws SQLException { try (ClickHouseConnection conn = newConnection(new Properties()); PreparedStatement stmt = conn.prepareStatement("select * from numbers(100) where number < ?")) { + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); Assert.assertThrows(SQLException.class, () -> stmt.setInt(0, 5)); Assert.assertThrows(SQLException.class, () -> stmt.setInt(2, 5)); Assert.assertThrows(SQLException.class, () -> stmt.addBatch()); stmt.setInt(1, 3); + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); stmt.addBatch(); stmt.setInt(1, 2); stmt.addBatch(); Assert.assertThrows(BatchUpdateException.class, () -> stmt.executeBatch()); + + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); } } diff --git a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java index 9a61a4bf..f0847918 100644 --- a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java +++ b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java @@ -136,6 +136,9 @@ public class ClickHouseStatementTest extends JdbcIntegrationTest { public void testMutation() throws SQLException { Properties props = new Properties(); try (ClickHouseConnection conn = newConnection(props); ClickHouseStatement stmt = conn.createStatement()) { + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); + Assert.assertFalse(stmt.execute("drop table if exists test_mutation;" + "create table test_mutation(a String, b UInt32) engine=MergeTree() order by tuple()"), "Should not return result set"); @@ -156,6 +159,9 @@ public class ClickHouseStatementTest extends JdbcIntegrationTest { stmt.addBatch("drop table non_existing_table"); stmt.addBatch("insert into test_mutation values('2',2)"); Assert.assertThrows(SQLException.class, () -> stmt.executeBatch()); + + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); } props.setProperty(JdbcConfig.PROP_CONTINUE_BATCH, "true"); @@ -269,7 +275,12 @@ public class ClickHouseStatementTest extends JdbcIntegrationTest { public void testExecuteBatch() throws SQLException { Properties props = new Properties(); try (Connection conn = newConnection(props); Statement stmt = conn.createStatement()) { - Assert.assertThrows(SQLException.class, () -> stmt.executeBatch()); + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); + stmt.addBatch("select 1"); + stmt.clearBatch(); + Assert.assertEquals(stmt.executeBatch(), new int[0]); + Assert.assertEquals(stmt.executeLargeBatch(), new long[0]); stmt.addBatch("select 1"); // mixed usage Assert.assertThrows(SQLException.class, () -> stmt.execute("select 2"));
    ['clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/SqlBasedPreparedStatement.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseConnectionImpl.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/SqlExceptionUtils.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/InputBasedPreparedStatement.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/TableBasedPreparedStatement.java', 'clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java']
    {'.java': 8}
    8
    8
    0
    0
    8
    2,480,744
    518,734
    73,778
    328
    815
    143
    16
    6
    4,890
    164
    976
    51
    0
    1
    1970-01-01T00:27:36
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,884
    clickhouse/clickhouse-java/1019/947
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/947
    https://github.com/ClickHouse/clickhouse-java/pull/1019
    https://github.com/ClickHouse/clickhouse-java/pull/1019
    1
    closes
    Incorrect update count (0.3.2-patch9)
    Hi! In `com.clickhouse.jdbc.internal.ClickHouseStatementImpl#updateResult`: ``` ... // FIXME apparently this is not always true if (currentUpdateCount <= 0L) { currentUpdateCount = 1L; } ... ``` Yes, this isn’t always true :) **Examples:** ``` Statement statement = connection.createStatement(); statement.execute(sql); int updateCount = statement.getUpdateCount(); ``` 1. `String sql = “CREATE TABLE new_table(x INT) engine = Memory;”` Expected `updateCount`: 0 Actual `updateCount`: 1 2. `String sql = "INSERT INTO new_table VALUES (1), (2), (3);"` Expected `updateCount`: 3 Actual `updateCount`: 1
    cdaf8f3f6cfd7c7227df00284a71f58b9399838a
    5f6d8b7ab6c0bd23db36ef807975b8f52c2f9abf
    https://github.com/clickhouse/clickhouse-java/compare/cdaf8f3f6cfd7c7227df00284a71f58b9399838a...5f6d8b7ab6c0bd23db36ef807975b8f52c2f9abf
    diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseResponseSummary.java b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseResponseSummary.java index c75c9b8a..33bc639b 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseResponseSummary.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseResponseSummary.java @@ -10,6 +10,8 @@ import java.util.concurrent.atomic.AtomicReference; public class ClickHouseResponseSummary implements Serializable { private static final long serialVersionUID = 6241261266635143197L; + static final String ERROR_CANNOT_UPDATE = "Sealed summary cannot be updated"; + public static final ClickHouseResponseSummary EMPTY = new ClickHouseResponseSummary(null, null, true); /** @@ -18,6 +20,8 @@ public class ClickHouseResponseSummary implements Serializable { public static final class Progress implements Serializable { private static final long serialVersionUID = -1447066780591278108L; + static final Progress EMPTY = new Progress(0L, 0L, 0L, 0L, 0L); + private final long read_rows; private final long read_bytes; private final long total_rows_to_read; @@ -61,6 +65,11 @@ public class ClickHouseResponseSummary implements Serializable { public long getWrittenBytes() { return written_bytes; } + + public boolean isEmpty() { + return read_rows == 0L && read_bytes == 0L && total_rows_to_read == 0L && written_rows == 0L + && written_bytes == 0L; + } } /** @@ -69,6 +78,8 @@ public class ClickHouseResponseSummary implements Serializable { public static class Statistics implements Serializable { private static final long serialVersionUID = -7744796632866829161L; + static final Statistics EMPTY = new Statistics(0L, 0L, 0L, false, 0L); + private final long rows; private final long blocks; private final long allocated_bytes; @@ -112,6 +123,10 @@ public class ClickHouseResponseSummary implements Serializable { public long getRowsBeforeLimit() { return rows_before_limit; } + + public boolean isEmpty() { + return rows == 0L && blocks == 0L && allocated_bytes == 0L && !applied_limit && rows_before_limit == 0L; + } } private final AtomicReference<Progress> progress; @@ -139,9 +154,15 @@ public class ClickHouseResponseSummary implements Serializable { * @param sealed whether the summary is sealed */ protected ClickHouseResponseSummary(Progress progress, Statistics stats, boolean sealed) { - this.progress = new AtomicReference<>(progress != null ? progress : new Progress(0L, 0L, 0L, 0L, 0L)); - this.stats = new AtomicReference<>(stats != null ? stats : new Statistics(0L, 0L, 0L, false, 0L)); - this.updates = new AtomicInteger(1); + if (progress == null) { + progress = Progress.EMPTY; + } + if (stats == null) { + stats = Statistics.EMPTY; + } + this.progress = new AtomicReference<>(progress); + this.stats = new AtomicReference<>(stats); + this.updates = new AtomicInteger(progress.isEmpty() && stats.isEmpty() ? 0 : 1); this.sealed = sealed; } @@ -159,6 +180,10 @@ public class ClickHouseResponseSummary implements Serializable { * @return increased update counter */ public int update() { + if (sealed) { + throw new IllegalStateException(ERROR_CANNOT_UPDATE); + } + return this.updates.incrementAndGet(); } @@ -169,7 +194,7 @@ public class ClickHouseResponseSummary implements Serializable { */ public void update(Progress progress) { if (sealed) { - throw new IllegalStateException("Sealed summary cannot be updated"); + throw new IllegalStateException(ERROR_CANNOT_UPDATE); } if (progress != null) { @@ -179,7 +204,7 @@ public class ClickHouseResponseSummary implements Serializable { public void update(Statistics stats) { if (sealed) { - throw new IllegalStateException("Sealed summary cannot be updated"); + throw new IllegalStateException(ERROR_CANNOT_UPDATE); } if (stats != null) { @@ -228,4 +253,8 @@ public class ClickHouseResponseSummary implements Serializable { public int getUpdateCount() { return updates.get(); } + + public boolean isEmpty() { + return progress.get().isEmpty() && stats.get().isEmpty(); + } } diff --git a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java index 82e20603..d1b47522 100644 --- a/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java +++ b/clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java @@ -95,8 +95,13 @@ public class ClickHouseStatementImpl extends JdbcWrapper } catch (Exception e) { throw SqlExceptionUtils.handle(e); } finally { - if (i + 1 < len && response != null) { + if (response == null) { + // something went wrong + } else if (i + 1 < len) { response.close(); + response = null; + } else { + updateResult(stmt, response); } } } @@ -166,18 +171,17 @@ public class ClickHouseStatementImpl extends JdbcWrapper protected int executeInsert(String sql, InputStream input) throws SQLException { boolean autoTx = connection.getAutoCommit() && connection.isTransactionSupported(); - ClickHouseResponseSummary summary = null; Mutation req = request.write().query(sql, queryId = connection.newQueryId()).data(input); try (ClickHouseResponse resp = autoTx ? req.executeWithinTransaction(connection.isImplicitTransactionSupported()) : req.transaction(connection.getTransaction()).sendAndWait(); ResultSet rs = updateResult(new ClickHouseSqlStatement(sql, StatementType.INSERT), resp)) { - summary = resp.getSummary(); + // ignore } catch (Exception e) { throw SqlExceptionUtils.handle(e); } - return summary != null && summary.getWrittenRows() > 0L ? (int) summary.getWrittenRows() : 1; + return (int) currentUpdateCount; } protected ClickHouseSqlStatement getLastStatement() { @@ -212,23 +216,17 @@ public class ClickHouseStatementImpl extends JdbcWrapper } protected ResultSet updateResult(ClickHouseSqlStatement stmt, ClickHouseResponse response) throws SQLException { - ResultSet rs = null; if (stmt.isQuery() || !response.getColumns().isEmpty()) { currentUpdateCount = -1L; currentResult = new ClickHouseResultSet(stmt.getDatabaseOrDefault(getConnection().getCurrentDatabase()), stmt.getTable(), this, response); - rs = currentResult; } else { - currentUpdateCount = response.getSummary().getWrittenRows(); - // FIXME apparently this is not always true - if (currentUpdateCount <= 0L) { - currentUpdateCount = 1L; - } - currentResult = null; response.close(); + currentUpdateCount = stmt.isDDL() ? 0L + : (response.getSummary().isEmpty() ? 1L : response.getSummary().getWrittenRows()); + currentResult = null; } - - return rs == null ? newEmptyResultSet() : rs; + return currentResult; } protected ClickHouseStatementImpl(ClickHouseConnectionImpl connection, ClickHouseRequest<?> request, @@ -303,18 +301,8 @@ public class ClickHouseStatementImpl extends JdbcWrapper } parseSqlStatements(sql); - - ClickHouseResponse response = getLastResponse(null, null, null); - - try { - return updateResult(getLastStatement(), response); - } catch (Exception e) { - if (response != null) { - response.close(); - } - - throw SqlExceptionUtils.handle(e); - } + getLastResponse(null, null, null); + return currentResult != null ? currentResult : newEmptyResultSet(); } @Override @@ -326,14 +314,11 @@ public class ClickHouseStatementImpl extends JdbcWrapper parseSqlStatements(sql); - ClickHouseResponseSummary summary = null; try (ClickHouseResponse response = getLastResponse(null, null, null)) { - summary = response.getSummary(); + return currentUpdateCount; } catch (Exception e) { throw SqlExceptionUtils.handle(e); } - - return summary != null ? summary.getWrittenRows() : 1L; } @Override diff --git a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java index c3ec0334..f8b54c32 100644 --- a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java +++ b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java @@ -845,6 +845,7 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { @Test(dataProvider = "statementAndParams", groups = "integration") public void testExecuteWithOrWithoutParameters(String tableSuffix, String query, Class<?> clazz, boolean hasResultSet, String[] params, boolean checkTable) throws SQLException { + int expectedRowCount = "ddl".equals(tableSuffix) ? 0 : 1; String tableName = "test_execute_ps_" + tableSuffix; query = query.replace("$table", tableName); Properties props = new Properties(); @@ -932,7 +933,7 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { if (hasResultSet) { Assert.assertThrows(SQLException.class, () -> ps.executeLargeBatch()); } else { - Assert.assertEquals(ps.executeLargeBatch(), new long[] { 1L }); + Assert.assertEquals(ps.executeLargeBatch(), new long[] { expectedRowCount }); } if (checkTable) checkTable(stmt, "select * from " + tableName, params); @@ -950,7 +951,7 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { if (hasResultSet) { Assert.assertThrows(SQLException.class, () -> ps.executeBatch()); } else { - Assert.assertEquals(ps.executeBatch(), new int[] { 1 }); + Assert.assertEquals(ps.executeBatch(), new int[] { expectedRowCount }); } if (checkTable) checkTable(stmt, "select * from " + tableName, params); @@ -973,7 +974,7 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { if (hasResultSet) { Assert.assertEquals(ps.executeLargeBatch(), new long[] { Statement.EXECUTE_FAILED }); } else { - Assert.assertEquals(ps.executeLargeBatch(), new long[] { 1L }); + Assert.assertEquals(ps.executeLargeBatch(), new long[] { expectedRowCount }); } if (checkTable) checkTable(stmt, "select * from " + tableName, params); @@ -988,7 +989,7 @@ public class ClickHousePreparedStatementTest extends JdbcIntegrationTest { if (hasResultSet) { Assert.assertEquals(ps.executeBatch(), new int[] { Statement.EXECUTE_FAILED }); } else { - Assert.assertEquals(ps.executeBatch(), new int[] { 1 }); + Assert.assertEquals(ps.executeBatch(), new int[] { expectedRowCount }); } if (checkTable) checkTable(stmt, "select * from " + tableName, params); diff --git a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java index 4861c29e..681bdeca 100644 --- a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java +++ b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java @@ -173,7 +173,7 @@ public class ClickHouseStatementTest extends JdbcIntegrationTest { // [update] tbl a [set] a.b = 1 where a.b != 1[ settings mutation_async=0] // alter table tbl a update a.b = 1 where a.b != 1 conn.setClientInfo("ApplicationName", "333"); - Assert.assertEquals(conn.createStatement().executeUpdate("update test_mutation set b = 22 where b = 1"), 0); + Assert.assertEquals(conn.createStatement().executeUpdate("update test_mutation set b = 22 where b = 1"), 1); Assert.assertThrows(SQLException.class, () -> stmt.executeUpdate("update non_existing_table set value=1 where key=1")); @@ -407,7 +407,7 @@ public class ClickHouseStatementTest extends JdbcIntegrationTest { rs = stmt.executeQuery("drop table if exists non_existing_table"); Assert.assertNotNull(rs, "Should never be null"); Assert.assertNull(stmt.getResultSet(), "Should be null"); - Assert.assertEquals(stmt.getUpdateCount(), 1); + Assert.assertEquals(stmt.getUpdateCount(), 0); Assert.assertFalse(rs.next(), "Should has no row"); } } @@ -519,7 +519,7 @@ public class ClickHouseStatementTest extends JdbcIntegrationTest { stmt.addBatch("drop table if exists non_existing_table2"); stmt.addBatch("drop table if exists non_existing_table3"); int[] results = stmt.executeBatch(); - Assert.assertEquals(results, new int[] { 1, 1, 1 }); + Assert.assertEquals(results, new int[] { 0, 0, 0 }); } }
    ['clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseResponseSummary.java', 'clickhouse-jdbc/src/main/java/com/clickhouse/jdbc/internal/ClickHouseStatementImpl.java', 'clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHousePreparedStatementTest.java', 'clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseStatementTest.java']
    {'.java': 4}
    4
    4
    0
    0
    4
    2,556,449
    533,465
    75,659
    332
    3,580
    753
    84
    2
    641
    76
    165
    30
    0
    2
    1970-01-01T00:27:39
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    9,885
    clickhouse/clickhouse-java/982/979
    clickhouse
    clickhouse-java
    https://github.com/ClickHouse/clickhouse-java/issues/979
    https://github.com/ClickHouse/clickhouse-java/pull/982
    https://github.com/ClickHouse/clickhouse-java/pull/982
    1
    fix
    ResultSet getObject with class return null values filled as it was not null
    When selecting values from table with getObject(index, Class) simple types (like float/int/boolean) return 0/false as result (when null is expected). ``` CREATE TABLE db.tbl ( id int not null, double_col double, float_col float, varchar_col varchar(36), boolean_col boolean, int_col int, bigint_col bigint, char_col char(10), int32_col int32 primary key (id) ) distributed by (id) ``` `Expected: [1, null, null, null, null, null, null, null, null]` `Actual: [1, 0.0, 0.0, null, false, 0, 0, null, 0]` getObject(int columnIndex) returns null as expected. Is that expected behaivor? (it breaks Vertx jdbc client as it always uses getObject with expected class)
    2f2f2eae501e59453aa0b8a77581cbe99f3949d3
    70612d802499ed8d64a989932beb21853c62e73d
    https://github.com/clickhouse/clickhouse-java/compare/2f2f2eae501e59453aa0b8a77581cbe99f3949d3...70612d802499ed8d64a989932beb21853c62e73d
    diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseValue.java index e13bceb1..b55fc5df 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseValue.java @@ -88,6 +88,16 @@ public interface ClickHouseValue extends Serializable { return v != v; } + /** + * Checks whether the value is nullable. This always returns {@code false} for + * nested value type. + * + * @return true if the value is nullable; false otherwise + */ + default boolean isNullable() { + return true; + } + /** * Checks if the value is null, or empty for non-null types like Array, Tuple * and Map. @@ -485,7 +495,7 @@ public interface ClickHouseValue extends Serializable { * @return a typed object representing the value, could be null */ default <T, E extends Enum<E>> T asObject(Class<T> clazz) { - if (clazz == null) { + if (clazz == null || (isNullable() && isNullOrEmpty())) { return null; } else if (clazz == boolean.class || clazz == Boolean.class) { return clazz.cast(asBoolean()); @@ -531,6 +541,8 @@ public interface ClickHouseValue extends Serializable { return clazz.cast(asArray()); } else if (List.class.isAssignableFrom(clazz)) { return clazz.cast(asTuple()); + } else if (Map.class.isAssignableFrom(clazz)) { + return clazz.cast(asMap()); } else if (Enum.class.isAssignableFrom(clazz)) { return clazz.cast(asEnum((Class<E>) clazz)); } else { diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseArrayValue.java index 9bbdaec6..08612456 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseArrayValue.java @@ -128,6 +128,11 @@ public class ClickHouseArrayValue<T> extends ClickHouseObjectValue<T[]> { return new ClickHouseArrayValue<>(newValue); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseBitmapValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseBitmapValue.java index 5aa18326..31c16d6e 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseBitmapValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseBitmapValue.java @@ -78,6 +78,11 @@ public class ClickHouseBitmapValue extends ClickHouseObjectValue<ClickHouseBitma return new ClickHouseBitmapValue(getValue()); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().isEmpty(); diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoMultiPolygonValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoMultiPolygonValue.java index 80627407..5ec4c456 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoMultiPolygonValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoMultiPolygonValue.java @@ -149,6 +149,11 @@ public class ClickHouseGeoMultiPolygonValue extends ClickHouseObjectValue<double return convert(getValue(), length); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPointValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPointValue.java index eec0ea3b..04bbe8bf 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPointValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPointValue.java @@ -95,6 +95,11 @@ public class ClickHouseGeoPointValue extends ClickHouseObjectValue<double[]> { return convert(getValue(), length); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return false; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPolygonValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPolygonValue.java index e59793da..899f6d4e 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPolygonValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPolygonValue.java @@ -144,6 +144,11 @@ public class ClickHouseGeoPolygonValue extends ClickHouseObjectValue<double[][][ return convert(getValue(), length); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoRingValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoRingValue.java index 5483b5ee..074f78b1 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoRingValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoRingValue.java @@ -140,6 +140,11 @@ public class ClickHouseGeoRingValue extends ClickHouseObjectValue<double[][]> { return convert(getValue(), length); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { double[][] value = getValue(); diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseNestedValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseNestedValue.java index 12d95888..5b57517e 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseNestedValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseNestedValue.java @@ -187,6 +187,11 @@ public class ClickHouseNestedValue extends ClickHouseObjectValue<Object[][]> { return str; } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { Object[][] value = getValue(); diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseTupleValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseTupleValue.java index def2aa66..ebf2722c 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseTupleValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseTupleValue.java @@ -152,6 +152,11 @@ public class ClickHouseTupleValue extends ClickHouseObjectValue<List<Object>> { return getValue(); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().isEmpty(); diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseByteArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseByteArrayValue.java index 22c851f5..c2e09d2c 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseByteArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseByteArrayValue.java @@ -133,6 +133,11 @@ public class ClickHouseByteArrayValue extends ClickHouseObjectValue<byte[]> { return new ClickHouseByteArrayValue(Arrays.copyOf(value, value.length)); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseDoubleArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseDoubleArrayValue.java index 47fd7853..1fde864a 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseDoubleArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseDoubleArrayValue.java @@ -133,6 +133,11 @@ public class ClickHouseDoubleArrayValue extends ClickHouseObjectValue<double[]> return new ClickHouseDoubleArrayValue(Arrays.copyOf(value, value.length)); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseFloatArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseFloatArrayValue.java index 5444253c..a9c0fd66 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseFloatArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseFloatArrayValue.java @@ -133,6 +133,11 @@ public class ClickHouseFloatArrayValue extends ClickHouseObjectValue<float[]> { return new ClickHouseFloatArrayValue(Arrays.copyOf(value, value.length)); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseIntArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseIntArrayValue.java index e91536e5..b2b28432 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseIntArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseIntArrayValue.java @@ -133,6 +133,11 @@ public class ClickHouseIntArrayValue extends ClickHouseObjectValue<int[]> { return new ClickHouseIntArrayValue(Arrays.copyOf(value, value.length)); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseLongArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseLongArrayValue.java index dd4392ff..e39fd682 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseLongArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseLongArrayValue.java @@ -133,6 +133,11 @@ public class ClickHouseLongArrayValue extends ClickHouseObjectValue<long[]> { return new ClickHouseLongArrayValue(Arrays.copyOf(value, value.length)); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseShortArrayValue.java b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseShortArrayValue.java index 2ac35b15..b7db7083 100644 --- a/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseShortArrayValue.java +++ b/clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseShortArrayValue.java @@ -133,6 +133,11 @@ public class ClickHouseShortArrayValue extends ClickHouseObjectValue<short[]> { return new ClickHouseShortArrayValue(Arrays.copyOf(value, value.length)); } + @Override + public boolean isNullable() { + return false; + } + @Override public boolean isNullOrEmpty() { return getValue().length == 0; diff --git a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseResultSetTest.java b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseResultSetTest.java index 56b774a0..ef975e78 100644 --- a/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseResultSetTest.java +++ b/clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseResultSetTest.java @@ -1,6 +1,7 @@ package com.clickhouse.jdbc; import java.math.BigDecimal; +import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -90,28 +91,28 @@ public class ClickHouseResultSetTest extends JdbcIntegrationTest { @DataProvider(name = "nullableColumns") private Object[][] getNullableColumns() { return new Object[][] { - new Object[] { "Bool", "false" }, - new Object[] { "Date", "1970-01-01" }, - new Object[] { "Date32", "1970-01-01" }, - new Object[] { "DateTime32('UTC')", "1970-01-01 00:00:00" }, - new Object[] { "DateTime64(3, 'UTC')", "1970-01-01 00:00:00" }, - new Object[] { "Decimal(10,4)", "0" }, - new Object[] { "Enum8('x'=0,'y'=1)", "x" }, - new Object[] { "Enum16('xx'=1,'yy'=0)", "yy" }, - new Object[] { "Float32", "0.0" }, - new Object[] { "Float64", "0.0" }, - new Object[] { "Int8", "0" }, - new Object[] { "UInt8", "0" }, - new Object[] { "Int16", "0" }, - new Object[] { "UInt16", "0" }, - new Object[] { "Int32", "0" }, - new Object[] { "UInt32", "0" }, - new Object[] { "Int64", "0" }, - new Object[] { "UInt64", "0" }, - new Object[] { "Int128", "0" }, - new Object[] { "UInt128", "0" }, - new Object[] { "Int256", "0" }, - new Object[] { "UInt256", "0" }, + new Object[] { "Bool", "false", Boolean.class }, + new Object[] { "Date", "1970-01-01", LocalDate.class }, + new Object[] { "Date32", "1970-01-01", LocalDate.class }, + new Object[] { "DateTime32('UTC')", "1970-01-01 00:00:00", LocalDateTime.class }, + new Object[] { "DateTime64(3, 'UTC')", "1970-01-01 00:00:00", OffsetDateTime.class }, + new Object[] { "Decimal(10,4)", "0", BigDecimal.class }, + new Object[] { "Enum8('x'=0,'y'=1)", "x", Integer.class }, + new Object[] { "Enum16('xx'=1,'yy'=0)", "yy", String.class }, + new Object[] { "Float32", "0.0", Float.class }, + new Object[] { "Float64", "0.0", Double.class }, + new Object[] { "Int8", "0", Byte.class }, + new Object[] { "UInt8", "0", Short.class }, + new Object[] { "Int16", "0", Short.class }, + new Object[] { "UInt16", "0", Integer.class }, + new Object[] { "Int32", "0", Integer.class }, + new Object[] { "UInt32", "0", Long.class }, + new Object[] { "Int64", "0", Long.class }, + new Object[] { "UInt64", "0", BigInteger.class }, + new Object[] { "Int128", "0", BigInteger.class }, + new Object[] { "UInt128", "0", BigInteger.class }, + new Object[] { "Int256", "0", BigInteger.class }, + new Object[] { "UInt256", "0", BigInteger.class }, }; } @@ -296,7 +297,7 @@ public class ClickHouseResultSetTest extends JdbcIntegrationTest { } @Test(dataProvider = "nullableColumns", groups = "integration") - public void testNullValue(String columnType, String defaultValue) throws Exception { + public void testNullValue(String columnType, String defaultValue, Class<?> clazz) throws Exception { Properties props = new Properties(); props.setProperty(JdbcConfig.PROP_NULL_AS_DEFAULT, "2"); String tableName = "test_query_null_value_" + columnType.split("\\\\(")[0].trim().toLowerCase(); @@ -312,6 +313,8 @@ public class ClickHouseResultSetTest extends JdbcIntegrationTest { Assert.assertTrue(rs.next(), "Should have at least one row"); Assert.assertEquals(rs.getInt(1), 1); Assert.assertEquals(rs.getString(2), defaultValue); + Assert.assertNotNull(rs.getObject(2)); + Assert.assertNotNull(rs.getObject(2, clazz)); Assert.assertFalse(rs.wasNull(), "Should not be null"); Assert.assertFalse(rs.next(), "Should have only one row"); } @@ -321,6 +324,7 @@ public class ClickHouseResultSetTest extends JdbcIntegrationTest { Assert.assertTrue(rs.next(), "Should have at least one row"); Assert.assertEquals(rs.getInt(1), 1); Assert.assertEquals(rs.getString(2), null); + Assert.assertEquals(rs.getObject(2, clazz), null); Assert.assertTrue(rs.wasNull(), "Should be null"); Assert.assertFalse(rs.next(), "Should have only one row"); } @@ -330,6 +334,7 @@ public class ClickHouseResultSetTest extends JdbcIntegrationTest { Assert.assertTrue(rs.next(), "Should have at least one row"); Assert.assertEquals(rs.getInt(1), 1); Assert.assertEquals(rs.getString(2), null); + Assert.assertEquals(rs.getObject(2, clazz), null); Assert.assertTrue(rs.wasNull(), "Should be null"); Assert.assertFalse(rs.next(), "Should have only one row"); }
    ['clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseBitmapValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseNestedValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseLongArrayValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseDoubleArrayValue.java', 'clickhouse-jdbc/src/test/java/com/clickhouse/jdbc/ClickHouseResultSetTest.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoMultiPolygonValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoRingValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseArrayValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPointValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseGeoPolygonValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseByteArrayValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseIntArrayValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseFloatArrayValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/ClickHouseTupleValue.java', 'clickhouse-client/src/main/java/com/clickhouse/client/data/array/ClickHouseShortArrayValue.java']
    {'.java': 16}
    16
    16
    0
    0
    16
    2,480,675
    518,723
    73,776
    328
    1,595
    339
    84
    15
    722
    96
    197
    24
    0
    1
    1970-01-01T00:27:36
    1,272
    Java
    {'Java': 3989428, 'Shell': 397}
    Apache License 2.0
    8,930
    gradle/gradle-profiler/457/456
    gradle
    gradle-profiler
    https://github.com/gradle/gradle-profiler/issues/456
    https://github.com/gradle/gradle-profiler/pull/457
    https://github.com/gradle/gradle-profiler/issues/456#issuecomment-1289037751
    2
    fixes
    Using `--profile yourkit` in Windows build failed with java.lang.NullPointerException
    ### Environment gradle-profiler version: 0.19.0 YourKit version: 2022.9 **Crash log** ``` java.lang.NullPointerException at org.gradle.profiler.yourkit.YourKitJvmArgsCalculator.calculateJvmArgs(YourKitJvmArgsCalculator.java:33) at org.gradle.profiler.GradleScenarioInvoker.run(GradleScenarioInvoker.java:87) at org.gradle.profiler.GradleScenarioInvoker.run(GradleScenarioInvoker.java:22) at org.gradle.profiler.Main.invoke(Main.java:126) at org.gradle.profiler.Main.run(Main.java:86) at org.gradle.profiler.Main.main(Main.java:25) ``` ### Root cause In YourKit HOME dir yjpagent.dll exist in `bin/windows-x86-64/` but in gradle-profiler, the path still was `bin/win64/` https://github.com/gradle/gradle-profiler/blob/master/src/main/java/org/gradle/profiler/yourkit/YourKit.java#L41 So the `findJniLib()` result will be null ### Temporary solution copy `bin/windows-x86-64` and rename to `bin/win64`
    5f376813f3042714121b41985e52a57dc9665e54
    bb4a3b0b8412c80bb2ed7dea4acb4654e31d28d1
    https://github.com/gradle/gradle-profiler/compare/5f376813f3042714121b41985e52a57dc9665e54...bb4a3b0b8412c80bb2ed7dea4acb4654e31d28d1
    diff --git a/src/main/java/org/gradle/profiler/yourkit/YourKit.java b/src/main/java/org/gradle/profiler/yourkit/YourKit.java index d1f5cf55..e6cb56d6 100644 --- a/src/main/java/org/gradle/profiler/yourkit/YourKit.java +++ b/src/main/java/org/gradle/profiler/yourkit/YourKit.java @@ -38,7 +38,7 @@ public static File findControllerJar() { public static File findJniLib() { File yourKitHome = findYourKitHome(); if (OperatingSystem.isWindows()) { - return tryLocations(yourKitHome, "bin/win64/yjpagent.dll"); + return tryLocations(yourKitHome, "bin/win64/yjpagent.dll", "bin/windows-x86-64/yjpagent.dll"); } String macLibLocationPrefix = "Contents/Resources/bin/mac/libyjpagent."; return tryLocations(yourKitHome, macLibLocationPrefix + "jnilib", macLibLocationPrefix + "dylib", "bin/linux-x86-64/libyjpagent.so");
    ['src/main/java/org/gradle/profiler/yourkit/YourKit.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    563,537
    111,022
    14,982
    237
    180
    48
    2
    1
    977
    61
    260
    26
    1
    1
    1970-01-01T00:27:46
    1,265
    Java
    {'Java': 569946, 'Groovy': 279034, 'Perl': 35996, 'Kotlin': 28566, 'HTML': 16578, 'JavaScript': 9668, 'XSLT': 1566}
    Apache License 2.0
    1,086
    google/conscrypt/920/902
    google
    conscrypt
    https://github.com/google/conscrypt/issues/902
    https://github.com/google/conscrypt/pull/920
    https://github.com/google/conscrypt/pull/920
    1
    fixes
    isAssignableFrom checks in KeyFactorySpi.engineGetKeySpec appear to be backwards
    I would like to report a minor bug in Conscrypt's KeyFactorySpi.engineGetKeySpec implementations. This bug appears to impact both [OpenSSLRSAKeyFactory](https://github.com/google/conscrypt/blob/6e29d195147e73f824ae3a7576f791eb4bb165df/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java#L77-L181) and [OpenSSLECKeyFactory](https://github.com/google/conscrypt/blob/6e29d195147e73f824ae3a7576f791eb4bb165df/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java#L76-L145). Specifically, the "isAssignableFrom" checks in "engineGetKeySpec" appear to be backwards. The intent of these checks is to ensure that the KeySpec implementation understood by the KeyFactorySpi implements or extends the requested KeySpec and thus can be safely cast to it. Instead, it incorrectly checks to see if the requested KeySpec implements or extends the concrete implementation. The vast majority of the time the requested KeySpec is equal to the concrete implementation so the inversion does not matter. There are two user/developer facing implications of these bugs. * If a caller requests a subclass of the known KeySpec implementation, then the OpenJDK engineGetKeySpec implementations will incorrectly throw a "ClassCastException" rather than an "InvalidKeySpec". * If a caller requests a RSAPrivateKeySpec for an RSAPrivateCrtKey, then sun.security.rsa.RSAKeyFactory.engineGetKeySpec will return an instance of RSAPrivateKeySpec rather than opportunistically returning the subclass RSAPrivateCrtKeySpec (as appears to be the intention). This means that the CRT parameters will be lost and any keys created from the returned KeySpec will lack the CRT parameters and be less efficient. Both of these behaviors can be seen for the RSAKeyFactory in the following sample code: ``` import org.conscrypt.OpenSSLProvider; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.spec.*; public class BadSpecChecks { public static void main(String[] args) throws Exception { Security.insertProviderAt(new OpenSSLProvider(), 1); KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA"); kg.initialize(2048); KeyPair pair = kg.generateKeyPair(); KeyFactory factory = KeyFactory.getInstance("RSA"); System.out.println("Since RSAPrivateCrtKeySpec inherits from RSAPrivateKeySpec, we'd expect this next line to return an instance of RSAPrivateKeySpec (because the private key has CRT parts). It doesn't."); KeySpec spec = factory.getKeySpec(pair.getPrivate(), RSAPrivateKeySpec.class); System.out.println(spec.getClass()); System.out.println("This next line should give an InvalidKeySpec exception"); try { FakeX509Spec oddSpec = factory.getKeySpec(pair.getPublic(), FakeX509Spec.class); System.out.println("This line shouldn't be reached."); } catch (final InvalidKeySpecException ex) { System.out.println("Caught expected exception"); ex.printStackTrace(System.out); } } public static class FakeX509Spec extends X509EncodedKeySpec { public FakeX509Spec(byte[] encodedKey) { super(encodedKey); } public FakeX509Spec(byte[] encodedKey, String algorithm) { super(encodedKey, algorithm); } } } ``` Please note that this bug is equivalent to [JDK-8254717](https://bugs.openjdk.java.net/browse/JDK-8254717)
    ae487934dcc1ec3d3c37a6084b07632f7ef76d38
    46ed27fda6350590b148a77037e2000e6f6ba1f7
    https://github.com/google/conscrypt/compare/ae487934dcc1ec3d3c37a6084b07632f7ef76d38...46ed27fda6350590b148a77037e2000e6f6ba1f7
    diff --git a/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java index 596e8711..b10e3391 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java @@ -87,12 +87,12 @@ public final class OpenSSLECKeyFactory extends KeyFactorySpi { throw new InvalidKeySpecException("Key must be an EC key"); } - if (key instanceof ECPublicKey && ECPublicKeySpec.class.isAssignableFrom(keySpec)) { + if (key instanceof ECPublicKey && keySpec.isAssignableFrom(ECPublicKeySpec.class)) { ECPublicKey ecKey = (ECPublicKey) key; @SuppressWarnings("unchecked") T result = (T) new ECPublicKeySpec(ecKey.getW(), ecKey.getParams()); return result; - } else if (key instanceof PublicKey && ECPublicKeySpec.class.isAssignableFrom(keySpec)) { + } else if (key instanceof PublicKey && keySpec.isAssignableFrom(ECPublicKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"X.509".equals(key.getFormat()) || encoded == null) { throw new InvalidKeySpecException("Not a valid X.509 encoding"); @@ -102,12 +102,12 @@ public final class OpenSSLECKeyFactory extends KeyFactorySpi { T result = (T) new ECPublicKeySpec(ecKey.getW(), ecKey.getParams()); return result; } else if (key instanceof ECPrivateKey - && ECPrivateKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(ECPrivateKeySpec.class)) { ECPrivateKey ecKey = (ECPrivateKey) key; @SuppressWarnings("unchecked") T result = (T) new ECPrivateKeySpec(ecKey.getS(), ecKey.getParams()); return result; - } else if (key instanceof PrivateKey && ECPrivateKeySpec.class.isAssignableFrom(keySpec)) { + } else if (key instanceof PrivateKey && keySpec.isAssignableFrom(ECPrivateKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat()) || encoded == null) { throw new InvalidKeySpecException("Not a valid PKCS#8 encoding"); @@ -118,7 +118,7 @@ public final class OpenSSLECKeyFactory extends KeyFactorySpi { T result = (T) new ECPrivateKeySpec(ecKey.getS(), ecKey.getParams()); return result; } else if (key instanceof PrivateKey - && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be PKCS#8; was " @@ -128,7 +128,7 @@ public final class OpenSSLECKeyFactory extends KeyFactorySpi { } @SuppressWarnings("unchecked") T result = (T) new PKCS8EncodedKeySpec(encoded); return result; - } else if (key instanceof PublicKey && X509EncodedKeySpec.class.isAssignableFrom(keySpec)) { + } else if (key instanceof PublicKey && keySpec.isAssignableFrom(X509EncodedKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"X.509".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be X.509; was " diff --git a/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java index ce08d50e..073821e0 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java @@ -88,12 +88,12 @@ public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { throw new InvalidKeySpecException("Key must be a RSA key"); } - if (key instanceof RSAPublicKey && RSAPublicKeySpec.class.isAssignableFrom(keySpec)) { + if (key instanceof RSAPublicKey && keySpec.isAssignableFrom(RSAPublicKeySpec.class)) { RSAPublicKey rsaKey = (RSAPublicKey) key; @SuppressWarnings("unchecked") T result = (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()); return result; - } else if (key instanceof PublicKey && RSAPublicKeySpec.class.isAssignableFrom(keySpec)) { + } else if (key instanceof PublicKey && keySpec.isAssignableFrom(RSAPublicKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"X.509".equals(key.getFormat()) || encoded == null) { throw new InvalidKeySpecException("Not a valid X.509 encoding"); @@ -104,7 +104,7 @@ public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { T result = (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()); return result; } else if (key instanceof RSAPrivateCrtKey - && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(RSAPrivateCrtKeySpec.class)) { RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; @SuppressWarnings("unchecked") T result = (T) new RSAPrivateCrtKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent(), @@ -113,19 +113,19 @@ public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { rsaKey.getCrtCoefficient()); return result; } else if (key instanceof RSAPrivateCrtKey - && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(RSAPrivateKeySpec.class)) { RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; @SuppressWarnings("unchecked") T result = (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()); return result; } else if (key instanceof RSAPrivateKey - && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(RSAPrivateKeySpec.class)) { RSAPrivateKey rsaKey = (RSAPrivateKey) key; @SuppressWarnings("unchecked") T result = (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()); return result; } else if (key instanceof PrivateKey - && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(RSAPrivateCrtKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat()) || encoded == null) { throw new InvalidKeySpecException("Not a valid PKCS#8 encoding"); @@ -143,7 +143,7 @@ public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { } else { throw new InvalidKeySpecException("Encoded key is not an RSAPrivateCrtKey"); } - } else if (key instanceof PrivateKey && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { + } else if (key instanceof PrivateKey && keySpec.isAssignableFrom(RSAPrivateKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat()) || encoded == null) { throw new InvalidKeySpecException("Not a valid PKCS#8 encoding"); @@ -154,7 +154,7 @@ public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { T result = (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()); return result; } else if (key instanceof PrivateKey - && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { + && keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be PKCS#8; was " @@ -164,7 +164,7 @@ public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { } @SuppressWarnings("unchecked") T result = (T) new PKCS8EncodedKeySpec(encoded); return result; - } else if (key instanceof PublicKey && X509EncodedKeySpec.class.isAssignableFrom(keySpec)) { + } else if (key instanceof PublicKey && keySpec.isAssignableFrom(X509EncodedKeySpec.class)) { final byte[] encoded = key.getEncoded(); if (!"X.509".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be X.509; was " diff --git a/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestEC.java b/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestEC.java index ee8fd515..dab3852e 100644 --- a/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestEC.java +++ b/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestEC.java @@ -15,54 +15,129 @@ */ package org.conscrypt.java.security; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; import java.security.spec.ECPrivateKeySpec; import java.security.spec.ECPublicKeySpec; import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.List; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import tests.util.ServiceTester; @RunWith(JUnit4.class) -public class KeyFactoryTestEC extends - AbstractKeyFactoryTest<ECPublicKeySpec, ECPrivateKeySpec> { - - public KeyFactoryTestEC() { - super("EC", ECPublicKeySpec.class, ECPrivateKeySpec.class); - } - - @Override - public ServiceTester customizeTester(ServiceTester tester) { - // BC's EC keys always use explicit params, even though it's a bad idea, and we don't support - // those, so don't test BC keys - return tester.skipProvider("BC"); - } - - @Override - protected void check(KeyPair keyPair) throws Exception { - new SignatureHelper("SHA256withECDSA").test(keyPair); - } - - @Override - protected List<KeyPair> getKeys() throws NoSuchAlgorithmException, InvalidKeySpecException { - return Arrays.asList( - new KeyPair( - DefaultKeys.getPublicKey("EC"), - DefaultKeys.getPrivateKey("EC") - ), - new KeyPair( - new TestPublicKey(DefaultKeys.getPublicKey("EC")), - new TestPrivateKey(DefaultKeys.getPrivateKey("EC")) - ), - new KeyPair( - new TestECPublicKey((ECPublicKey)DefaultKeys.getPublicKey("EC")), - new TestECPrivateKey((ECPrivateKey)DefaultKeys.getPrivateKey("EC")) - ) - ); - } +public class KeyFactoryTestEC extends AbstractKeyFactoryTest<ECPublicKeySpec, ECPrivateKeySpec> { + public KeyFactoryTestEC() { + super("EC", ECPublicKeySpec.class, ECPrivateKeySpec.class); + } + + @Override + public ServiceTester customizeTester(ServiceTester tester) { + // BC's EC keys always use explicit params, even though it's a bad idea, and we don't + // support those, so don't test BC keys + return tester.skipProvider("BC"); + } + + @Override + protected void check(KeyPair keyPair) throws Exception { + new SignatureHelper("SHA256withECDSA").test(keyPair); + } + + @Override + protected List<KeyPair> getKeys() throws NoSuchAlgorithmException, InvalidKeySpecException { + return Arrays.asList( + new KeyPair(DefaultKeys.getPublicKey("EC"), DefaultKeys.getPrivateKey("EC")), + new KeyPair(new TestPublicKey(DefaultKeys.getPublicKey("EC")), + new TestPrivateKey(DefaultKeys.getPrivateKey("EC"))), + new KeyPair(new TestECPublicKey((ECPublicKey) DefaultKeys.getPublicKey("EC")), + new TestECPrivateKey((ECPrivateKey) DefaultKeys.getPrivateKey("EC")))); + } + + @Test + public void shouldThrowInvalidKeySpecException_whenKeySpecIsOdd() throws Exception { + Provider p = Security.getProvider(StandardNames.JSSE_PROVIDER_NAME); + final KeyFactory factory = KeyFactory.getInstance("EC", p); + + try { + factory.getKeySpec(new TestECPublicKey((ECPublicKey) DefaultKeys.getPublicKey("EC")), + FakeECPublicKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(DefaultKeys.getPublicKey("EC"), FakeECPublicKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(new TestECPrivateKey((ECPrivateKey) DefaultKeys.getPrivateKey("EC")), + FakeECPrivateKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(DefaultKeys.getPrivateKey("EC"), FakeECPrivateKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(DefaultKeys.getPrivateKey("EC"), FakePKCS8.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(DefaultKeys.getPublicKey("EC"), FakeX509.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + } + + private static class FakeECPublicKeySpec extends ECPublicKeySpec { + public FakeECPublicKeySpec(ECPoint w, ECParameterSpec params) { + super(w, params); + } + } + + private static class FakeECPrivateKeySpec extends ECPrivateKeySpec { + public FakeECPrivateKeySpec(BigInteger s, ECParameterSpec params) { + super(s, params); + } + } + + private static class FakePKCS8 extends PKCS8EncodedKeySpec { + public FakePKCS8(byte[] encodedKey) { + super(encodedKey); + } + } + + private static class FakeX509 extends X509EncodedKeySpec { + public FakeX509(byte[] encodedKey) { + super(encodedKey); + } + } } diff --git a/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java b/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java index c8fc2da0..76608ad5 100644 --- a/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java +++ b/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java @@ -17,12 +17,15 @@ package org.conscrypt.java.security; import static org.junit.Assert.fail; +import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; +import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.Security; +import java.security.interfaces.RSAPrivateCrtKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; @@ -34,9 +37,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -public class KeyFactoryTestRSA extends - AbstractKeyFactoryTest<RSAPublicKeySpec, RSAPrivateKeySpec> { - +public class KeyFactoryTestRSA extends AbstractKeyFactoryTest<RSAPublicKeySpec, RSAPrivateKeySpec> { public KeyFactoryTestRSA() { super("RSA", RSAPublicKeySpec.class, RSAPrivateKeySpec.class); } @@ -65,13 +66,13 @@ public class KeyFactoryTestRSA extends } @Test - public void testInvalidKeySpec() throws Exception { + public void shouldThrowInvalidKeySpec_whenKeyIsInvalid() throws Exception { Provider p = Security.getProvider(StandardNames.JSSE_PROVIDER_NAME); final KeyFactory factory = KeyFactory.getInstance("RSA", p); try { factory.getKeySpec(new TestPrivateKey(DefaultKeys.getPrivateKey("RSA"), "Invalid"), - RSAPrivateKeySpec.class); + RSAPrivateKeySpec.class); fail(); } catch (InvalidKeySpecException e) { // expected @@ -79,7 +80,7 @@ public class KeyFactoryTestRSA extends try { factory.getKeySpec(new TestPrivateKey(DefaultKeys.getPrivateKey("RSA"), "Invalid"), - RSAPrivateCrtKeySpec.class); + RSAPrivateCrtKeySpec.class); fail(); } catch (InvalidKeySpecException e) { // expected @@ -87,10 +88,86 @@ public class KeyFactoryTestRSA extends try { factory.getKeySpec(new TestPublicKey(DefaultKeys.getPublicKey("RSA"), "Invalid"), - RSAPublicKeySpec.class); + RSAPublicKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + } + + @Test + public void shouldThrowInvalidKeySpec_whenKeySpecIsOdd() throws Exception { + Provider p = Security.getProvider(StandardNames.JSSE_PROVIDER_NAME); + final KeyFactory factory = KeyFactory.getInstance("RSA", p); + + try { + factory.getKeySpec(DefaultKeys.getPublicKey("RSA"), FakeRSAPublicKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(generateRsaKey(), FakeRSAPrivateCrtKeySpec.class); fail(); } catch (InvalidKeySpecException e) { // expected } + + try { + factory.getKeySpec(DefaultKeys.getPrivateKey("RSA"), FakeRSAPrivateCrtKeySpec.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(DefaultKeys.getPrivateKey("RSA"), FakePKCS8.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + + try { + factory.getKeySpec(DefaultKeys.getPublicKey("RSA"), FakeX509.class); + fail(); + } catch (InvalidKeySpecException e) { + // expected + } + } + + private static RSAPrivateCrtKey generateRsaKey() throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); + kpg.initialize(512); + + KeyPair keyPair = kpg.generateKeyPair(); + return (RSAPrivateCrtKey) keyPair.getPrivate(); + } + + private static class FakeRSAPublicKeySpec extends RSAPublicKeySpec { + public FakeRSAPublicKeySpec(BigInteger modulus, BigInteger publicExponent) { + super(modulus, publicExponent); + } + } + + private static class FakePKCS8 extends PKCS8EncodedKeySpec { + public FakePKCS8(byte[] encodedKey) { + super(encodedKey); + } + } + + private static class FakeRSAPrivateCrtKeySpec extends RSAPrivateCrtKeySpec { + public FakeRSAPrivateCrtKeySpec(BigInteger modulus, BigInteger publicExponent, + BigInteger privateExponent, BigInteger primeP, BigInteger primeQ, + BigInteger primeExponentP, BigInteger primeExponentQ, BigInteger crtCoefficient) { + super(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, + primeExponentQ, crtCoefficient); + } + } + + private static class FakeX509 extends X509EncodedKeySpec { + public FakeX509(byte[] encodedKey) { + super(encodedKey); + } } }
    ['common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java', 'common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java', 'common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java', 'common/src/test/java/org/conscrypt/java/security/KeyFactoryTestEC.java']
    {'.java': 4}
    4
    4
    0
    0
    4
    1,780,545
    390,735
    48,160
    250
    2,630
    537
    30
    2
    3,566
    343
    769
    54
    3
    1
    1970-01-01T00:26:44
    1,164
    Java
    {'Java': 3533745, 'C++': 526129, 'C': 7529, 'Python': 6764, 'Shell': 5171, 'Dockerfile': 3414, 'CMake': 1784, 'PowerShell': 1675, 'Batchfile': 1140, 'HTML': 756}
    Apache License 2.0
    1,087
    google/conscrypt/843/840
    google
    conscrypt
    https://github.com/google/conscrypt/issues/840
    https://github.com/google/conscrypt/pull/843
    https://github.com/google/conscrypt/pull/843
    1
    fixes
    SSLEngine.beginHandshake() should throw SSLException after it was closed
    During testing conscrypt in the netty testsuite we encountered that Conscrypt does not correct implement SSLEngine.beginHandshake(). See https://github.com/netty/netty/pull/10211/files#diff-08da41869dfc1d842df441440b1c605bR2084 If you call `beginHandshake()` after the engine was closed it must throw an `SSLException`. At the moment it throws an `IllegalStateException`. See also https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html#beginHandshake()
    78433b95e34e7455a2dcd6aedfbf5708f34c1650
    2f7404fa4ca6de8683dbeb75f732cd4ad7235395
    https://github.com/google/conscrypt/compare/78433b95e34e7455a2dcd6aedfbf5708f34c1650...2f7404fa4ca6de8683dbeb75f732cd4ad7235395
    diff --git a/common/src/main/java/org/conscrypt/ConscryptEngine.java b/common/src/main/java/org/conscrypt/ConscryptEngine.java index f1eedcc7..8df11b5b 100644 --- a/common/src/main/java/org/conscrypt/ConscryptEngine.java +++ b/common/src/main/java/org/conscrypt/ConscryptEngine.java @@ -413,7 +413,7 @@ final class ConscryptEngine extends AbstractConscryptEngine implements NativeCry case STATE_CLOSED_INBOUND: case STATE_CLOSED_OUTBOUND: case STATE_CLOSED: - throw new IllegalStateException("Engine has already been closed"); + throw new SSLHandshakeException("Engine has already been closed"); default: // We've already started the handshake, just return return;
    ['common/src/main/java/org/conscrypt/ConscryptEngine.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,750,377
    384,313
    47,402
    245
    167
    25
    2
    1
    479
    42
    127
    8
    2
    0
    1970-01-01T00:26:28
    1,164
    Java
    {'Java': 3533745, 'C++': 526129, 'C': 7529, 'Python': 6764, 'Shell': 5171, 'Dockerfile': 3414, 'CMake': 1784, 'PowerShell': 1675, 'Batchfile': 1140, 'HTML': 756}
    Apache License 2.0
    1,089
    google/conscrypt/785/781
    google
    conscrypt
    https://github.com/google/conscrypt/issues/781
    https://github.com/google/conscrypt/pull/785
    https://github.com/google/conscrypt/pull/785
    1
    fixes
    NullPointerException in getAlpnSelectedProtocol
    We’ve got the exact same crash as #379 but this time we’re calling `getAlpnSelectedProtocol()` instead of `getProtocol()`. I presume the same fix will work: cache more session state when the connection is closed. ``` FATAL EXCEPTION: MockWebServer Process: com.xxx.xxx.xxx, PID: 5607 java.lang.AssertionError: java.lang.reflect.InvocationTargetException at okhttp3.internal.platform.android.AndroidSocketAdapter.a(SourceFile:86) at okhttp3.internal.platform.AndroidPlatform.b(SourceFile:86) at okhttp3.mockwebserver.MockWebServer$SocketHandler.handle(MockWebServer.kt:516) at okhttp3.mockwebserver.MockWebServer$serveConnection$$inlined$execute$1.run(Util.kt:580) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at okhttp3.internal.platform.android.AndroidSocketAdapter.a(SourceFile:81) ... 6 more Caused by: java.lang.NullPointerException: ssl == null at com.android.org.conscrypt.NativeCrypto.getApplicationProtocol(Native Method) at com.android.org.conscrypt.NativeSsl.getApplicationProtocol(NativeSsl.java:568) at com.android.org.conscrypt.ConscryptFileDescriptorSocket.getApplicationProtocol(ConscryptFileDescriptorSocket.java:1085) at com.android.org.conscrypt.OpenSSLSocketImpl.getAlpnSelectedProtocol(OpenSSLSocketImpl.java:134) ... 8 more ```
    d2aa6104ac4a9c92a36213bce65f144efdcd1a1b
    d28d0a8d85a0461baa1cb29aec8dd813384f2ee1
    https://github.com/google/conscrypt/compare/d2aa6104ac4a9c92a36213bce65f144efdcd1a1b...d28d0a8d85a0461baa1cb29aec8dd813384f2ee1
    diff --git a/common/src/main/java/org/conscrypt/ActiveSession.java b/common/src/main/java/org/conscrypt/ActiveSession.java index 4726499a..b00a3fa5 100644 --- a/common/src/main/java/org/conscrypt/ActiveSession.java +++ b/common/src/main/java/org/conscrypt/ActiveSession.java @@ -37,6 +37,7 @@ final class ActiveSession implements ConscryptSession { private byte[] id; private long creationTime; private String protocol; + private String applicationProtocol; private String peerHost; private int peerPort = -1; private long lastAccessedTime = 0; @@ -153,25 +154,25 @@ final class ActiveSession implements ConscryptSession { @Override public void putValue(String name, Object value) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public Object getValue(String name) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public void removeValue(String name) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public String[] getValueNames() { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override @@ -275,6 +276,18 @@ final class ActiveSession implements ConscryptSession { return NativeConstants.SSL3_RT_MAX_PLAIN_LENGTH; } + @Override + public String getApplicationProtocol() { + String applicationProtocol = this.applicationProtocol; + if (applicationProtocol == null) { + synchronized (ssl) { + applicationProtocol = SSLUtils.toProtocolString(ssl.getApplicationProtocol()); + } + this.applicationProtocol = applicationProtocol; + } + return applicationProtocol; + } + /** * Configures the peer information once it has been received by the handshake. */ diff --git a/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java b/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java index efbc80a0..aa17760a 100644 --- a/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java +++ b/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java @@ -1118,7 +1118,7 @@ class ConscryptFileDescriptorSocket extends OpenSSLSocketImpl @Override public final String getApplicationProtocol() { - return SSLUtils.toProtocolString(ssl.getApplicationProtocol()); + return provideSession().getApplicationProtocol(); } @Override diff --git a/common/src/main/java/org/conscrypt/ConscryptSession.java b/common/src/main/java/org/conscrypt/ConscryptSession.java index e59c1921..ce89b418 100644 --- a/common/src/main/java/org/conscrypt/ConscryptSession.java +++ b/common/src/main/java/org/conscrypt/ConscryptSession.java @@ -52,4 +52,6 @@ interface ConscryptSession extends SSLSession { @Override X509Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException; + + String getApplicationProtocol(); } diff --git a/common/src/main/java/org/conscrypt/ExternalSession.java b/common/src/main/java/org/conscrypt/ExternalSession.java index 38a96c1b..18c67a3f 100644 --- a/common/src/main/java/org/conscrypt/ExternalSession.java +++ b/common/src/main/java/org/conscrypt/ExternalSession.java @@ -47,7 +47,7 @@ import javax.security.cert.X509Certificate; */ final class ExternalSession implements ConscryptSession { - // Use an initialcapacity of 2 to keep it small in the average case. + // Use an initial capacity of 2 to keep it small in the average case. private final HashMap<String, Object> values = new HashMap<String, Object>(2); private final Provider provider; @@ -156,6 +156,11 @@ final class ExternalSession implements ConscryptSession { return provider.provideSession().getApplicationBufferSize(); } + @Override + public String getApplicationProtocol() { + return provider.provideSession().getApplicationProtocol(); + } + @Override public Object getValue(String name) { if (name == null) { diff --git a/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java b/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java index 32cb0823..10b11046 100644 --- a/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java +++ b/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java @@ -177,4 +177,9 @@ class Java7ExtendedSSLSession extends ExtendedSSLSession implements ConscryptSes public final int getApplicationBufferSize() { return delegate.getApplicationBufferSize(); } + + @Override + public String getApplicationProtocol() { + return delegate.getApplicationProtocol(); + } } diff --git a/common/src/main/java/org/conscrypt/SSLNullSession.java b/common/src/main/java/org/conscrypt/SSLNullSession.java index 0cc9066a..b2668439 100644 --- a/common/src/main/java/org/conscrypt/SSLNullSession.java +++ b/common/src/main/java/org/conscrypt/SSLNullSession.java @@ -75,6 +75,11 @@ final class SSLNullSession implements ConscryptSession, Cloneable { return NativeConstants.SSL3_RT_MAX_PLAIN_LENGTH; } + @Override + public String getApplicationProtocol() { + return null; + } + @Override public String getCipherSuite() { return INVALID_CIPHER; @@ -149,13 +154,13 @@ final class SSLNullSession implements ConscryptSession, Cloneable { @Override public Object getValue(String name) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public String[] getValueNames() { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override @@ -170,12 +175,12 @@ final class SSLNullSession implements ConscryptSession, Cloneable { @Override public void putValue(String name, Object value) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public void removeValue(String name) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } } diff --git a/common/src/main/java/org/conscrypt/SessionSnapshot.java b/common/src/main/java/org/conscrypt/SessionSnapshot.java index d4a8bff4..28e63b96 100644 --- a/common/src/main/java/org/conscrypt/SessionSnapshot.java +++ b/common/src/main/java/org/conscrypt/SessionSnapshot.java @@ -39,6 +39,7 @@ final class SessionSnapshot implements ConscryptSession { private final String cipherSuite; private final String protocol; private final String peerHost; + private final String applicationProtocol; private final int peerPort; SessionSnapshot(ConscryptSession session) { @@ -53,6 +54,7 @@ final class SessionSnapshot implements ConscryptSession { protocol = session.getProtocol(); peerHost = session.getPeerHost(); peerPort = session.getPeerPort(); + applicationProtocol = session.getApplicationProtocol(); } @Override @@ -107,25 +109,25 @@ final class SessionSnapshot implements ConscryptSession { @Override public void putValue(String s, Object o) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public Object getValue(String s) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public void removeValue(String s) { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override public String[] getValueNames() { throw new UnsupportedOperationException( - "All calls to this method should be intercepted by ProvidedSessionDecorator."); + "All calls to this method should be intercepted by ExternalSession."); } @Override @@ -183,4 +185,9 @@ final class SessionSnapshot implements ConscryptSession { public int getApplicationBufferSize() { return NativeConstants.SSL3_RT_MAX_PLAIN_LENGTH; } + + @Override + public String getApplicationProtocol() { + return applicationProtocol; + } } diff --git a/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java b/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java index 6cdd235b..473cc738 100644 --- a/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java +++ b/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java @@ -375,16 +375,26 @@ public class ConscryptEngineTest { @Test public void savedSessionWorksAfterClose() throws Exception { + String alpnProtocol = "spdy/2"; + String[] alpnProtocols = new String[]{alpnProtocol}; + setupEngines(TestKeyStore.getClient(), TestKeyStore.getServer()); + Conscrypt.setApplicationProtocols(clientEngine, alpnProtocols); + Conscrypt.setApplicationProtocols(serverEngine, alpnProtocols); + doHandshake(true); SSLSession session = clientEngine.getSession(); String cipherSuite = session.getCipherSuite(); + String protocol = session.getProtocol(); + assertEquals(alpnProtocol, Conscrypt.getApplicationProtocol(clientEngine)); clientEngine.closeOutbound(); clientEngine.closeInbound(); assertEquals(cipherSuite, session.getCipherSuite()); + assertEquals(protocol, session.getProtocol()); + assertEquals(alpnProtocol, Conscrypt.getApplicationProtocol(clientEngine)); } private void doMutualAuthHandshake( diff --git a/openjdk/src/test/java/org/conscrypt/ConscryptSocketTest.java b/openjdk/src/test/java/org/conscrypt/ConscryptSocketTest.java index 7a15eefd..d0a7eb1d 100644 --- a/openjdk/src/test/java/org/conscrypt/ConscryptSocketTest.java +++ b/openjdk/src/test/java/org/conscrypt/ConscryptSocketTest.java @@ -623,15 +623,23 @@ public class ConscryptSocketTest { @Test public void savedSessionWorksAfterClose() throws Exception { + String alpnProtocol = "spdy/2"; + String[] alpnProtocols = new String[]{alpnProtocol}; TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey); + connection.clientHooks.alpnProtocols = alpnProtocols; + connection.serverHooks.alpnProtocols = alpnProtocols; connection.doHandshakeSuccess(); SSLSession session = connection.client.getSession(); String cipherSuite = session.getCipherSuite(); + String protocol = session.getProtocol(); + assertEquals(alpnProtocol, Conscrypt.getApplicationProtocol(connection.client)); connection.client.close(); assertEquals(cipherSuite, session.getCipherSuite()); + assertEquals(protocol, session.getProtocol()); + assertEquals(alpnProtocol, Conscrypt.getApplicationProtocol(connection.client)); } private static ServerSocket newServerSocket() throws IOException {
    ['common/src/main/java/org/conscrypt/ActiveSession.java', 'common/src/main/java/org/conscrypt/SessionSnapshot.java', 'common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java', 'openjdk/src/test/java/org/conscrypt/ConscryptSocketTest.java', 'openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java', 'common/src/main/java/org/conscrypt/SSLNullSession.java', 'common/src/main/java/org/conscrypt/ConscryptSession.java', 'common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java', 'common/src/main/java/org/conscrypt/ExternalSession.java']
    {'.java': 9}
    9
    9
    0
    0
    9
    1,746,819
    383,662
    47,311
    245
    3,562
    589
    65
    7
    1,558
    87
    357
    26
    0
    1
    1970-01-01T00:26:13
    1,164
    Java
    {'Java': 3533745, 'C++': 526129, 'C': 7529, 'Python': 6764, 'Shell': 5171, 'Dockerfile': 3414, 'CMake': 1784, 'PowerShell': 1675, 'Batchfile': 1140, 'HTML': 756}
    Apache License 2.0
    1,090
    google/conscrypt/784/783
    google
    conscrypt
    https://github.com/google/conscrypt/issues/783
    https://github.com/google/conscrypt/pull/784
    https://github.com/google/conscrypt/pull/784
    1
    fixes
    Possible java.util.ConcurrentModificationException when notifying handshake listeners
    The listeners should be iterated that allows modification of the underlying list (such as using `toArray`). The listener implementation might remove the listener using `removeHandshakeCompletedListener` when notified. ``` Caused by: java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.base/java.util.ArrayList$Itr.next(Unknown Source) at org.conscrypt.AbstractConscryptSocket.notifyHandshakeCompletedListeners(AbstractConscryptSocket.java:594) at org.conscrypt.ConscryptEngineSocket.onHandshakeFinished(ConscryptEngineSocket.java:515) at org.conscrypt.ConscryptEngineSocket.access$000(ConscryptEngineSocket.java:50) at org.conscrypt.ConscryptEngineSocket$1.onHandshakeFinished(ConscryptEngineSocket.java:120) at org.conscrypt.ConscryptEngine.finishHandshake(ConscryptEngine.java:1007) at org.conscrypt.ConscryptEngine.handshake(ConscryptEngine.java:996) ... 58 more ```
    d2aa6104ac4a9c92a36213bce65f144efdcd1a1b
    8ba5432c469d73062bd7e56f355729415e7a22ba
    https://github.com/google/conscrypt/compare/d2aa6104ac4a9c92a36213bce65f144efdcd1a1b...8ba5432c469d73062bd7e56f355729415e7a22ba
    diff --git a/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java b/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java index 7d67285b..1fe7a238 100644 --- a/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java +++ b/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java @@ -588,10 +588,11 @@ abstract class AbstractConscryptSocket extends SSLSocket { abstract void setApplicationProtocolSelector(ApplicationProtocolSelectorAdapter selector); final void notifyHandshakeCompletedListeners() { - if (listeners != null && !listeners.isEmpty()) { + List<HandshakeCompletedListener> listenersCopy = new ArrayList<>(listeners); + if (!listenersCopy.isEmpty()) { // notify the listeners HandshakeCompletedEvent event = new HandshakeCompletedEvent(this, getActiveSession()); - for (HandshakeCompletedListener listener : listeners) { + for (HandshakeCompletedListener listener : listenersCopy) { try { listener.handshakeCompleted(event); } catch (RuntimeException e) { diff --git a/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketVersionCompatibilityTest.java b/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketVersionCompatibilityTest.java index bfbd3a17..8f6c14b6 100644 --- a/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketVersionCompatibilityTest.java +++ b/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketVersionCompatibilityTest.java @@ -417,6 +417,7 @@ public class SSLSocketVersionCompatibilityTest { handshakeCompletedListenerCalled.notify(); } handshakeCompletedListenerCalled[0] = true; + socket.removeHandshakeCompletedListener(this); } catch (RuntimeException e) { throw e; } catch (Exception e) {
    ['common/src/main/java/org/conscrypt/AbstractConscryptSocket.java', 'common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketVersionCompatibilityTest.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,746,819
    383,662
    47,311
    245
    326
    61
    5
    1
    978
    53
    230
    15
    0
    1
    1970-01-01T00:26:13
    1,164
    Java
    {'Java': 3533745, 'C++': 526129, 'C': 7529, 'Python': 6764, 'Shell': 5171, 'Dockerfile': 3414, 'CMake': 1784, 'PowerShell': 1675, 'Batchfile': 1140, 'HTML': 756}
    Apache License 2.0
    1,088
    google/conscrypt/809/801
    google
    conscrypt
    https://github.com/google/conscrypt/issues/801
    https://github.com/google/conscrypt/pull/809
    https://github.com/google/conscrypt/pull/809
    1
    fixes
    resource stream leak on android
    see log below from conscrypt 2.2.1 (2.3.0 is not yet available for android?) (tested on android 4.4) E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks. java.lang.Throwable: Explicit termination method 'end' not called at dalvik.system.CloseGuard.open(CloseGuard.java:184) at java.util.zip.Inflater.<init>(Inflater.java:82) at java.util.zip.ZipFile.getInputStream(ZipFile.java:310) at java.util.jar.JarFile.getInputStream(JarFile.java:409) at libcore.net.url.JarURLConnectionImpl.getInputStream(JarURLConnectionImpl.java:222) at java.net.URL.openStream(URL.java:470) at java.lang.ClassLoader.getResourceAsStream(ClassLoader.java:432) at java.lang.Class.getResourceAsStream(Class.java:1037) at org.conscrypt.Conscrypt.<clinit>(Conscrypt.java:80)
    dec987186b9d716dd8814e7d22a61796c416e08c
    64d4b3cbc43ca52b6b5784d3093637f7ada9bdde
    https://github.com/google/conscrypt/compare/dec987186b9d716dd8814e7d22a61796c416e08c...64d4b3cbc43ca52b6b5784d3093637f7ada9bdde
    diff --git a/common/src/main/java/org/conscrypt/Conscrypt.java b/common/src/main/java/org/conscrypt/Conscrypt.java index c562a69b..42440fdd 100644 --- a/common/src/main/java/org/conscrypt/Conscrypt.java +++ b/common/src/main/java/org/conscrypt/Conscrypt.java @@ -34,6 +34,7 @@ import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import org.conscrypt.io.IoUtils; /** * Core API for creating and configuring all Conscrypt types. @@ -76,8 +77,9 @@ public final class Conscrypt { int major = -1; int minor = -1; int patch = -1; + InputStream stream = null; try { - InputStream stream = Conscrypt.class.getResourceAsStream("conscrypt.properties"); + stream = Conscrypt.class.getResourceAsStream("conscrypt.properties"); if (stream != null) { Properties props = new Properties(); props.load(stream); @@ -86,6 +88,8 @@ public final class Conscrypt { patch = Integer.parseInt(props.getProperty("org.conscrypt.version.patch", "-1")); } } catch (IOException e) { + } finally { + IoUtils.closeQuietly(stream); } if ((major >= 0) && (minor >= 0) && (patch >= 0)) { VERSION = new Version(major, minor, patch);
    ['common/src/main/java/org/conscrypt/Conscrypt.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,748,656
    384,000
    47,366
    245
    311
    59
    6
    1
    932
    62
    217
    15
    0
    0
    1970-01-01T00:26:21
    1,164
    Java
    {'Java': 3533745, 'C++': 526129, 'C': 7529, 'Python': 6764, 'Shell': 5171, 'Dockerfile': 3414, 'CMake': 1784, 'PowerShell': 1675, 'Batchfile': 1140, 'HTML': 756}
    Apache License 2.0
    9,341
    dtstack/taier/657/655
    dtstack
    taier
    https://github.com/DTStack/Taier/issues/655
    https://github.com/DTStack/Taier/pull/657
    https://github.com/DTStack/Taier/pull/657
    1
    fix
    资源组件HiveServer连接测试失败
    报错信息: {"componentTypeCode":0,"errorMsg":"com.dtstack.taier.pluginapi.exception.PluginDefineException: get conn exception:com.dtstack.taier.pluginapi.exception.PluginDefineException: get conn exception:com.dtstack.taier.pluginapi.exception.PluginDefineException: java.lang.NullPointerException\\r\\ncom.dtstack.taier.pluginapi.exception.PluginDefineException: get conn exception:com.dtstack.taier.pluginapi.exception.PluginDefineException: get conn exception:com.dtstack.taier.pluginapi.exception.PluginDefineException: java.lang.NullPointerException\\r\\n\\tat com.dtstack.taier.rdbs.common.executor.AbstractConnFactory.init(AbstractConnFactory.java:91)\\r\\n\\tat com.dtstack.taier.rdbs.hive.HiveConnFactory.init(HiveConnFactory.java:66)\\r\\n\\tat com.dtstack.taier.rdbs.common.AbstractRdbsClient.testConnect(AbstractRdbsClient.java:160)\\r\\n\\tat com.dtstack.taier.common.client.ClientProxy.lambda$null$9(ClientProxy.java:273)\\r\\n\\tat com.dtstack.taier.pluginapi.callback.ClassLoaderCallBackMethod.callbackAndReset(ClassLoaderCallBackMethod.java:31)\\r\\n\\tat com.dtstack.taier.common.client.ClientProxy.lambda$testConnect$10(ClientProxy.java:273)\\r\\n\\tat java.util.concurrent.CompletableFuture$AsyncSupply.run$$$capture(CompletableFuture.java:1590)\\r\\n\\tat java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java)\\r\\n\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\\r\\n\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\\r\\n\\tat java.lang.Thread.run(Thread.java:748)\\r\\n","result":false} 报错原因: com.dtstack.taier.rdbs.common.executor.AbstractConnFactory 85行处 properties.get("yarnConf")为null 解决办法: 重载com.dtstack.taier.scheduler.service.ComponentService中wrapperConfig方法:(对hiveserver组间补充yarnConf配置) public JSONObject wrapperConfig(int componentType, String componentConfig, Map<String, String> sftpConfig, KerberosConfig kerberosConfig) { JSONObject dataInfo = JSONObject.parseObject(componentConfig); if (EComponentType.YARN.getTypeCode() == componentType) { JSONObject confInfo = new JSONObject(); confInfo.put(EComponentType.YARN.getConfName(), dataInfo); dataInfo = confInfo; } else if (EComponentType.HDFS.getTypeCode() == componentType) { JSONObject confInfo = new JSONObject(); confInfo.put(EComponentType.HDFS.getConfName(), dataInfo); dataInfo = confInfo; } //开启了kerberos if (null != kerberosConfig) { dataInfo.put(KERBEROS_FILE_TIMESTAMP, kerberosConfig.getGmtModified()); dataInfo.put(OPEN_KERBEROS, kerberosConfig.getOpenKerberos()); dataInfo.put(REMOTE_DIR, kerberosConfig.getRemotePath()); dataInfo.put(PRINCIPAL_FILE, kerberosConfig.getName()); dataInfo.put(KRB_NAME, kerberosConfig.getKrbName()); dataInfo.put(PRINCIPAL, kerberosConfig.getPrincipal()); dataInfo.put(MERGE_KRB5_CONTENT_KEY, kerberosConfig.getMergeKrbContent()); } //common参数 dataInfo.put(EComponentType.SFTP.getConfName(), sftpConfig); return dataInfo; } private void putYarnConfig(Long clusterId, JSONObject dataInfo) { Map yarnMap = getComponentByClusterId(clusterId, EComponentType.YARN.getTypeCode(), false, Map.class, null); if (null != yarnMap) { dataInfo.put(EComponentType.YARN.getConfName(), yarnMap); } }
    6f5f2e15ae6a25583d6ddc19fc0147147f8081cb
    c125025e67ad7bc0a2414634671adfb3ec3e4b9c
    https://github.com/dtstack/taier/compare/6f5f2e15ae6a25583d6ddc19fc0147147f8081cb...c125025e67ad7bc0a2414634671adfb3ec3e4b9c
    diff --git a/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleComponentService.java b/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleComponentService.java index 2847d19f..c1e9fbc8 100644 --- a/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleComponentService.java +++ b/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleComponentService.java @@ -1098,7 +1098,7 @@ public class ConsoleComponentService { if (EComponentType.HDFS.getTypeCode().equals(componentType)) { typeName = componentService.buildHdfsTypeName(null, clusterId); } - JSONObject pluginInfo = componentService.wrapperConfig(componentType, componentConfig, sftpConfig, kerberosConfig); + JSONObject pluginInfo = componentService.wrapperConfig(componentType, componentConfig, sftpConfig, kerberosConfig, clusterId); pluginInfo.put(TYPE_NAME_KEY, typeName); componentTestResult = workerOperator.testConnect(pluginInfo.toJSONString()); if (null == componentTestResult) { diff --git a/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleService.java b/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleService.java index aab6dcb3..e257f6c8 100644 --- a/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleService.java +++ b/taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleService.java @@ -457,7 +457,7 @@ public class ConsoleService { //开启kerberos 添加信息 KerberosConfig kerberosConfig = consoleKerberosMapper.getByComponentType(cluster.getId(), yarnComponent.getComponentTypeCode(), ComponentVersionUtil.formatMultiVersion(yarnComponent.getComponentTypeCode(),yarnComponent.getVersionValue())); Map sftpMap = componentService.getComponentByClusterId(cluster.getId(), EComponentType.SFTP.getTypeCode(), false, Map.class,null); - pluginInfo = componentService.wrapperConfig(yarnComponent.getComponentTypeCode(),componentConfig.toJSONString(),sftpMap,kerberosConfig); + pluginInfo = componentService.wrapperConfig(yarnComponent.getComponentTypeCode(),componentConfig.toJSONString(),sftpMap,kerberosConfig,cluster.getId()); } String typeName = componentConfig.getString(ConfigConstant.TYPE_NAME_KEY); if (StringUtils.isBlank(typeName)) { diff --git a/taier-scheduler/src/main/java/com/dtstack/taier/scheduler/service/ComponentService.java b/taier-scheduler/src/main/java/com/dtstack/taier/scheduler/service/ComponentService.java index df3127c0..abf42fb3 100644 --- a/taier-scheduler/src/main/java/com/dtstack/taier/scheduler/service/ComponentService.java +++ b/taier-scheduler/src/main/java/com/dtstack/taier/scheduler/service/ComponentService.java @@ -93,7 +93,7 @@ public class ComponentService { ComponentVersionUtil.formatMultiVersion(componentCode, componentVersion)); } Map sftpMap = getComponentByClusterId(clusterId, EComponentType.SFTP.getTypeCode(), false, Map.class, null); - pluginInfo = wrapperConfig(componentCode, componentConfig.toJSONString(), sftpMap, kerberosConfig); + pluginInfo = wrapperConfig(componentCode, componentConfig.toJSONString(), sftpMap, kerberosConfig,clusterId); return pluginInfo; } @@ -105,11 +105,13 @@ public class ComponentService { * @param componentConfig * @return */ - public JSONObject wrapperConfig(int componentType, String componentConfig, Map<String, String> sftpConfig, KerberosConfig kerberosConfig) { + public JSONObject wrapperConfig(int componentType, String componentConfig, Map<String, String> sftpConfig, KerberosConfig kerberosConfig,Long clusterId) { EComponentType eComponentType = EComponentType.getByCode(componentType); JSONObject dataInfo = new JSONObject(); if (EComponentType.YARN.equals(eComponentType) || EComponentType.HDFS.equals(eComponentType)) { dataInfo.put(eComponentType.getConfName(), JSONObject.parseObject(componentConfig)); + } if (EComponentType.HIVE_SERVER.equals(eComponentType)) { + putYarnConfig(clusterId, dataInfo); } else { dataInfo = JSONObject.parseObject(componentConfig); } @@ -130,6 +132,13 @@ public class ComponentService { return dataInfo; } + private void putYarnConfig(Long clusterId, JSONObject dataInfo) { + Map yarnMap = getComponentByClusterId(clusterId, EComponentType.YARN.getTypeCode(), false, Map.class, null); + if (null != yarnMap) { + dataInfo.put(EComponentType.YARN.getConfName(), yarnMap); + } + } + public Component getComponentByClusterId(Long clusterId, Integer componentType, String componentVersion) { return componentMapper.getByClusterIdAndComponentType(clusterId, componentType, componentVersion, null); }
    ['taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleComponentService.java', 'taier-data-develop/src/main/java/com/dtstack/taier/develop/service/console/ConsoleService.java', 'taier-scheduler/src/main/java/com/dtstack/taier/scheduler/service/ComponentService.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    6,139,810
    1,336,390
    184,706
    1,386
    1,552
    315
    17
    3
    3,499
    133
    823
    40
    0
    0
    1970-01-01T00:27:39
    1,159
    Java
    {'Java': 9989416, 'TypeScript': 2279705, 'CSS': 713033, 'PLpgSQL': 515685, 'Scala': 85975, 'SCSS': 76346, 'JavaScript': 37746, 'Shell': 5499, 'Dockerfile': 1573, 'Mustache': 241}
    Apache License 2.0
    228
    mekanism/mekanism/4868/4852
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4852
    https://github.com/mekanism/Mekanism/pull/4868
    https://github.com/mekanism/Mekanism/pull/4868
    1
    fixes
    [1.12] Electrolytic Separator + Energy Upgrades = Hydrogen Power
    #### Issue description: The Electrolytic Separator accepts Energy Upgrades. In the past, this only increased the energy capacity. The Electrolytic Separator was the only machine to not receive a boost in efficiency in order to prevent an infinite energy loop using Hydrogen Gas. The Electrolytic Separator currently does get the energy boost and can produce an infinite energy loop using Hydrogen Gas. #### Steps to reproduce: 1. Stick a full set of Energy Upgrades in the Electrolytic Separator. 2. Supply Water 3. Burn Hydrogen in a Gas-Burning Generator for 10x the power you put in. A full set of Speed Upgrades will net you nearly 18k J/t. #### Version (make sure you are on the latest version before reporting): **Forge: 14.23.1.2561** **Mekanism: 9.4.2.327** Test pack included Mek Generators and Tools, and JEI 4.8.5.134. No other mods.
    f09f8d28384592b7f16318b0ec04ad6c4faf218b
    b8a83fb9ef6c0ac3499fd6f798556cd85c52aebe
    https://github.com/mekanism/mekanism/compare/f09f8d28384592b7f16318b0ec04ad6c4faf218b...b8a83fb9ef6c0ac3499fd6f798556cd85c52aebe
    diff --git a/src/main/java/mekanism/common/tile/TileEntityElectrolyticSeparator.java b/src/main/java/mekanism/common/tile/TileEntityElectrolyticSeparator.java index 15fe5ff389..26df3dd624 100644 --- a/src/main/java/mekanism/common/tile/TileEntityElectrolyticSeparator.java +++ b/src/main/java/mekanism/common/tile/TileEntityElectrolyticSeparator.java @@ -646,4 +646,21 @@ public class TileEntityElectrolyticSeparator extends TileEntityMachine implement { return new Object[] {fluidTank, leftTank, rightTank}; } + + @Override + public void recalculateUpgradables(Upgrade upgrade) + { + super.recalculateUpgradables(upgrade); + + switch(upgrade) + { + case ENERGY: + maxEnergy = MekanismUtils.getMaxEnergy(this, BASE_MAX_ENERGY); + energyPerTick = BlockStateMachine.MachineType.ELECTROLYTIC_SEPARATOR.getUsage(); + setEnergy(Math.min(getMaxEnergy(), getEnergy())); + break; + default: + break; + } + } }
    ['src/main/java/mekanism/common/tile/TileEntityElectrolyticSeparator.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    4,185,091
    1,116,250
    145,081
    928
    411
    103
    17
    1
    866
    136
    214
    15
    0
    0
    1970-01-01T00:25:13
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    237
    mekanism/mekanism/4544/3613
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/3613
    https://github.com/mekanism/Mekanism/pull/4544
    https://github.com/mekanism/Mekanism/pull/4544
    1
    fixes
    [1.10.2] Cardboard box deletes Advanced Solar Generator when boxing the base of it.
    The box and the Advanced Solar Generator just straight up disappear, never to be seen again.
    b3f1a9fee43e6aec5689664f268fa6dbeebb50b0
    6ba975b84f792322472582edf21bcf9d65394f5a
    https://github.com/mekanism/mekanism/compare/b3f1a9fee43e6aec5689664f268fa6dbeebb50b0...6ba975b84f792322472582edf21bcf9d65394f5a
    diff --git a/src/main/java/mekanism/common/Mekanism.java b/src/main/java/mekanism/common/Mekanism.java index a2860b183e..4033bc2254 100644 --- a/src/main/java/mekanism/common/Mekanism.java +++ b/src/main/java/mekanism/common/Mekanism.java @@ -1426,11 +1426,21 @@ public class Mekanism public void onBlacklistUpdate(BoxBlacklistEvent event) { MekanismAPI.addBoxBlacklist(MekanismBlocks.CardboardBox, OreDictionary.WILDCARD_VALUE); + + // Mekanism multiblock structures MekanismAPI.addBoxBlacklist(MekanismBlocks.BoundingBlock, OreDictionary.WILDCARD_VALUE); + MekanismAPI.addBoxBlacklist(MekanismBlocks.BasicBlock2, 9); // Security Desk + MekanismAPI.addBoxBlacklist(MekanismBlocks.MachineBlock, 4); // Digital Miner + MekanismAPI.addBoxBlacklist(MekanismBlocks.MachineBlock2, 9); // Seismic Vibrator + MekanismAPI.addBoxBlacklist(MekanismBlocks.MachineBlock3, 1); // Solar Neutron Activator + + // Minecraft unobtainable MekanismAPI.addBoxBlacklist(Blocks.BEDROCK, 0); MekanismAPI.addBoxBlacklist(Blocks.PORTAL, OreDictionary.WILDCARD_VALUE); MekanismAPI.addBoxBlacklist(Blocks.END_PORTAL, OreDictionary.WILDCARD_VALUE); MekanismAPI.addBoxBlacklist(Blocks.END_PORTAL_FRAME, OreDictionary.WILDCARD_VALUE); + + // Minecraft multiblock structures MekanismAPI.addBoxBlacklist(Blocks.BED, OreDictionary.WILDCARD_VALUE); MekanismAPI.addBoxBlacklist(Blocks.OAK_DOOR, OreDictionary.WILDCARD_VALUE); MekanismAPI.addBoxBlacklist(Blocks.SPRUCE_DOOR, OreDictionary.WILDCARD_VALUE); diff --git a/src/main/java/mekanism/generators/common/MekanismGenerators.java b/src/main/java/mekanism/generators/common/MekanismGenerators.java index b06fb7bc0b..0620e12a0e 100644 --- a/src/main/java/mekanism/generators/common/MekanismGenerators.java +++ b/src/main/java/mekanism/generators/common/MekanismGenerators.java @@ -4,6 +4,7 @@ import io.netty.buffer.ByteBuf; import java.io.IOException; +import mekanism.api.MekanismAPI; import mekanism.api.gas.Gas; import mekanism.api.gas.GasRegistry; import mekanism.api.infuse.InfuseRegistry; @@ -275,4 +276,12 @@ public class MekanismGenerators implements IModule TypeConfigManager.updateConfigRecipes(GeneratorType.getGeneratorsForConfig(), generators.generatorsManager); } } + + @SubscribeEvent + public void onBlacklistUpdate(MekanismAPI.BoxBlacklistEvent event) + { + // Mekanism Generators multiblock structures + MekanismAPI.addBoxBlacklist(GeneratorsBlocks.Generator, 5); // Advanced Solar Generator + MekanismAPI.addBoxBlacklist(GeneratorsBlocks.Generator, 6); // Wind Generator + } }
    ['src/main/java/mekanism/generators/common/MekanismGenerators.java', 'src/main/java/mekanism/common/Mekanism.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    4,691,959
    1,234,542
    161,646
    1,283
    800
    230
    19
    2
    93
    16
    18
    2
    0
    0
    1970-01-01T00:25:00
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    236
    mekanism/mekanism/4549/3534
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/3534
    https://github.com/mekanism/Mekanism/pull/4549
    https://github.com/mekanism/Mekanism/pull/4549
    1
    fixes
    [Issue] Tesselating block model
    Hi, Random client crash when i'm in my base, it seems to begin to happen since i've built a boiler. Crash log : http://pastebin.com/qQqD8yf6
    b3f1a9fee43e6aec5689664f268fa6dbeebb50b0
    4614c6775059b2533b7427b26a8d9e079f38805c
    https://github.com/mekanism/mekanism/compare/b3f1a9fee43e6aec5689664f268fa6dbeebb50b0...4614c6775059b2533b7427b26a8d9e079f38805c
    diff --git a/src/main/java/mekanism/common/block/BlockBasic.java b/src/main/java/mekanism/common/block/BlockBasic.java index 6be823ca10..f420ff9d59 100644 --- a/src/main/java/mekanism/common/block/BlockBasic.java +++ b/src/main/java/mekanism/common/block/BlockBasic.java @@ -158,8 +158,8 @@ public abstract class BlockBasic extends Block implements ICTMBlock @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); - + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); + if(tile instanceof TileEntityBasicBlock && ((TileEntityBasicBlock)tile).facing != null) { state = state.withProperty(BlockStateFacing.facingProperty, ((TileEntityBasicBlock)tile).facing); @@ -344,7 +344,7 @@ public abstract class BlockBasic extends Block implements ICTMBlock return false; case 9: case 11: - TileEntityDynamicTank tileEntity = (TileEntityDynamicTank)world.getTileEntity(pos); + TileEntityDynamicTank tileEntity = (TileEntityDynamicTank) MekanismUtils.getTileEntitySafe(world, pos); if(tileEntity != null) { @@ -372,7 +372,7 @@ public abstract class BlockBasic extends Block implements ICTMBlock case 2: case 7: case 8: - TileEntityMultiblock tileEntity = (TileEntityMultiblock)world.getTileEntity(pos); + TileEntityMultiblock tileEntity = (TileEntityMultiblock) MekanismUtils.getTileEntitySafe(world, pos); if(tileEntity != null) { @@ -716,7 +716,7 @@ public abstract class BlockBasic extends Block implements ICTMBlock @Override public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos) { - TileEntity tileEntity = world.getTileEntity(pos); + TileEntity tileEntity = MekanismUtils.getTileEntitySafe(world, pos); int metadata = state.getBlock().getMetaFromState(state); if(tileEntity instanceof IActiveState) @@ -1044,4 +1044,4 @@ public abstract class BlockBasic extends Block implements ICTMBlock { return BasicBlockType.get(world.getBlockState(pos)).isBeaconBase; } -} \\ No newline at end of file +} diff --git a/src/main/java/mekanism/common/block/BlockEnergyCube.java b/src/main/java/mekanism/common/block/BlockEnergyCube.java index b2afc48576..45d337ab6b 100644 --- a/src/main/java/mekanism/common/block/BlockEnergyCube.java +++ b/src/main/java/mekanism/common/block/BlockEnergyCube.java @@ -87,7 +87,7 @@ public class BlockEnergyCube extends BlockContainer @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); if(tile instanceof TileEntityEnergyCube) { diff --git a/src/main/java/mekanism/common/block/BlockGasTank.java b/src/main/java/mekanism/common/block/BlockGasTank.java index 64297680fa..f30c2c5c93 100644 --- a/src/main/java/mekanism/common/block/BlockGasTank.java +++ b/src/main/java/mekanism/common/block/BlockGasTank.java @@ -74,7 +74,7 @@ public class BlockGasTank extends BlockContainer @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); if(tile instanceof TileEntityGasTank) { diff --git a/src/main/java/mekanism/common/block/BlockGlowPanel.java b/src/main/java/mekanism/common/block/BlockGlowPanel.java index 0480378b6a..7aeea339d0 100644 --- a/src/main/java/mekanism/common/block/BlockGlowPanel.java +++ b/src/main/java/mekanism/common/block/BlockGlowPanel.java @@ -9,6 +9,7 @@ import mekanism.common.block.property.PropertyColor; import mekanism.common.block.states.BlockStateFacing; import mekanism.common.block.states.BlockStateGlowPanel; import mekanism.common.tile.TileEntityGlowPanel; +import mekanism.common.util.MekanismUtils; import mekanism.common.util.MultipartUtils; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; @@ -71,7 +72,7 @@ public class BlockGlowPanel extends Block implements ITileEntityProvider @Override public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { - TileEntityGlowPanel tileEntity = (TileEntityGlowPanel)world.getTileEntity(pos); + TileEntityGlowPanel tileEntity = (TileEntityGlowPanel) MekanismUtils.getTileEntitySafe(world, pos); return tileEntity != null ? state.withProperty(BlockStateFacing.facingProperty, tileEntity.side) : state; } @@ -79,8 +80,8 @@ public class BlockGlowPanel extends Block implements ITileEntityProvider @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { - TileEntityGlowPanel tileEntity = (TileEntityGlowPanel)world.getTileEntity(pos); - + TileEntityGlowPanel tileEntity = (TileEntityGlowPanel) MekanismUtils.getTileEntitySafe(world, pos); + if(tileEntity != null) { state = state.withProperty(BlockStateFacing.facingProperty, tileEntity.side); @@ -117,7 +118,7 @@ public class BlockGlowPanel extends Block implements ITileEntityProvider @Override public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { - TileEntityGlowPanel tileEntity = (TileEntityGlowPanel)world.getTileEntity(pos); + TileEntityGlowPanel tileEntity = (TileEntityGlowPanel) MekanismUtils.getTileEntitySafe(world, pos); if(!tileEntity.getWorld().isRemote && !canStay(tileEntity)) { @@ -137,7 +138,7 @@ public class BlockGlowPanel extends Block implements ITileEntityProvider @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { - TileEntity tile = world.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(world, pos); if(tile != null && tile instanceof TileEntityGlowPanel) { diff --git a/src/main/java/mekanism/common/block/BlockMachine.java b/src/main/java/mekanism/common/block/BlockMachine.java index 6529f9ed9e..b29cee2430 100644 --- a/src/main/java/mekanism/common/block/BlockMachine.java +++ b/src/main/java/mekanism/common/block/BlockMachine.java @@ -206,7 +206,7 @@ public abstract class BlockMachine extends BlockContainer implements ICTMBlock @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); if(tile instanceof TileEntityBasicBlock && ((TileEntityBasicBlock)tile).facing != null) { @@ -383,7 +383,7 @@ public abstract class BlockMachine extends BlockContainer implements ICTMBlock { if(client.enableAmbientLighting) { - TileEntity tileEntity = world.getTileEntity(pos); + TileEntity tileEntity = MekanismUtils.getTileEntitySafe(world, pos); if(tileEntity instanceof IActiveState) { @@ -992,7 +992,7 @@ public abstract class BlockMachine extends BlockContainer implements ICTMBlock public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { MachineType type = MachineType.get(getMachineBlock(), state.getBlock().getMetaFromState(state)); - TileEntity tile = world.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(world, pos); if(type == null) { @@ -1025,12 +1025,6 @@ public abstract class BlockMachine extends BlockContainer implements ICTMBlock { return false; } - - @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) - { - return super.getCollisionBoundingBox(state, world, pos); - } @Override public boolean isSideSolid(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) @@ -1111,7 +1105,7 @@ public abstract class BlockMachine extends BlockContainer implements ICTMBlock @Override public int getWeakPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { - TileEntity tile = world.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(world, pos); if(tile instanceof TileEntityLaserAmplifier) { diff --git a/src/main/java/mekanism/common/block/BlockPlastic.java b/src/main/java/mekanism/common/block/BlockPlastic.java index 4b10f95f49..43061a2ab5 100644 --- a/src/main/java/mekanism/common/block/BlockPlastic.java +++ b/src/main/java/mekanism/common/block/BlockPlastic.java @@ -14,9 +14,7 @@ import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; diff --git a/src/main/java/mekanism/common/block/BlockTransmitter.java b/src/main/java/mekanism/common/block/BlockTransmitter.java index 7b094a3fd5..2600250994 100644 --- a/src/main/java/mekanism/common/block/BlockTransmitter.java +++ b/src/main/java/mekanism/common/block/BlockTransmitter.java @@ -95,7 +95,7 @@ public class BlockTransmitter extends Block implements ITileEntityProvider @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); if(tile instanceof TileEntitySidedPipe) { @@ -129,7 +129,7 @@ public class BlockTransmitter extends Block implements ITileEntityProvider @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess w, BlockPos pos) { - TileEntitySidedPipe tile = (TileEntitySidedPipe)w.getTileEntity(pos); + TileEntitySidedPipe tile = (TileEntitySidedPipe) MekanismUtils.getTileEntitySafe(w, pos); if(tile != null) { @@ -147,7 +147,7 @@ public class BlockTransmitter extends Block implements ITileEntityProvider @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { - TileEntity tile = world.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(world, pos); if(tile instanceof TileEntitySidedPipe && ((TileEntitySidedPipe)tile).getTransmitterType().getSize() == Size.SMALL) { @@ -301,7 +301,7 @@ public class BlockTransmitter extends Block implements ITileEntityProvider @Override public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { - TileEntitySidedPipe tile = (TileEntitySidedPipe)world.getTileEntity(pos); + TileEntitySidedPipe tile = (TileEntitySidedPipe) MekanismUtils.getTileEntitySafe(world, pos); EnumFacing side = EnumFacing.getFacingFromVector(neighbor.getX() - pos.getX(), neighbor.getY() - pos.getY(), neighbor.getZ() - pos.getZ()); tile.onNeighborTileChange(side); } diff --git a/src/main/java/mekanism/common/util/MekanismUtils.java b/src/main/java/mekanism/common/util/MekanismUtils.java index cdb259d814..c3abcca998 100644 --- a/src/main/java/mekanism/common/util/MekanismUtils.java +++ b/src/main/java/mekanism/common/util/MekanismUtils.java @@ -82,9 +82,11 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.ChunkCache; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; @@ -1526,4 +1528,9 @@ public final class MekanismUtils return prefix + "/"; } } + + public static TileEntity getTileEntitySafe(IBlockAccess worldIn, BlockPos pos) + { + return worldIn instanceof ChunkCache ? ((ChunkCache)worldIn).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : worldIn.getTileEntity(pos); + } } diff --git a/src/main/java/mekanism/generators/common/GeneratorsItems.java b/src/main/java/mekanism/generators/common/GeneratorsItems.java index af3d46d507..70e8fe0f34 100644 --- a/src/main/java/mekanism/generators/common/GeneratorsItems.java +++ b/src/main/java/mekanism/generators/common/GeneratorsItems.java @@ -1,6 +1,7 @@ package mekanism.generators.common; import mekanism.common.item.ItemMekanism; +import mekanism.common.util.MekanismUtils; import mekanism.generators.common.item.ItemHohlraum; import mekanism.generators.common.tile.turbine.TileEntityTurbineRotor; import net.minecraft.entity.player.EntityPlayer; @@ -20,7 +21,7 @@ public class GeneratorsItems @Override public boolean doesSneakBypassUse(ItemStack stack, IBlockAccess world, BlockPos pos, EntityPlayer player) { - return world.getTileEntity(pos) instanceof TileEntityTurbineRotor; + return MekanismUtils.getTileEntitySafe(world, pos) instanceof TileEntityTurbineRotor; } }; diff --git a/src/main/java/mekanism/generators/common/block/BlockGenerator.java b/src/main/java/mekanism/generators/common/block/BlockGenerator.java index 03976ab9af..a02c398a5d 100644 --- a/src/main/java/mekanism/generators/common/block/BlockGenerator.java +++ b/src/main/java/mekanism/generators/common/block/BlockGenerator.java @@ -169,7 +169,7 @@ public abstract class BlockGenerator extends BlockContainer implements ICTMBlock @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); if(tile instanceof TileEntityBasicBlock && ((TileEntityBasicBlock)tile).facing != null) { @@ -254,7 +254,7 @@ public abstract class BlockGenerator extends BlockContainer implements ICTMBlock { if(client.enableAmbientLighting) { - TileEntity tileEntity = world.getTileEntity(pos); + TileEntity tileEntity = MekanismUtils.getTileEntitySafe(world, pos); if(tileEntity instanceof IActiveState && !(tileEntity instanceof TileEntitySolarGenerator)) { diff --git a/src/main/java/mekanism/generators/common/block/BlockReactor.java b/src/main/java/mekanism/generators/common/block/BlockReactor.java index 00d86b3057..dea26a93be 100644 --- a/src/main/java/mekanism/generators/common/block/BlockReactor.java +++ b/src/main/java/mekanism/generators/common/block/BlockReactor.java @@ -75,7 +75,7 @@ public abstract class BlockReactor extends Block implements ICTMBlock, ITileEnti @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - TileEntity tile = worldIn.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(worldIn, pos); if(tile instanceof TileEntityReactorController) { @@ -293,7 +293,7 @@ public abstract class BlockReactor extends Block implements ICTMBlock, ITileEnti @Override public int getWeakPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { - TileEntity tile = world.getTileEntity(pos); + TileEntity tile = MekanismUtils.getTileEntitySafe(world, pos); if(tile instanceof TileEntityReactorLogicAdapter) {
    ['src/main/java/mekanism/generators/common/GeneratorsItems.java', 'src/main/java/mekanism/common/block/BlockMachine.java', 'src/main/java/mekanism/generators/common/block/BlockReactor.java', 'src/main/java/mekanism/common/block/BlockGlowPanel.java', 'src/main/java/mekanism/common/block/BlockGasTank.java', 'src/main/java/mekanism/common/block/BlockPlastic.java', 'src/main/java/mekanism/generators/common/block/BlockGenerator.java', 'src/main/java/mekanism/common/block/BlockBasic.java', 'src/main/java/mekanism/common/block/BlockTransmitter.java', 'src/main/java/mekanism/common/block/BlockEnergyCube.java', 'src/main/java/mekanism/common/util/MekanismUtils.java']
    {'.java': 11}
    11
    11
    0
    0
    11
    4,691,959
    1,234,542
    161,646
    1,283
    3,905
    1,021
    69
    11
    143
    24
    43
    6
    1
    0
    1970-01-01T00:25:00
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    235
    mekanism/mekanism/4550/4484
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4484
    https://github.com/mekanism/Mekanism/pull/4550
    https://github.com/mekanism/Mekanism/pull/4550
    1
    fixes
    [1.11.2] Server Crash
    #### Issue description: Hello! A few days ago, our official pack server started crashing whenever someone is near a Mekanism machine (tested with a Metallurgic Infuser and Enrichment Chamber). At first we thought that it was all due to Mekanism, but today we figured out that it doesn't happen when the crafting recipes in JEI bug out, as it sometimes happens with the 1.11.2 version. Then we tried changing the JEI version on the client back to the version where all was fine, but it didn't help. Either way, by the crash log we can tell that it has something to do with Mekanism. #### Version (make sure you are on the latest version before reporting): **Forge:** 13.20.0.2315 **Mekanism:** 9.3.2.307 **JEI (if it actually has to do with it)** 4.5.0.289 #### If a (crash)log is relevant for this issue, link it here: (_It's almost always relevant_) https://paste.ee/p/a1wzk
    7b1e965509307591e82df93cb364118650288cf1
    4a7b457bfc7bb1703b9d220fdeeffee3b7504972
    https://github.com/mekanism/mekanism/compare/7b1e965509307591e82df93cb364118650288cf1...4a7b457bfc7bb1703b9d220fdeeffee3b7504972
    diff --git a/src/main/java/mekanism/common/content/transporter/TransporterManager.java b/src/main/java/mekanism/common/content/transporter/TransporterManager.java index ca9cd31ed6..9609b648b4 100644 --- a/src/main/java/mekanism/common/content/transporter/TransporterManager.java +++ b/src/main/java/mekanism/common/content/transporter/TransporterManager.java @@ -9,6 +9,7 @@ import java.util.Set; import mekanism.api.Coord4D; import mekanism.api.EnumColor; +import mekanism.common.Mekanism; import mekanism.common.base.ISideConfiguration; import mekanism.common.content.transporter.TransitRequest.TransitResponse; import mekanism.common.content.transporter.TransporterStack.Path; @@ -113,6 +114,11 @@ public class TransporterManager { int slotID = slots[get]; + if (slotID >= ret.size()){ + Mekanism.logger.error("Inventory {} gave slot number >= the number of slots it reported! {} >= {} ", inv.getClass().getName(), slotID, ret.size()); + continue; + } + ret.set(slotID, !sidedInventory.getStackInSlot(slotID).isEmpty() ? sidedInventory.getStackInSlot(slotID).copy() : ItemStack.EMPTY); } diff --git a/src/main/java/mekanism/common/entity/EntityRobit.java b/src/main/java/mekanism/common/entity/EntityRobit.java index 97cd975679..110c845a9e 100644 --- a/src/main/java/mekanism/common/entity/EntityRobit.java +++ b/src/main/java/mekanism/common/entity/EntityRobit.java @@ -578,7 +578,7 @@ public class EntityRobit extends EntityCreature implements IInventory, ISustaine public void setOwnerUUID(UUID uuid) { dataManager.set(OWNER_UUID, uuid.toString()); - dataManager.set(OWNER_NAME, UsernameCache.getLastKnownUsername(uuid)); + dataManager.set(OWNER_NAME, MekanismUtils.getLastKnownUsername(uuid)); } public boolean getFollowing() diff --git a/src/main/java/mekanism/common/frequency/Frequency.java b/src/main/java/mekanism/common/frequency/Frequency.java index b4d76e39e2..059b80db7b 100644 --- a/src/main/java/mekanism/common/frequency/Frequency.java +++ b/src/main/java/mekanism/common/frequency/Frequency.java @@ -9,6 +9,7 @@ import java.util.UUID; import mekanism.api.Coord4D; import mekanism.common.PacketHandler; +import mekanism.common.util.MekanismUtils; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.UsernameCache; @@ -118,7 +119,7 @@ public class Frequency { data.add(name); data.add(ownerUUID.toString()); - data.add(UsernameCache.getLastKnownUsername(ownerUUID)); + data.add(MekanismUtils.getLastKnownUsername(ownerUUID)); data.add(publicFreq); } diff --git a/src/main/java/mekanism/common/network/PacketSecurityUpdate.java b/src/main/java/mekanism/common/network/PacketSecurityUpdate.java index 4146b91b47..4c4c26e217 100644 --- a/src/main/java/mekanism/common/network/PacketSecurityUpdate.java +++ b/src/main/java/mekanism/common/network/PacketSecurityUpdate.java @@ -13,6 +13,7 @@ import mekanism.common.frequency.Frequency; import mekanism.common.network.PacketSecurityUpdate.SecurityUpdateMessage; import mekanism.common.security.SecurityData; import mekanism.common.security.SecurityFrequency; +import mekanism.common.util.MekanismUtils; import net.minecraftforge.common.UsernameCache; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; @@ -51,7 +52,7 @@ public class PacketSecurityUpdate implements IMessageHandler<SecurityUpdateMessa if(packetType == SecurityPacket.UPDATE) { playerUUID = uuid; - playerUsername = UsernameCache.getLastKnownUsername(uuid); + playerUsername = MekanismUtils.getLastKnownUsername(uuid); securityData = data; } } @@ -92,7 +93,7 @@ public class PacketSecurityUpdate implements IMessageHandler<SecurityUpdateMessa for(SecurityFrequency frequency : frequencies) { PacketHandler.writeString(dataStream, frequency.ownerUUID.toString()); - PacketHandler.writeString(dataStream, UsernameCache.getLastKnownUsername(frequency.ownerUUID)); + PacketHandler.writeString(dataStream, MekanismUtils.getLastKnownUsername(frequency.ownerUUID)); new SecurityData(frequency).write(dataStream); } } diff --git a/src/main/java/mekanism/common/tile/TileEntitySecurityDesk.java b/src/main/java/mekanism/common/tile/TileEntitySecurityDesk.java index 1a2c383d11..c4274f92c6 100644 --- a/src/main/java/mekanism/common/tile/TileEntitySecurityDesk.java +++ b/src/main/java/mekanism/common/tile/TileEntitySecurityDesk.java @@ -262,7 +262,7 @@ public class TileEntitySecurityDesk extends TileEntityContainerBlock implements if(ownerUUID != null) { data.add(true); - data.add(UsernameCache.getLastKnownUsername(ownerUUID)); + data.add(MekanismUtils.getLastKnownUsername(ownerUUID)); } else { data.add(false); diff --git a/src/main/java/mekanism/common/tile/component/TileComponentSecurity.java b/src/main/java/mekanism/common/tile/component/TileComponentSecurity.java index a2af50f493..3bf566b347 100644 --- a/src/main/java/mekanism/common/tile/component/TileComponentSecurity.java +++ b/src/main/java/mekanism/common/tile/component/TileComponentSecurity.java @@ -214,7 +214,7 @@ public class TileComponentSecurity implements ITileComponent { data.add(true); data.add(ownerUUID.toString()); - data.add(UsernameCache.getLastKnownUsername(ownerUUID)); + data.add(MekanismUtils.getLastKnownUsername(ownerUUID)); } else { data.add(false); diff --git a/src/main/java/mekanism/common/util/MekanismUtils.java b/src/main/java/mekanism/common/util/MekanismUtils.java index 15638a322c..ce2b9d4b8b 100644 --- a/src/main/java/mekanism/common/util/MekanismUtils.java +++ b/src/main/java/mekanism/common/util/MekanismUtils.java @@ -1,5 +1,6 @@ package mekanism.common.util; +import com.mojang.authlib.GameProfile; import ic2.api.energy.EnergyNet; import java.io.BufferedReader; @@ -12,6 +13,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.UUID; import mekanism.api.Chunk3D; import mekanism.api.Coord4D; @@ -86,18 +88,22 @@ import net.minecraft.world.ChunkCache; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import net.minecraftforge.common.UsernameCache; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidBlock; +import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import cofh.api.item.IToolHammer; +import javax.annotation.Nonnull; + /** * Utilities used by Mekanism. All miscellaneous methods are located here. * @author AidanBrady @@ -109,6 +115,8 @@ public final class MekanismUtils public static final Map<String, Class<?>> classesFound = new HashMap<String, Class<?>>(); + private static final List<UUID> warnedFails = new ArrayList<>(); + /** * Checks for a new version of Mekanism. */ @@ -1518,6 +1526,23 @@ public final class MekanismUtils return false; } + @Nonnull + public static String getLastKnownUsername(UUID uuid) + { + String ret = UsernameCache.getLastKnownUsername(uuid); + if (ret == null && !warnedFails.contains(uuid) && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER){ // see if MC/Yggdrasil knows about it?! + GameProfile gp = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerProfileCache().getProfileByUUID(uuid); + if (gp != null){ + ret = gp.getName(); + } + } + if (ret == null && !warnedFails.contains(uuid)){ + Mekanism.logger.warn("Failed to retrieve username for UUID {}, you might want to add it to the JSON cache", uuid); + warnedFails.add(uuid); + } + return ret != null ? ret : "<???>"; + } + public static enum ResourceType { GUI("gui"),
    ['src/main/java/mekanism/common/frequency/Frequency.java', 'src/main/java/mekanism/common/entity/EntityRobit.java', 'src/main/java/mekanism/common/tile/TileEntitySecurityDesk.java', 'src/main/java/mekanism/common/content/transporter/TransporterManager.java', 'src/main/java/mekanism/common/tile/component/TileComponentSecurity.java', 'src/main/java/mekanism/common/network/PacketSecurityUpdate.java', 'src/main/java/mekanism/common/util/MekanismUtils.java']
    {'.java': 7}
    7
    7
    0
    0
    7
    4,695,748
    1,235,555
    161,733
    1,283
    2,160
    484
    45
    7
    889
    147
    236
    11
    1
    0
    1970-01-01T00:25:00
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    234
    mekanism/mekanism/4551/4539
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4539
    https://github.com/mekanism/Mekanism/pull/4551
    https://github.com/mekanism/Mekanism/pull/4551
    1
    fixes
    [1.11.2] Placing water in a machine with a forestry tin can or capsule causes a ticking tile entity
    Using a forestry tin can or capsule instead of a bucket in Mekanism machines causes ticking block crash. 1. Place electrolytic separator 2. Put water can in water slot 3. Crash Mekanism 307 Forge 13.20.1.2386 Minecraft 1.11.2 Log: https://paste.ee/p/oxUq9
    b3f1a9fee43e6aec5689664f268fa6dbeebb50b0
    9106ac94a747bf5c59884e470ede5e19cc2a6e24
    https://github.com/mekanism/mekanism/compare/b3f1a9fee43e6aec5689664f268fa6dbeebb50b0...9106ac94a747bf5c59884e470ede5e19cc2a6e24
    diff --git a/src/main/java/mekanism/common/util/FluidContainerUtils.java b/src/main/java/mekanism/common/util/FluidContainerUtils.java index 330829f5f9..37602c11c2 100644 --- a/src/main/java/mekanism/common/util/FluidContainerUtils.java +++ b/src/main/java/mekanism/common/util/FluidContainerUtils.java @@ -13,8 +13,10 @@ import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.items.ItemHandlerHelper; -public final class FluidContainerUtils +public final class FluidContainerUtils { + private FluidContainerUtils(){} + public static boolean isFluidContainer(ItemStack stack) { return !stack.isEmpty() && stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); @@ -27,28 +29,25 @@ public final class FluidContainerUtils public static FluidStack extractFluid(FluidTank tileTank, TileEntityContainerBlock tile, int slotID, FluidChecker checker) { - FluidStack ret = extractFluid(tileTank.getCapacity()-tileTank.getFluidAmount(), tile.inventory.get(slotID), checker); - tile.inventory.set(slotID, FluidUtil.getFluidHandler(tile.inventory.get(slotID)).getContainer()); - return ret; + return extractFluid(tileTank.getCapacity()-tileTank.getFluidAmount(), tile.inventory.get(slotID), checker); } public static FluidStack extractFluid(int needed, ItemStack container, FluidChecker checker) { IFluidHandlerItem handler = FluidUtil.getFluidHandler(container); + FluidStack fluidStack = FluidUtil.getFluidContained(container); - if(handler == null || FluidUtil.getFluidContained(container) == null) + if(handler == null || fluidStack == null) { return null; } - if(checker != null && !checker.isValid(FluidUtil.getFluidContained(container).getFluid())) + if(checker != null && !checker.isValid(fluidStack.getFluid())) { return null; } - FluidStack ret = handler.drain(needed, true); - - return ret; + return handler.drain(needed, true); } public static int insertFluid(FluidTank tileTank, ItemStack container) @@ -60,7 +59,7 @@ public final class FluidContainerUtils { IFluidHandler handler = FluidUtil.getFluidHandler(container); - if(fluid == null) + if(fluid == null || handler == null) { return 0; } @@ -128,8 +127,9 @@ public final class FluidContainerUtils return (checker == null || checker.isValid(f)) && (storedFinal == null || storedFinal == f); } }); - - ItemStack inputCopy = FluidUtil.getFluidHandler(input).getContainer(); + + IFluidHandlerItem iFluidHandlerItem = FluidUtil.getFluidHandler(input); + ItemStack inputCopy = iFluidHandlerItem != null ? iFluidHandlerItem.getContainer() : ItemStack.EMPTY; if(FluidUtil.getFluidContained(inputCopy) == null && !inputCopy.isEmpty()) {
    ['src/main/java/mekanism/common/util/FluidContainerUtils.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    4,691,959
    1,234,542
    161,646
    1,283
    1,237
    280
    24
    1
    269
    39
    80
    12
    1
    0
    1970-01-01T00:25:00
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    233
    mekanism/mekanism/4552/4539
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4539
    https://github.com/mekanism/Mekanism/pull/4552
    https://github.com/mekanism/Mekanism/pull/4552
    1
    fixes
    [1.11.2] Placing water in a machine with a forestry tin can or capsule causes a ticking tile entity
    Using a forestry tin can or capsule instead of a bucket in Mekanism machines causes ticking block crash. 1. Place electrolytic separator 2. Put water can in water slot 3. Crash Mekanism 307 Forge 13.20.1.2386 Minecraft 1.11.2 Log: https://paste.ee/p/oxUq9
    46367a445ed8fc21871f15384f9a0ef0a68133c7
    3815945d1efc4db3a3da7928cc868e1e4d5949a7
    https://github.com/mekanism/mekanism/compare/46367a445ed8fc21871f15384f9a0ef0a68133c7...3815945d1efc4db3a3da7928cc868e1e4d5949a7
    diff --git a/src/main/java/mekanism/common/util/FluidContainerUtils.java b/src/main/java/mekanism/common/util/FluidContainerUtils.java index 330829f5f9..7fa9616a04 100644 --- a/src/main/java/mekanism/common/util/FluidContainerUtils.java +++ b/src/main/java/mekanism/common/util/FluidContainerUtils.java @@ -27,40 +27,46 @@ public final class FluidContainerUtils public static FluidStack extractFluid(FluidTank tileTank, TileEntityContainerBlock tile, int slotID, FluidChecker checker) { - FluidStack ret = extractFluid(tileTank.getCapacity()-tileTank.getFluidAmount(), tile.inventory.get(slotID), checker); - tile.inventory.set(slotID, FluidUtil.getFluidHandler(tile.inventory.get(slotID)).getContainer()); + IFluidHandlerItem handler = FluidUtil.getFluidHandler(tile.inventory.get(slotID)); + FluidStack ret = null; + if (handler != null) + { + ret = extractFluid(tileTank.getCapacity() - tileTank.getFluidAmount(), handler, checker); + tile.inventory.set(slotID, handler.getContainer()); + } return ret; } - public static FluidStack extractFluid(int needed, ItemStack container, FluidChecker checker) + public static FluidStack extractFluid(int needed, IFluidHandlerItem handler, FluidChecker checker) { - IFluidHandlerItem handler = FluidUtil.getFluidHandler(container); - - if(handler == null || FluidUtil.getFluidContained(container) == null) + if (handler == null) { return null; } + + FluidStack fluidStack = handler.drain(Integer.MAX_VALUE, false); - if(checker != null && !checker.isValid(FluidUtil.getFluidContained(container).getFluid())) + if(fluidStack == null) { return null; } - FluidStack ret = handler.drain(needed, true); + if(checker != null && !checker.isValid(fluidStack.getFluid())) + { + return null; + } - return ret; + return handler.drain(needed, true); } public static int insertFluid(FluidTank tileTank, ItemStack container) { - return insertFluid(tileTank.getFluid(), container); + return insertFluid(tileTank.getFluid(), FluidUtil.getFluidHandler(container)); } - public static int insertFluid(FluidStack fluid, ItemStack container) + public static int insertFluid(FluidStack fluid, IFluidHandler handler) { - IFluidHandler handler = FluidUtil.getFluidHandler(container); - - if(fluid == null) + if(fluid == null || handler == null) { return 0; } @@ -79,8 +85,13 @@ public final class FluidContainerUtils { ItemStack inputCopy = StackUtils.size(inventory.get(inSlot).copy(), 1); - int drained = insertFluid(stack, inputCopy); - inputCopy = FluidUtil.getFluidHandler(inputCopy).getContainer(); + IFluidHandlerItem handler = FluidUtil.getFluidHandler(inputCopy); + int drained = 0; + if (handler != null) + { + drained = insertFluid(stack, handler); + inputCopy = handler.getContainer(); + } if(!inventory.get(outSlot).isEmpty() && (!ItemHandlerHelper.canItemStacksStack(inventory.get(outSlot), inputCopy) || inventory.get(outSlot).getCount() == inventory.get(outSlot).getMaxStackSize())) { @@ -120,8 +131,14 @@ public final class FluidContainerUtils { final Fluid storedFinal = stored != null ? stored.getFluid() : null; final ItemStack input = StackUtils.size(inventory.get(inSlot).copy(), 1); + final IFluidHandlerItem handler = FluidUtil.getFluidHandler(input); + + if (handler == null) + { + return stored; + } - FluidStack ret = extractFluid(needed, input, new FluidChecker() { + FluidStack ret = extractFluid(needed, handler, new FluidChecker() { @Override public boolean isValid(Fluid f) { @@ -129,7 +146,7 @@ public final class FluidContainerUtils } }); - ItemStack inputCopy = FluidUtil.getFluidHandler(input).getContainer(); + ItemStack inputCopy = handler.getContainer(); if(FluidUtil.getFluidContained(inputCopy) == null && !inputCopy.isEmpty()) {
    ['src/main/java/mekanism/common/util/FluidContainerUtils.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    4,369,978
    1,164,709
    152,470
    1,050
    2,400
    560
    53
    1
    269
    39
    80
    12
    1
    0
    1970-01-01T00:25:00
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    229
    mekanism/mekanism/4752/4694
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4694
    https://github.com/mekanism/Mekanism/pull/4752
    https://github.com/mekanism/Mekanism/pull/4752
    1
    fixes
    [1.11.2] Logistical Sorter item filtering issue
    #### Issue description: Using the logistical sorter to sort the drops from a mob farm and I've run into an issue when trying to send items like bows ect which are damaged to a different location it will only filter the exact bow that was used to create the filter because it's using the metadata from that item. With a bow filter in place it will send the bow or those with identical metadata to the correct storage but at the same time it also wont send the other bows to the other storage which is currently set to take everything not filtered so the bows will just sit in the original storage. I found a <a href="https://github.com/aidancbrady/Mekanism/issues/992">similar issue from 2014</a> where a subtype check was added but this doesn't seem to be an option in the logistical sorter anymore. #### Steps to reproduce: 1. Place storage. 2. Place logistical sorter pulling from the storage. 3. Place logistical transporters connecting the sorter to two more storage and paint the transporters different colours. 4. Set the sorters default filter to 1 of the colours then create a filter for bows set to the 2nd colour. 5. Add some random items and bows with different metadata to the first storage. 6. The random items will now be in the 2nd storage and any bows with the same metadata as the original will be in the 3rd storage all the remaining bows will still be in the first storage. #### Version (make sure you are on the latest version before reporting): **Forge:** 13.20.1.2454 **Mekanism:** 9.3.4 **Other relevant version:**
    9c7164c0db3877538a6c525700b64d4353d20da5
    6103bc2b119293dd5f15f95a2a3233538aaafff6
    https://github.com/mekanism/mekanism/compare/9c7164c0db3877538a6c525700b64d4353d20da5...6103bc2b119293dd5f15f95a2a3233538aaafff6
    diff --git a/src/main/java/mekanism/common/content/transporter/Finder.java b/src/main/java/mekanism/common/content/transporter/Finder.java index 0d268be899..64c42a809d 100644 --- a/src/main/java/mekanism/common/content/transporter/Finder.java +++ b/src/main/java/mekanism/common/content/transporter/Finder.java @@ -87,7 +87,7 @@ public abstract class Finder @Override public boolean modifies(ItemStack stack) { - return StackUtils.equalsWildcard(itemType, stack); + return itemType.getHasSubtypes() ? StackUtils.equalsWildcard(itemType, stack) : itemType.getItem() == stack.getItem(); } }
    ['src/main/java/mekanism/common/content/transporter/Finder.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    4,100,917
    1,095,234
    142,504
    907
    177
    37
    2
    1
    1,558
    265
    347
    17
    1
    0
    1970-01-01T00:25:07
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    232
    mekanism/mekanism/4562/4560
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4560
    https://github.com/mekanism/Mekanism/pull/4562
    https://github.com/mekanism/Mekanism/pull/4562
    1
    fixes
    [1.11.2] Energy side configuration doesn't respect block orientation
    #### Issue description: Regardless of which way a block is oriented the side configuration for energy always treats the faces as follows: - Front is North - Back is South - Left is West - Right is East - Bottom is Down - Top is Up Also tested with items but this seems to be functioning as expected. #### Steps to reproduce: 1. Face north 2. Place an energy cube / machine / quantum entangloporter 3. Configure the block to accept energy on every side 3. Surround the block with universal energy cables 4. Toggle the energy acceptance for each side on/off and make note of which cables detach 5. Repeat the process facing South, East, West, Up, Down as desired #### Version: **Forge:** 13.20.1.2393 **Mekanism:** 9.3.3.311-fix
    77e46985ac243728b3210edcac2592852149d628
    90cf4cea0849e9937b703789449933c62f87400b
    https://github.com/mekanism/mekanism/compare/77e46985ac243728b3210edcac2592852149d628...90cf4cea0849e9937b703789449933c62f87400b
    diff --git a/src/main/java/mekanism/common/tile/TileEntityFactory.java b/src/main/java/mekanism/common/tile/TileEntityFactory.java index 21c55246dd..5df3f9693f 100644 --- a/src/main/java/mekanism/common/tile/TileEntityFactory.java +++ b/src/main/java/mekanism/common/tile/TileEntityFactory.java @@ -394,6 +394,12 @@ public class TileEntityFactory extends TileEntityMachine implements IComputerInt { return configComponent.getSidesForData(TransmissionType.ENERGY, facing, 1); } + + @Override + public boolean sideIsConsumer(EnumFacing side) + { + return configComponent.hasSideForData(TransmissionType.ENERGY, facing, 1, side); + } public void sortInventory() { diff --git a/src/main/java/mekanism/common/tile/component/TileComponentConfig.java b/src/main/java/mekanism/common/tile/component/TileComponentConfig.java index 682f2dafb7..5e8e65a9b2 100644 --- a/src/main/java/mekanism/common/tile/component/TileComponentConfig.java +++ b/src/main/java/mekanism/common/tile/component/TileComponentConfig.java @@ -70,11 +70,11 @@ public class TileComponentConfig implements ITileComponent SideConfig config = getConfig(type); EnumFacing[] translatedFacings = MekanismUtils.getBaseOrientations(facing); - for(int i = 0; i < EnumFacing.VALUES.length; i++) + for(EnumFacing sideToCheck : EnumFacing.values()) { - if(config.get(translatedFacings[i]) == dataIndex) + if(config.get(translatedFacings[sideToCheck.ordinal()]) == dataIndex) { - ret.add(translatedFacings[i]); + ret.add(sideToCheck); } } @@ -87,8 +87,8 @@ public class TileComponentConfig implements ITileComponent { return false; } - - return getConfig(type).get(sideToTest) == dataIndex; + EnumFacing[] translatedFacings = MekanismUtils.getBaseOrientations(facing); + return getConfig(type).get(translatedFacings[sideToTest.ordinal()]) == dataIndex; } public void setCanEject(TransmissionType type, boolean eject)
    ['src/main/java/mekanism/common/tile/TileEntityFactory.java', 'src/main/java/mekanism/common/tile/component/TileComponentConfig.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    4,388,554
    1,169,528
    153,214
    1,052
    675
    172
    16
    2
    750
    127
    181
    22
    0
    0
    1970-01-01T00:25:00
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    231
    mekanism/mekanism/4567/4560
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4560
    https://github.com/mekanism/Mekanism/pull/4567
    https://github.com/mekanism/Mekanism/pull/4567
    1
    fixes
    [1.11.2] Energy side configuration doesn't respect block orientation
    #### Issue description: Regardless of which way a block is oriented the side configuration for energy always treats the faces as follows: - Front is North - Back is South - Left is West - Right is East - Bottom is Down - Top is Up Also tested with items but this seems to be functioning as expected. #### Steps to reproduce: 1. Face north 2. Place an energy cube / machine / quantum entangloporter 3. Configure the block to accept energy on every side 3. Surround the block with universal energy cables 4. Toggle the energy acceptance for each side on/off and make note of which cables detach 5. Repeat the process facing South, East, West, Up, Down as desired #### Version: **Forge:** 13.20.1.2393 **Mekanism:** 9.3.3.311-fix
    2a535733c1b5a5c38361acf5f3b267ea78efb165
    341e11da7009aa077ff3c2240c504ec586d0a0fd
    https://github.com/mekanism/mekanism/compare/2a535733c1b5a5c38361acf5f3b267ea78efb165...341e11da7009aa077ff3c2240c504ec586d0a0fd
    diff --git a/src/main/java/mekanism/common/tile/TileEntityDigitalMiner.java b/src/main/java/mekanism/common/tile/TileEntityDigitalMiner.java index 7d56ed0a0d..602769200c 100644 --- a/src/main/java/mekanism/common/tile/TileEntityDigitalMiner.java +++ b/src/main/java/mekanism/common/tile/TileEntityDigitalMiner.java @@ -1566,6 +1566,13 @@ public class TileEntityDigitalMiner extends TileEntityElectricBlock implements I return EnumSet.of(MekanismUtils.getLeft(facing), MekanismUtils.getRight(facing), EnumFacing.DOWN); } + @Override + public boolean sideIsConsumer(EnumFacing side) + { + return side == MekanismUtils.getLeft(facing) || side == MekanismUtils.getRight(facing) || side == EnumFacing.DOWN; + } + + @Override public TileComponentSecurity getSecurity() { diff --git a/src/main/java/mekanism/common/tile/TileEntityElectricPump.java b/src/main/java/mekanism/common/tile/TileEntityElectricPump.java index 9ddc607d74..48301963d5 100644 --- a/src/main/java/mekanism/common/tile/TileEntityElectricPump.java +++ b/src/main/java/mekanism/common/tile/TileEntityElectricPump.java @@ -421,6 +421,12 @@ public class TileEntityElectricPump extends TileEntityElectricBlock implements I return EnumSet.of(facing.getOpposite()); } + @Override + public boolean sideIsConsumer(EnumFacing side) + { + return facing.getOpposite() == side; + } + @Override public boolean canSetFacing(int side) { diff --git a/src/main/java/mekanism/common/tile/TileEntityFluidicPlenisher.java b/src/main/java/mekanism/common/tile/TileEntityFluidicPlenisher.java index 41770eb8a5..55b5e7b5d3 100644 --- a/src/main/java/mekanism/common/tile/TileEntityFluidicPlenisher.java +++ b/src/main/java/mekanism/common/tile/TileEntityFluidicPlenisher.java @@ -384,6 +384,12 @@ public class TileEntityFluidicPlenisher extends TileEntityElectricBlock implemen return EnumSet.of(facing.getOpposite()); } + @Override + public boolean sideIsConsumer(EnumFacing side) + { + return facing.getOpposite() == side; + } + @Override public boolean canSetFacing(int side) {
    ['src/main/java/mekanism/common/tile/TileEntityFluidicPlenisher.java', 'src/main/java/mekanism/common/tile/TileEntityDigitalMiner.java', 'src/main/java/mekanism/common/tile/TileEntityElectricPump.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    4,389,887
    1,169,828
    153,244
    1,052
    410
    98
    19
    3
    750
    127
    181
    22
    0
    0
    1970-01-01T00:25:01
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    230
    mekanism/mekanism/4575/4573
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4573
    https://github.com/mekanism/Mekanism/pull/4575
    https://github.com/mekanism/Mekanism/pull/4575
    1
    closes
    [1.10.2] Rotary Condensentrator Bucket issue
    #### Issue description: So when placing a bucket in the Rotary Condensentrator seems to not empty it but in fact gives you infinite liquid see the video below #### Steps to reproduce: https://www.youtube.com/watch?v=ZF6JDSpxur4 #### Version (make sure you are on the latest version before reporting): **Forge:** 12.18.3.2316 **Mekanism:** 9.2.2-final-fix **Other relevant version:** Mod pack tested in https://minecraft.curseforge.com/projects/space-astronomy-2
    cf436ab42392749265a5cc986ce26379eb5b0687
    8d98a98dd8b88302cf9058fe6809311eca6c1b4c
    https://github.com/mekanism/mekanism/compare/cf436ab42392749265a5cc986ce26379eb5b0687...8d98a98dd8b88302cf9058fe6809311eca6c1b4c
    diff --git a/src/main/java/mekanism/common/util/FluidContainerUtils.java b/src/main/java/mekanism/common/util/FluidContainerUtils.java index 35ac06d7b6..bb010342d8 100644 --- a/src/main/java/mekanism/common/util/FluidContainerUtils.java +++ b/src/main/java/mekanism/common/util/FluidContainerUtils.java @@ -123,8 +123,7 @@ public final class FluidContainerUtils public static FluidStack handleContainerItemEmpty(TileEntity tileEntity, ItemStack[] inventory, FluidStack stored, int needed, int inSlot, int outSlot, final FluidChecker checker) { final Fluid storedFinal = stored != null ? stored.getFluid() : null; - final ItemStack input = StackUtils.size(inventory[inSlot].copy(), 1); - + FluidStack ret = extractFluid(needed, inventory, inSlot, new FluidChecker() { @Override public boolean isValid(Fluid f) @@ -132,22 +131,7 @@ public final class FluidContainerUtils return (checker == null || checker.isValid(f)) && (storedFinal == null || storedFinal == f); } }); - - ItemStack inputCopy = input.copy(); - - if(inputCopy.stackSize == 0) - { - inputCopy = null; - } - - if(FluidUtil.getFluidContained(inputCopy) == null && inputCopy != null) - { - if(inventory[outSlot] != null && (!ItemHandlerHelper.canItemStacksStack(inventory[outSlot], inputCopy) || inventory[outSlot].stackSize == inventory[outSlot].getMaxStackSize())) - { - return stored; - } - } - + if(ret != null) { if(stored == null) @@ -157,37 +141,29 @@ public final class FluidContainerUtils else { stored.amount += ret.amount; } - + needed -= ret.amount; - + tileEntity.markDirty(); } - - if(FluidUtil.getFluidContained(inputCopy) == null || needed == 0) + + if(FluidUtil.getFluidContained(inventory[inSlot]) == null || needed == 0) { - if(inputCopy != null) + if (inventory[inSlot].stackSize > 0) { - if(inventory[outSlot] == null) - { - inventory[outSlot] = inputCopy; - } - else if(ItemHandlerHelper.canItemStacksStack(inventory[outSlot], inputCopy)) - { + if (inventory[outSlot] == null) { + inventory[outSlot] = inventory[inSlot].copy(); + inventory[inSlot] = null; + } else if (inventory[outSlot].isItemEqual(inventory[inSlot]) && ItemStack.areItemStackTagsEqual(inventory[inSlot], inventory[outSlot])){ inventory[outSlot].stackSize++; + inventory[inSlot] = null; } - } - - inventory[inSlot].stackSize--; - - if(inventory[inSlot].stackSize == 0) - { + tileEntity.markDirty(); + } else { inventory[inSlot] = null; + + tileEntity.markDirty(); } - - tileEntity.markDirty(); - } - else { - inventory[inSlot] = inputCopy; } return stored;
    ['src/main/java/mekanism/common/util/FluidContainerUtils.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    4,882,339
    1,280,704
    166,896
    1,306
    1,459
    394
    56
    1
    473
    57
    119
    10
    2
    0
    1970-01-01T00:25:01
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    239
    mekanism/mekanism/4426/4425
    mekanism
    mekanism
    https://github.com/mekanism/Mekanism/issues/4425
    https://github.com/mekanism/Mekanism/pull/4426
    https://github.com/mekanism/Mekanism/pull/4426
    1
    fixes
    Thermal Evaporation Plant causes massive lag while entering world
    It is caused by instancing many display lists during recalculation of water model inside the plant. Reproduction: Add one level to fully built and filled plant
    16b6860f94d6c82ac9a40951b920bd478da2485e
    b6d77c595d39bcca24795dbff1d3f1408bdb3d1e
    https://github.com/mekanism/mekanism/compare/16b6860f94d6c82ac9a40951b920bd478da2485e...b6d77c595d39bcca24795dbff1d3f1408bdb3d1e
    diff --git a/src/main/java/mekanism/client/render/RenderResizableCuboid.java b/src/main/java/mekanism/client/render/RenderResizableCuboid.java index db994b3325..b750223eca 100644 --- a/src/main/java/mekanism/client/render/RenderResizableCuboid.java +++ b/src/main/java/mekanism/client/render/RenderResizableCuboid.java @@ -161,7 +161,8 @@ public class RenderResizableCuboid { wr.begin(GL11.GL_QUADS, shadeTypes.vertexFormat); for (EnumFacing face : EnumFacing.values()) { - renderCuboidFace(wr, face, sprites, flips, textureStart, textureSize, size, textureOffset, shadeTypes, formula, faceFormula, world); + if(cube.shouldSideRender(face)) + renderCuboidFace(wr, face, sprites, flips, textureStart, textureSize, size, textureOffset, shadeTypes, formula, faceFormula, world); } tess.draw(); diff --git a/src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java b/src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java index ef8cb2a975..94e4f89d05 100644 --- a/src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java +++ b/src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java @@ -19,25 +19,26 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; +import java.util.Arrays; @SideOnly(Side.CLIENT) public class RenderThermalEvaporationController extends TileEntitySpecialRenderer<TileEntityThermalEvaporationController> { - private static Map<SalinationRenderData, HashMap<Fluid, DisplayInteger[]>> cachedCenterFluids = new HashMap<SalinationRenderData, HashMap<Fluid, DisplayInteger[]>>(); + private static HashMap<Fluid, DisplayInteger[]> cachedCenterFluids = new HashMap<Fluid, DisplayInteger[]>(); + private static final int LEVELS = 16; + private static final int ALL_LEVELS = LEVELS + 2; + private static final int RING_INDEX = ALL_LEVELS-2; + private static final int CONCAVE_INDEX = ALL_LEVELS-1; @Override public void renderTileEntityAt(TileEntityThermalEvaporationController tileEntity, double x, double y, double z, float partialTick, int destroyStage) { if(tileEntity.structured && tileEntity.inputTank.getFluid() != null) { - SalinationRenderData data = new SalinationRenderData(); - - data.height = tileEntity.height-2; - data.side = tileEntity.facing; bindTexture(MekanismRenderer.getBlocksTexture()); - if(data.height >= 1 && tileEntity.inputTank.getCapacity() > 0) + if(tileEntity.height-2 >= 1 && tileEntity.inputTank.getCapacity() > 0) { push(); @@ -45,11 +46,41 @@ public class RenderThermalEvaporationController extends TileEntitySpecialRendere MekanismRenderer.glowOn(tileEntity.inputTank.getFluid().getFluid().getLuminosity()); - DisplayInteger[] displayList = getListAndRender(data, tileEntity.inputTank.getFluid().getFluid()); + DisplayInteger[] displayList = getListAndRender(tileEntity.inputTank.getFluid().getFluid()); + + float levels = Math.min(((float)tileEntity.inputTank.getFluidAmount()/tileEntity.inputTank.getCapacity()), 1); + + levels *= (tileEntity.height-2); - float tankFillPercentage = Math.min(((float)tileEntity.inputTank.getFluidAmount()/tileEntity.inputTank.getCapacity()), 1); + int partialLevels = (int)((levels-(int)levels)*16); + + switch (tileEntity.facing) + { + case SOUTH: + GlStateManager.translate(-1, 0, -1); + break; + case EAST: + GlStateManager.translate(-1, 0, 0); + break; + case WEST: + GlStateManager.translate(0, 0, -1); + break; + } - displayList[(int)(tankFillPercentage * ((float)getStages(data.height)-1))].render(); + GlStateManager.translate(0, 0.01, 0); + + if((int)levels>0) + { + displayList[CONCAVE_INDEX].render(); + GlStateManager.translate(0, 1, 0); + + for (int i = 1; i < (int)levels; i++) + { + displayList[RING_INDEX].render(); + GlStateManager.translate(0, 1, 0); + } + } + displayList[partialLevels].render(); MekanismRenderer.glowOff(); @@ -74,118 +105,66 @@ public class RenderThermalEvaporationController extends TileEntitySpecialRendere GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } - @SuppressWarnings("incomplete-switch") - private DisplayInteger[] getListAndRender(SalinationRenderData data, Fluid fluid) + + private DisplayInteger[] getListAndRender(Fluid fluid) { - if(cachedCenterFluids.containsKey(data) && cachedCenterFluids.get(data).containsKey(fluid)) + if(cachedCenterFluids.containsKey(fluid)) { - return cachedCenterFluids.get(data).get(fluid); + return cachedCenterFluids.get(fluid); } - Model3D toReturn = new Model3D(); - toReturn.baseBlock = Blocks.WATER; - toReturn.setTexture(MekanismRenderer.getFluidTexture(fluid, FluidType.STILL)); + DisplayInteger[] displays = new DisplayInteger[ALL_LEVELS]; - final int stages = getStages(data.height); - DisplayInteger[] displays = new DisplayInteger[stages]; - - if(cachedCenterFluids.containsKey(data)) - { - cachedCenterFluids.get(data).put(fluid, displays); - } - else { - HashMap<Fluid, DisplayInteger[]> map = new HashMap<Fluid, DisplayInteger[]>(); - map.put(fluid, displays); - cachedCenterFluids.put(data, map); - } + Model3D model = new Model3D(); + model.baseBlock = fluid.getBlock(); + model.setTexture(MekanismRenderer.getFluidTexture(fluid, FluidType.STILL)); MekanismRenderer.colorFluid(fluid); - for(int i = 0; i < stages; i++) + if(fluid.getStill() == null) { - displays[i] = DisplayInteger.createAndStart(); - - if(fluid.getStill() != null) + DisplayInteger empty = DisplayInteger.createAndStart(); + DisplayInteger.endList(); + Arrays.fill(displays, 0, LEVELS, empty); + } + else + { + model.setSideRender(EnumFacing.DOWN, false); + for (int i = 0; i < LEVELS; i++) { - switch(data.side) - { - case NORTH: - toReturn.minX = 0 + .01; - toReturn.minY = 0 + .01; - toReturn.minZ = 0 + .01; - - toReturn.maxX = 2 - .01; - toReturn.maxY = ((float)i/(float)stages)*data.height - .01; - toReturn.maxZ = 2 - .01; - break; - case SOUTH: - toReturn.minX = -1 + .01; - toReturn.minY = 0 + .01; - toReturn.minZ = -1 + .01; - - toReturn.maxX = 1 - .01; - toReturn.maxY = ((float)i/(float)stages)*data.height - .01; - toReturn.maxZ = 1 - .01; - break; - case WEST: - toReturn.minX = 0 + .01; - toReturn.minY = 0 + .01; - toReturn.minZ = -1 + .01; - - toReturn.maxX = 2 - .01; - toReturn.maxY = ((float)i/(float)stages)*data.height - .01; - toReturn.maxZ = 1 - .01; - break; - case EAST: - toReturn.minX = -1 + .01; - toReturn.minY = 0 + .01; - toReturn.minZ = 0 + .01; - - toReturn.maxX = 1 - .01; - toReturn.maxY = ((float)i/(float)stages)*data.height - .01; - toReturn.maxZ = 2 - .01; - break; - } - - MekanismRenderer.renderObject(toReturn); + displays[i] = generateLevel(i, model); } - - displays[i].endList(); + model.setSideRender(EnumFacing.UP, false); + displays[RING_INDEX] = generateLevel(LEVELS-1, model); + model.setSideRender(EnumFacing.DOWN, true); + displays[CONCAVE_INDEX] = generateLevel(LEVELS-1, model); } MekanismRenderer.resetColor(); - + cachedCenterFluids.put(fluid, displays); return displays; } - private int getStages(int height) + private DisplayInteger generateLevel(int height, Model3D model) { - return height*(TankUpdateProtocol.FLUID_PER_TANK/10); - } + DisplayInteger displayInteger = DisplayInteger.createAndStart(); - public static class SalinationRenderData - { - public int height; - public EnumFacing side; + model.minX = 0 + .01; + model.minY = 0; + model.minZ = 0 + .01; + model.maxX = 2 - .01; + model.maxY = (float)height/(float)(LEVELS-1) + (height==0?.02:0); + model.maxZ = 2 - .01; - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + height; - return code; - } + MekanismRenderer.renderObject(model); + DisplayInteger.endList(); - @Override - public boolean equals(Object data) - { - return data instanceof SalinationRenderData && ((SalinationRenderData)data).height == height && - ((SalinationRenderData)data).side == side; - } + return displayInteger; } public static void resetDisplayInts() { cachedCenterFluids.clear(); } -} + +} \\ No newline at end of file
    ['src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java', 'src/main/java/mekanism/client/render/RenderResizableCuboid.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    4,692,558
    1,234,831
    161,686
    1,285
    6,360
    1,744
    176
    2
    162
    26
    32
    3
    0
    0
    1970-01-01T00:24:56
    1,137
    Java
    {'Java': 10634221, 'ZenScript': 66932, 'Groovy': 7193, 'Perl': 4725, 'GLSL': 4576, 'JavaScript': 1156, 'Python': 511}
    MIT License
    262
    slimeknights/tinkersconstruct/1584/1561
    slimeknights
    tinkersconstruct
    https://github.com/SlimeKnights/TinkersConstruct/issues/1561
    https://github.com/SlimeKnights/TinkersConstruct/pull/1584
    https://github.com/SlimeKnights/TinkersConstruct/pull/1584
    1
    fixes
    Drying rack mirrors items horizontally if placed while facing north or west
    http://i.imgur.com/6i51sRL.png Signs in the picture label which direction the player is facing. Also possibly worth noting: as evident in the pictures, they're not properly centered on the rack. This has been a problem as long as I can remember, frankly I'm surprised I can't find anything mentioning it.
    9f0349c66b264e858d23665aebd4fdc99108dcaa
    dfed1dd9f44505522d464622b204bb45aec4d0f6
    https://github.com/slimeknights/tinkersconstruct/compare/9f0349c66b264e858d23665aebd4fdc99108dcaa...dfed1dd9f44505522d464622b204bb45aec4d0f6
    diff --git a/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java b/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java index 23f46f3de..ee94797ba 100644 --- a/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java +++ b/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java @@ -55,11 +55,23 @@ public class DryingRackSpecialRender extends TileEntitySpecialRenderer if (meta == 2) GL11.glTranslatef(0F, 0F, 0.375F); if (meta == 3) - GL11.glTranslatef(0F, 0F, -0.375F); + { + // Rotate, Flip. + GL11.glRotatef(180F, 0F, 1F, 0F); + GL11.glTranslatef(0F, 0F, 0.2F); + //GL11.glTranslatef(0F, 0F, -0.375F); + } if (meta == 4) + { GL11.glTranslatef(0F, 0F, 0.2875F); + } if (meta == 5) - GL11.glTranslatef(0F, 0F, -0.5F); + { + //Rotate, Flip. + GL11.glRotatef(180F, 0F, 1F, 0F); + GL11.glTranslatef(0F, 0F, 0.3F); + //GL11.glTranslatef(0F, 0F, -0.5F); + } } GL11.glScalef(2F, 2F, 2F); if (stack.getItem() instanceof ItemBlock)
    ['src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    2,803,930
    682,154
    78,537
    600
    549
    187
    16
    1
    307
    48
    70
    7
    1
    0
    1970-01-01T00:23:50
    1,133
    Java
    {'Java': 5527226, 'ZenScript': 28851}
    MIT License
    3,338
    stripe/stripe-android/57/55
    stripe
    stripe-android
    https://github.com/stripe/stripe-android/issues/55
    https://github.com/stripe/stripe-android/pull/57
    https://github.com/stripe/stripe-android/pull/57
    2
    fixes
    Duplicate card number prefix
    Just wondering if there was a mistake on this line https://github.com/stripe/stripe-android/blob/master/stripe/src/main/java/com/stripe/android/model/Card.java#L19 or why is it that you are including `37` as a `Diners Club` prefix if according to your source page https://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 it clearly exclude `37`
    f3366f28b0842f398984d6858d21a732ba0e7193
    1d90219e20bf60db6c26ccf4455a0b0a5fffc410
    https://github.com/stripe/stripe-android/compare/f3366f28b0842f398984d6858d21a732ba0e7193...1d90219e20bf60db6c26ccf4455a0b0a5fffc410
    diff --git a/stripe/src/main/java/com/stripe/android/model/Card.java b/stripe/src/main/java/com/stripe/android/model/Card.java index 8bd357522e..395aa01d83 100644 --- a/stripe/src/main/java/com/stripe/android/model/Card.java +++ b/stripe/src/main/java/com/stripe/android/model/Card.java @@ -16,7 +16,7 @@ public class Card extends com.stripe.model.StripeObject { public static final String[] PREFIXES_AMERICAN_EXPRESS = {"34", "37"}; public static final String[] PREFIXES_DISCOVER = {"60", "62", "64", "65"}; public static final String[] PREFIXES_JCB = {"35"}; - public static final String[] PREFIXES_DINERS_CLUB = {"300", "301", "302", "303", "304", "305", "309", "36", "38", "37", "39"}; + public static final String[] PREFIXES_DINERS_CLUB = {"300", "301", "302", "303", "304", "305", "309", "36", "38", "39"}; public static final String[] PREFIXES_VISA = {"4"}; public static final String[] PREFIXES_MASTERCARD = {"50", "51", "52", "53", "54", "55"};
    ['stripe/src/main/java/com/stripe/android/model/Card.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    60,816
    12,635
    1,735
    16
    257
    91
    2
    1
    375
    36
    90
    4
    2
    0
    1970-01-01T00:24:13
    1,115
    Kotlin
    {'Kotlin': 9267111, 'Java': 69683, 'Shell': 18879, 'Python': 13927, 'Ruby': 7073}
    MIT License
    94
    tony19/logback-android/221/213
    tony19
    logback-android
    https://github.com/tony19/logback-android/issues/213
    https://github.com/tony19/logback-android/pull/221
    https://github.com/tony19/logback-android/pull/221
    1
    fixes
    Daily rollover uses UTC instead of local time
    ## Description I configured daily rollover with TimeBasedRollingPolicy, according to example in [wiki](https://github.com/tony19/logback-android/wiki/Appender-Notes#configuration-in-code). It generally works, but rollover happens at UTC midnight, not local midnight. This may be confusing. I know it's possible to specify time zone explicitly, but I suppose local time should be used by default, like it was in older versions (e.g. 1.1.1). Maybe the same issue was reported at #198. ## Steps to reproduce 1. Checkout [sample project](https://github.com/gmk57/TestLogback) 1. Configure GMT+3 time zone on device or emulator 1. Leave app running overnight 1. log.txt contains events since 3:00, not 0:00 ## Environment * **`logback-android` version:** 2.0.0 * **Android version:** 5.1, 6.0 * **Platform:** devices, emulator
    8386981b046084492df784bca739db2598db3107
    e40e9fa4c1518038e066f4a246a4f6a539bfaed0
    https://github.com/tony19/logback-android/compare/8386981b046084492df784bca739db2598db3107...e40e9fa4c1518038e066f4a246a4f6a539bfaed0
    diff --git a/logback-android/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java b/logback-android/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java index 2d461e535..d94336e94 100644 --- a/logback-android/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java +++ b/logback-android/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java @@ -72,7 +72,9 @@ public class RollingCalendar extends GregorianCalendar { } public RollingCalendar(String datePattern) { - this(datePattern, GMT_TIMEZONE, Locale.US); + super(); + this.datePattern = datePattern; + this.periodicityType = computePeriodicityType(); } public RollingCalendar(String datePattern, TimeZone tz, Locale locale) { diff --git a/logback-android/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java b/logback-android/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java index 42578f15d..4ac32b39e 100644 --- a/logback-android/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java +++ b/logback-android/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java @@ -90,7 +90,7 @@ public class RollingCalendarTest { } private Calendar getEndOfNextNthPeriod(String dateFormat, Date date, int n) { - RollingCalendar rc = new RollingCalendar(dateFormat); + RollingCalendar rc = new RollingCalendar(dateFormat, GMT_TIMEZONE, Locale.US); Date nextDate = rc.getEndOfNextNthPeriod(date, n); Calendar cal = Calendar.getInstance(GMT_TIMEZONE, Locale.US); cal.setTime(nextDate); @@ -242,4 +242,4 @@ public class RollingCalendarTest { assertFalse(rc.isCollisionFree()); } } -} \\ No newline at end of file +}
    ['logback-android/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java', 'logback-android/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,282,267
    294,498
    42,373
    422
    153
    34
    4
    1
    845
    109
    216
    19
    2
    0
    1970-01-01T00:26:40
    1,110
    Java
    {'Java': 2511833, 'TypeScript': 19668, 'Shell': 8371, 'HTML': 6656, 'Roff': 482}
    Apache License 2.0
    498
    appium/java-client/313/311
    appium
    java-client
    https://github.com/appium/java-client/issues/311
    https://github.com/appium/java-client/pull/313
    https://github.com/appium/java-client/pull/313#issuecomment-180294535
    1
    resolve
    Update page object features. Server node 1.5.x
    These things should be done: - mark _name_ parameter _Decrecated_ as _By.name_ selector is not supported by native app automation - _By.id_ selector should be used by default (native content) when not any selector strategy defined. - _org.openqa.selenium.InvalidSelectorException_ should be handled.
    138e2e8071c9346aeda51f995d506066b3b6ba41
    c823138cf5f6605f834bfb33f5a1b5b11227b8f5
    https://github.com/appium/java-client/compare/138e2e8071c9346aeda51f995d506066b3b6ba41...c823138cf5f6605f834bfb33f5a1b5b11227b8f5
    diff --git a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java index 1dd3e485..5569fe83 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java @@ -35,7 +35,11 @@ public @interface AndroidFindBy { String uiAutomator() default ""; String accessibility() default ""; String id() default ""; - String name() default ""; + @Deprecated + /** + * By.name selector is not supported by Appium server node since 1.5.x. + * So this option is going to be removed further. Be careful. + */String name() default ""; String className() default ""; String tagName() default ""; String xpath() default ""; diff --git a/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java b/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java index b7c71fe9..bcfb18bf 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java +++ b/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java @@ -16,6 +16,7 @@ package io.appium.java_client.pagefactory; +import org.openqa.selenium.InvalidSelectorException; import org.openqa.selenium.StaleElementReferenceException; import java.lang.reflect.InvocationTargetException; @@ -28,7 +29,11 @@ class ThrowableUtil { return false; } - if (String.valueOf(e.getMessage()).contains(INVALID_SELECTOR_PATTERN)) { + if (InvalidSelectorException.class.isAssignableFrom(e.getClass())) { + return true; + } + + if (String.valueOf(e.getMessage()).contains(INVALID_SELECTOR_PATTERN) || String.valueOf(e.getMessage()).contains("Locator Strategy \\\\w+ is not supported")) { return true; } diff --git a/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java b/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java index b666df94..6f38ed2a 100644 --- a/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java @@ -35,7 +35,11 @@ public @interface iOSFindBy { String uiAutomator() default ""; String accessibility() default ""; String id() default ""; - String name() default ""; + @Deprecated + /** + * By.name selector is not supported by Appium server node since 1.5.x. + * So this option is going to be removed further. Be careful. + */String name() default ""; String className() default ""; String tagName() default ""; String xpath() default ""; diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java index b3129e67..fd15db3f 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java @@ -17,6 +17,7 @@ package io.appium.java_client.pagefactory_tests; import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.*; import io.appium.java_client.remote.AutomationName; import io.appium.java_client.remote.MobileCapabilityType; @@ -37,7 +38,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class SelendroidModeTest { - private static int SELENDROID_PORT = 9999; + private static int SELENDROID_PORT = 9999; private static WebDriver driver; private static AppiumDriverLocalService service; @@ -63,15 +64,15 @@ public class SelendroidModeTest { private WebElement textXpath; @SelendroidFindBys({ - @SelendroidFindBy(id = "text1")}) + @SelendroidFindBy(id = "text1")}) private WebElement textIds; @SelendroidFindAll({ - @SelendroidFindBy(id = "text1")}) + @SelendroidFindBy(id = "text1")}) private WebElement textAll; @SelendroidFindAll({ - @SelendroidFindBy(id = "text1")}) + @SelendroidFindBy(id = "text1")}) private List<WebElement> textsAll; @SelendroidFindBy(className = "android.widget.TextView") @@ -79,14 +80,14 @@ public class SelendroidModeTest { @SelendroidFindBy(tagName = "TextView") private WebElement textTag; - + @SelendroidFindBy(linkText = "Accessibility") private WebElement textLink; - + @SelendroidFindBy(partialLinkText = "ccessibilit") private WebElement textPartialLink; - @BeforeClass + @BeforeClass public static void beforeClass() throws Exception { AppiumServiceBuilder builder = new AppiumServiceBuilder().withArgument(GeneralServerFlag.AUTOMATION_NAME, AutomationName.SELENDROID); service = builder.build(); @@ -123,8 +124,8 @@ public class SelendroidModeTest { public void findByIdElementTest() { assertNotEquals(null, textId.getAttribute("text")); } - - @Test + + @Test public void findBySelendroidSelectorTest() { assertNotEquals(null, textSelendroidId.getAttribute("text")); } @@ -173,15 +174,15 @@ public class SelendroidModeTest { public void findByElementByTagTest() { assertNotEquals(null, textTag.getAttribute("text")); } - + @Test public void findBySelendroidAnnotationOnlyTest() { assertNotEquals(null, textSelendroidId.getAttribute("text")); } - + @Test public void findBySelendroidLinkTextTest() { assertEquals("Accessibility", textLink.getText()); } -} +} \\ No newline at end of file diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java index ac7c04d1..ce83f338 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java @@ -37,9 +37,9 @@ import java.util.List; public class iOSPageObjectTest { - private static WebDriver driver; - private static AppiumDriverLocalService service; - private boolean populated = false; + private static WebDriver driver; + private static AppiumDriverLocalService service; + private boolean populated = false; @FindBy(className = "UIAButton") private List<WebElement> uiButtons; @@ -67,9 +67,9 @@ public class iOSPageObjectTest { private List<RemoteWebElement> remoteElementViews; @AndroidFindBys({ - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), + @AndroidFindBy(className = "android.widget.TextView") + }) private List<WebElement> chainElementViews; @@ -92,11 +92,11 @@ public class iOSPageObjectTest { @iOSFindBy(uiAutomator = ".elements()[0]") private MobileElement mobileButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private TouchableElement touchableButton; + @iOSFindBy(uiAutomator = ".elements()[0]") + private TouchableElement touchableButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List<TouchableElement> touchableButtons; + @iOSFindBy(uiAutomator = ".elements()[0]") + private List<TouchableElement> touchableButtons; @FindBy(className = "UIAButton") private MobileElement mobiletFindBy_Button; @@ -105,69 +105,70 @@ public class iOSPageObjectTest { private RemoteWebElement remotetextVieW; @AndroidFindBys({ - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), + @AndroidFindBy(className = "android.widget.TextView") + }) private WebElement chainElementView; - + @iOSFindBy(uiAutomator = ".elements()[0]") private IOSElement iosButton; - + @iOSFindBy(uiAutomator = ".elements()[0]") private List<IOSElement> iosButtons; - + @iOSFindAll({ - @iOSFindBy(xpath = "ComputeSumButton_Test"), - @iOSFindBy(name = "ComputeSumButton") //it is real locator + @iOSFindBy(xpath = "ComputeSumButton_Test"), + @iOSFindBy(name = "ComputeSumButton") //it is real locator }) private WebElement findAllElement; - + @iOSFindAll({ - @iOSFindBy(xpath = "ComputeSumButton_Test"), - @iOSFindBy(name = "ComputeSumButton") //it is real locator + @iOSFindBy(xpath = "ComputeSumButton_Test"), + @iOSFindBy(name = "ComputeSumButton") //it is real locator }) private List<WebElement> findAllElements; - @AndroidFindBy(className = "android.widget.TextView") - @FindBy(css = "e.e1.e2") - private List<WebElement> elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - - @AndroidFindBy(className = "android.widget.TextView") - @FindBy(css = "e.e1.e2") - private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - - - @BeforeClass - public static void beforeClass() throws Exception { - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); + @AndroidFindBy(className = "android.widget.TextView") + @FindBy(css = "e.e1.e2") + private List<WebElement> elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "TestApp.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver<>(service.getUrl(), capabilities); - } + @AndroidFindBy(className = "android.widget.TextView") + @FindBy(css = "e.e1.e2") + private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; + + + @BeforeClass + public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "TestApp.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } + @SuppressWarnings("rawtypes") @Before public void setUp() throws Exception { - if (!populated) - PageFactory.initElements(new AppiumFieldDecorator(driver), this); + if (!populated) + PageFactory.initElements(new AppiumFieldDecorator(driver), this); - populated = true; + populated = true; } - @AfterClass - public static void afterClass() throws Exception { - if (driver != null) - driver.quit(); + @AfterClass + public static void afterClass() throws Exception { + if (driver != null) + driver.quit(); - if (service != null) - service.stop(); - } + if (service != null) + service.stop(); + } @Test public void findByElementsTest() { @@ -273,7 +274,7 @@ public class iOSPageObjectTest { } Assert.assertNotNull(nsee); } - + @Test public void isIOSElementTest(){ Assert.assertNotEquals(null, iosButton.getText()); @@ -294,38 +295,38 @@ public class iOSPageObjectTest { Assert.assertNotEquals(null, findAllElement.getText()); } - @Test - public void isTouchAbleElement(){ - Assert.assertNotEquals(null, touchableButton.getText()); - } + @Test + public void isTouchAbleElement(){ + Assert.assertNotEquals(null, touchableButton.getText()); + } - @Test - public void areTouchAbleElements(){ - Assert.assertNotEquals(0, touchableButtons.size()); - } + @Test + public void areTouchAbleElements(){ + Assert.assertNotEquals(0, touchableButtons.size()); + } - @Test - @SuppressWarnings("unused") - public void isTheFieldIOSElement(){ + @Test + public void isTheFieldIOSElement(){ + @SuppressWarnings("unused") IOSElement iOSElement = (IOSElement) mobileButton; //declared as MobileElement - iOSElement = (IOSElement) iosUIAutomatorButton; //declared as WebElement - iOSElement = (IOSElement) remotetextVieW; //declared as RemoteWebElement - iOSElement = (IOSElement) touchableButton; //declared as TouchABLEElement - } - - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy(){ - try { - Assert.assertNotEquals(null, elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); - } - catch (NoSuchElementException ignored){ - return; - } - throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); - } - - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List(){ - Assert.assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); - } -} + iOSElement = (IOSElement) iosUIAutomatorButton; //declared as WebElement + iOSElement = (IOSElement) remotetextVieW; //declared as RemoteWebElement + iOSElement = (IOSElement) touchableButton; //declared as TouchABLEElement + } + + @Test + public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy(){ + try { + Assert.assertNotEquals(null, elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); + } + catch (NoSuchElementException ignored){ + return; + } + throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); + } + + @Test + public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List(){ + Assert.assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); + } +} \\ No newline at end of file
    ['src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java', 'src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java', 'src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java', 'src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java', 'src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java']
    {'.java': 5}
    5
    5
    0
    0
    5
    354,320
    76,767
    10,144
    108
    851
    180
    19
    3
    301
    41
    66
    5
    0
    0
    1970-01-01T00:24:14
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    500
    appium/java-client/769/764
    appium
    java-client
    https://github.com/appium/java-client/issues/764
    https://github.com/appium/java-client/pull/769
    https://github.com/appium/java-client/pull/769
    1
    fix
    Client asking to many times for session
    ## Description I'm seeing the java client asking for getSession too many times, probably like 5,6 times between commands, making the test to run slower. This make a big difference when running on a testing cloud since this calls are adding ~4 seconds between commands in the test. ## Environment This is a problem with the client itself. * java client build version or git revision if you use some shapshot: 5.0.4 (havent tried another version) * Appium server version or git revision if you use some shapshot: Any * Desktop OS/version used to run Appium if necessary: Any * Node.js version (unless using Appium.app|exe) or Appium CLI or Appium.app|exe: Any * Mobile platform/version under test: Any * Real device or emulator/simulator: Any ## Details ## Code To Reproduce Issue [ Good To Have ] Running a simple test using the java client, during logs we can see all the getSession commands. For ex. ``` INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, findElements {using=id, value=com.test.app:id/text1}] Nov 09, 2017 5:39:45 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:45 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:45 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:46 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:47 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:47 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:47 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:47 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:47 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:47 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:48 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:49 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:49 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:49 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:49 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:49 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:49 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getSession [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:50 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getSession {}] Nov 09, 2017 5:39:50 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executing: getElementText [f8b4312dda7c43bfba2620ef50605eec, getElementText {id=5201}] Nov 09, 2017 5:39:50 PM org.openqa.selenium.remote.RemoteWebDriver log INFO: Executed: [f8b4312dda7c43bfba2620ef50605eec, getElementText {id=5201}] ``` ## Ecxeption stacktraces No errors. ## Link to Appium logs
    5dab23d599ac04bd4550c0b2cda68e110551d7c4
    d10f5d1df3482ce8049cca115444aa0a2b191633
    https://github.com/appium/java-client/compare/5dab23d599ac04bd4550c0b2cda68e110551d7c4...d10f5d1df3482ce8049cca115444aa0a2b191633
    diff --git a/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java b/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java index 23e188b2..6376a265 100644 --- a/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java +++ b/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java @@ -153,7 +153,7 @@ abstract class DefaultGenericMobileDriver<T extends WebElement> extends RemoteWe @Override public String toString() { - return String.format("%s: %s", getPlatformName(), - getAutomationName()); + return String.format("%s, Capabilities: %s", getClass().getCanonicalName(), + getCapabilities().asMap().toString()); } } diff --git a/src/main/java/io/appium/java_client/internal/ElementMap.java b/src/main/java/io/appium/java_client/internal/ElementMap.java index 1d150ae9..65ff376e 100644 --- a/src/main/java/io/appium/java_client/internal/ElementMap.java +++ b/src/main/java/io/appium/java_client/internal/ElementMap.java @@ -16,9 +16,10 @@ package io.appium.java_client.internal; +import static org.apache.commons.lang3.StringUtils.isBlank; + import com.google.common.collect.ImmutableMap; -import io.appium.java_client.HasSessionDetails; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.ios.IOSElement; @@ -68,17 +69,19 @@ public enum ElementMap { } /** - * @param hasSessionDetails something that implements {@link io.appium.java_client.HasSessionDetails}. - * @return subclass of {@link io.appium.java_client.MobileElement} that convenient to current session details. + * @param platform is the mobile platform. See {@link MobilePlatform}. + * @param automation is the mobile automation type. See {@link AutomationName} + * @return subclass of {@link org.openqa.selenium.remote.RemoteWebElement} that convenient + * to current session details. */ - public static Class<? extends RemoteWebElement> getElementClass(HasSessionDetails hasSessionDetails) { - if (hasSessionDetails == null) { + public static Class<? extends RemoteWebElement> getElementClass(String platform, String automation) { + if (isBlank(platform) && isBlank(automation)) { return RemoteWebElement.class; } - ElementMap element = Optional.ofNullable(mobileElementMap.get(String - .valueOf(hasSessionDetails.getAutomationName()).toLowerCase().trim())) + ElementMap element = Optional.ofNullable(mobileElementMap.get( + String.valueOf(platform).toLowerCase().trim())) .orElseGet(() -> mobileElementMap - .get(String.valueOf(hasSessionDetails.getPlatformName()).toLowerCase().trim())); + .get(String.valueOf(automation).toLowerCase().trim())); if (element == null) { return RemoteWebElement.class; } diff --git a/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java b/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java index 923910e7..5d752f64 100644 --- a/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java +++ b/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java @@ -37,7 +37,10 @@ import java.util.Collection; public class JsonToMobileElementConverter extends JsonToWebElementConverter { protected final RemoteWebDriver driver; - private final HasSessionDetails hasSessionDetails; + + private final String platform; + private final String automation; + /** * @param driver an instance of {@link org.openqa.selenium.remote.RemoteWebDriver} subclass @@ -46,7 +49,8 @@ public class JsonToMobileElementConverter extends JsonToWebElementConverter { public JsonToMobileElementConverter(RemoteWebDriver driver, HasSessionDetails hasSessionDetails) { super(driver); this.driver = driver; - this.hasSessionDetails = hasSessionDetails; + this.platform = hasSessionDetails.getPlatformName(); + this.automation = hasSessionDetails.getAutomationName(); } /** @@ -80,9 +84,9 @@ public class JsonToMobileElementConverter extends JsonToWebElementConverter { return result; } - protected RemoteWebElement newMobileElement() { + private RemoteWebElement newMobileElement() { Class<? extends RemoteWebElement> target; - target = getElementClass(hasSessionDetails); + target = getElementClass(platform, automation); try { Constructor<? extends RemoteWebElement> constructor = target.getDeclaredConstructor(); constructor.setAccessible(true); diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java index a08ffc31..a7acc71a 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java @@ -19,8 +19,11 @@ package io.appium.java_client.pagefactory; import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; import static io.appium.java_client.pagefactory.ThrowableUtil.isInvalidSelectorRootCause; import static io.appium.java_client.pagefactory.ThrowableUtil.isStaleElementReferenceException; +import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; +import static java.lang.String.format; +import io.appium.java_client.pagefactory.bys.ContentMappedBy; import io.appium.java_client.pagefactory.locator.CacheableLocator; import org.openqa.selenium.By; @@ -39,13 +42,15 @@ import java.util.function.Supplier; class AppiumElementLocator implements CacheableLocator { + private static final String exceptionMessageIfElementNotFound = "Can't locate an element by this strategy: %s"; + private final boolean shouldCache; private final By by; private final TimeOutDuration duration; private final SearchContext searchContext; private WebElement cachedElement; private List<WebElement> cachedElementList; - private final String exceptionMessageIfElementNotFound; + /** * Creates a new mobile element locator. It instantiates {@link WebElement} * using @AndroidFindBy (-s), @iOSFindBy (-s) and @FindBy (-s) annotation @@ -64,7 +69,25 @@ class AppiumElementLocator implements CacheableLocator { this.shouldCache = shouldCache; this.duration = duration; this.by = by; - this.exceptionMessageIfElementNotFound = "Can't locate an element by this strategy: " + by.toString(); + } + + /** + * This methods makes sets some settings of the {@link By} according to + * the given instance of {@link SearchContext}. If there is some {@link ContentMappedBy} + * then it is switched to the searching for some html or native mobile element. + * Otherwise nothing happens there. + * + * @param currentBy is some locator strategy + * @param currentContent is an instance of some subclass of the {@link SearchContext}. + * @return the corrected {@link By} for the further searching + */ + private static By getBy(By currentBy, SearchContext currentContent) { + if (!ContentMappedBy.class.isAssignableFrom(currentBy.getClass())) { + return currentBy; + } + + return ContentMappedBy.class.cast(currentBy) + .useContent(getCurrentContentType(currentContent)); } private <T> T waitFor(Supplier<T> supplier) { @@ -91,15 +114,16 @@ class AppiumElementLocator implements CacheableLocator { return cachedElement; } + By bySearching = getBy(this.by, searchContext); try { WebElement result = waitFor(() -> - searchContext.findElement(by)); + searchContext.findElement(bySearching)); if (shouldCache) { cachedElement = result; } return result; } catch (TimeoutException | StaleElementReferenceException e) { - throw new NoSuchElementException(exceptionMessageIfElementNotFound, e); + throw new NoSuchElementException(format(exceptionMessageIfElementNotFound, bySearching.toString()), e); } } @@ -114,11 +138,9 @@ class AppiumElementLocator implements CacheableLocator { List<WebElement> result; try { result = waitFor(() -> { - List<WebElement> list = searchContext.findElements(by); - if (list.size() > 0) { - return list; - } - return null; + List<WebElement> list = searchContext + .findElements(getBy(by, searchContext)); + return list.size() > 0 ? list : null; }); } catch (TimeoutException | StaleElementReferenceException e) { result = new ArrayList<>(); @@ -135,7 +157,7 @@ class AppiumElementLocator implements CacheableLocator { } @Override public String toString() { - return String.format("Located by %s", by); + return format("Located by %s", by); } diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java index 9753736e..9d189d31 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java @@ -20,6 +20,7 @@ import static io.appium.java_client.internal.ElementMap.getElementClass; import static io.appium.java_client.pagefactory.utils.ProxyFactory.getEnhancedProxy; import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility .unpackWebDriverFromSearchContext; +import static java.util.Optional.ofNullable; import com.google.common.collect.ImmutableList; @@ -64,13 +65,12 @@ public class AppiumFieldDecorator implements FieldDecorator { IOSElement.class, WindowsElement.class); public static long DEFAULT_TIMEOUT = 1; public static TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS; - private final WebDriver originalDriver; + private final WebDriver webDriver; private final DefaultFieldDecorator defaultElementFieldDecoracor; private final AppiumElementLocatorFactory widgetLocatorFactory; private final String platform; private final String automation; private final TimeOutDuration duration; - private final HasSessionDetails hasSessionDetails; public AppiumFieldDecorator(SearchContext context, long timeout, @@ -87,14 +87,18 @@ public class AppiumFieldDecorator implements FieldDecorator { * @param duration is a desired duration of the waiting for an element presence. */ public AppiumFieldDecorator(SearchContext context, TimeOutDuration duration) { - this.originalDriver = unpackWebDriverFromSearchContext(context); - if (originalDriver == null - || !HasSessionDetails.class.isAssignableFrom(originalDriver.getClass())) { - hasSessionDetails = null; + this.webDriver = unpackWebDriverFromSearchContext(context); + HasSessionDetails hasSessionDetails = ofNullable(this.webDriver).map(webDriver -> { + if (!HasSessionDetails.class.isAssignableFrom(webDriver.getClass())) { + return null; + } + return HasSessionDetails.class.cast(webDriver); + }).orElse(null); + + if (hasSessionDetails == null) { platform = null; automation = null; } else { - hasSessionDetails = HasSessionDetails.class.cast(originalDriver); platform = hasSessionDetails.getPlatformName(); automation = hasSessionDetails.getAutomationName(); } @@ -202,7 +206,7 @@ public class AppiumFieldDecorator implements FieldDecorator { if (isAlist) { return getEnhancedProxy(ArrayList.class, - new WidgetListInterceptor(locator, originalDriver, map, widgetType, + new WidgetListInterceptor(locator, webDriver, map, widgetType, duration)); } @@ -210,11 +214,11 @@ public class AppiumFieldDecorator implements FieldDecorator { WidgetConstructorUtil.findConvenientConstructor(widgetType); return getEnhancedProxy(widgetType, new Class[] {constructor.getParameterTypes()[0]}, new Object[] {proxyForAnElement(locator)}, - new WidgetInterceptor(locator, originalDriver, null, map, duration)); + new WidgetInterceptor(locator, webDriver, null, map, duration)); } private WebElement proxyForAnElement(ElementLocator locator) { - ElementInterceptor elementInterceptor = new ElementInterceptor(locator, originalDriver); - return getEnhancedProxy(getElementClass(hasSessionDetails), elementInterceptor); + ElementInterceptor elementInterceptor = new ElementInterceptor(locator, webDriver); + return getEnhancedProxy(getElementClass(platform, automation), elementInterceptor); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java index ff4a9f74..9c752322 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java @@ -18,6 +18,7 @@ package io.appium.java_client.pagefactory; import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; +import static java.util.Optional.ofNullable; import io.appium.java_client.pagefactory.bys.ContentType; import io.appium.java_client.pagefactory.interceptors.InterceptorOfAListOfElements; @@ -59,8 +60,9 @@ class WidgetListInterceptor extends InterceptorOfAListOfElements { cachedElements = elements; cachedWidgets.clear(); + ContentType type = null; for (WebElement element : cachedElements) { - ContentType type = getCurrentContentType(element); + type = ofNullable(type).orElseGet(() -> getCurrentContentType(element)); Class<?>[] params = new Class<?>[] {instantiationMap.get(type).getParameterTypes()[0]}; cachedWidgets.add(ProxyFactory diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java b/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java index 95a6659c..1f995bbe 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java @@ -16,7 +16,8 @@ package io.appium.java_client.pagefactory.bys; -import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; +import static com.google.common.base.Preconditions.checkNotNull; +import static io.appium.java_client.pagefactory.bys.ContentType.NATIVE_MOBILE_SPECIFIC; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; @@ -24,32 +25,36 @@ import org.openqa.selenium.WebElement; import java.util.List; import java.util.Map; +import javax.annotation.Nonnull; public class ContentMappedBy extends By { private final Map<ContentType, By> map; + private ContentType currentContent = NATIVE_MOBILE_SPECIFIC; public ContentMappedBy(Map<ContentType, By> map) { this.map = map; } + /** + * This method sets required content type for the further searching. + * @param type required content type {@link ContentType} + * @return self-reference. + */ + public By useContent(@Nonnull ContentType type) { + checkNotNull(type); + currentContent = type; + return this; + } + @Override public WebElement findElement(SearchContext context) { - return context.findElement(map.get(getCurrentContentType(context))); + return context.findElement(map.get(currentContent)); } @Override public List<WebElement> findElements(SearchContext context) { - return context.findElements(map.get(getCurrentContentType(context))); + return context.findElements(map.get(currentContent)); } @Override public String toString() { - By defaultBy = map.get(ContentType.HTML_OR_DEFAULT); - By nativeBy = map.get(ContentType.NATIVE_MOBILE_SPECIFIC); - - if (defaultBy.equals(nativeBy)) { - return defaultBy.toString(); - } - - return "Locator map: " + "\\n" - + "- native content: \\"" + nativeBy.toString() + "\\" \\n" - + "- html content: \\"" + defaultBy.toString() + "\\""; + return map.get(currentContent).toString(); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java b/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java index 279ba4f0..ac004a41 100644 --- a/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java +++ b/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java @@ -19,6 +19,7 @@ package io.appium.java_client.pagefactory.utils; import static io.appium.java_client.pagefactory.bys.ContentType.HTML_OR_DEFAULT; import static io.appium.java_client.pagefactory.bys.ContentType.NATIVE_MOBILE_SPECIFIC; import static java.util.Optional.ofNullable; +import static org.apache.commons.lang3.StringUtils.containsIgnoreCase; import io.appium.java_client.HasSessionDetails; import io.appium.java_client.pagefactory.bys.ContentType; @@ -77,7 +78,8 @@ public final class WebDriverUnpackUtility { * extension/implementation. * Note: if you want to use your own implementation then it should * implement {@link org.openqa.selenium.ContextAware} or - * {@link org.openqa.selenium.internal.WrapsDriver} + * {@link org.openqa.selenium.internal.WrapsDriver} or + * {@link HasSessionDetails} * @return current content type. It depends on current context. If current context is * NATIVE_APP it will return * {@link io.appium.java_client.pagefactory.bys.ContentType#NATIVE_MOBILE_SPECIFIC}. @@ -93,20 +95,17 @@ public final class WebDriverUnpackUtility { if (HasSessionDetails.class.isAssignableFrom(driver.getClass())) { HasSessionDetails hasSessionDetails = HasSessionDetails.class.cast(driver); - if (hasSessionDetails.isBrowser()) { - return HTML_OR_DEFAULT; + if (!hasSessionDetails.isBrowser()) { + return NATIVE_MOBILE_SPECIFIC; } - return NATIVE_MOBILE_SPECIFIC; - } - - if (!ContextAware.class.isAssignableFrom(driver.getClass())) { //it is desktop browser - return HTML_OR_DEFAULT; } - ContextAware contextAware = ContextAware.class.cast(driver); - String currentContext = contextAware.getContext(); - if (currentContext.contains(NATIVE_APP_PATTERN)) { - return NATIVE_MOBILE_SPECIFIC; + if (ContextAware.class.isAssignableFrom(driver.getClass())) { //it is desktop browser + ContextAware contextAware = ContextAware.class.cast(driver); + String currentContext = contextAware.getContext(); + if (containsIgnoreCase(currentContext, NATIVE_APP_PATTERN)) { + return NATIVE_MOBILE_SPECIFIC; + } } return HTML_OR_DEFAULT;
    ['src/main/java/io/appium/java_client/internal/ElementMap.java', 'src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java', 'src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java', 'src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java', 'src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java', 'src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java', 'src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java', 'src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java']
    {'.java': 8}
    8
    8
    0
    0
    8
    634,995
    133,291
    17,502
    193
    9,025
    1,634
    161
    8
    6,075
    597
    1,976
    100
    0
    1
    1970-01-01T00:25:10
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    501
    appium/java-client/733/732
    appium
    java-client
    https://github.com/appium/java-client/issues/732
    https://github.com/appium/java-client/pull/733
    https://github.com/appium/java-client/pull/733
    1
    fix
    Appium 1.7.0 crashes Java client 5.0.3 when testing iOS
    ## Description When attempting to use java-client 5.0.3 to test an iOS device with Appium 1.7.0, the java-client crashes with java.lang.NullPointerException: null value in entry: browserName=null ## Environment * java client build version or git revision if you use some shapshot: 5.0.3 * Appium server version or git revision if you use some shapshot: 1.7.0 * Desktop OS/version used to run Appium if necessary: macOS Sierra 10.12.6 * Node.js version (unless using Appium.app|exe) or Appium CLI or Appium.app|exe: Node.js v8.5.0, Appium 1.7.0 * Mobile platform/version under test: iOS * Real device or emulator/simulator: Real Device ## Details Using the same Appium Server, I can use appium-desktop using the custom server option to connect to the iOS device just fine. Android is unaffected. I believe this chunk of the logs are could relevant: ``` 2017-09-19 22:43:55:863 - info: [HTTP] <-- POST /wd/hub/session 200 23221 ms - 589 2017-09-19 22:43:55:908 - info: [HTTP] --> GET /wd/hub/session/c4c0364a-9a80-442e-b328-3dbb5d77418b {} 2017-09-19 22:43:55:909 - info: [debug] [MJSONWP] Calling AppiumDriver.getSession() with args: ["c4c0364a-9a80-442e-b328-3dbb5d77418b"] 2017-09-19 22:43:55:909 - info: [debug] [XCUITest] Executing command 'getSession' 2017-09-19 22:43:55:924 - info: [debug] [JSONWP Proxy] Proxying [GET /] to [GET http://localhost:8100/session/25E38EC3-E56F-44E4-806E-9B404F0A9D80] with no body 2017-09-19 22:43:56:103 - info: [debug] [JSONWP Proxy] Got response with status 200: "{\\n \\"value\\" : {\\n \\"sessionId\\" : \\"25E38EC3-E56F-44E4-806E-9B404F0A9D80\\",\\n \\"capabilities\\" : {\\n \\"device\\" : \\"iphone\\",\\n \\"browserName\\" : null,\\n \\"sdkVersion\\" : \\"10.3.2\\",\\n \\"CFBundleIdentifier\\" : \\"local.pid.53\\"\\n }\\n },\\n \\"sessionId\\" : \\"25E38EC3-E56F-44E4-806E-9B404F0A9D80\\",\\n \\"status\\" : 0\\n}" 2017-09-19 22:43:56:103 - info: [XCUITest] Merging WDA caps over Appium caps for session detail response 2017-09-19 22:43:56:104 - info: [debug] [MJSONWP] Responding to client with driver.getSession() result: {"udid":"67e44e99a952683ca27e8beccc50687bf4a71490","app":"/Users/nwelna/Documents/app-automation/appFiles/ios/app.ipa","xcodeOrgId":"UTURYJS693","automationName":"XCUITest","browserName":null,"platformName":"iOS","deviceName":"Test Device","xcodeSigningId":"iPhone Developer","usePrebuiltWDA":true,"device":"iphone","sdkVersion":"10.3.2","CFBundleIdentifier":"local.pid.53"} 2017-09-19 22:43:56:105 - info: [HTTP] <-- GET /wd/hub/session/c4c0364a-9a80-442e-b328-3dbb5d77418b 200 196 ms - 486 2017-09-19 22:43:56:196 - info: [Appium] Received SIGTERM - shutting down ``` ## Code To Reproduce Issue [ Good To Have ] Just attempt to connect to a real iOS device ## Ecxeption stacktraces [gist](https://gist.github.com/welnanick/2e553ea885185829c7e589dee45f71bd)
    9e3946cfd22905841f9a1cb7d4a3750960e41106
    89b22dddd55ab708d0ac923ad508b73bb1d1e5b6
    https://github.com/appium/java-client/compare/9e3946cfd22905841f9a1cb7d4a3750960e41106...89b22dddd55ab708d0ac923ad508b73bb1d1e5b6
    diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java index be4900a2..dc7df872 100644 --- a/src/main/java/io/appium/java_client/AppiumDriver.java +++ b/src/main/java/io/appium/java_client/AppiumDriver.java @@ -17,9 +17,8 @@ package io.appium.java_client; import static com.google.common.base.Preconditions.checkNotNull; -import static io.appium.java_client.remote.MobileCapabilityType.AUTOMATION_NAME; import static io.appium.java_client.remote.MobileCapabilityType.PLATFORM_NAME; -import static java.util.Optional.ofNullable; +import static org.apache.commons.lang3.StringUtils.containsIgnoreCase; import com.google.common.collect.ImmutableMap; @@ -72,9 +71,6 @@ public class AppiumDriver<T extends WebElement> private URL remoteAddress; private RemoteLocationContext locationContext; private ExecuteMethod executeMethod; - private final String platformName; - private final String automationName; - /** * @param executor is an instance of {@link org.openqa.selenium.remote.HttpCommandExecutor} @@ -89,20 +85,6 @@ public class AppiumDriver<T extends WebElement> locationContext = new RemoteLocationContext(executeMethod); super.setErrorHandler(errorHandler); this.remoteAddress = executor.getAddressOfRemoteServer(); - - Object capabilityPlatform1 = getCapabilities().getCapability(PLATFORM_NAME); - Object capabilityAutomation1 = getCapabilities().getCapability(AUTOMATION_NAME); - - Object capabilityPlatform2 = capabilities.getCapability(PLATFORM_NAME); - Object capabilityAutomation2 = capabilities.getCapability(AUTOMATION_NAME); - - platformName = ofNullable(ofNullable(super.getPlatformName()) - .orElse(capabilityPlatform1 != null ? String.valueOf(capabilityPlatform1) : null)) - .orElse(capabilityPlatform2 != null ? String.valueOf(capabilityPlatform2) : null); - automationName = ofNullable(ofNullable(super.getAutomationName()) - .orElse(capabilityAutomation1 != null ? String.valueOf(capabilityAutomation1) : null)) - .orElse(capabilityAutomation2 != null ? String.valueOf(capabilityAutomation2) : null); - this.setElementConverter(new JsonToMobileElementConverter(this, this)); } @@ -282,15 +264,8 @@ public class AppiumDriver<T extends WebElement> return remoteAddress; } - @Override public String getPlatformName() { - return platformName; - } - - @Override public String getAutomationName() { - return automationName; - } - @Override public boolean isBrowser() { - return !getContext().toLowerCase().contains("NATIVE_APP".toLowerCase()); + return super.isBrowser() + && !containsIgnoreCase(getContext(), "NATIVE_APP"); } } diff --git a/src/main/java/io/appium/java_client/HasSessionDetails.java b/src/main/java/io/appium/java_client/HasSessionDetails.java index 3106b290..cefdfdf3 100644 --- a/src/main/java/io/appium/java_client/HasSessionDetails.java +++ b/src/main/java/io/appium/java_client/HasSessionDetails.java @@ -18,6 +18,7 @@ package io.appium.java_client; import static io.appium.java_client.MobileCommand.GET_SESSION; import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.toMap; import static org.apache.commons.lang3.StringUtils.isBlank; import com.google.common.collect.ImmutableMap; @@ -25,6 +26,7 @@ import com.google.common.collect.ImmutableMap; import org.openqa.selenium.remote.Response; import java.util.Map; +import javax.annotation.Nullable; public interface HasSessionDetails extends ExecutesMethod { /** @@ -34,26 +36,47 @@ public interface HasSessionDetails extends ExecutesMethod { @SuppressWarnings("unchecked") default Map<String, Object> getSessionDetails() { Response response = execute(GET_SESSION); + Map<String, Object> resultMap = Map.class.cast(response.getValue()); + + //this filtering was added to clear returned result. + //results of further operations should be simply interpreted by users return ImmutableMap.<String, Object>builder() - .putAll(Map.class.cast(response.getValue())).build(); + .putAll(resultMap.entrySet() + .stream().filter(entry -> { + String key = entry.getKey(); + Object value = entry.getValue(); + return !isBlank(key) + && value != null + && !isBlank(String.valueOf(value)); + }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue))).build(); } - default Object getSessionDetail(String detail) { + default @Nullable Object getSessionDetail(String detail) { return getSessionDetails().get(detail); } - default String getPlatformName() { - Object platformName = getSessionDetail("platformName"); - return ofNullable(platformName != null ? String.valueOf(platformName) : null).orElse(null); + /** + * @return name of the current mobile platform. + */ + default @Nullable String getPlatformName() { + Object platformName = ofNullable(getSessionDetail("platformName")) + .orElseGet(() -> getSessionDetail("platform")); + return ofNullable(platformName).map(String::valueOf).orElse(null); } - default String getAutomationName() { - Object automationName = getSessionDetail("automationName"); - return ofNullable(automationName != null ? String.valueOf(automationName) : null).orElse(null); + /** + * @return current automation name. + */ + default @Nullable String getAutomationName() { + return ofNullable(getSessionDetail("automationName")) + .map(String::valueOf).orElse(null); } /** * @return is focus on browser or on native content. */ - boolean isBrowser(); + default boolean isBrowser() { + return ofNullable(getSessionDetail("browserName")) + .orElse(null) != null; + } }
    ['src/main/java/io/appium/java_client/AppiumDriver.java', 'src/main/java/io/appium/java_client/HasSessionDetails.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    618,032
    129,727
    16,954
    185
    3,684
    663
    72
    2
    2,876
    310
    998
    40
    2
    1
    1970-01-01T00:25:06
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    512
    appium/java-client/314/294
    appium
    java-client
    https://github.com/appium/java-client/issues/294
    https://github.com/appium/java-client/pull/314
    https://github.com/appium/java-client/pull/314
    1
    fix
    Not able to build project locally
    @TikhomirovSergey i was unable to build the project locally. I cloned the java_client and ran the the command ``` mvn clean install -Dmaven.test.skip=true ``` Please check the gist for errors. https://gist.github.com/saikrishna321/03f85f7bfce8d2199f7d More Info: ``` Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30) Maven home: /usr/local/Cellar/maven/3.3.3/libexec Java version: 1.8.0_51, vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x", version: "10.10.4", arch: "x86_64", family: "mac" ```
    138e2e8071c9346aeda51f995d506066b3b6ba41
    53d4edee8763339bb6550f765057c28b6f3a5661
    https://github.com/appium/java-client/compare/138e2e8071c9346aeda51f995d506066b3b6ba41...53d4edee8763339bb6550f765057c28b6f3a5661
    diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java index 3b5c6b62..aad34a91 100644 --- a/src/main/java/io/appium/java_client/AppiumDriver.java +++ b/src/main/java/io/appium/java_client/AppiumDriver.java @@ -42,14 +42,13 @@ import static io.appium.java_client.MobileCommand.*; import org.openqa.selenium.remote.http.HttpClient; /** - * @param <RequiredElementType> means the required type from the list of allowed types below - * that implement {@link WebElement} Instances of the defined type will be - * returned via findElement* and findElements*. - * Warning (!!!). Allowed types:<br/> - * {@link WebElement}<br/> - * {@link TouchableElement}<br/> - * {@link RemoteWebElement}<br/> - * {@link MobileElement} and its subclasses that designed specifically for each target mobile OS (still Android and iOS) + * @param <RequiredElementType> the required type of class which implement {@link org.openqa.selenium.WebElement}. + * Instances of the defined type will be returned via findElement* and findElements*. + * Warning (!!!). Allowed types: + * {@link org.openqa.selenium.WebElement} + * {@link io.appium.java_client.TouchableElement} + * {@link org.openqa.selenium.remote.RemoteWebElement} + * {@link io.appium.java_client.MobileElement} and its subclasses that designed specifically for each target mobile OS (still Android and iOS) */ @SuppressWarnings("unchecked") public abstract class AppiumDriver<RequiredElementType extends WebElement> extends DefaultGenericMobileDriver<RequiredElementType> { diff --git a/src/main/java/io/appium/java_client/NetworkConnectionSetting.java b/src/main/java/io/appium/java_client/NetworkConnectionSetting.java index 4529d043..5f4c1d0f 100644 --- a/src/main/java/io/appium/java_client/NetworkConnectionSetting.java +++ b/src/main/java/io/appium/java_client/NetworkConnectionSetting.java @@ -44,7 +44,7 @@ public class NetworkConnectionSetting { /** * Instantiate Network Connection Settings with the straight-up bitmask. See the Mobile JSON Wire Protocol spec for details. - * @param bitmask + * @param bitmask a straight-up bitmask */ public NetworkConnectionSetting(int bitmask) { value = bitmask; diff --git a/src/main/java/io/appium/java_client/NoSuchContextException.java b/src/main/java/io/appium/java_client/NoSuchContextException.java index 0b9e2cf4..ae7217ad 100644 --- a/src/main/java/io/appium/java_client/NoSuchContextException.java +++ b/src/main/java/io/appium/java_client/NoSuchContextException.java @@ -18,10 +18,6 @@ package io.appium.java_client; import org.openqa.selenium.NotFoundException; -/** - * Thrown by {@link org.openqa.selenium.WebDriver.TargetLocator#context(String) WebDriver.switchTo().context(String - * name)}. - */ @SuppressWarnings("serial") public class NoSuchContextException extends NotFoundException { diff --git a/src/main/java/io/appium/java_client/ScrollsTo.java b/src/main/java/io/appium/java_client/ScrollsTo.java index 15a56ffd..dd37be11 100644 --- a/src/main/java/io/appium/java_client/ScrollsTo.java +++ b/src/main/java/io/appium/java_client/ScrollsTo.java @@ -22,13 +22,16 @@ public interface ScrollsTo<T extends WebElement> { /** * Scroll to an element which contains the given text. - * @param text + * @param text description or text of an element scroll to + * + * @return an element that matches */ T scrollTo(String text); /** * Scroll to an element with the given text. - * @param text + * @param text description or text of an element scroll to + * @return an element that matches */ T scrollToExact(String text); diff --git a/src/main/java/io/appium/java_client/TouchShortcuts.java b/src/main/java/io/appium/java_client/TouchShortcuts.java index e0359d01..92e4c715 100644 --- a/src/main/java/io/appium/java_client/TouchShortcuts.java +++ b/src/main/java/io/appium/java_client/TouchShortcuts.java @@ -54,7 +54,7 @@ public interface TouchShortcuts { * x coordinate * @param y * y coordinate - * @param duration + * @param duration how long between pressing down, and lifting fingers/appendages */ void tap(int fingers, int x, int y, int duration); diff --git a/src/main/java/io/appium/java_client/android/AndroidDriver.java b/src/main/java/io/appium/java_client/android/AndroidDriver.java index 15351b8f..558624bd 100644 --- a/src/main/java/io/appium/java_client/android/AndroidDriver.java +++ b/src/main/java/io/appium/java_client/android/AndroidDriver.java @@ -54,15 +54,14 @@ import static io.appium.java_client.remote.MobileCapabilityType.DONT_STOP_APP_ON import org.openqa.selenium.remote.http.HttpClient; /** - * @param <RequiredElementType> means the required type from the list of allowed types below - * that implement {@link WebElement} Instances of the defined type will be - * returned via findElement* and findElements*. - * Warning (!!!). Allowed types:<br/> - * {@link WebElement}<br/> - * {@link TouchableElement}<br/> - * {@link RemoteWebElement}<br/> - * {@link MobileElement} - * {@link AndroidElement} + * @param <RequiredElementType> the required type of class which implement {@link org.openqa.selenium.WebElement}. + * Instances of the defined type will be returned via findElement* and findElements*. + * Warning (!!!). Allowed types: + * {@link org.openqa.selenium.WebElement} + * {@link io.appium.java_client.TouchableElement} + * {@link org.openqa.selenium.remote.RemoteWebElement} + * {@link io.appium.java_client.MobileElement} + * {@link io.appium.java_client.android.AndroidElement} */ public class AndroidDriver<RequiredElementType extends WebElement> extends AppiumDriver<RequiredElementType> implements AndroidDeviceActionShortcuts, HasNetworkConnection, PushesFiles, @@ -126,11 +125,6 @@ public class AndroidDriver<RequiredElementType extends WebElement> extends Appiu this.setElementConverter(new JsonToAndroidElementConverter(this)); } - /** - * Scroll forward to the element which has a description or name which contains the input text. - * The scrolling is performed on the first scrollView present on the UI - * @param text - */ @Override public RequiredElementType scrollTo(String text) { String uiScrollables = UiScrollable("new UiSelector().descriptionContains(\\"" + text + "\\")") + @@ -138,11 +132,6 @@ public class AndroidDriver<RequiredElementType extends WebElement> extends Appiu return findElementByAndroidUIAutomator(uiScrollables); } - /** - * Scroll forward to the element which has a description or name which exactly matches the input text. - * The scrolling is performed on the first scrollView present on the UI - * @param text - */ @Override public RequiredElementType scrollToExact(String text) { String uiScrollables = UiScrollable("new UiSelector().description(\\"" + text + "\\")") + @@ -268,8 +257,6 @@ public class AndroidDriver<RequiredElementType extends WebElement> extends Appiu * Automation will begin after this activity starts. [Optional] * @param stopApp * If true, target app will be stopped. [Optional] - * @example driver.startActivity("com.foo.bar", ".MyActivity", null, null, true); - * * @see StartsActivity#startActivity(String, String, String, String) */ public void startActivity(String appPackage, String appActivity, @@ -303,8 +290,6 @@ public class AndroidDriver<RequiredElementType extends WebElement> extends Appiu * Automation will begin after this package starts. [Optional] * @param appWaitActivity * Automation will begin after this activity starts. [Optional] - * @example driver.startActivity("com.foo.bar", ".MyActivity", null, null); - * * @see StartsActivity#startActivity(String, String, String, String) */ public void startActivity(String appPackage, String appActivity, @@ -317,8 +302,6 @@ public class AndroidDriver<RequiredElementType extends WebElement> extends Appiu /** * @param appPackage The package containing the activity. [Required] * @param appActivity The activity to start. [Required] - * @example - * *.startActivity("com.foo.bar", ".MyActivity"); * @see StartsActivity#startActivity(String, String) */ @Override @@ -343,6 +326,7 @@ public class AndroidDriver<RequiredElementType extends WebElement> extends Appiu /** * Get the current activity being run on the mobile device + * @return a current activity being run on the mobile device */ public String currentActivity() { Response response = execute(CURRENT_ACTIVITY); diff --git a/src/main/java/io/appium/java_client/android/StartsActivity.java b/src/main/java/io/appium/java_client/android/StartsActivity.java index ebb0b211..c93e7498 100644 --- a/src/main/java/io/appium/java_client/android/StartsActivity.java +++ b/src/main/java/io/appium/java_client/android/StartsActivity.java @@ -26,8 +26,6 @@ public interface StartsActivity { * @param appWaitPackage Automation will begin after this package starts. [Optional] * @param appWaitActivity Automation will begin after this activity starts. [Optional] * @param stopApp If true, target app will be stopped. [Optional] - * @example - * *.startActivity("com.foo.bar", ".MyActivity", null, null, true); */ void startActivity(String appPackage, String appActivity, String appWaitPackage, String appWaitActivity, boolean stopApp) throws IllegalArgumentException; @@ -40,8 +38,6 @@ public interface StartsActivity { * @param appActivity The activity to start. [Required] * @param appWaitPackage Automation will begin after this package starts. [Optional] * @param appWaitActivity Automation will begin after this activity starts. [Optional] - * @example - * *.startActivity("com.foo.bar", ".MyActivity", null, null); */ void startActivity(String appPackage, String appActivity, String appWaitPackage, String appWaitActivity) throws IllegalArgumentException; @@ -52,8 +48,6 @@ public interface StartsActivity { * * @param appPackage The package containing the activity. [Required] * @param appActivity The activity to start. [Required] - * @example - * *.startActivity("com.foo.bar", ".MyActivity"); */ void startActivity(String appPackage, String appActivity) throws IllegalArgumentException; diff --git a/src/main/java/io/appium/java_client/ios/IOSDriver.java b/src/main/java/io/appium/java_client/ios/IOSDriver.java index 7d2adc26..5f0a48dd 100644 --- a/src/main/java/io/appium/java_client/ios/IOSDriver.java +++ b/src/main/java/io/appium/java_client/ios/IOSDriver.java @@ -38,15 +38,14 @@ import static io.appium.java_client.MobileCommand.*; import org.openqa.selenium.remote.http.HttpClient; /** - * @param <RequiredElementType> means the required type from the list of allowed types below - * that implement {@link WebElement} Instances of the defined type will be - * returned via findElement* and findElements*. - * Warning (!!!). Allowed types:<br/> - * {@link WebElement}<br/> - * {@link TouchableElement}<br/> - * {@link RemoteWebElement}<br/> - * {@link MobileElement} - * {@link IOSElement} + * @param <RequiredElementType> the required type of class which implement {@link org.openqa.selenium.WebElement}. + * Instances of the defined type will be returned via findElement* and findElements*. + * Warning (!!!). Allowed types: + * {@link org.openqa.selenium.WebElement} + * {@link io.appium.java_client.TouchableElement} + * {@link org.openqa.selenium.remote.RemoteWebElement} + * {@link io.appium.java_client.MobileElement} + * {@link io.appium.java_client.ios.IOSElement} */ public class IOSDriver<RequiredElementType extends WebElement> extends AppiumDriver<RequiredElementType> implements IOSDeviceActionShortcuts, GetsNamedTextField<RequiredElementType>, FindsByIosUIAutomation<RequiredElementType>{ diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java index e75901de..30ee14a8 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java @@ -47,7 +47,7 @@ import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.unp /** * Default decorator for use with PageFactory. Will decorate 1) all of the - * WebElement fields and 2) List<WebElement> fields that have + * WebElement fields and 2) List of WebElement that have * {@literal @AndroidFindBy}, {@literal @AndroidFindBys}, or * {@literal @iOSFindBy/@iOSFindBys} annotation with a proxy that locates the * elements using the passed in ElementLocatorFactory. diff --git a/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java b/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java index db48fbf6..44f25da5 100644 --- a/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java +++ b/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java @@ -39,6 +39,8 @@ public @interface OverrideWidget { * * A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. + * + * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class<? extends Widget> html() default Widget.class; /** @@ -46,6 +48,8 @@ public @interface OverrideWidget { * * A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. + * + * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class<? extends Widget> androidUIAutomator() default Widget.class; /** @@ -53,6 +57,8 @@ public @interface OverrideWidget { * * A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. + * + * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class<? extends Widget> iOSUIAutomation() default Widget.class; /** @@ -60,6 +66,8 @@ public @interface OverrideWidget { * * A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. + * + * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class<? extends Widget> selendroid() default Widget.class; } diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java index 6e7b3ffa..f07c0178 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java @@ -155,6 +155,9 @@ public abstract class AppiumByBuilder extends AbstractAnnotations { * This method should be used for the setting up of * AnnotatedElement instances before the building of * By-locator strategies + * + * @param annotated is an instance of class which type extends + * {@link java.lang.reflect.AnnotatedElement} */ public void setAnnotated(AnnotatedElement annotated) { this.annotatedElementContainer.setAnnotated(annotated); diff --git a/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java b/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java index 09bd8ae5..01b0f431 100644 --- a/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java +++ b/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java @@ -38,8 +38,8 @@ public final class AppiumServiceBuilder extends DriverService.Builder<AppiumDriv /** * The environmental variable used to define - * the path to executable appium.js (node server v<=1.4.x) or - * main.js (node server v>=1.5.x) + * the path to executable appium.js (1.4.x and lower) or + * main.js (1.5.x and higher) */ public static final String APPIUM_PATH = "APPIUM_BINARY_PATH"; diff --git a/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java b/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java index 05d7fa13..1ae137be 100644 --- a/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java +++ b/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java @@ -19,147 +19,122 @@ package io.appium.java_client.service.local.flags; /** * Here is the list of Android specific server arguments. * All flags are optional, but some are required in conjunction with certain others. -* The full list is available here: {@link http://appium.io/slate/en/master/?ruby#appium-server-arguments} +* The full list is available here: http://appium.io/slate/en/master/?ruby#appium-server-arguments * Android specific arguments are marked by (Android-only) */ public enum AndroidServerFlag implements ServerArgument{ /** - * Port to use on device to talk to Appium<br/> - * Sample:<br/> + * Port to use on device to talk to Appium. Sample: * --bootstrap-port 4724 */ BOOTSTRAP_PORT_NUMBER("--bootstrap-port"), /** * Java package of the Android app you want to run (e.g., - * com.example.android.MyApp)<br/> - * Sample:<br/> + * com.example.android.MyApp). Sample: * --app-pkg com.example.android.MyApp */ PACKAGE("--app-pkg"), /** * Activity name for the Android activity you want to launch - * from your package (e.g., MainActivity)<br/> - * Sample:<br/> + * from your package (e.g., MainActivity). Sample: * --app-activity MainActivity */ ACTIVITY("--app-activity"), /** * Package name for the Android activity you want to wait for - * (e.g., com.example.android.MyApp)<br/> - * Sample:<br/> + * (e.g., com.example.android.MyApp). Sample: * --app-wait-package com.example.android.MyApp */ APP_WAIT_PACKAGE("--app-wait-package"), /** * Activity name for the Android activity you want to wait - * for (e.g., SplashActivity) - * Sample:<br/> + * for (e.g., SplashActivity). Sample: * --app-wait-activity SplashActivity */ APP_WAIT_ACTIVITY("--app-wait-activity"), /** * Fully qualified instrumentation class. - * Passed to -w in adb shell am instrument -e coverage true -w <br/> - * Sample: <br/> + * Passed to -w in adb shell am instrument -e coverage true -w. Sample: * --android-coverage com.my.Pkg/com.my.Pkg.instrumentation.MyInstrumentation */ ANDROID_COVERAGE("--android-coverage"), /** - * Name of the avd to launch<br/> - * Sample:<br/> + * Name of the avd to launch. Sample: * --avd @default */ AVD("--avd"), /** - * Additional emulator arguments to launch the avd<br/> - * Sample:<br/> + * Additional emulator arguments to launch the avd. Sample: * --avd-args -no-snapshot-load */ AVD_ARGS("--avd-args"), /** * Timeout in seconds while waiting for device to become - * ready<br/> - * Sample:<br/> + * ready. Sample: * --device-ready-timeout 5 */ DEVICE_READY_TIMEOUT("--device-ready-timeout"), /** - * Local port used for communication with Selendroid<br/> - * Sample:<br/> + * Local port used for communication with Selendroid. Sample: * --selendroid-port 8080 */ SELENDROID_PORT("--selendroid-port"), /** - * When set the keystore will be used to sign apks.<br/> - * Default: false + * When set the keystore will be used to sign apks. Default: false */ USE_KEY_STORE("--use-keystore"), /** - * Path to keystore<br/> - * Sample:<br/> + * Path to keystore. Sample: * --keystore-path /Users/user/.android/debug.keystore */ KEY_STORE_PATH("--keystore-path"), /** - * Password to keystore<br/> - * Default: android + * Password to keystore. Default: android */ KEY_STORE_PASSWORD("--keystore-password"), /** - * Key alias<br/> - * Default: androiddebugkey + * Key alias. Default: androiddebugkey */ KEY_ALIAS("--key-alias"), /** - * Key password<br/> - * Default: android + * Key password. Default: android */ KEY_PASSWORD("--key-password"), /** - * Intent action which will be used to start activity<br/> - * Default: android.intent.action.MAIN<br/> - * Sample:<br/> - * --intent-action android.intent.action.MAIN + * Intent action which will be used to start activity. Default: + * android.intent.action.MAIN. Sample: --intent-action android.intent.action.MAIN */ INTENT_ACTION("--intent-action"), /** - * Intent category which will be used to start activity<br/> - * Default: android.intent.category.LAUNCHER<br/> - * Sample:<br/> - * --intent-category android.intent.category.APP_CONTACTS + * Intent category which will be used to start activity. Default: android.intent.category.LAUNCHER. + * Sample:s --intent-category android.intent.category.APP_CONTACTS */ INTENT_CATEGORY("--intent-category"), /** - * Flags that will be used to start activity<br/> - * Default: 0x10200000<br/> - * Sample:<br/> - * --intent-flags 0x10200000 + * Flags that will be used to start activity. Default: 0x10200000. + * Sample: --intent-flags 0x10200000 */ INTENT_FLAGS("--intent-flags"), /** * Additional intent arguments that will be used to start - * activity<br/> - * Default: null<br/> - * Sample:<br/> - * --intent-args 0x10200000 + * activity. Default: null. + * Sample: --intent-args 0x10200000 */ INTENT_ARGUMENTS("--intent-args"), /** * When included, refrains from stopping the app before - * restart<br/> - * Default: false<br/> + * restart. Default: false */ DO_NOT_STOP_APP_ON_RESET("--dont-stop-app-on-reset"), /** * If set, prevents Appium from killing the adb server - * instance<br/> - * Default: false<br/> + * instance. Default: false */ SUPPRESS_ADB_KILL_SERVER("--suppress-adb-kill-server"); private final String arg; - private AndroidServerFlag(String arg) { + AndroidServerFlag(String arg) { this.arg = arg; } diff --git a/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java b/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java index 24e5e428..5c0aeb54 100644 --- a/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java +++ b/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java @@ -19,7 +19,7 @@ package io.appium.java_client.service.local.flags; /** * Here is the list of common Appium server arguments. * All flags are optional, but some are required in conjunction with certain others. - * The full list is available here: {@link http://appium.io/slate/en/master/?ruby#appium-server-arguments} + * The full list is available here: @link http://appium.io/slate/en/master/?ruby#appium-server-arguments */ public enum GeneralServerFlag implements ServerArgument{ /** @@ -27,135 +27,110 @@ public enum GeneralServerFlag implements ServerArgument{ */ SHELL("--shell"), /** - * IOS: abs path to simulator-compiled .app file or the bundle_id of the desired target on device; Android: abs path to .apk file<br/> - * Sample <br/> - * --app /abs/path/to/my.app + * IOS: abs path to simulator-compiled .app file or the bundle_id of the desired target on device; Android: abs path to .apk file. + * Sample: --app /abs/path/to/my.app */ APP("--app"), /** - * Unique device identifier of the connected physical device<br/> - * Sample <br/> + * Unique device identifier of the connected physical device. + * Sample: * --udid 1adsf-sdfas-asdf-123sdf */ UIID("--udid"), /** - * callback IP Address (default: same as address) <br/> - * Sample <br/> - * --callback-address 127.0.0.1 + * callback IP Address (default: same as address). + * Sample: --callback-address 127.0.0.1 */ CALLBACK_ADDRESS("--callback-address"), /** - * callback port (default: same as port)<br/> - * Sample <br/> - * --callback-port 4723 + * callback port (default: same as port). + * Sample: --callback-port 4723 */ CALLBACK_PORT("--callback-port"), /** - * Enables session override (clobbering) <br/> - * Default: false + * Enables session override (clobbering). Default: false */ SESSION_OVERRIDE("--session-override"), /** - * Don’t reset app state between sessions (IOS: don’t delete app plist files; Android: don’t uninstall app before new session)<br/> + * Don’t reset app state between sessions (IOS: don’t delete app plist files; Android: don’t uninstall app before new session). * Default: false */ NO_RESET("--no-reset"), /** - * Pre-launch the application before allowing the first session (Requires –app and, for Android, –app-pkg and –app-activity) <br/> + * Pre-launch the application before allowing the first session (Requires –app and, for Android, –app-pkg and –app-activity). * Default: false */ PRE_LAUNCH("--pre-launch"), /** - * The message log level to be shown <br/> - * Sample:<br/> - * --log-level debug + * The message log level to be shown. + * Sample: --log-level debug */ LOG_LEVEL("--log-level"), /** - * Show timestamps in console output <br/> + * Show timestamps in console output. * Default: false */ LOG_TIMESTAMP("--log-timestamp"), /** - * Use local timezone for timestamps <br/> + * Use local timezone for timestamps. * Default: false */ LOCAL_TIMEZONE("--local-timezone"), /** - * Don’t use colors in console output <br/> + * Don’t use colors in console output. * Default: false */ LOG_NO_COLORS("--log-no-colors"), /** - * Also send log output to this HTTP listener <br/> - * Sample: <br/> - * --webhook localhost:9876 + * Also send log output to this HTTP listener. + * Sample: --webhook localhost:9876 */ WEB_HOOK("--webhook"), /** - * Name of the mobile device to use<br/> - * Sample: <br/> - * --device-name iPhone Retina (4-inch), Android Emulator + * Name of the mobile device to use. + * Sample: --device-name iPhone Retina (4-inch), Android Emulator */ DEVICE_NAME("--device-name"), /** - * Name of the mobile platform: iOS, Android, or FirefoxOS <br/> - * Sample:<br/> - * --platform-name iOS + * Name of the mobile platform: iOS, Android, or FirefoxOS + * Sample: --platform-name iOS */ PLATFORM_NAME("--platform-name"), /** - * Version of the mobile platform <br/> - * Sample:<br/> - * --platform-version 7.1 + * Version of the mobile platform. Sample: --platform-version 7.1 */ PLATFORM_VERSION("--platform-version"), /** - * Name of the automation tool: Appium or Selendroid<br/> - * Sample:<br/> - * --automation-name Appium + * Name of the automation tool: Appium or Selendroid. Sample: --automation-name Appium */ AUTOMATION_NAME("--automation-name"), /** - * Name of the mobile browser: Safari or Chrome<br/> - * Sample: <br/> - * --browser-name Safari + * Name of the mobile browser: Safari or Chrome. Sample: --browser-name Safari */ BROWSER_NAME("--browser-name"), /** - * Language for the iOS simulator / Android Emulator <br/> - * Sample:<br/> - * --language en + * Language for the iOS simulator / Android Emulator. Sample: --language en */ LANGUAGE("--language"), /** - * Locale for the iOS simulator / Android Emulator<br/> - * Sample:<br/> - * --locale en_US + * Locale for the iOS simulator / Android Emulator. Sample: --locale en_US */ LOCALE("--locale"), /** - * Configuration JSON file to register Appium with selenium grid<br/> - * Sample:<br/> + * Configuration JSON file to register Appium with selenium grid. Sample: * --nodeconfig /abs/path/to/nodeconfig.json */ CONFIGURATION_FILE("--nodeconfig"), /** - * IP Address of robot<br/> - * Sample:<br/> - * --robot-address 0.0.0.0 + * IP Address of robot. Sample: --robot-address 0.0.0.0 */ ROBOT_ADDRESS("--robot-address"), /** - * Port for robot<br/> - * Sample: <br/> - * --robot-port 4242 + * Port for robot. Sample: --robot-port 4242 */ ROBOT_PORT("--robot-port"), /** - * Port upon which ChromeDriver will run<br/> - * Sample:<br/> - * --chromedriver-port 9515 + * Port upon which ChromeDriver will run. Sample: --chromedriver-port 9515 */ CHROME_DRIVER_PORT("--chromedriver-port"), /** @@ -163,39 +138,33 @@ public enum GeneralServerFlag implements ServerArgument{ */ CHROME_DRIVER_EXECUTABLE("--chromedriver-executable"), /** - * Show info about the Appium server configuration and exit<br/> - * Default: false + * Show info about the Appium server configuration and exit. Default: false */ SHOW_CONFIG("--show-config"), /** - * Bypass Appium’s checks to ensure we can read/write necessary files<br/> - * Default: false + * Bypass Appium’s checks to ensure we can read/write necessary files. Default: false */ NO_PERMS_CHECKS( "--no-perms-check"), /** * The default command timeout for the server to use for all sessions. Will - * still be overridden by newCommandTimeout cap<br/> - * Default: 60 + * still be overridden by newCommandTimeout cap. Default: 60 */ COMMAND_TIMEOUT("--command-timeout"), /** * Cause sessions to fail if desired caps are sent in that Appium does not - * recognize as valid for the selected device<br/> - * Default: false + * recognize as valid for the selected device. Default: false */ STRICT_CAPS("--strict-caps"), /** * Absolute path to directory Appium can use to manage temporary files, like * built-in iOS apps it needs to move around. On *nix/Mac defaults to /tmp, - * on Windows defaults to C:\\Windows\\Temp<br/> + * on Windows defaults to C:\\Windows\\Temp. */ TEMP_DIRECTORY("--tmp"), /** - * Add exaggerated spacing in logs to help with visual inspection<br/> - * Default: false + * Add exaggerated spacing in logs to help with visual inspection. Default: false */ DEBUG_LOG_SPACING("--debug-log-spacing"); - ; private final String arg; diff --git a/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java b/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java index d77f5e93..40d7a285 100644 --- a/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java +++ b/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java @@ -19,104 +19,81 @@ package io.appium.java_client.service.local.flags; /** * Here is the list of iOS specific server arguments. * All flags are optional, but some are required in conjunction with certain others. -* The full list is available here: {@link http://appium.io/slate/en/master/?ruby#appium-server-arguments} +* The full list is available here: http://appium.io/slate/en/master/?ruby#appium-server-arguments * iOS specific arguments are marked by (IOS-only) */ public enum IOSServerFlag implements ServerArgument{ /** * the relative path of the dir where Localizable.strings file - * resides<br/> - * Default: en.lproj<br/> - * Sample:<br/> - * --localizable-strings-dir en.lproj + * resides. Default: en.lproj. Sample: --localizable-strings-dir en.lproj */ LOCALIZABLE_STRING_PATH("--localizable-strings-dir"), /** - * absolute path to compiled .ipa file - * Sample:<br/> - * --ipa /abs/path/to/my.ipa + * absolute path to compiled .ipa file. Sample: --ipa /abs/path/to/my.ipa */ IPA_ABSOLUTE_PATH("--ipa"), /** * How many times to retry launching Instruments before saying it - * crashed or timed out<br/> - * Sample:<br/> - * --backend-retries 3 + * crashed or timed out. Sample: --backend-retries 3 */ BACK_END_RETRIES("--backend-retries"), /** - * how long in ms to wait for Instruments to launch<br/> - * Default: 90000 + * how long in ms to wait for Instruments to launch. Default: 90000 */ LAUNCH_TIMEOUT("--launch-timeout"), /** * IOS has a weird built-in unavoidable delay. We patch this in - * appium. If you do not want it patched, pass in this flag.<br/> - * Default: false + * appium. If you do not want it patched, pass in this flag. Default: false */ USE_NATIVE_INSTRUMENTS("--native-instruments-lib"), /** - * Use the safari app<br/> - * Default: false + * Use the safari app. Default: false */ SAFARI("--safari"), /** * use the default simulator that instruments launches - * on its own<br/> - * Default: false + * on its own. Default: false * */ DEFAULT_DEVICE("--default-device"), /** - * Use the iPhone Simulator no matter what the app wants<br/> - * Default: false + * Use the iPhone Simulator no matter what the app wants. Default: false */ FORCE_IPHONE_SIMULATOR("--force-iphone"), /** - * Use the iPad Simulator no matter what the app wants<br/> - * Default: false + * Use the iPad Simulator no matter what the app wants. Default: false */ FORCE_IPAD_SIMULATOR("--force-ipad"), /** - * Calendar format for the iOS simulator<br/> - * Default: null<br/> - * Sample:<br/> - * --calendar-format gregorian + * Calendar format for the iOS simulator. + * Default: null + * Sample: --calendar-format gregorian */ CALENDAR_FORMAT("--calendar-format"), /** * use LANDSCAPE or PORTRAIT to initialize all requests to this - * orientation<br/> - * Sample:<br/> - * --orientation LANDSCAPE + * orientation. Sample: --orientation LANDSCAPE */ ORIENTATION("--orientation"), /** - * .tracetemplate file to use with Instruments<br/> - * Sample:<br/> - * --tracetemplate /Users/me/Automation.tracetemplate + * .tracetemplate file to use with Instruments. Sample: --tracetemplate /Users/me/Automation.tracetemplate */ TRACE_TEMPLATE_FILE_PATH("--tracetemplate"), /** - * custom path to the instruments commandline tool<br/> - * Sample:<br/> - * --instruments /path/to/instruments + * custom path to the instruments commandline tool. Sample: --instruments /path/to/instruments */ CUSTOM_INSTRUMENTS_PATH("--instruments"), /** - * if set, the iOS simulator log will be written to the console<br/> - * Default: false + * if set, the iOS simulator log will be written to the console. Default: false */ SHOW_SIMULATOR_LOG("--show-sim-log"), /** - * if set, the iOS system log will be written to the console<br/> - * Default: false + * if set, the iOS system log will be written to the console. Default: false */ SHOW_IOS_LOG("--show-ios-log"), /** * Whether to keep keychains (Library/Keychains) when reset app - * between sessions<br/> - * Default: false + * between sessions. Default: false */ KEEP_KEYCHAINS("--keep-keychains"), /** @@ -125,20 +102,18 @@ public enum IOSServerFlag implements ServerArgument{ * This option causes Appium to delete all devices other than the one being * used by Appium. Note that this is a permanent deletion, and you are * responsible for using simctl or xcode to manage the categories of devices - * used with Appium<br/>. - * Default: false + * used with Appium. Default: false */ ISOLATE_SIM_DEVICE("--isolate-sim-device"), /** * Absolute path to directory Appium use to save ios instruments traces, - * defaults to /appium-instruments<br/> - * Default: null + * defaults to /appium-instruments. Default: null */ TRACE_DIRECTORY_ABSOLUTE_PATH("--trace-dir"); private final String arg; - private IOSServerFlag(String arg) { + IOSServerFlag(String arg) { this.arg = arg; }
    ['src/main/java/io/appium/java_client/android/StartsActivity.java', 'src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java', 'src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java', 'src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java', 'src/main/java/io/appium/java_client/ios/IOSDriver.java', 'src/main/java/io/appium/java_client/android/AndroidDriver.java', 'src/main/java/io/appium/java_client/ScrollsTo.java', 'src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java', 'src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java', 'src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java', 'src/main/java/io/appium/java_client/TouchShortcuts.java', 'src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java', 'src/main/java/io/appium/java_client/AppiumDriver.java', 'src/main/java/io/appium/java_client/NetworkConnectionSetting.java', 'src/main/java/io/appium/java_client/NoSuchContextException.java']
    {'.java': 15}
    15
    15
    0
    0
    15
    354,320
    76,767
    10,144
    108
    17,215
    4,139
    359
    15
    667
    69
    246
    22
    1
    2
    1970-01-01T00:24:14
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    503
    appium/java-client/705/704
    appium
    java-client
    https://github.com/appium/java-client/issues/704
    https://github.com/appium/java-client/pull/705
    https://github.com/appium/java-client/pull/705
    1
    fix
    5.0.0: Brokes iOS tests
    ## Description Move from 5.0.0-BETA9 -> 5.0.0 cause iOS tests fail to find any element ## Environment * java client build version or git revision if you use some shapshot: 5.0.0 * Appium server version or git revision if you use some shapshot: 1.6.6-beta.4 * Desktop OS/version used to run Appium if necessary: macOS 10.12.6 * Mobile platform/version under test: iOS Simulator ## Code To Reproduce Issue [ Good To Have ] ``` @iOSFindBy(id = "xxxxxx") private List<IOSElement> mainContainer; // .... !mainContainer.isEmpty(); ``` ## Ecxeption stacktraces org.openqa.selenium.WebDriverException: org.openqa.selenium.WebDriverException: Unrecognized platform: iOS Build info: version: '3.5.2', revision: '10229a9', time: '2017-08-21T17:29:55.15Z' System info: host: 'aleks.local', ip: '192.168.2.4', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_131' Driver info: driver.version: AppiumDriver at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:187) at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:1) at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:209) at io.appium.java_client.pagefactory.AppiumElementLocator.waitFor(AppiumElementLocator.java:91) at io.appium.java_client.pagefactory.AppiumElementLocator.findElements(AppiumElementLocator.java:133) at io.appium.java_client.pagefactory.interceptors.InterceptorOfAListOfElements.intercept(InterceptorOfAListOfElements.java:50) at $java.util.ArrayList$$EnhancerByCGLIB$$c0a2d785.isEmpty(<generated>) at com.xxxx.pages.ios.xxxx.xxxxxx(xxxxx.java:54) ## Link to Appium logs 2017-08-28 12:13:02:801 - [HTTP] --> POST /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/timeouts {"type":"implicit","ms":0} 2017-08-28 12:13:02:802 - [debug] [MJSONWP] Calling AppiumDriver.timeouts() with args: ["implicit",0,"1de3a575-8506-4df8-95b9-9689c461c92a"] 2017-08-28 12:13:02:802 - [debug] [XCUITest] Executing command 'timeouts' 2017-08-28 12:13:02:804 - [debug] [BaseDriver] Set implicit wait to 0ms 2017-08-28 12:13:02:804 - [debug] [MJSONWP] Responding to client with driver.timeouts() result: null 2017-08-28 12:13:02:804 - [HTTP] <-- POST /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/timeouts 200 3 ms - 76 2017-08-28 12:13:02:807 - [HTTP] --> GET /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/context {} 2017-08-28 12:13:02:808 - [debug] [MJSONWP] Calling AppiumDriver.getCurrentContext() with args: ["1de3a575-8506-4df8-95b9-9689c461c92a"] 2017-08-28 12:13:02:808 - [debug] [XCUITest] Executing command 'getCurrentContext' 2017-08-28 12:13:02:810 - [debug] [MJSONWP] Responding to client with driver.getCurrentContext() result: "NATIVE_APP" 2017-08-28 12:13:02:811 - [HTTP] <-- GET /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/context 200 3 ms - 84 2017-08-28 12:13:02:814 - [HTTP] --> POST /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/elements {"using":"id","value":"xxxxxx"} 2017-08-28 12:13:02:814 - [debug] [MJSONWP] Calling AppiumDriver.findElements() with args: ["id","xxxxxx","1de3a575-8506-4df8-95b9-9689c461c92a"] 2017-08-28 12:13:02:814 - [debug] [XCUITest] Executing command 'findElements' 2017-08-28 12:13:02:816 - [debug] [BaseDriver] Valid locator strategies for this request: xpath, id, name, class name, -ios predicate string, -ios class chain, accessibility id 2017-08-28 12:13:02:817 - [debug] [BaseDriver] Waiting up to 0 ms for condition 2017-08-28 12:13:02:818 - [debug] [JSONWP Proxy] Proxying [POST /elements] to [POST http://localhost:8100/session/51967F2C-AC5B-46F0-BD61-3AD0F24FD06D/elements] with body: {"using":"id","value":"xxxxx"} 2017-08-28 12:13:02:957 - [debug] [JSONWP Proxy] Got response with status 200: {"value":[{"ELEMENT":"328606E0-86FD-40BF-A8CD-1A9BC18F3AAC"}],"sessionId":"51967F2C-AC5B-46F0-BD61-3AD0F24FD06D","status":0} 2017-08-28 12:13:02:958 - [debug] [MJSONWP] Responding to client with driver.findElements() result: [{"ELEMENT":"328606E0-86FD-40BF-A8CD-1A9BC18F3AAC"}] 2017-08-28 12:13:02:958 - [HTTP] <-- POST /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/elements 200 144 ms - 124 2017-08-28 12:13:02:965 - [HTTP] --> POST /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/timeouts {"type":"implicit","ms":1000} 2017-08-28 12:13:02:966 - [debug] [MJSONWP] Calling AppiumDriver.timeouts() with args: ["implicit",1000,"1de3a575-8506-4df8-95b9-9689c461c92a"] 2017-08-28 12:13:02:966 - [debug] [XCUITest] Executing command 'timeouts' 2017-08-28 12:13:02:968 - [debug] [BaseDriver] Set implicit wait to 1000ms 2017-08-28 12:13:02:968 - [debug] [MJSONWP] Responding to client with driver.timeouts() result: null 2017-08-28 12:13:02:968 - [HTTP] <-- POST /wd/hub/session/1de3a575-8506-4df8-95b9-9689c461c92a/timeouts 200 3 ms - 76
    8f914fb2467e21368603bf76d98e97ed37e4fde3
    4d87d9396d569fbf01c2e142e111b1091c06f63d
    https://github.com/appium/java-client/compare/8f914fb2467e21368603bf76d98e97ed37e4fde3...4d87d9396d569fbf01c2e142e111b1091c06f63d
    diff --git a/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java b/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java index e3a27cb9..23e188b2 100644 --- a/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java +++ b/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java @@ -150,4 +150,10 @@ abstract class DefaultGenericMobileDriver<T extends WebElement> extends RemoteWe @Deprecated public Mouse getMouse() { return super.getMouse(); } + + @Override + public String toString() { + return String.format("%s: %s", getPlatformName(), + getAutomationName()); + } }
    ['src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    615,108
    129,111
    16,885
    184
    153
    32
    6
    1
    4,937
    423
    1,823
    68
    1
    1
    1970-01-01T00:25:03
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    506
    appium/java-client/582/574
    appium
    java-client
    https://github.com/appium/java-client/issues/574
    https://github.com/appium/java-client/pull/582
    https://github.com/appium/java-client/pull/582
    1
    fix
    wait.until(ExpectedConditions.visibilityOf(elementName)) related issue
    ## Description I've below code `WebDriverWait wait = new WebDriverWait(AppiumController.instance.driver, timeout); wait.until(ExpectedConditions.visibilityOf(elementName));` Here I pass timeout value but observed that instead of waiting for timeout value, it waits for default time mentioned in `PageFactory.initElements(new AppiumFieldDecorator(driver, 30, TimeUnit.SECONDS), this);` ## Environment * java client build version or git revision if you use some shapshot: 5.0.0-BETA3 * Appium server version or git revision if you use some shapshot: 1.6.3 * Desktop OS/version used to run Appium if necessary: Mac * Node.js version (unless using Appium.app|exe) or Appium CLI or Appium.app|exe: * Mobile platform/version under test: iOS 10.2 * Real device or emulator/simulator: simulator ## Details 1. When I set wait , I expect element to wait for that time interval itself. 2. But value set for wait is ignored and element waits for default timeout mentioned in PageFactory.initElements 3. Later I tried `@WithTimeout(time = 3, unit = TimeUnit.SECONDS)` for this element but still it waits for defaulttime, my understanding is this particular tag overrides the default time. ## Code To Reproduce Issue [ Good To Have ] NA ## Ecxeption stacktraces NA ## Link to Appium logs https://gist.github.com/vikramvi/2eedd0643f89140fa3d6ffac8f347644
    df7168b4c39fb0ea914150b89fb1a34d552468b5
    615ef51b07a5a0fc471a278b7602146f83047706
    https://github.com/appium/java-client/compare/df7168b4c39fb0ea914150b89fb1a34d552468b5...615ef51b07a5a0fc471a278b7602146f83047706
    diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java index 1f1c9c0f..6ce4e3b1 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java @@ -151,6 +151,10 @@ class AppiumElementLocator implements CacheableLocator { return shouldCache; } + @Override public String toString() { + return String.format("Located by %s", by); + } + // This function waits for not empty element list using all defined by private static class WaitingFunction<T> implements Function<Supplier<T>, T> { diff --git a/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java index 17d4a2a6..a95740af 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java @@ -16,6 +16,8 @@ package io.appium.java_client.pagefactory; +import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; + import io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -37,7 +39,7 @@ class ElementInterceptor extends InterceptorOfASingleElement { try { return method.invoke(element, args); } catch (Throwable t) { - throw ThrowableUtil.extractReadableException(t); + throw extractReadableException(t); } } } diff --git a/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java index 0c326c2f..08c58627 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java @@ -16,6 +16,8 @@ package io.appium.java_client.pagefactory; +import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; + import io.appium.java_client.pagefactory.interceptors.InterceptorOfAListOfElements; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.pagefactory.ElementLocator; @@ -37,7 +39,7 @@ class ElementListInterceptor extends InterceptorOfAListOfElements { try { return method.invoke(elements, args); } catch (Throwable t) { - throw ThrowableUtil.extractReadableException(t); + throw extractReadableException(t); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java index 76823a5c..37fb1c21 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java @@ -16,6 +16,7 @@ package io.appium.java_client.pagefactory; +import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; import io.appium.java_client.pagefactory.bys.ContentType; @@ -76,7 +77,7 @@ class WidgetInterceptor extends InterceptorOfASingleElement { method.setAccessible(true); return method.invoke(cachedInstances.get(type), args); } catch (Throwable t) { - throw ThrowableUtil.extractReadableException(t); + throw extractReadableException(t); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java index 86647f9a..ff4a9f74 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java @@ -16,6 +16,7 @@ package io.appium.java_client.pagefactory; +import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; import io.appium.java_client.pagefactory.bys.ContentType; @@ -70,7 +71,7 @@ class WidgetListInterceptor extends InterceptorOfAListOfElements { try { return method.invoke(cachedWidgets, args); } catch (Throwable t) { - throw ThrowableUtil.extractReadableException(t); + throw extractReadableException(t); } } } diff --git a/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java b/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java index 1dca59a4..6322a3c0 100644 --- a/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java +++ b/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java @@ -23,7 +23,6 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.WrapsDriver; import org.openqa.selenium.support.pagefactory.ElementLocator; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -37,7 +36,7 @@ public abstract class InterceptorOfASingleElement implements MethodInterceptor { } protected abstract Object getObject(WebElement element, Method method, Object[] args) - throws InvocationTargetException, IllegalAccessException, InstantiationException, Throwable; + throws Throwable; /** * Look at @@ -45,6 +44,11 @@ public abstract class InterceptorOfASingleElement implements MethodInterceptor { */ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { + + if (method.getName().equals("toString") && args.length == 0) { + return locator.toString(); + } + if (Object.class.equals(method.getDeclaringClass())) { return proxy.invokeSuper(obj, args); }
    ['src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java', 'src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java', 'src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java', 'src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java', 'src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java', 'src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java']
    {'.java': 6}
    6
    6
    0
    0
    6
    569,817
    119,764
    15,561
    167
    1,206
    199
    26
    6
    1,400
    186
    341
    38
    1
    0
    1970-01-01T00:24:47
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    507
    appium/java-client/568/567
    appium
    java-client
    https://github.com/appium/java-client/issues/567
    https://github.com/appium/java-client/pull/568
    https://github.com/appium/java-client/pull/568
    1
    fix
    5.0.0-BETA2: ClassCastException: WebElement -> IOSElement
    ## Description Failed to cast WebElement into IOSElement. Worked with 5.0.0-BETA1. ## Environment * java client build version or git revision if you use some shapshot: 5.0.0-BETA2 * Appium server version or git revision if you use some shapshot: 1.6.4-beta * Mobile platform/version under test: iOS * Real device or emulator/simulator: Simulator ## Code To Reproduce Issue [ Good To Have ] `((IOSElement) driver.findElement(MobileBy.className("XCUIElementTypePickerWheel"))).setValue(countryName);` ## Ecxeption stacktraces java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to io.appium.java_client.ios.IOSElement
    1d3e9705527435c48005f0a50a60b1371e03bbd1
    b3351034ac0eb7b814ecfcacb1b097b8fd547a55
    https://github.com/appium/java-client/compare/1d3e9705527435c48005f0a50a60b1371e03bbd1...b3351034ac0eb7b814ecfcacb1b097b8fd547a55
    diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java index a3adf2e9..fa9696cf 100644 --- a/src/main/java/io/appium/java_client/AppiumDriver.java +++ b/src/main/java/io/appium/java_client/AppiumDriver.java @@ -76,7 +76,6 @@ public class AppiumDriver<T extends WebElement> private ExecuteMethod executeMethod; private final String platformName; private final String automationName; - private String currentContext; /** @@ -92,19 +91,6 @@ public class AppiumDriver<T extends WebElement> locationContext = new RemoteLocationContext(executeMethod); super.setErrorHandler(errorHandler); this.remoteAddress = executor.getAddressOfRemoteServer(); - final AppiumDriver<?> driver = this; - - HasSessionDetails hasSessionDetails = new HasSessionDetails() { - @Override - public Response execute(String driverCommand, Map<String, ?> parameters) { - return driver.execute(driverCommand, parameters); - } - - @Override - public Response execute(String driverCommand) { - return driver.execute(driverCommand); - } - }; Object capabilityPlatform1 = getCapabilities().getCapability(PLATFORM_NAME); Object capabilityAutomation1 = getCapabilities().getCapability(AUTOMATION_NAME); @@ -112,15 +98,14 @@ public class AppiumDriver<T extends WebElement> Object capabilityPlatform2 = capabilities.getCapability(PLATFORM_NAME); Object capabilityAutomation2 = capabilities.getCapability(AUTOMATION_NAME); - platformName = ofNullable(ofNullable(hasSessionDetails.getPlatformName()) + platformName = ofNullable(ofNullable(super.getPlatformName()) .orElse(capabilityPlatform1 != null ? String.valueOf(capabilityPlatform1) : null)) .orElse(capabilityPlatform2 != null ? String.valueOf(capabilityPlatform2) : null); - automationName = ofNullable(ofNullable(hasSessionDetails.getAutomationName()) + automationName = ofNullable(ofNullable(super.getAutomationName()) .orElse(capabilityAutomation1 != null ? String.valueOf(capabilityAutomation1) : null)) .orElse(capabilityAutomation2 != null ? String.valueOf(capabilityAutomation2) : null); this.setElementConverter(new JsonToMobileElementConverter(this, this)); - currentContext = getContext(); } public AppiumDriver(URL remoteAddress, Capabilities desiredCapabilities) { @@ -352,7 +337,6 @@ public class AppiumDriver<T extends WebElement> @Override public WebDriver context(String name) { checkNotNull(name, "Must supply a context name"); execute(DriverCommand.SWITCH_TO_CONTEXT, ImmutableMap.of("name", name)); - currentContext = name; return this; } @@ -430,9 +414,6 @@ public class AppiumDriver<T extends WebElement> } @Override public boolean isBrowser() { - if (super.isBrowser()) { - return true; - } - return !currentContext.toLowerCase().contains("NATIVE_APP".toLowerCase()); + return !getContext().toLowerCase().contains("NATIVE_APP".toLowerCase()); } } diff --git a/src/main/java/io/appium/java_client/HasSessionDetails.java b/src/main/java/io/appium/java_client/HasSessionDetails.java index 2e91b7b8..3106b290 100644 --- a/src/main/java/io/appium/java_client/HasSessionDetails.java +++ b/src/main/java/io/appium/java_client/HasSessionDetails.java @@ -55,8 +55,5 @@ public interface HasSessionDetails extends ExecutesMethod { /** * @return is focus on browser or on native content. */ - default boolean isBrowser() { - Object browserName = getSessionDetail("browserName"); - return browserName != null && !isBlank(String.valueOf(browserName)); - } + boolean isBrowser(); } diff --git a/src/main/java/io/appium/java_client/internal/ElementMap.java b/src/main/java/io/appium/java_client/internal/ElementMap.java index 3dacc2ce..9435a7e7 100644 --- a/src/main/java/io/appium/java_client/internal/ElementMap.java +++ b/src/main/java/io/appium/java_client/internal/ElementMap.java @@ -18,6 +18,7 @@ package io.appium.java_client.internal; import com.google.common.collect.ImmutableMap; +import io.appium.java_client.HasSessionDetails; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.ios.IOSElement; @@ -69,14 +70,17 @@ public enum ElementMap { } /** - * @param platform platform name. - * @param automation automation name. + * @param hasSessionDetails something that implements {@link io.appium.java_client.HasSessionDetails}. * @return subclass of {@link io.appium.java_client.MobileElement} that convenient to current session details. */ - public static Class<? extends RemoteWebElement> getElementClass(String platform, String automation) { + public static Class<? extends RemoteWebElement> getElementClass(HasSessionDetails hasSessionDetails) { + if (hasSessionDetails == null) { + return RemoteWebElement.class; + } ElementMap element = Optional.ofNullable(mobileElementMap.get(String - .valueOf(automation).toLowerCase().trim())) - .orElse(mobileElementMap.get(String.valueOf(platform).toLowerCase().trim())); + .valueOf(hasSessionDetails.getAutomationName()).toLowerCase().trim())) + .orElse(mobileElementMap + .get(String.valueOf(hasSessionDetails.getPlatformName()).toLowerCase().trim())); if (element == null) { return RemoteWebElement.class; } diff --git a/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java b/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java index a2bb0143..103963d1 100644 --- a/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java +++ b/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java @@ -87,13 +87,7 @@ public class JsonToMobileElementConverter extends JsonToWebElementConverter { protected RemoteWebElement newMobileElement() { Class<? extends RemoteWebElement> target; - if (hasSessionDetails.isBrowser()) { - target = getElementClass(null, null); - } else { - target = getElementClass(hasSessionDetails.getPlatformName(), - hasSessionDetails.getAutomationName()); - } - + target = getElementClass(hasSessionDetails); try { Constructor<? extends RemoteWebElement> constructor = target.getDeclaredConstructor(); constructor.setAccessible(true); diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java index 7ac6d1f0..0f7f3990 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java @@ -72,18 +72,8 @@ public class AppiumFieldDecorator implements FieldDecorator { private final String platform; private final String automation; private final TimeOutDuration timeOutDuration; + private final HasSessionDetails hasSessionDetails; - private static String extractSessionData(WebDriver driver, Supplier<String> dataSupplier) { - if (driver == null) { - return null; - } - - if (!(driver instanceof HasSessionDetails)) { - return null; - } - - return String.valueOf(dataSupplier.get()); - } public AppiumFieldDecorator(SearchContext context, long implicitlyWaitTimeOut, TimeUnit timeUnit) { @@ -100,10 +90,17 @@ public class AppiumFieldDecorator implements FieldDecorator { */ public AppiumFieldDecorator(SearchContext context, TimeOutDuration timeOutDuration) { this.originalDriver = unpackWebDriverFromSearchContext(context); - platform = extractSessionData(originalDriver, () -> - HasSessionDetails.class.cast(originalDriver).getPlatformName()); - automation = extractSessionData(originalDriver, () -> - HasSessionDetails.class.cast(originalDriver).getAutomationName()); + if (originalDriver == null + || !HasSessionDetails.class.isAssignableFrom(originalDriver.getClass())) { + hasSessionDetails = null; + platform = null; + automation = null; + } else { + hasSessionDetails = HasSessionDetails.class.cast(originalDriver); + platform = hasSessionDetails.getPlatformName(); + automation = hasSessionDetails.getAutomationName(); + } + this.timeOutDuration = timeOutDuration; defaultElementFieldDecoracor = new DefaultFieldDecorator( @@ -221,6 +218,6 @@ public class AppiumFieldDecorator implements FieldDecorator { private WebElement proxyForAnElement(ElementLocator locator) { ElementInterceptor elementInterceptor = new ElementInterceptor(locator, originalDriver); - return getEnhancedProxy(getElementClass(platform, automation), elementInterceptor); + return getEnhancedProxy(getElementClass(hasSessionDetails), elementInterceptor); } } diff --git a/src/test/java/io/appium/java_client/appium/element/generation/android/AndroidElementGeneratingTest.java b/src/test/java/io/appium/java_client/appium/element/generation/android/AndroidElementGeneratingTest.java index ae2d1112..dc1d8947 100644 --- a/src/test/java/io/appium/java_client/appium/element/generation/android/AndroidElementGeneratingTest.java +++ b/src/test/java/io/appium/java_client/appium/element/generation/android/AndroidElementGeneratingTest.java @@ -13,7 +13,6 @@ import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.remote.MobilePlatform; import org.junit.Test; import org.openqa.selenium.remote.DesiredCapabilities; -import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.util.function.Supplier; @@ -49,7 +48,7 @@ public class AndroidElementGeneratingTest extends BaseElementGenerationTest { }, (by, aClass) -> { driver.context("WEBVIEW_io.appium.android.apis"); return commonPredicate.test(by, aClass); - }, tagName("a"), RemoteWebElement.class)); + }, tagName("a"), AndroidElement.class)); } @Test public void whenAndroidBrowserIsLaunched() { @@ -65,6 +64,6 @@ public class AndroidElementGeneratingTest extends BaseElementGenerationTest { }, (by, aClass) -> { driver.get("https://www.google.com"); return commonPredicate.test(by, aClass); - }, className("gsfi"), RemoteWebElement.class)); + }, className("gsfi"), AndroidElement.class)); } } diff --git a/src/test/java/io/appium/java_client/appium/element/generation/ios/IOSElementGenerationTest.java b/src/test/java/io/appium/java_client/appium/element/generation/ios/IOSElementGenerationTest.java index 3c4cd9e7..3d0d995e 100644 --- a/src/test/java/io/appium/java_client/appium/element/generation/ios/IOSElementGenerationTest.java +++ b/src/test/java/io/appium/java_client/appium/element/generation/ios/IOSElementGenerationTest.java @@ -14,7 +14,6 @@ import io.appium.java_client.remote.MobilePlatform; import org.junit.Test; import org.openqa.selenium.Capabilities; import org.openqa.selenium.remote.DesiredCapabilities; -import org.openqa.selenium.remote.RemoteWebElement; import java.io.File; import java.util.function.Function; @@ -89,7 +88,7 @@ public class IOSElementGenerationTest extends BaseElementGenerationTest { } }); return commonPredicate.test(by, aClass); - }, className("gsfi"), RemoteWebElement.class)); + }, className("gsfi"), IOSElement.class)); } @Test public void whenIOSBrowserIsLaunched() { @@ -97,7 +96,7 @@ public class IOSElementGenerationTest extends BaseElementGenerationTest { clientBrowserCapabilitiesSupplier, (by, aClass) -> { driver.get("https://www.google.com"); return commonPredicate.test(by, aClass); - }, className("gsfi"), RemoteWebElement.class)); + }, className("gsfi"), IOSElement.class)); } @Test @@ -117,6 +116,6 @@ public class IOSElementGenerationTest extends BaseElementGenerationTest { }, clientBrowserCapabilitiesSupplier, (by, aClass) -> { driver.get("https://www.google.com"); return commonPredicate.test(by, aClass); - }, className("gsfi"), RemoteWebElement.class)); + }, className("gsfi"), IOSElement.class)); } }
    ['src/main/java/io/appium/java_client/internal/ElementMap.java', 'src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java', 'src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java', 'src/main/java/io/appium/java_client/AppiumDriver.java', 'src/test/java/io/appium/java_client/appium/element/generation/android/AndroidElementGeneratingTest.java', 'src/test/java/io/appium/java_client/appium/element/generation/ios/IOSElementGenerationTest.java', 'src/main/java/io/appium/java_client/HasSessionDetails.java']
    {'.java': 7}
    7
    7
    0
    0
    7
    570,684
    119,915
    15,588
    167
    3,923
    686
    81
    5
    674
    74
    168
    17
    0
    0
    1970-01-01T00:24:46
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    508
    appium/java-client/468/467
    appium
    java-client
    https://github.com/appium/java-client/issues/467
    https://github.com/appium/java-client/pull/468
    https://github.com/appium/java-client/pull/468
    1
    fixes
    page object pattern, field with "@WithTimeout" would change the global implicit wait time
    ## Description page object pattern, field with "@WithTimeout" would change the global implicit wait time ## Environment Always exists. see code analysis below ## Details in method [AppiumElementLocatorFactory#createLocator](https://github.com/appium/java-client/blob/master/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java#L47): - if the page object field contains annoation `WithTimeout`, it would create a new `TimeOutDuration` instance. - This instance would be passed to `AppiumElementLocator`. - When element tries to find the element. It would invoke method [AppiumElementLocator#waitFor](https://github.com/appium/java-client/blob/master/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java#L92). See the line in `finally` block. it would change the global implicit wait time using the `WithTimeout` value. So this would make the page object and global appium driver implicit wait both change to that value. It would mess the implicit timeout when there are many `WithTimeout` elements in page objects that contains `driver.findElement` methods. There is no getter for implicit wait by design. so it is not easy to fix this. Solution suggestion: IMO changing constructors that also passes original timeout duration as argument, in finally block it would set back to original timeout duration.
    ef779eb9a72926fe0349f18e5fea3146d2995d5a
    31ce398dc771455f42b4673973db150e6940ef7a
    https://github.com/appium/java-client/compare/ef779eb9a72926fe0349f18e5fea3146d2995d5a...31ce398dc771455f42b4673973db150e6940ef7a
    diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java index 5ccfdb09..eb11f441 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java @@ -42,6 +42,7 @@ class AppiumElementLocator implements CacheableLocator { final boolean shouldCache; final By by; final TimeOutDuration timeOutDuration; + private final TimeOutDuration originalTimeOutDuration; final WebDriver originalWebDriver; private final SearchContext searchContext; private final WaitingFunction waitingFunction; @@ -56,16 +57,18 @@ class AppiumElementLocator implements CacheableLocator { * @param by a By locator strategy * @param shouldCache is the flag that signalizes that elements which * are found once should be cached - * @param duration is a POJO which contains timeout parameters + * @param duration is a POJO which contains timeout parameters for the element to be searched + * @param originalDuration is a POJO which contains timeout parameters from page object which contains the element * @param originalWebDriver is an instance of WebDriver that is going to be * used by a proxied element */ public AppiumElementLocator(SearchContext searchContext, By by, boolean shouldCache, - TimeOutDuration duration, WebDriver originalWebDriver) { + TimeOutDuration duration, TimeOutDuration originalDuration, WebDriver originalWebDriver) { this.searchContext = searchContext; this.shouldCache = shouldCache; this.timeOutDuration = duration; + this.originalTimeOutDuration = originalDuration; this.by = by; this.originalWebDriver = originalWebDriver; waitingFunction = new WaitingFunction(this.searchContext); @@ -89,7 +92,7 @@ class AppiumElementLocator implements CacheableLocator { } catch (TimeoutException e) { return new ArrayList<>(); } finally { - changeImplicitlyWaitTimeOut(timeOutDuration.getTime(), timeOutDuration.getTimeUnit()); + changeImplicitlyWaitTimeOut(originalTimeOutDuration.getTime(), originalTimeOutDuration.getTimeUnit()); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java index fa13938e..1b9c8ebe 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java @@ -57,7 +57,7 @@ class AppiumElementLocatorFactory implements CacheableElementLocatorFactory { By by = builder.buildBy(); if (by != null) { return new AppiumElementLocator(searchContext, by, builder.isLookupCached(), - customDuration, originalWebDriver); + customDuration, timeOutDuration, originalWebDriver); } return null; }
    ['src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java', 'src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    516,520
    108,730
    14,151
    136
    935
    164
    11
    2
    1,361
    161
    283
    20
    2
    0
    1970-01-01T00:24:33
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    509
    appium/java-client/451/450
    appium
    java-client
    https://github.com/appium/java-client/issues/450
    https://github.com/appium/java-client/pull/451
    https://github.com/appium/java-client/pull/451
    2
    fix
    java -client4.1 "EventFiringWebDriverFactory.getEventFiringWebDriver"capabilities turn to null
    ## Description use java-client 4.1 found :+1: capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, browser_Name); capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, platform_Name); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,device_Name); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, platform_Version); ``` driver = new AndroidDriver(new URL(hubURL),capabilities); driver2= EventFiringWebDriverFactory.getEventFiringWebDriver(driver, new AlertListener(), new ElementListener()); ``` the driver2 is null!!!!! when i debug found when the code run into "EventFiringWebDriverFactory.getEventFiringWebDriver(driver, new AlertListener(), new ElementListener());" the capabilities turn to null; ## Environment jdk 1,7 java -client 4.1 selenium 2.53
    bd19d78b0696aec602e4685b314e818af9b2dddb
    a3065c24c338e7ecf266da9f155e60a32f1048ac
    https://github.com/appium/java-client/compare/bd19d78b0696aec602e4685b314e818af9b2dddb...a3065c24c338e7ecf266da9f155e60a32f1048ac
    diff --git a/src/main/java/io/appium/java_client/events/DefaultAspect.java b/src/main/java/io/appium/java_client/events/DefaultAspect.java index 3bec135a..652c17a8 100644 --- a/src/main/java/io/appium/java_client/events/DefaultAspect.java +++ b/src/main/java/io/appium/java_client/events/DefaultAspect.java @@ -156,7 +156,7 @@ class DefaultAspect { return null; } - Object result = null; + Object result = toBeTransformed; if (getClassForProxy(toBeTransformed.getClass()) != null) { result = context.getBean(DefaultBeanConfiguration.COMPONENT_BEAN, toBeTransformed); } diff --git a/src/main/java/io/appium/java_client/events/DefaultListener.java b/src/main/java/io/appium/java_client/events/DefaultListener.java index e665ad5e..e33b11eb 100644 --- a/src/main/java/io/appium/java_client/events/DefaultListener.java +++ b/src/main/java/io/appium/java_client/events/DefaultListener.java @@ -42,7 +42,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -public class DefaultListener implements Listener, AppiumWebDriverEventListener, ListensToException, +class DefaultListener implements Listener, AppiumWebDriverEventListener, ListensToException, SearchingEventListener, NavigationEventListener, JavaScriptEventListener, ElementEventListener, AlertEventListener, WindowEventListener, ContextEventListener, RotationEventListener { diff --git a/src/test/java/io/appium/java_client/events/DefaultEventListenerTest.java b/src/test/java/io/appium/java_client/events/DefaultEventListenerTest.java index 084b5918..a2dfc33a 100644 --- a/src/test/java/io/appium/java_client/events/DefaultEventListenerTest.java +++ b/src/test/java/io/appium/java_client/events/DefaultEventListenerTest.java @@ -1,6 +1,8 @@ package io.appium.java_client.events; import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import io.appium.java_client.events.listeners.AlertListener; @@ -18,6 +20,7 @@ import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; +import org.openqa.selenium.Capabilities; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DefaultEventListenerTest extends BaseListenerTest { @@ -88,4 +91,11 @@ public class DefaultEventListenerTest extends BaseListenerTest { assertThat(super.assertThatWindowListenerWorks(driver, SingleListeners .listeners.get(WindowListener.class), StringUtils.EMPTY), is(true)); } + + @Test + public void whenNonListenableObjectIsReturned() { + Capabilities capabilities = driver.getCapabilities(); + assertNotNull(capabilities); + assertEquals(capabilities.asMap().size(), 2); + } } diff --git a/src/test/java/io/appium/java_client/events/EmptyWebDriver.java b/src/test/java/io/appium/java_client/events/EmptyWebDriver.java index b3763040..64e7c8f9 100644 --- a/src/test/java/io/appium/java_client/events/EmptyWebDriver.java +++ b/src/test/java/io/appium/java_client/events/EmptyWebDriver.java @@ -10,7 +10,9 @@ import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.ContextAware; +import org.openqa.selenium.Capabilities; import org.openqa.selenium.Cookie; +import org.openqa.selenium.HasCapabilities; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Rotatable; import org.openqa.selenium.ScreenOrientation; @@ -24,15 +26,18 @@ import org.openqa.selenium.internal.FindsByLinkText; import org.openqa.selenium.internal.FindsByTagName; import org.openqa.selenium.internal.FindsByXPath; import org.openqa.selenium.logging.Logs; +import org.openqa.selenium.remote.DesiredCapabilities; import java.net.URL; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; public class EmptyWebDriver implements WebDriver, ContextAware, Rotatable, FindsByClassName, FindsByCssSelector, FindsById, FindsByLinkText, FindsByTagName, FindsByXPath, FindsByAccessibilityId<StubWebElement>, FindsByAndroidUIAutomator<StubWebElement>, - FindsByIosUIAutomation<StubWebElement>, JavascriptExecutor { + FindsByIosUIAutomation<StubWebElement>, JavascriptExecutor, HasCapabilities { private static List<StubWebElement> createStubList() { return ImmutableList.of(new StubWebElement(), new StubWebElement()); @@ -198,6 +203,13 @@ public class EmptyWebDriver implements WebDriver, ContextAware, Rotatable, Finds return null; } + @Override public Capabilities getCapabilities() { + Map<String, Object> map = new HashMap<>(); + map.put("0",StringUtils.EMPTY); + map.put("1",StringUtils.EMPTY); + return new DesiredCapabilities(map); + } + private class StubTargetLocator implements TargetLocator { private final WebDriver driver;
    ['src/main/java/io/appium/java_client/events/DefaultListener.java', 'src/test/java/io/appium/java_client/events/EmptyWebDriver.java', 'src/test/java/io/appium/java_client/events/DefaultEventListenerTest.java', 'src/main/java/io/appium/java_client/events/DefaultAspect.java']
    {'.java': 4}
    4
    4
    0
    0
    4
    505,422
    106,832
    13,934
    140
    266
    48
    4
    2
    855
    59
    189
    25
    0
    1
    1970-01-01T00:24:30
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    511
    appium/java-client/317/311
    appium
    java-client
    https://github.com/appium/java-client/issues/311
    https://github.com/appium/java-client/pull/317
    https://github.com/appium/java-client/pull/317
    1
    fix
    Update page object features. Server node 1.5.x
    These things should be done: - mark _name_ parameter _Decrecated_ as _By.name_ selector is not supported by native app automation - _By.id_ selector should be used by default (native content) when not any selector strategy defined. - _org.openqa.selenium.InvalidSelectorException_ should be handled.
    8f88f67ff6a8c63b5d37d93864600e63455f6889
    5ed8b9e5ac3b4eda1ee20788cba31c0899220dea
    https://github.com/appium/java-client/compare/8f88f67ff6a8c63b5d37d93864600e63455f6889...5ed8b9e5ac3b4eda1ee20788cba31c0899220dea
    diff --git a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java index 1dd3e485..5569fe83 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java @@ -35,7 +35,11 @@ public @interface AndroidFindBy { String uiAutomator() default ""; String accessibility() default ""; String id() default ""; - String name() default ""; + @Deprecated + /** + * By.name selector is not supported by Appium server node since 1.5.x. + * So this option is going to be removed further. Be careful. + */String name() default ""; String className() default ""; String tagName() default ""; String xpath() default ""; diff --git a/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java index a9825902..3e581a0e 100644 --- a/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java @@ -16,9 +16,6 @@ package io.appium.java_client.pagefactory; -import static io.appium.java_client.remote.MobilePlatform.*; -import static io.appium.java_client.remote.AutomationName.*; - import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.HashMap; @@ -117,8 +114,7 @@ class DefaultElementByBuilder extends AppiumByBuilder { @Override protected By buildMobileNativeBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); - if (ANDROID.toUpperCase().equals(platform) - && SELENDROID.toUpperCase().equals(automation)) { + if (isSelendroidAutomation()) { SelendroidFindBy selendroidFindBy = annotatedElement.getAnnotation(SelendroidFindBy.class); SelendroidFindBys selendroidFindBys = annotatedElement.getAnnotation(SelendroidFindBys.class); SelendroidFindAll selendroidFindByAll = annotatedElement.getAnnotation(SelendroidFindAll.class); @@ -136,7 +132,7 @@ class DefaultElementByBuilder extends AppiumByBuilder { } } - if (ANDROID.toUpperCase().equals(platform)) { + if (isAndroid()) { AndroidFindBy androidFindBy = annotatedElement.getAnnotation(AndroidFindBy.class); AndroidFindBys androidFindBys= annotatedElement.getAnnotation(AndroidFindBys.class); AndroidFindAll androidFindAll = annotatedElement.getAnnotation(AndroidFindAll.class); @@ -154,7 +150,7 @@ class DefaultElementByBuilder extends AppiumByBuilder { } } - if (IOS.toUpperCase().equals(platform)) { + if (isIOS()) { iOSFindBy iOSFindBy = annotatedElement.getAnnotation(iOSFindBy.class); iOSFindBys iOSFindBys= annotatedElement.getAnnotation(iOSFindBys.class); iOSFindAll iOSFindAll = annotatedElement.getAnnotation(iOSFindAll.class); @@ -181,6 +177,13 @@ class DefaultElementByBuilder extends AppiumByBuilder { return (annotatedElement.getAnnotation(CacheLookup.class) != null); } + private By returnMappedBy(By byDefault, By nativeAppBy) { + Map<ContentType, By> contentMap = new HashMap<>(); + contentMap.put(ContentType.HTML_OR_DEFAULT, byDefault); + contentMap.put(ContentType.NATIVE_MOBILE_SPECIFIC, nativeAppBy); + return new ContentMappedBy(contentMap); + } + @Override public By buildBy() { assertValidAnnotations(); @@ -188,18 +191,24 @@ class DefaultElementByBuilder extends AppiumByBuilder { By defaultBy = buildDefaultBy(); By mobileNativeBy = buildMobileNativeBy(); - if (defaultBy == null) { + String idOrName = ((Field) annotatedElementContainer.getAnnotated()).getName(); + + if (defaultBy == null && mobileNativeBy == null) { defaultBy = new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); + mobileNativeBy = new By.ById(idOrName); + return returnMappedBy(defaultBy, mobileNativeBy); } + if (defaultBy == null) { + defaultBy = new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); + return returnMappedBy(defaultBy, mobileNativeBy); + } if (mobileNativeBy == null) { mobileNativeBy = defaultBy; + return returnMappedBy(defaultBy, mobileNativeBy); } - Map<ContentType, By> contentMap = new HashMap<>(); - contentMap.put(ContentType.HTML_OR_DEFAULT, defaultBy); - contentMap.put(ContentType.NATIVE_MOBILE_SPECIFIC, mobileNativeBy); - return new ContentMappedBy(contentMap); + return returnMappedBy(defaultBy, mobileNativeBy); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java b/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java index b7c71fe9..bcfb18bf 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java +++ b/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java @@ -16,6 +16,7 @@ package io.appium.java_client.pagefactory; +import org.openqa.selenium.InvalidSelectorException; import org.openqa.selenium.StaleElementReferenceException; import java.lang.reflect.InvocationTargetException; @@ -28,7 +29,11 @@ class ThrowableUtil { return false; } - if (String.valueOf(e.getMessage()).contains(INVALID_SELECTOR_PATTERN)) { + if (InvalidSelectorException.class.isAssignableFrom(e.getClass())) { + return true; + } + + if (String.valueOf(e.getMessage()).contains(INVALID_SELECTOR_PATTERN) || String.valueOf(e.getMessage()).contains("Locator Strategy \\\\w+ is not supported")) { return true; } diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java index f07c0178..5602331a 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java @@ -24,6 +24,10 @@ import java.lang.reflect.*; import java.util.ArrayList; import java.util.List; +import static io.appium.java_client.remote.AutomationName.SELENDROID; +import static io.appium.java_client.remote.MobilePlatform.ANDROID; +import static io.appium.java_client.remote.MobilePlatform.IOS; + /** * It is the basic handler of Appium-specific page object annotations * About the Page Object design pattern please read these documents: @@ -163,6 +167,18 @@ public abstract class AppiumByBuilder extends AbstractAnnotations { this.annotatedElementContainer.setAnnotated(annotated); } + protected boolean isAndroid() { + return ANDROID.toUpperCase().equals(platform); + } + + protected boolean isSelendroidAutomation() { + return isAndroid() && SELENDROID.toUpperCase().equals(automation); + } + + protected boolean isIOS() { + return IOS.toUpperCase().equals(platform); + } + /** * Defines how to transform given object (field, class, etc) * into {@link org.openqa.selenium.By} class used by webdriver to locate elements. diff --git a/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java b/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java index b666df94..6f38ed2a 100644 --- a/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java @@ -35,7 +35,11 @@ public @interface iOSFindBy { String uiAutomator() default ""; String accessibility() default ""; String id() default ""; - String name() default ""; + @Deprecated + /** + * By.name selector is not supported by Appium server node since 1.5.x. + * So this option is going to be removed further. Be careful. + */String name() default ""; String className() default ""; String tagName() default ""; String xpath() default ""; diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java index dee99a56..3fe6773b 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java @@ -41,18 +41,18 @@ import java.util.concurrent.TimeUnit; public class MobileBrowserCompatibilityTest { private WebDriver driver; - - @FindBy(name = "q") - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/someId\\")") - private WebElement searchTextField; + private AppiumDriverLocalService service; @AndroidFindBys({ @AndroidFindBy(className = "someClass"), @AndroidFindBy(xpath = "//someTag")}) - @FindBy(name="btnG") - private RemoteWebElement searchButton; - + private RemoteWebElement btnG; //this element should be found by id = 'btnG' or name = 'btnG' + + @FindBy(name = "q") + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/someId\\")") + private WebElement searchTextField; + @AndroidFindBy(className = "someClass") @FindBys({@FindBy(className = "r"), @FindBy(tagName = "a")}) private List<WebElement> foundLinks; @@ -84,7 +84,7 @@ public class MobileBrowserCompatibilityTest { driver.get("https://www.google.com"); searchTextField.sendKeys("Hello"); - searchButton.click(); + btnG.click(); Assert.assertNotEquals(0, foundLinks.size()); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java index b3129e67..fd15db3f 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java @@ -17,6 +17,7 @@ package io.appium.java_client.pagefactory_tests; import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.*; import io.appium.java_client.remote.AutomationName; import io.appium.java_client.remote.MobileCapabilityType; @@ -37,7 +38,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class SelendroidModeTest { - private static int SELENDROID_PORT = 9999; + private static int SELENDROID_PORT = 9999; private static WebDriver driver; private static AppiumDriverLocalService service; @@ -63,15 +64,15 @@ public class SelendroidModeTest { private WebElement textXpath; @SelendroidFindBys({ - @SelendroidFindBy(id = "text1")}) + @SelendroidFindBy(id = "text1")}) private WebElement textIds; @SelendroidFindAll({ - @SelendroidFindBy(id = "text1")}) + @SelendroidFindBy(id = "text1")}) private WebElement textAll; @SelendroidFindAll({ - @SelendroidFindBy(id = "text1")}) + @SelendroidFindBy(id = "text1")}) private List<WebElement> textsAll; @SelendroidFindBy(className = "android.widget.TextView") @@ -79,14 +80,14 @@ public class SelendroidModeTest { @SelendroidFindBy(tagName = "TextView") private WebElement textTag; - + @SelendroidFindBy(linkText = "Accessibility") private WebElement textLink; - + @SelendroidFindBy(partialLinkText = "ccessibilit") private WebElement textPartialLink; - @BeforeClass + @BeforeClass public static void beforeClass() throws Exception { AppiumServiceBuilder builder = new AppiumServiceBuilder().withArgument(GeneralServerFlag.AUTOMATION_NAME, AutomationName.SELENDROID); service = builder.build(); @@ -123,8 +124,8 @@ public class SelendroidModeTest { public void findByIdElementTest() { assertNotEquals(null, textId.getAttribute("text")); } - - @Test + + @Test public void findBySelendroidSelectorTest() { assertNotEquals(null, textSelendroidId.getAttribute("text")); } @@ -173,15 +174,15 @@ public class SelendroidModeTest { public void findByElementByTagTest() { assertNotEquals(null, textTag.getAttribute("text")); } - + @Test public void findBySelendroidAnnotationOnlyTest() { assertNotEquals(null, textSelendroidId.getAttribute("text")); } - + @Test public void findBySelendroidLinkTextTest() { assertEquals("Accessibility", textLink.getText()); } -} +} \\ No newline at end of file diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java index ac7c04d1..5805b736 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java @@ -37,9 +37,9 @@ import java.util.List; public class iOSPageObjectTest { - private static WebDriver driver; - private static AppiumDriverLocalService service; - private boolean populated = false; + private static WebDriver driver; + private static AppiumDriverLocalService service; + private boolean populated = false; @FindBy(className = "UIAButton") private List<WebElement> uiButtons; @@ -67,9 +67,9 @@ public class iOSPageObjectTest { private List<RemoteWebElement> remoteElementViews; @AndroidFindBys({ - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), + @AndroidFindBy(className = "android.widget.TextView") + }) private List<WebElement> chainElementViews; @@ -92,11 +92,11 @@ public class iOSPageObjectTest { @iOSFindBy(uiAutomator = ".elements()[0]") private MobileElement mobileButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private TouchableElement touchableButton; + @iOSFindBy(uiAutomator = ".elements()[0]") + private TouchableElement touchableButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List<TouchableElement> touchableButtons; + @iOSFindBy(uiAutomator = ".elements()[0]") + private List<TouchableElement> touchableButtons; @FindBy(className = "UIAButton") private MobileElement mobiletFindBy_Button; @@ -105,69 +105,70 @@ public class iOSPageObjectTest { private RemoteWebElement remotetextVieW; @AndroidFindBys({ - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\\"android:id/list\\")"), + @AndroidFindBy(className = "android.widget.TextView") + }) private WebElement chainElementView; - + @iOSFindBy(uiAutomator = ".elements()[0]") private IOSElement iosButton; - + @iOSFindBy(uiAutomator = ".elements()[0]") private List<IOSElement> iosButtons; - + @iOSFindAll({ - @iOSFindBy(xpath = "ComputeSumButton_Test"), - @iOSFindBy(name = "ComputeSumButton") //it is real locator + @iOSFindBy(id = "ComputeSumButton_Test"), + @iOSFindBy(xpath = "//*[@name = \\"ComputeSumButton\\"]") //it is real locator }) private WebElement findAllElement; - + @iOSFindAll({ - @iOSFindBy(xpath = "ComputeSumButton_Test"), - @iOSFindBy(name = "ComputeSumButton") //it is real locator + @iOSFindBy(id = "ComputeSumButton_Test"), + @iOSFindBy(xpath = "//*[@name = \\"ComputeSumButton\\"]") //it is real locator }) private List<WebElement> findAllElements; - @AndroidFindBy(className = "android.widget.TextView") - @FindBy(css = "e.e1.e2") - private List<WebElement> elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - - @AndroidFindBy(className = "android.widget.TextView") - @FindBy(css = "e.e1.e2") - private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - - - @BeforeClass - public static void beforeClass() throws Exception { - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); + @AndroidFindBy(className = "android.widget.TextView") + @FindBy(css = "e.e1.e2") + private List<WebElement> elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "TestApp.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver<>(service.getUrl(), capabilities); - } + @AndroidFindBy(className = "android.widget.TextView") + @FindBy(css = "e.e1.e2") + private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; + + + @BeforeClass + public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "TestApp.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } + @SuppressWarnings("rawtypes") @Before public void setUp() throws Exception { - if (!populated) - PageFactory.initElements(new AppiumFieldDecorator(driver), this); + if (!populated) + PageFactory.initElements(new AppiumFieldDecorator(driver), this); - populated = true; + populated = true; } - @AfterClass - public static void afterClass() throws Exception { - if (driver != null) - driver.quit(); + @AfterClass + public static void afterClass() throws Exception { + if (driver != null) + driver.quit(); - if (service != null) - service.stop(); - } + if (service != null) + service.stop(); + } @Test public void findByElementsTest() { @@ -273,7 +274,7 @@ public class iOSPageObjectTest { } Assert.assertNotNull(nsee); } - + @Test public void isIOSElementTest(){ Assert.assertNotEquals(null, iosButton.getText()); @@ -294,38 +295,38 @@ public class iOSPageObjectTest { Assert.assertNotEquals(null, findAllElement.getText()); } - @Test - public void isTouchAbleElement(){ - Assert.assertNotEquals(null, touchableButton.getText()); - } + @Test + public void isTouchAbleElement(){ + Assert.assertNotEquals(null, touchableButton.getText()); + } - @Test - public void areTouchAbleElements(){ - Assert.assertNotEquals(0, touchableButtons.size()); - } + @Test + public void areTouchAbleElements(){ + Assert.assertNotEquals(0, touchableButtons.size()); + } - @Test - @SuppressWarnings("unused") - public void isTheFieldIOSElement(){ + @Test + public void isTheFieldIOSElement(){ + @SuppressWarnings("unused") IOSElement iOSElement = (IOSElement) mobileButton; //declared as MobileElement - iOSElement = (IOSElement) iosUIAutomatorButton; //declared as WebElement - iOSElement = (IOSElement) remotetextVieW; //declared as RemoteWebElement - iOSElement = (IOSElement) touchableButton; //declared as TouchABLEElement - } - - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy(){ - try { - Assert.assertNotEquals(null, elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); - } - catch (NoSuchElementException ignored){ - return; - } - throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); - } - - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List(){ - Assert.assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); - } -} + iOSElement = (IOSElement) iosUIAutomatorButton; //declared as WebElement + iOSElement = (IOSElement) remotetextVieW; //declared as RemoteWebElement + iOSElement = (IOSElement) touchableButton; //declared as TouchABLEElement + } + + @Test + public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy(){ + try { + Assert.assertNotEquals(null, elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); + } + catch (NoSuchElementException ignored){ + return; + } + throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); + } + + @Test + public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List(){ + Assert.assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); + } +} \\ No newline at end of file
    ['src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java', 'src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java', 'src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java', 'src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java', 'src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java', 'src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java', 'src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java', 'src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java']
    {'.java': 8}
    8
    8
    0
    0
    8
    353,902
    76,522
    10,060
    108
    3,034
    629
    68
    5
    301
    41
    66
    5
    0
    0
    1970-01-01T00:24:15
    1,098
    Java
    {'Java': 1674245, 'HTML': 80758}
    Apache License 2.0
    393
    javers/javers/541/455
    javers
    javers
    https://github.com/javers/javers/issues/455
    https://github.com/javers/javers/pull/541
    https://github.com/javers/javers/pull/541
    1
    fix
    MySQL error: Specified key was too long; max key length is 767 bytes
    Hi, I'm initializing repository this way: ``` JaversSqlRepository sqlRepository = SqlRepositoryBuilder.sqlRepository() .withConnectionProvider(connectionProvider) .withDialect(DialectName.MYSQL) .build(); Javers javers = JaversBuilder.javers().registerJaversRepository(sqlRepository).build(); ``` however I get an error in the application: ``` 13:22:18,689 INFO SqlRepositoryBuilder:55 - starting up SQL repository module ... 13:22:18,719 INFO Java8AddOns:13 - loading Java8 add-ons ... 13:22:18,738 INFO ScannerModule:28 - using FIELD mappingStyle 13:22:18,753 INFO JaversSchemaManager:244 - creating javers table jv_commit_property ... 13:22:18,753 INFO SchemaManagerImpl:51 - creating entity with name jv_commit_property using ddl: CREATE TABLE jv_commit_property ( property_name VARCHAR(200), property_value VARCHAR(200), commit_fk BIGINT, CONSTRAINT jv_commit_property_pk PRIMARY KEY(commit_fk, property_name), CONSTRAINT jv_commit_property_commit_fk FOREIGN KEY(commit_fk) REFERENCES jv_commit(commit_pk) ) ENGINE = InnoDB 13:22:18,755 WARN RequestCycleExtra:346 - ******************************** 13:22:18,755 WARN RequestCycleExtra:347 - Handling the following exception org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL: CREATE TABLE jv_commit_property ( property_name VARCHAR(200), property_value VARCHAR(200), commit_fk BIGINT, CONSTRAINT jv_commit_property_pk PRIMARY KEY(commit_fk, property_name), CONSTRAINT jv_commit_property_commit_fk FOREIGN KEY(commit_fk) REFERENCES jv_commit(commit_pk) ) ENGINE = InnoDB at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:91) at org.polyjdbc.core.schema.SchemaManagerImpl.create(SchemaManagerImpl.java:52) at org.javers.repository.sql.schema.JaversSchemaManager.ensureTable(JaversSchemaManager.java:245) at org.javers.repository.sql.schema.JaversSchemaManager.ensureSchema(JaversSchemaManager.java:42) at org.javers.repository.sql.JaversSqlRepository.ensureSchema(JaversSqlRepository.java:81) at org.javers.core.JaversBuilder.build(JaversBuilder.java:107) at cz.jaclean.pages.TestPage.onInitialize(TestPage.java:56) at org.apache.wicket.Component.fireInitialize(Component.java:891) at org.apache.wicket.MarkupContainer.internalInitialize(MarkupContainer.java:1081) at org.apache.wicket.Page.isPageStateless(Page.java:465) at org.apache.wicket.request.handler.render.WebPageRenderer.isPageStateless(WebPageRenderer.java:287) at org.apache.wicket.request.handler.render.WebPageRenderer.shouldRenderPageAndWriteResponse(WebPageRenderer.java:329) at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:193) at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:175) at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:895) at org.apache.wicket.request.RequestHandlerStack.execute(RequestHandlerStack.java:64) at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:265) at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:222) at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:293) at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:261) at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:203) at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:284) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1668) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:523) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) at java.lang.Thread.run(Thread.java:745) Caused by: java.sql.SQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:560) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:537) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:527) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115) at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2011) at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1964) at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:891) at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:795) at com.mchange.v2.c3p0.impl.NewProxyStatement.execute(NewProxyStatement.java:75) at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:88) ... 44 more 13:22:18,757 WARN RequestCycleExtra:348 - ******************************** 13:22:18,758 ERROR DefaultExceptionMapper:170 - Unexpected error occurred org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL: CREATE TABLE jv_commit_property ( property_name VARCHAR(200), property_value VARCHAR(200), commit_fk BIGINT, CONSTRAINT jv_commit_property_pk PRIMARY KEY(commit_fk, property_name), CONSTRAINT jv_commit_property_commit_fk FOREIGN KEY(commit_fk) REFERENCES jv_commit(commit_pk) ) ENGINE = InnoDB at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:91) at org.polyjdbc.core.schema.SchemaManagerImpl.create(SchemaManagerImpl.java:52) at org.javers.repository.sql.schema.JaversSchemaManager.ensureTable(JaversSchemaManager.java:245) at org.javers.repository.sql.schema.JaversSchemaManager.ensureSchema(JaversSchemaManager.java:42) at org.javers.repository.sql.JaversSqlRepository.ensureSchema(JaversSqlRepository.java:81) at org.javers.core.JaversBuilder.build(JaversBuilder.java:107) at cz.jaclean.pages.TestPage.onInitialize(TestPage.java:56) at org.apache.wicket.Component.fireInitialize(Component.java:891) at org.apache.wicket.MarkupContainer.internalInitialize(MarkupContainer.java:1081) at org.apache.wicket.Page.isPageStateless(Page.java:465) at org.apache.wicket.request.handler.render.WebPageRenderer.isPageStateless(WebPageRenderer.java:287) at org.apache.wicket.request.handler.render.WebPageRenderer.shouldRenderPageAndWriteResponse(WebPageRenderer.java:329) at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:193) at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:175) at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:895) at org.apache.wicket.request.RequestHandlerStack.execute(RequestHandlerStack.java:64) at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:265) at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:222) at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:293) at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:261) at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:203) at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:284) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1668) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:523) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) at java.lang.Thread.run(Thread.java:745) Caused by: java.sql.SQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:560) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:537) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:527) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115) at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2011) at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1964) at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:891) at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:795) at com.mchange.v2.c3p0.impl.NewProxyStatement.execute(NewProxyStatement.java:75) at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:88) ... 44 more ``` When I try to run DDL separately in the database: ``` CREATE TABLE jv_commit_property ( property_name VARCHAR(200), property_value VARCHAR(200), commit_fk BIGINT, CONSTRAINT jv_commit_property_pk PRIMARY KEY(commit_fk, property_name), CONSTRAINT jv_commit_property_commit_fk FOREIGN KEY(commit_fk) REFERENCES jv_commit(commit_pk) ) ENGINE = InnoDB ``` I get the same error.. As you do not specify encoding and my database used utf16_czech_ci collation, this maxed out allowed 767 bytes for a key size. After setting it to utf8_czech_ci, the problem went away. Either it would be good to specify encoding or check encoding first and then set a limit on a key. Related discussions: [#1071 - Specified key was too long; max key length is 767 bytes](http://stackoverflow.com/questions/1814532/1071-specified-key-was-too-long-max-key-length-is-767-bytes) [UTF8, UTF16, and UTF32](http://stackoverflow.com/questions/496321/utf8-utf16-and-utf32)
    174c15278998eb1ba17809c40c2199eb7f411da4
    36fae3ed1f9822be9eba4afc2c0ee7490fff6684
    https://github.com/javers/javers/compare/174c15278998eb1ba17809c40c2199eb7f411da4...36fae3ed1f9822be9eba4afc2c0ee7490fff6684
    diff --git a/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java b/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java index 7aac9530..f3d77fc0 100644 --- a/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java +++ b/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java @@ -110,7 +110,7 @@ public class FixedSchemaFactory extends SchemaNameAware { RelationBuilder relationBuilder = schema.addRelation(tableName.nameWithSchema()); relationBuilder .primaryKey(tableName.localName() + "_pk").using(COMMIT_PROPERTY_COMMIT_FK, COMMIT_PROPERTY_NAME).and() - .withAttribute().string(COMMIT_PROPERTY_NAME).withMaxLength(200).and() + .withAttribute().string(COMMIT_PROPERTY_NAME).withMaxLength(190).and() .withAttribute().string(COMMIT_PROPERTY_VALUE).withMaxLength(600).and(); foreignKey(tableName, COMMIT_PROPERTY_COMMIT_FK, getCommitTableNameWithSchema(), COMMIT_PK, relationBuilder); relationBuilder.build(); @@ -136,7 +136,7 @@ public class FixedSchemaFactory extends SchemaNameAware { RelationBuilder relationBuilder = schema.addRelation(tableName.nameWithSchema()); primaryKey(GLOBAL_ID_PK, schema,relationBuilder); relationBuilder - .withAttribute().string(GLOBAL_ID_LOCAL_ID).withMaxLength(200).and() + .withAttribute().string(GLOBAL_ID_LOCAL_ID).withMaxLength(190).and() .withAttribute().string(GLOBAL_ID_FRAGMENT).withMaxLength(200).and() .withAttribute().string(GLOBAL_ID_TYPE_NAME).withMaxLength(200).and(); foreignKey(tableName, GLOBAL_ID_OWNER_ID_FK, getGlobalIdTableNameWithSchema(), GLOBAL_ID_PK, relationBuilder);
    ['javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    730,352
    149,959
    22,779
    378
    339
    74
    4
    1
    12,711
    552
    2,835
    179
    2
    3
    1970-01-01T00:24:54
    1,096
    Java
    {'Java': 1158177, 'Groovy': 842390, 'Shell': 608}
    Apache License 2.0
    392
    javers/javers/598/597
    javers
    javers
    https://github.com/javers/javers/issues/597
    https://github.com/javers/javers/pull/598
    https://github.com/javers/javers/pull/598
    1
    fix
    Again: MySQL error: Specified key was too long; max key length is 767 bytes
    #455 is back in 3.6.0 (or earlier?) affecting mysql <= 4.6.. mysql <= 4.6 has a max key length of 767 bytes (whereas >= 4.7 has a limit of 3072 bytes) ``` Caused by: org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL: CREATE INDEX jv_commit_property_property_name_property_value_idx ON jv_commit_property(property_name,property_value(200)) at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:91) at org.polyjdbc.core.schema.SchemaManagerImpl.create(SchemaManagerImpl.java:52) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes ``` The property value index has a length of 200 [here](https://github.com/javers/javers/blob/master/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java#L124). Should it be 191 instead? ```java RelationBuilder relationBuilder = schema.addRelation(tableName.nameWithSchema()); relationBuilder .primaryKey(tableName.localName() + "_pk").using(COMMIT_PROPERTY_COMMIT_FK, COMMIT_PROPERTY_NAME).and() .withAttribute().string(COMMIT_PROPERTY_NAME).withMaxLength(190).and() /// <------- .withAttribute().string(COMMIT_PROPERTY_VALUE).withMaxLength(600).and(); /// <------ foreignKey(tableName, COMMIT_PROPERTY_COMMIT_FK, getCommitTableNameWithSchema(), COMMIT_PK, relationBuilder); relationBuilder.build(); columnsIndex(tableName, schema, COMMIT_PROPERTY_COMMIT_FK); // Add index prefix length for MySql if (dialect instanceof MysqlDialect) { columnsIndex(tableName, schema, new IndexedCols( new String[]{COMMIT_PROPERTY_NAME, COMMIT_PROPERTY_VALUE}, new int[]{0, 200})); // <-------------- } else { columnsIndex(tableName, schema, COMMIT_PROPERTY_NAME, COMMIT_PROPERTY_VALUE); } ``` 1. The col COMMIT_PROPERTY_NAME has max length of 190, and a prefix length of 0 for the index 2. The col COMMIT_PROPERTY_VALUE has a max length of 600, and a prefix length of 200 for the index. Why is the prefix length 0 for PROPERTY_NAME? This effectively makes the index useless? Or does 0 mean it indexes the entire length. But for COMMIT_PROPERTY_VALUE the maximum prefix length is `767 / 4 = 191` in mysql 4.6 and `3072 / 4 = 768` in mysql 4.7
    89e68859667afc5908d4eb5fb514ff9c3eb3a7bd
    0b923c46d61e01b192d2ead3a6d20bddaef2bad6
    https://github.com/javers/javers/compare/89e68859667afc5908d4eb5fb514ff9c3eb3a7bd...0b923c46d61e01b192d2ead3a6d20bddaef2bad6
    diff --git a/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java b/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java index f3d77fc0..354ab67b 100644 --- a/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java +++ b/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java @@ -16,6 +16,7 @@ import java.util.TreeMap; * @author bartosz walacik */ public class FixedSchemaFactory extends SchemaNameAware { + private static final int MAX_INDEX_KEY_LEN_IN_MYSQL = 191; public static final String GLOBAL_ID_TABLE_NAME = "jv_global_id"; public static final String GLOBAL_ID_PK = "global_id_pk"; @@ -110,7 +111,7 @@ public class FixedSchemaFactory extends SchemaNameAware { RelationBuilder relationBuilder = schema.addRelation(tableName.nameWithSchema()); relationBuilder .primaryKey(tableName.localName() + "_pk").using(COMMIT_PROPERTY_COMMIT_FK, COMMIT_PROPERTY_NAME).and() - .withAttribute().string(COMMIT_PROPERTY_NAME).withMaxLength(190).and() + .withAttribute().string(COMMIT_PROPERTY_NAME).withMaxLength(MAX_INDEX_KEY_LEN_IN_MYSQL).and() .withAttribute().string(COMMIT_PROPERTY_VALUE).withMaxLength(600).and(); foreignKey(tableName, COMMIT_PROPERTY_COMMIT_FK, getCommitTableNameWithSchema(), COMMIT_PK, relationBuilder); relationBuilder.build(); @@ -121,7 +122,7 @@ public class FixedSchemaFactory extends SchemaNameAware { if (dialect instanceof MysqlDialect) { columnsIndex(tableName, schema, new IndexedCols( new String[]{COMMIT_PROPERTY_NAME, COMMIT_PROPERTY_VALUE}, - new int[]{0, 200})); + new int[]{0, MAX_INDEX_KEY_LEN_IN_MYSQL})); } else { columnsIndex(tableName, schema, COMMIT_PROPERTY_NAME, COMMIT_PROPERTY_VALUE); @@ -136,7 +137,7 @@ public class FixedSchemaFactory extends SchemaNameAware { RelationBuilder relationBuilder = schema.addRelation(tableName.nameWithSchema()); primaryKey(GLOBAL_ID_PK, schema,relationBuilder); relationBuilder - .withAttribute().string(GLOBAL_ID_LOCAL_ID).withMaxLength(190).and() + .withAttribute().string(GLOBAL_ID_LOCAL_ID).withMaxLength(MAX_INDEX_KEY_LEN_IN_MYSQL).and() .withAttribute().string(GLOBAL_ID_FRAGMENT).withMaxLength(200).and() .withAttribute().string(GLOBAL_ID_TYPE_NAME).withMaxLength(200).and(); foreignKey(tableName, GLOBAL_ID_OWNER_ID_FK, getGlobalIdTableNameWithSchema(), GLOBAL_ID_PK, relationBuilder);
    ['javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    762,023
    157,199
    23,620
    382
    556
    123
    7
    1
    2,461
    222
    570
    44
    1
    2
    1970-01-01T00:25:10
    1,096
    Java
    {'Java': 1158177, 'Groovy': 842390, 'Shell': 608}
    Apache License 2.0
    389
    javers/javers/696/692
    javers
    javers
    https://github.com/javers/javers/issues/692
    https://github.com/javers/javers/pull/696
    https://github.com/javers/javers/pull/696
    1
    fixes
    JaVers dependency on Google Guava
    As documented I just ran the below code to view the diff. It seems that Google Guava is required as a runtime dependency for the below code to work. ```java Javers javers = JaversBuilder.javers().build(); Person tommyOld = new Person("tommy", "Tommy Smart"); Person tommyNew = new Person("tommy", "Tommy C. Smart"); Diff diff = javers.compare(tommyOld, tommyNew); System.out.println(diff.prettyPrint()); ``` The code above throws an exception as shown below: ``` Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap at org.javers.core.Changes.<init>(Changes.java:35) at org.javers.core.diff.Diff.groupByObject(Diff.java:88) at org.javers.core.diff.Diff.toString(Diff.java:129) at org.javers.core.diff.Diff.prettyPrint(Diff.java:120) ... Caused by: java.lang.ClassNotFoundException: com.google.common.collect.ImmutableMap at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 5 more ``` Not sure how the below line of code is used in [org.javers.core.Changes.java](https://github.com/javers/javers/blob/d5ac085c94b5459d464a14ab3e489f31e3c7c110/javers-core/src/main/java/org/javers/core/Changes.java#L35) There are 3 more references in other classes HibernateConfig.java, JaversSpringJpaApplicationConfig.java and JaversSpringMongoApplicationConfig.java The above code can be easily replaced with standard Java code to remove dependency on Goolge Guava. Do let me know if these changes can be done. I will submit a PR.
    ecaa45ed4965f6c243c05ffa85248e2ab9209f77
    9cdedbe0c836af2af84d7b58fe85961d9ff76339
    https://github.com/javers/javers/compare/ecaa45ed4965f6c243c05ffa85248e2ab9209f77...9cdedbe0c836af2af84d7b58fe85961d9ff76339
    diff --git a/javers-core/src/main/java/org/javers/common/collections/Primitives.java b/javers-core/src/main/java/org/javers/common/collections/Primitives.java index eee8a3c4..c9ff294d 100644 --- a/javers-core/src/main/java/org/javers/common/collections/Primitives.java +++ b/javers-core/src/main/java/org/javers/common/collections/Primitives.java @@ -1,10 +1,10 @@ package org.javers.common.collections; -import com.google.common.collect.Streams; import org.javers.common.reflection.ReflectionUtil; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author bartosz walacik @@ -27,7 +27,7 @@ public class Primitives { public static List<Class<?>> getPrimitiveAndBoxTypes() { return java.util.Collections.unmodifiableList( - Streams.concat(PRIMITIVE_NUMBER_TYPES.stream(), + Stream.concat(PRIMITIVE_NUMBER_TYPES.stream(), PRIMITIVE_TYPES.stream()).collect(Collectors.toList())); }
    ['javers-core/src/main/java/org/javers/common/collections/Primitives.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    833,230
    172,127
    25,728
    402
    204
    32
    4
    1
    1,700
    153
    423
    33
    1
    2
    1970-01-01T00:25:33
    1,096
    Java
    {'Java': 1158177, 'Groovy': 842390, 'Shell': 608}
    Apache License 2.0
    387
    javers/javers/1222/1183
    javers
    javers
    https://github.com/javers/javers/issues/1183
    https://github.com/javers/javers/pull/1222
    https://github.com/javers/javers/pull/1222
    1
    fixes
    Possible issue with skip value check
    While reading the code, I found this snippet on`master`: https://github.com/javers/javers/blob/f49b0aea4c371b90ada54144843e3e1eae81fe65/javers-core/src/main/java/org/javers/repository/api/QueryParamsBuilder.java#L111 ``` public QueryParamsBuilder skip(int skip) { Validate.argumentCheck(limit >= 0, "Skip is not a non-negative number."); this.skip = skip; return this; } ``` Shouldn't it be ` Validate.argumentCheck(skip >= 0, "Skip is not a non-negative number.");` ?
    c92044c41f3bfb8ee30879a73f880f470b26ef06
    3e504dd5494f339fd497d354f9b5eed8f403e89b
    https://github.com/javers/javers/compare/c92044c41f3bfb8ee30879a73f880f470b26ef06...3e504dd5494f339fd497d354f9b5eed8f403e89b
    diff --git a/javers-core/src/main/java/org/javers/repository/api/QueryParamsBuilder.java b/javers-core/src/main/java/org/javers/repository/api/QueryParamsBuilder.java index 24122e34..a46ad839 100644 --- a/javers-core/src/main/java/org/javers/repository/api/QueryParamsBuilder.java +++ b/javers-core/src/main/java/org/javers/repository/api/QueryParamsBuilder.java @@ -108,7 +108,7 @@ public class QueryParamsBuilder { * @see QueryBuilder#skip(int) */ public QueryParamsBuilder skip(int skip) { - Validate.argumentCheck(limit >= 0, "Skip is not a non-negative number."); + Validate.argumentCheck(skip >= 0, "Skip is not a non-negative number."); this.skip = skip; return this; }
    ['javers-core/src/main/java/org/javers/repository/api/QueryParamsBuilder.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,049,140
    215,043
    31,806
    452
    164
    36
    2
    1
    514
    46
    135
    11
    1
    1
    1970-01-01T00:27:44
    1,096
    Java
    {'Java': 1158177, 'Groovy': 842390, 'Shell': 608}
    Apache License 2.0
    388
    javers/javers/1189/1188
    javers
    javers
    https://github.com/javers/javers/issues/1188
    https://github.com/javers/javers/pull/1189
    https://github.com/javers/javers/pull/1189
    1
    fixes
    ClassNotFoundException when using javers-persistence-sql and gson 2.9.0
    **Clear description of my expectations versus reality** I'm using javers with javers-persistence-sql and expected that updating gson from 2.8.9 to 2.9.0 wouldn't do any harm. But using gson 2.9.0 will result in ``` Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/internal/LinkedHashTreeMap at org.javers.repository.sql.schema.FixedSchemaFactory.allTablesSchema(FixedSchemaFactory.java:54) at org.javers.repository.sql.schema.JaversSchemaManager.ensureSchema(JaversSchemaManager.java:46) at org.javers.repository.sql.JaversSqlRepository.ensureSchema(JaversSqlRepository.java:186) at org.javers.core.JaversBuilder.build(JaversBuilder.java:133) Caused by: java.lang.ClassNotFoundException: com.google.gson.internal.LinkedHashTreeMap at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source) at java.base/java.lang.ClassLoader.loadClass(Unknown Source) ... 10 more ``` ... **Steps To Reproduce** Update gson to 2.9.0 and call JaversBuilder.build **Javers' Version** 6.6.2 **Additional context** As stated in in https://github.com/google/gson/releases/tag/gson-parent-2.9.0 LinkedHashTreeMap is removed from gson but is used in javers-persistence-sql here https://github.com/javers/javers/blob/javers-6.6.2/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java ...
    f49b0aea4c371b90ada54144843e3e1eae81fe65
    34d11f594b57ff4c0d266d9e4bd2532d030ec4c8
    https://github.com/javers/javers/compare/f49b0aea4c371b90ada54144843e3e1eae81fe65...34d11f594b57ff4c0d266d9e4bd2532d030ec4c8
    diff --git a/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java b/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java index ea6c93b1..7d5a99a0 100644 --- a/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java +++ b/javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java @@ -1,12 +1,12 @@ package org.javers.repository.sql.schema; -import com.google.gson.internal.LinkedHashTreeMap; import org.polyjdbc.core.dialect.*; import org.polyjdbc.core.schema.model.LongAttributeBuilder; import org.polyjdbc.core.schema.model.RelationBuilder; import org.polyjdbc.core.schema.model.Schema; import org.polyjdbc.core.util.StringUtils; +import java.util.HashMap; import java.util.Map; /** @@ -51,7 +51,7 @@ public class FixedSchemaFactory extends SchemaNameAware { } Map<String, Schema> allTablesSchema(Dialect dialect) { - Map<String, Schema> schema = new LinkedHashTreeMap<>(); + Map<String, Schema> schema = new HashMap<>(); schema.put(getGlobalIdTableName().localName(), globalIdTableSchema(dialect)); schema.put(getCommitTableName().localName(), commitTableSchema(dialect));
    ['javers-persistence-sql/src/main/java/org/javers/repository/sql/schema/FixedSchemaFactory.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,045,742
    214,343
    31,715
    452
    198
    40
    4
    1
    1,476
    98
    355
    29
    2
    1
    1970-01-01T00:27:25
    1,096
    Java
    {'Java': 1158177, 'Groovy': 842390, 'Shell': 608}
    Apache License 2.0
    390
    javers/javers/693/692
    javers
    javers
    https://github.com/javers/javers/issues/692
    https://github.com/javers/javers/pull/693
    https://github.com/javers/javers/pull/693
    1
    fixes
    JaVers dependency on Google Guava
    As documented I just ran the below code to view the diff. It seems that Google Guava is required as a runtime dependency for the below code to work. ```java Javers javers = JaversBuilder.javers().build(); Person tommyOld = new Person("tommy", "Tommy Smart"); Person tommyNew = new Person("tommy", "Tommy C. Smart"); Diff diff = javers.compare(tommyOld, tommyNew); System.out.println(diff.prettyPrint()); ``` The code above throws an exception as shown below: ``` Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap at org.javers.core.Changes.<init>(Changes.java:35) at org.javers.core.diff.Diff.groupByObject(Diff.java:88) at org.javers.core.diff.Diff.toString(Diff.java:129) at org.javers.core.diff.Diff.prettyPrint(Diff.java:120) ... Caused by: java.lang.ClassNotFoundException: com.google.common.collect.ImmutableMap at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 5 more ``` Not sure how the below line of code is used in [org.javers.core.Changes.java](https://github.com/javers/javers/blob/d5ac085c94b5459d464a14ab3e489f31e3c7c110/javers-core/src/main/java/org/javers/core/Changes.java#L35) There are 3 more references in other classes HibernateConfig.java, JaversSpringJpaApplicationConfig.java and JaversSpringMongoApplicationConfig.java The above code can be easily replaced with standard Java code to remove dependency on Goolge Guava. Do let me know if these changes can be done. I will submit a PR.
    432bd6d2de60e62e075d78a04ee274279abcfc88
    c129c04808f5144d8021eaa1ff804ae6584d268d
    https://github.com/javers/javers/compare/432bd6d2de60e62e075d78a04ee274279abcfc88...c129c04808f5144d8021eaa1ff804ae6584d268d
    diff --git a/javers-core/src/main/java/org/javers/core/Changes.java b/javers-core/src/main/java/org/javers/core/Changes.java index 2496ae6c..8cf726a8 100644 --- a/javers-core/src/main/java/org/javers/core/Changes.java +++ b/javers-core/src/main/java/org/javers/core/Changes.java @@ -1,6 +1,5 @@ package org.javers.core; -import com.google.common.collect.ImmutableMap; import org.javers.common.string.PrettyValuePrinter; import org.javers.common.validation.Validate; import org.javers.core.commit.CommitMetadata; @@ -31,9 +30,6 @@ public class Changes extends AbstractList<Change> { private final transient PrettyValuePrinter valuePrinter; public Changes(List<Change> changes, PrettyValuePrinter valuePrinter) { - - Map<String, String> string = ImmutableMap.of("a", "b", "c", "d"); - Validate.argumentsAreNotNull(changes, valuePrinter); this.changes = changes; this.valuePrinter = valuePrinter; diff --git a/javers-spring-jpa/src/test/java/org/javers/hibernate/integration/config/HibernateConfig.java b/javers-spring-jpa/src/test/java/org/javers/hibernate/integration/config/HibernateConfig.java index 515b0d8f..9fb95836 100644 --- a/javers-spring-jpa/src/test/java/org/javers/hibernate/integration/config/HibernateConfig.java +++ b/javers-spring-jpa/src/test/java/org/javers/hibernate/integration/config/HibernateConfig.java @@ -1,6 +1,5 @@ package org.javers.hibernate.integration.config; -import com.google.common.collect.ImmutableMap; import org.javers.core.Javers; import org.javers.repository.sql.ConnectionProvider; import org.javers.repository.sql.JaversSqlRepository; @@ -20,6 +19,8 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; +import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.Properties; @@ -98,12 +99,9 @@ public class HibernateConfig { @Bean public CommitPropertiesProvider commitPropertiesProvider() { - return new CommitPropertiesProvider() { - @Override - public Map<String, String> provide() { - return ImmutableMap.of("key", "ok"); - } - }; + final Map<String, String> rv = new HashMap<>(); + rv.put("key", "ok"); + return () -> Collections.unmodifiableMap(rv); } Properties additionalProperties() { diff --git a/javers-spring-jpa/src/test/java/org/javers/spring/example/JaversSpringJpaApplicationConfig.java b/javers-spring-jpa/src/test/java/org/javers/spring/example/JaversSpringJpaApplicationConfig.java index 6b66e7ac..51b70512 100644 --- a/javers-spring-jpa/src/test/java/org/javers/spring/example/JaversSpringJpaApplicationConfig.java +++ b/javers-spring-jpa/src/test/java/org/javers/spring/example/JaversSpringJpaApplicationConfig.java @@ -1,6 +1,5 @@ package org.javers.spring.example; -import com.google.common.collect.ImmutableMap; import org.javers.core.Javers; import org.javers.hibernate.integration.HibernateUnproxyObjectAccessHook; import org.javers.repository.sql.ConnectionProvider; @@ -11,7 +10,6 @@ import org.javers.spring.auditable.AuthorProvider; import org.javers.spring.auditable.CommitPropertiesProvider; import org.javers.spring.auditable.SpringSecurityAuthorProvider; import org.javers.spring.auditable.aspect.JaversAuditableAspect; -import org.javers.spring.auditable.aspect.springdata.JaversSpringDataAuditableRepositoryAspect; import org.javers.spring.auditable.aspect.springdatajpa.JaversSpringDataJpaAuditableRepositoryAspect; import org.javers.spring.jpa.JpaHibernateConnectionProvider; import org.javers.spring.jpa.TransactionalJaversBuilder; @@ -31,6 +29,8 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; +import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.Properties; @@ -102,7 +102,9 @@ public class JaversSpringJpaApplicationConfig { */ @Bean public CommitPropertiesProvider commitPropertiesProvider() { - return () -> ImmutableMap.of("key", "ok"); + final Map<String, String> rv = new HashMap<>(); + rv.put("key", "ok"); + return () -> Collections.unmodifiableMap(rv); } /** diff --git a/javers-spring/src/test/java/org/javers/spring/example/JaversSpringMongoApplicationConfig.java b/javers-spring/src/test/java/org/javers/spring/example/JaversSpringMongoApplicationConfig.java index ad03d629..03dd33ed 100644 --- a/javers-spring/src/test/java/org/javers/spring/example/JaversSpringMongoApplicationConfig.java +++ b/javers-spring/src/test/java/org/javers/spring/example/JaversSpringMongoApplicationConfig.java @@ -1,7 +1,6 @@ package org.javers.spring.example; import com.github.fakemongo.Fongo; -import com.google.common.collect.ImmutableMap; import com.mongodb.MongoClient; import org.javers.core.Javers; import org.javers.core.JaversBuilder; @@ -18,6 +17,10 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + @Configuration @ComponentScan(basePackages = "org.javers.spring.repository") @EnableMongoRepositories({"org.javers.spring.repository"}) @@ -94,6 +97,8 @@ public class JaversSpringMongoApplicationConfig { */ @Bean public CommitPropertiesProvider commitPropertiesProvider() { - return () -> ImmutableMap.of("key", "ok"); + final Map<String, String> rv = new HashMap<>(); + rv.put("key", "ok"); + return () -> Collections.unmodifiableMap(rv); } }
    ['javers-spring-jpa/src/test/java/org/javers/hibernate/integration/config/HibernateConfig.java', 'javers-spring-jpa/src/test/java/org/javers/spring/example/JaversSpringJpaApplicationConfig.java', 'javers-core/src/main/java/org/javers/core/Changes.java', 'javers-spring/src/test/java/org/javers/spring/example/JaversSpringMongoApplicationConfig.java']
    {'.java': 4}
    4
    4
    0
    0
    4
    826,405
    170,826
    25,563
    402
    126
    31
    4
    1
    1,700
    153
    423
    33
    1
    2
    1970-01-01T00:25:33
    1,096
    Java
    {'Java': 1158177, 'Groovy': 842390, 'Shell': 608}
    Apache License 2.0
    829
    netflix/hollow/341/339
    netflix
    hollow
    https://github.com/Netflix/hollow/issues/339
    https://github.com/Netflix/hollow/pull/341
    https://github.com/Netflix/hollow/pull/341
    1
    fixes
    Ergonomic HollowObjectDelegateCachedImpls refer to object ordinal
    Looks like the problem is here: https://github.com/Netflix/hollow/blob/f0126b04575a897b3e7ceefa07baa0f354b79683/hollow/src/main/java/com/netflix/hollow/api/codegen/delegate/HollowObjectDelegateCachedImplGenerator.java#L131 For a `String` field I get: ``` this.nameOrdinal = typeAPI.getNameOrdinal(ordinal); int nameTempOrdinal = typeAPI.getNameOrdinal(ordinal); this.name = nameTempOrdinal == -1 ? null : typeAPI.getAPI().getStringTypeAPI().getValue(ordinal); ``` Also seems that `TempOrdinal` is unnecessary, and the generator could refer to the field. Edit: Ah, looks like they're for shortcut paths with more than one length. Still could conditionalize on the path length to avoid the double lookup I guess.
    7590c8442a4df35bcc620e2360f8ad896a3d3285
    d807d5254c07ad294392c88b7bd13e65c1e14ac9
    https://github.com/netflix/hollow/compare/7590c8442a4df35bcc620e2360f8ad896a3d3285...d807d5254c07ad294392c88b7bd13e65c1e14ac9
    diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/delegate/HollowObjectDelegateCachedImplGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/delegate/HollowObjectDelegateCachedImplGenerator.java index 1692f5910..d1631fe27 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/delegate/HollowObjectDelegateCachedImplGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/delegate/HollowObjectDelegateCachedImplGenerator.java @@ -128,7 +128,7 @@ public class HollowObjectDelegateCachedImplGenerator extends HollowObjectDelegat } String typeAPIName = HollowCodeGenerationUtils.typeAPIClassname(shortcut.getPathTypes()[shortcut.getPathTypes().length-1]); - builder.append(" this.").append(fieldName).append(" = ").append(ordinalVariableName).append(" == -1 ? null : ").append("typeAPI.getAPI().get").append(typeAPIName).append("().get").append(uppercase(shortcut.getPath()[shortcut.getPath().length-1])).append("(ordinal);\\n"); + builder.append(" this.").append(fieldName).append(" = ").append(ordinalVariableName).append(" == -1 ? null : ").append("typeAPI.getAPI().get").append(typeAPIName).append("().get").append(uppercase(shortcut.getPath()[shortcut.getPath().length-1])).append("(").append(ordinalVariableName).append(");\\n"); } } }
    ['hollow/src/main/java/com/netflix/hollow/api/codegen/delegate/HollowObjectDelegateCachedImplGenerator.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    2,658,735
    549,230
    68,670
    537
    629
    144
    2
    1
    748
    72
    182
    12
    1
    1
    1970-01-01T00:25:42
    1,094
    Java
    {'Java': 4858508, 'CSS': 4299, 'JavaScript': 1703, 'Shell': 1383, 'Makefile': 1217, 'C++': 798, 'Pawn': 701}
    Apache License 2.0
    828
    netflix/hollow/417/416
    netflix
    hollow
    https://github.com/Netflix/hollow/issues/416
    https://github.com/Netflix/hollow/pull/417
    https://github.com/Netflix/hollow/pull/417
    1
    fixes
    PrimaryKeyIndex doesn't index large changes efficiently
    It's intended for `PrimaryKeyIndex` to do a full re-index when more than 10% of the previous ordinals have been removed (record removed or modified). A [bug in the code (HollowPrimaryKeyIndex.java#L582)](https://github.com/Netflix/hollow/blob/240417b373d1b6aeead886152603201cbbd01fc2/hollow/src/main/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndex.java#L582) prevents the `> 10%` condition from ever being true. Thus the index always follows the delta update logic regardless of the relative magnitude of changes. ``` BitSet previousOrdinals = typeState.getListener(…).getPopulatedOrdinals(); ^ should be getPreviousOrdinals() BitSet ordinals = typeState.getListener(…).getPopulatedOrdinals(); ```
    240417b373d1b6aeead886152603201cbbd01fc2
    3850981a86ecf947d2e24286ba95d7988dcb0cc0
    https://github.com/netflix/hollow/compare/240417b373d1b6aeead886152603201cbbd01fc2...3850981a86ecf947d2e24286ba95d7988dcb0cc0
    diff --git a/hollow/src/main/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndex.java b/hollow/src/main/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndex.java index e6dc2cc7d..525fe3d1a 100644 --- a/hollow/src/main/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndex.java +++ b/hollow/src/main/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndex.java @@ -579,7 +579,7 @@ public class HollowPrimaryKeyIndex implements HollowTypeStateListener { } private boolean shouldPerformDeltaUpdate() { - BitSet previousOrdinals = typeState.getListener(PopulatedOrdinalListener.class).getPopulatedOrdinals(); + BitSet previousOrdinals = typeState.getListener(PopulatedOrdinalListener.class).getPreviousOrdinals(); BitSet ordinals = typeState.getListener(PopulatedOrdinalListener.class).getPopulatedOrdinals(); int prevCardinality = 0;
    ['hollow/src/main/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndex.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    2,963,462
    615,591
    75,235
    576
    224
    45
    2
    1
    767
    69
    184
    9
    1
    1
    1970-01-01T00:25:55
    1,094
    Java
    {'Java': 4858508, 'CSS': 4299, 'JavaScript': 1703, 'Shell': 1383, 'Makefile': 1217, 'C++': 798, 'Pawn': 701}
    Apache License 2.0
    830
    netflix/hollow/177/176
    netflix
    hollow
    https://github.com/Netflix/hollow/issues/176
    https://github.com/Netflix/hollow/pull/177
    https://github.com/Netflix/hollow/pull/177
    1
    fixes
    Compilation of generated files fails if data model object has `Byte`
    If you try and generate an API for object that contains a Byte, the generated files to do not compile. Any generated files that to try reference the type (eg <APIName>HashIndex.java) conflict between my.generated.package.Byte and java.lang.Byte, since we import my.generated.*. A couple ways to fix this: * have similar treatment for Byte as we do for String, Integer, etc (include them in com.netflix.hollow.core.type and replace with HByte) #172 * import the generated Byte classes directly, instead of using a star import (WIP)
    11cb87e9703810c3d9912b91dbadb4aa5c5a2c31
    1951a8089654b865f2f96b9d7b0958b50c3023c8
    https://github.com/netflix/hollow/compare/11cb87e9703810c3d9912b91dbadb4aa5c5a2c31...1951a8089654b865f2f96b9d7b0958b50c3023c8
    diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIFactoryJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIFactoryJavaGenerator.java index ee0b3a4f7..59739c0bd 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIFactoryJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIFactoryJavaGenerator.java @@ -44,7 +44,7 @@ public class HollowAPIFactoryJavaGenerator extends HollowConsumerJavaFileGenerat @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname); builder.append("import ").append(HollowAPIFactory.class.getName()).append(";\\n"); builder.append("import ").append(HollowAPI.class.getName()).append(";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowConsumerJavaFileGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowConsumerJavaFileGenerator.java index 5ee932458..1080e6361 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowConsumerJavaFileGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowConsumerJavaFileGenerator.java @@ -15,6 +15,16 @@ */ package com.netflix.hollow.api.codegen; +import com.netflix.hollow.core.schema.HollowListSchema; +import com.netflix.hollow.core.schema.HollowMapSchema; +import com.netflix.hollow.core.schema.HollowSchema; +import com.netflix.hollow.core.schema.HollowSetSchema; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** * Not intended for external consumption. * @@ -54,7 +64,18 @@ public abstract class HollowConsumerJavaFileGenerator implements HollowJavaFileG } protected void appendPackageAndCommonImports(StringBuilder builder) { - String fullPackageName = createFullPackageName(packageName, subPackageName, config.isUsePackageGrouping()); + appendPackageAndCommonImports(builder, null, new ArrayList<HollowSchema>()); + } + + protected void appendPackageAndCommonImports(StringBuilder builder, + String apiClassname) { + appendPackageAndCommonImports(builder, apiClassname, new ArrayList<HollowSchema>()); + } + + protected void appendPackageAndCommonImports(StringBuilder builder, + String apiClassname, List<HollowSchema> schemasToImport) { + String fullPackageName = + createFullPackageName(packageName, subPackageName, config.isUsePackageGrouping()); if (!isEmpty(fullPackageName)) { builder.append("package ").append(fullPackageName).append(";\\n\\n"); @@ -63,9 +84,42 @@ public abstract class HollowConsumerJavaFileGenerator implements HollowJavaFileG } if (config.isUsePackageGrouping()) { - builder.append("import ").append(packageName).append(".*;\\n"); - builder.append("import ").append(packageName).append(".core.*;\\n"); - if (useCollectionsImport) builder.append("import ").append(packageName).append(".collections.*;\\n\\n"); + if (apiClassname != null) { + appendImportFromBasePackage(builder, apiClassname); + } + Set<String> schemaNameSet = new HashSet<>(); + for (HollowSchema schema : schemasToImport) { + switch (schema.getSchemaType()) { + case OBJECT: + addToSetIfNotPrimitive(schemaNameSet, schema.getName()); + break; + case SET: + addToSetIfNotPrimitive(schemaNameSet, + ((HollowSetSchema) schema).getElementType()); + break; + case LIST: + addToSetIfNotPrimitive(schemaNameSet, + ((HollowListSchema) schema).getElementType()); + break; + case MAP: + HollowMapSchema mapSchema = (HollowMapSchema) schema; + addToSetIfNotPrimitive(schemaNameSet, mapSchema.getKeyType(), + mapSchema.getValueType()); + break; + default: + throw new IllegalArgumentException( + "Unexpected HollowSchema to import: " + schema); + + } + } + for (String schemaName : schemaNameSet) { + appendImportFromBasePackage(builder, schemaName); + } + appendImportFromBasePackage(builder, "core.*"); + if (useCollectionsImport) { + appendImportFromBasePackage(builder, "collections.*"); + } + builder.append("\\n"); } } } @@ -82,4 +136,22 @@ public abstract class HollowConsumerJavaFileGenerator implements HollowJavaFileG private boolean isEmpty(String value) { return value == null || value.trim().isEmpty(); } + + private void appendImportFromBasePackage(StringBuilder builder, String leaf) { + builder.append("import ").append(packageName).append(".").append(leaf).append(";\\n"); + } + + /** + * Adds the schema name to the set if the schema name doesn't correspond to a Hollow + * primitive type. Factored out to prevent bloat in the switch statement it is called + * from. + */ + private void addToSetIfNotPrimitive(Set<String> schemaNameSet, + String... schemaNames) { + for (String schemaName : schemaNames) { + if (!HollowCodeGenerationUtils.isPrimitiveType(schemaName)) { + schemaNameSet.add(schemaName); + } + } + } } diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/HollowDataAccessorGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/HollowDataAccessorGenerator.java index e4619c4cf..0d6c1e4b9 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/HollowDataAccessorGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/HollowDataAccessorGenerator.java @@ -26,6 +26,9 @@ import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowObjectSchema; +import com.netflix.hollow.core.schema.HollowSchema; + +import java.util.Arrays; /** * This class contains template logic for generating a {@link HollowAPI} implementation. Not intended for external consumption. @@ -54,7 +57,7 @@ public class HollowDataAccessorGenerator extends HollowConsumerJavaFileGenerator @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiclassName, Arrays.<HollowSchema>asList(schema)); builder.append("import " + HollowConsumer.class.getName() + ";\\n"); builder.append("import " + AbstractHollowDataAccessor.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIListJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIListJavaGenerator.java index f87262b7b..79e0b8dcb 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIListJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIListJavaGenerator.java @@ -47,7 +47,7 @@ public class TypeAPIListJavaGenerator extends HollowTypeAPIGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname); builder.append("import " + HollowListTypeAPI.class.getName() + ";\\n\\n"); builder.append("import " + HollowListTypeDataAccess.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIMapJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIMapJavaGenerator.java index edd531d57..be3b6f3b7 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIMapJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIMapJavaGenerator.java @@ -47,7 +47,7 @@ public class TypeAPIMapJavaGenerator extends HollowTypeAPIGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname); builder.append("import " + HollowMapTypeAPI.class.getName() + ";\\n\\n"); builder.append("import " + HollowMapTypeDataAccess.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIObjectJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIObjectJavaGenerator.java index d7391c6a5..efe84c902 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIObjectJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIObjectJavaGenerator.java @@ -116,7 +116,7 @@ public class TypeAPIObjectJavaGenerator extends HollowTypeAPIGenerator { classBodyBuilder.append("}"); StringBuilder classBuilder = new StringBuilder(); - appendPackageAndCommonImports(classBuilder); + appendPackageAndCommonImports(classBuilder, apiClassname); for(Class<?> clazz : importClasses) { classBuilder.append("import ").append(clazz.getName()).append(";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPISetJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPISetJavaGenerator.java index 832697cf2..ca04c9749 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPISetJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPISetJavaGenerator.java @@ -47,7 +47,7 @@ public class TypeAPISetJavaGenerator extends HollowTypeAPIGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname); builder.append("import " + HollowSetTypeAPI.class.getName() + ";\\n\\n"); builder.append("import " + HollowSetTypeDataAccess.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowHashIndexGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowHashIndexGenerator.java index fed75797a..04d615a7c 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowHashIndexGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowHashIndexGenerator.java @@ -21,6 +21,7 @@ import static com.netflix.hollow.api.codegen.HollowCodeGenerationUtils.substitut import com.netflix.hollow.api.codegen.CodeGeneratorConfig; import com.netflix.hollow.api.codegen.HollowAPIGenerator; +import com.netflix.hollow.api.codegen.HollowCodeGenerationUtils; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.data.AbstractHollowOrdinalIterable; import com.netflix.hollow.api.consumer.index.AbstractHollowHashIndex; @@ -29,6 +30,8 @@ import com.netflix.hollow.core.HollowDataset; import com.netflix.hollow.core.index.HollowHashIndexResult; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchemaSorter; + +import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -55,7 +58,7 @@ public class HollowHashIndexGenerator extends HollowIndexGenerator { List<HollowSchema> schemaList = HollowSchemaSorter.dependencyOrderedSchemaList(dataset); StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname, schemaList); builder.append("import " + HollowConsumer.class.getName() + ";\\n"); builder.append("import " + HollowHashIndexResult.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowUniqueKeyIndexGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowUniqueKeyIndexGenerator.java index 9b7132bf6..c92c0a24c 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowUniqueKeyIndexGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowUniqueKeyIndexGenerator.java @@ -23,6 +23,9 @@ import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.index.AbstractHollowUniqueKeyIndex; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.core.schema.HollowObjectSchema; +import com.netflix.hollow.core.schema.HollowSchema; + +import java.util.Arrays; /** * This class contains template logic for generating a {@link HollowAPI} implementation. Not intended for external consumption. @@ -53,8 +56,7 @@ public class HollowUniqueKeyIndexGenerator extends HollowIndexGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); - + appendPackageAndCommonImports(builder, apiClassname, Arrays.<HollowSchema>asList(schema)); builder.append("import " + HollowConsumer.class.getName() + ";\\n"); builder.append("import " + AbstractHollowUniqueKeyIndex.class.getName() + ";\\n"); if (isGenSimpleConstructor) diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowFactoryJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowFactoryJavaGenerator.java index c5e698b96..5a6c0b1ca 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowFactoryJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowFactoryJavaGenerator.java @@ -36,6 +36,8 @@ import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSetSchema; +import java.util.Arrays; + /** * This class contains template logic for generating a {@link HollowAPI} implementation. Not intended for external consumption. * @@ -59,7 +61,7 @@ public class HollowFactoryJavaGenerator extends HollowConsumerJavaFileGenerator @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, null, Arrays.asList(schema)); builder.append("import " + HollowFactory.class.getName() + ";\\n"); builder.append("import " + HollowTypeDataAccess.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowListJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowListJavaGenerator.java index 4369d1a0e..c677dfd8b 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowListJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowListJavaGenerator.java @@ -26,6 +26,9 @@ import com.netflix.hollow.api.objects.HollowList; import com.netflix.hollow.api.objects.delegate.HollowListDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.schema.HollowListSchema; +import com.netflix.hollow.core.schema.HollowSchema; + +import java.util.Arrays; import java.util.Set; /** @@ -51,7 +54,7 @@ public class HollowListJavaGenerator extends HollowCollectionsGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname, Arrays.<HollowSchema>asList(schema)); builder.append("import " + HollowList.class.getName() + ";\\n"); builder.append("import " + HollowListSchema.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowMapJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowMapJavaGenerator.java index f986235c9..83fba3574 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowMapJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowMapJavaGenerator.java @@ -30,6 +30,9 @@ import com.netflix.hollow.core.HollowDataset; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; +import com.netflix.hollow.core.schema.HollowSchema; + +import java.util.Arrays; import java.util.Set; /** @@ -63,7 +66,7 @@ public class HollowMapJavaGenerator extends HollowCollectionsGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname, Arrays.<HollowSchema>asList(schema)); builder.append("import " + HollowMap.class.getName() + ";\\n"); builder.append("import " + HollowMapSchema.class.getName() + ";\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowObjectJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowObjectJavaGenerator.java index eb224dac8..9bede915e 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowObjectJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowObjectJavaGenerator.java @@ -80,7 +80,7 @@ public class HollowObjectJavaGenerator extends HollowConsumerJavaFileGenerator { @Override public String generate() { StringBuilder classBuilder = new StringBuilder(); - appendPackageAndCommonImports(classBuilder); + appendPackageAndCommonImports(classBuilder, apiClassname); classBuilder.append("import " + HollowObject.class.getName() + ";\\n"); classBuilder.append("import " + HollowObjectSchema.class.getName() + ";\\n\\n"); diff --git a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowSetJavaGenerator.java b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowSetJavaGenerator.java index 0b56b4a69..b16a363e3 100644 --- a/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowSetJavaGenerator.java +++ b/hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowSetJavaGenerator.java @@ -25,7 +25,10 @@ import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.HollowSet; import com.netflix.hollow.api.objects.delegate.HollowSetDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; +import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSetSchema; + +import java.util.Arrays; import java.util.Set; /** @@ -52,7 +55,7 @@ public class HollowSetJavaGenerator extends HollowCollectionsGenerator { @Override public String generate() { StringBuilder builder = new StringBuilder(); - appendPackageAndCommonImports(builder); + appendPackageAndCommonImports(builder, apiClassname, Arrays.<HollowSchema>asList(schema)); builder.append("import " + HollowSet.class.getName() + ";\\n"); builder.append("import " + HollowSetSchema.class.getName() + ";\\n");
    ['hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowHashIndexGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowMapJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/HollowConsumerJavaFileGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/indexes/HollowUniqueKeyIndexGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowListJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIListJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowObjectJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/api/HollowDataAccessorGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPISetJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIFactoryJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIObjectJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowSetJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/objects/HollowFactoryJavaGenerator.java', 'hollow/src/main/java/com/netflix/hollow/api/codegen/api/TypeAPIMapJavaGenerator.java']
    {'.java': 14}
    14
    14
    0
    0
    14
    2,517,651
    520,759
    65,419
    514
    6,085
    1,094
    127
    14
    535
    82
    118
    5
    0
    0
    1970-01-01T00:25:19
    1,094
    Java
    {'Java': 4858508, 'CSS': 4299, 'JavaScript': 1703, 'Shell': 1383, 'Makefile': 1217, 'C++': 798, 'Pawn': 701}
    Apache License 2.0
    1,262
    vert-x3/vertx-web/1731/1730
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1730
    https://github.com/vert-x3/vertx-web/pull/1731
    https://github.com/vert-x3/vertx-web/pull/1731
    1
    fix
    Template engine not working for parametrized paths like "/:project/"
    ### Version 4.0.0.Beta3 ### Context I am trying to use a template for this routing: ``` router .route() .path("/:project/") .produces("text/html") .handler(routingContext -> { @Nullable String projectName = routingContext.request().getParam("project"); routingContext.put("projectName",projectName); routingContext.next(); } }) .handler(templateHandler); ``` ### Do you have a reproducer? I created a test that shows the problem. The result is a java.lang.StringIndexOutOfBoundsException: https://github.com/paweld2/vertx-web/commit/ea2fed6591f449da614ace36e4a4deab89774bc5 ### Steps to reproduce The test shows the resulting exception. To reproduce on a project 1. Create a routing to "/:product" and add the template hander as next 2. Call "/test1/" 3. The result is a exception java.lang.StringIndexOutOfBoundsException ### Extra Maybe a option to select a target template independently of the request path could be usefull here.
    635bcb56673965244680f00dc65ae69a862426eb
    065f3a8d0cc0f4042ff9f5e2772210f5f1c69d28
    https://github.com/vert-x3/vertx-web/compare/635bcb56673965244680f00dc65ae69a862426eb...065f3a8d0cc0f4042ff9f5e2772210f5f1c69d28
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java index 4e8c1ec6e..2425fe96b 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java @@ -55,6 +55,19 @@ public class Utils extends io.vertx.core.impl.Utils { } public static String pathOffset(String path, RoutingContext context) { + final String rest = context.pathParam("*"); + if (rest != null) { + // normalize + if (rest.length() > 0) { + if (rest.charAt(0) == '/') { + return rest; + } else { + return "/" + rest; + } + } else { + return "/"; + } + } int prefixLen = 0; String mountPoint = context.mountPoint(); if (mountPoint != null) { diff --git a/vertx-web/src/test/java/io/vertx/ext/web/templ/TemplateTest.java b/vertx-web/src/test/java/io/vertx/ext/web/templ/TemplateTest.java index 16f9bc293..e109eddfb 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/templ/TemplateTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/templ/TemplateTest.java @@ -87,6 +87,25 @@ public class TemplateTest extends WebTestBase { await(); } + @Test + public void testTemplateEngineWithPathVariables() throws Exception { + TemplateEngine engine = new TestEngine(false); + router.route().handler(context -> { + context.put("foo", "badger"); + context.put("bar", "fox"); + context.next(); + }); + router.route("/:project/*").handler(TemplateHandler.create(engine, "somedir", "text/html")); + String expected = + "<html>\\n" + + "<body>\\n" + + "<h1>Test template</h1>\\n" + + "foo is badger bar is fox<br>\\n" + + "</body>\\n" + + "</html>"; + testRequest(HttpMethod.GET, "/1/test-template.html", 200, "OK", expected); + } + @Test public void testRenderDirectly() throws Exception { TemplateEngine engine = new TestEngine(false); @@ -158,6 +177,5 @@ public class TemplateTest extends WebTestBase { handler.handle(Future.succeededFuture(Buffer.buffer(rendered))); } } - } }
    ['vertx-web/src/test/java/io/vertx/ext/web/templ/TemplateTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,671,865
    369,986
    51,775
    404
    299
    72
    13
    1
    1,170
    111
    244
    41
    1
    1
    1970-01-01T00:26:41
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,263
    vert-x3/vertx-web/1729/1472
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1472
    https://github.com/vert-x3/vertx-web/pull/1729
    https://github.com/vert-x3/vertx-web/pull/1729
    1
    fixes
    SubRouter Mount acting as Exact Path
    ### 3.8.4 * vert.x web: ### Context The handlers mounted on sub-router are ignored when the mount point is `"/"`. `router.mountSubRouter("/", subRouter);` Note that, we can't have empty string as mount point. It was functional until v3.8.1. With v3.8.4 it behaves as exactMatch and ending with slash. Below table shows the difference between 3.8.1 and 3.8.4 based on the reproducer shared below: | Path | v3.8.1 | v3.8.4 | | --- | --- | --- | | /primary | Success | Resource Not Found | | /primary?query | Success | Resource Not Found | | /primary/ | Success | Success | | /primary/random | Resource Not Found | Resource Not Found | | With subrouter mounted at `/abc`| | /primary/abc | Success | Success | | /primary/abc/ | Success | Success | | /primary/abc?query | Success | Success | ### Do you have a reproducer? * https://github.com/ramtech123/pocs/tree/master/vertx-subrouter-test ### Steps to reproduce By default, Vertx version is set to 3.8.4 in the reproducer. Change it to 3.8.1 to verify the behavior. 1. Build and run the `RouterTestMain` given in the reproducer. Server will start listening on 8443 2. Curl the given paths to observe the behavior. Ex: `curl http://localhost:8443/primary?query` ### References I have gone through below issues, wondering if this change was intended? - https://github.com/vert-x3/vertx-web/issues/1435 - https://github.com/vert-x3/vertx-web/issues/1441 ### Extra First two scenarios return success response in v3.8.4 also if we attach the handlers directly to the primary router instead of sub router (set `useSubRouters` flag in RouterTestServer.java to `false` to verify the behavior). However, raising this ticket as the behavior of sub router mounting has changed.
    c729ef5b0afad23568758fec09b58f9514b99fc8
    acd45048af85bbdf08f2db1163e9d81b442a1cc3
    https://github.com/vert-x3/vertx-web/compare/c729ef5b0afad23568758fec09b58f9514b99fc8...acd45048af85bbdf08f2db1163e9d81b442a1cc3
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java index 9d8360619..19d777bae 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java @@ -51,11 +51,12 @@ public class RoutingContextWrapper extends RoutingContextImplBase { // just use the override this.mountPoint = mountPoint; } else { - if (parentMountPoint.charAt(parentMountPoint.length() - 1) == '/') { - // Remove the trailing slash or we won't match - this.mountPoint = parentMountPoint.substring(0, parentMountPoint.length() - 1) + mountPoint; + // special case: when a sub router is mounting on / basically it's telling + // that it wants to use the parent mount, otherwise it's extending the parent + // path + if ("/".equals(mountPoint)) { + this.mountPoint = parentMountPoint; } else { - // slashes are ok, just concat this.mountPoint = parentMountPoint + mountPoint; } } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java index cd6bfd044..3ed96dea1 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java @@ -572,4 +572,25 @@ public class SubRouterTest extends WebTestBase { testRequest(HttpMethod.POST, "/bank/order/deposit", 200, "OK"); testRequest(HttpMethod.GET, "/bank/order/deposit", 405, "Method Not Allowed"); } + + + @Test + public void testMountMultiLevel() throws Exception { + Router routerFirstLevel = Router.router(vertx); + router.mountSubRouter("/primary", routerFirstLevel); + + Router routerSecondLevel = Router.router(vertx); + routerSecondLevel.get("/").handler(ctx -> { + ctx.response().setStatusMessage("Hi").end(); + }); + routerFirstLevel.mountSubRouter("/", routerSecondLevel); + + // Below two scenarios will fail with 3.8.4 and higher, pass with 3.8.1 and lower. + testRequest(HttpMethod.GET, "/primary", 200, "Hi"); + testRequest(HttpMethod.GET, "/primary?query=1", 200, "Hi"); + + // Below scenarios will pass + testRequest(HttpMethod.GET, "/primary/", 200, "Hi"); + testRequest(HttpMethod.GET, "/primary/random", 404, "Not Found"); + } }
    ['vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,671,876
    369,992
    51,774
    404
    537
    124
    9
    1
    1,781
    265
    468
    48
    4
    0
    1970-01-01T00:26:41
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,264
    vert-x3/vertx-web/1724/1720
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1720
    https://github.com/vert-x3/vertx-web/pull/1724
    https://github.com/vert-x3/vertx-web/pull/1724
    1
    fix
    SockJSHandlerTest intermittent failures in CI
    ### Questions There is an intermittent failures about `SockJSHandlerTest` in CI ### Version `master` branch ### Context ### Exceptions found ```java Starting test: SockJSHandlerTest#testCombineBinaryContinuationFramesRawWebSocket Unhandled exception java.lang.IllegalStateException: assert or failure occurred after test has completed at io.vertx.test.core.AsyncTestBase.handleThrowable(AsyncTestBase.java:183) at io.vertx.test.core.AsyncTestBase.fail(AsyncTestBase.java:422) at io.vertx.core.impl.AbstractContext.dispatch(AbstractContext.java:96) at io.vertx.core.http.impl.WebSocketImplBase.handleClosed(WebSocketImplBase.java:694) at io.vertx.core.http.impl.Http1xServerConnection.lambda$handleClosed$6(Http1xServerConnection.java:458) at io.vertx.core.impl.EventLoopContext.execute(EventLoopContext.java:73) at io.vertx.core.impl.DuplicatedContext.execute(DuplicatedContext.java:184) at io.vertx.core.impl.AbstractContext.execute(AbstractContext.java:54) at io.vertx.core.http.impl.Http1xServerConnection.handleClosed(Http1xServerConnection.java:458) at io.vertx.core.net.impl.VertxHandler.channelInactive(VertxHandler.java:136) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241) at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:389) at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:354) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1405) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248) at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:901) at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:818) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:497) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:748) ``` ### Do you have a reproducer? https://travis-ci.org/github/vert-x3/vertx-web/jobs/731209417 as reference ### Extra * Looks like it happens in `OpenJDK8` mostly.
    8e6e4681df8d1262ae5a00dc6607752055ad9133
    714d9280cf78ac0a788d5a640b2caff1aa151a9b
    https://github.com/vert-x3/vertx-web/compare/8e6e4681df8d1262ae5a00dc6607752055ad9133...714d9280cf78ac0a788d5a640b2caff1aa151a9b
    diff --git a/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java b/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java index db07598b9..7c3e7e86c 100644 --- a/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java +++ b/vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java @@ -62,7 +62,7 @@ public interface PebbleTemplateEngine extends TemplateEngine { */ @GenIgnore static PebbleTemplateEngine create(Vertx vertx, PebbleEngine engine) { - return new PebbleTemplateEngineImpl(vertx, DEFAULT_TEMPLATE_EXTENSION, engine); + return create(vertx, DEFAULT_TEMPLATE_EXTENSION, engine); } /** diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java index 9f7eda5ba..7e13a9ca1 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java @@ -395,12 +395,16 @@ class SockJSSession extends SockJSSocketBase implements Shareable { } } - synchronized void handleException(Throwable t) { - if (exceptionHandler != null) { + void handleException(Throwable t) { + Handler<Throwable> eh; + synchronized (this) { + eh = exceptionHandler; + } + if (eh != null) { if (context == Vertx.currentContext()) { - exceptionHandler.handle(t); + eh.handle(t); } else { - context.runOnContext(v -> exceptionHandler.handle(t)); + context.runOnContext(v -> handleException(t)); } } else { log.error("Unhandled exception", t); diff --git a/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java b/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java index 5400af059..7e5db09f6 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java @@ -73,10 +73,12 @@ public class WebTestBase extends VertxTestBase { @Override public void tearDown() throws Exception { if (client != null) { - try { - client.close(); - } catch (IllegalStateException e) { - } + CountDownLatch latch = new CountDownLatch(1); + client.close((asyncResult) -> { + assertTrue(asyncResult.succeeded()); + latch.countDown(); + }); + awaitLatch(latch); } if (server != null) { CountDownLatch latch = new CountDownLatch(1);
    ['vertx-web/src/test/java/io/vertx/ext/web/WebTestBase.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/SockJSSession.java', 'vertx-template-engines/vertx-web-templ-pebble/src/main/java/io/vertx/ext/web/templ/pebble/PebbleTemplateEngine.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,669,283
    369,360
    51,681
    404
    569
    120
    14
    2
    3,325
    115
    661
    56
    1
    1
    1970-01-01T00:26:41
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,266
    vert-x3/vertx-web/1686/1685
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1685
    https://github.com/vert-x3/vertx-web/pull/1686
    https://github.com/vert-x3/vertx-web/pull/1686
    1
    fixes
    StatusCode still remains -1 when catching a runtime exception
    ### Questions The status code in failure handler remains -1 when catching a runtime exception ### Version 3.9.2, 4.0.0beta1 ### Do you have a reproducer? try this example: ```java Route route1 = router.get("/somepath/path1/"); route1.handler(ctx -> { // Let's say this throws a RuntimeException throw new RuntimeException("something happened!"); }); // Define a failure handler // This will get called for any failures in the above handlers Route route3 = router.get("/somepath/*"); route3.failureHandler(failureRoutingContext -> { int statusCode = failureRoutingContext.statusCode(); System.out.println(statusCode); //remains -1 here // Status code should be 500 for the RuntimeException HttpServerResponse response = failureRoutingContext.response(); response.setStatusCode(statusCode).end("Sorry! Not today"); }); ```
    f56655459e50661c8d13367193b2bf27b823702e
    10c0ebcd54c4b448d8c5bcd27a9b9c8a1f7ca6a6
    https://github.com/vert-x3/vertx-web/compare/f56655459e50661c8d13367193b2bf27b823702e...10c0ebcd54c4b448d8c5bcd27a9b9c8a1f7ca6a6
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java index 948941020..2c35e033a 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java @@ -16,9 +16,6 @@ package io.vertx.ext.web.handler.impl; -import java.util.List; -import java.util.Objects; - import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; @@ -28,6 +25,9 @@ import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.ErrorHandler; import io.vertx.ext.web.impl.Utils; +import java.util.List; +import java.util.Objects; + /** * @author <a href="http://[email protected]">Paulo Lopes</a> * @author <a href="http://tfox.org">Tim Fox</a> @@ -58,48 +58,48 @@ public class ErrorHandlerImpl implements ErrorHandler { Throwable failure = context.failure(); int errorCode = context.statusCode(); - String errorMessage = null; - if (errorCode != -1) { - context.response().setStatusCode(errorCode); - errorMessage = context.response().getStatusMessage(); - } else { + + // force default error code + if (errorCode == -1) { errorCode = 500; - if (displayExceptionDetails) { - errorMessage = failure.getMessage(); - } - if (errorMessage == null) { - errorMessage = "Internal Server Error"; + } + + response.setStatusCode(errorCode); + String errorMessage = response.getStatusMessage(); + + if (displayExceptionDetails) { + errorMessage = failure.getMessage(); + if (errorMessage != null) { + // no new lines are allowed in the status message + errorMessage = errorMessage.replaceAll("\\\\r|\\\\n", " "); + // apply the newly desired message + response.setStatusMessage(errorMessage); } - // no new lines are allowed in the status message - response.setStatusMessage(errorMessage.replaceAll("\\\\r|\\\\n", " ")); } answerWithError(context, errorCode, errorMessage); } - private void answerWithError(RoutingContext context, int errorCode, String errorMessage){ - context.response().setStatusCode(errorCode); - if( !sendErrorResponseMIME(context, errorCode, errorMessage) && - !sendErrorAcceptMIME(context, errorCode, errorMessage) - ){ + private void answerWithError(RoutingContext context, int errorCode, String errorMessage) { + if (!sendErrorResponseMIME(context, errorCode, errorMessage) && !sendErrorAcceptMIME(context, errorCode, errorMessage)) { // fallback plain/text sendError(context, "text/plain", errorCode, errorMessage); } } - private boolean sendErrorResponseMIME(RoutingContext context, int errorCode, String errorMessage){ + private boolean sendErrorResponseMIME(RoutingContext context, int errorCode, String errorMessage) { // does the response already set the mime type? String mime = context.response().headers().get(HttpHeaders.CONTENT_TYPE); - if(mime == null) { + if (mime == null) { // does the route have an acceptable content type? mime = context.getAcceptableContentType(); } - + return mime != null && sendError(context, mime, errorCode, errorMessage); } - private boolean sendErrorAcceptMIME(RoutingContext context, int errorCode, String errorMessage){ + private boolean sendErrorAcceptMIME(RoutingContext context, int errorCode, String errorMessage) { // respect the client accept order List<MIMEHeader> acceptableMimes = context.parsedHeaders().accept(); @@ -120,11 +120,11 @@ public class ErrorHandlerImpl implements ErrorHandler { if (mime.startsWith("text/html")) { StringBuilder stack = new StringBuilder(); if (context.failure() != null && displayExceptionDetails) { - for (StackTraceElement elem: context.failure().getStackTrace()) { + for (StackTraceElement elem : context.failure().getStackTrace()) { stack.append("<li>").append(elem).append("</li>"); } } - response.putHeader(HttpHeaders.CONTENT_TYPE,"text/html"); + response.putHeader(HttpHeaders.CONTENT_TYPE, "text/html"); response.end( errorTemplate.replace("{title}", title) .replace("{errorCode}", Integer.toString(errorCode)) @@ -139,7 +139,7 @@ public class ErrorHandlerImpl implements ErrorHandler { jsonError.put("error", new JsonObject().put("code", errorCode).put("message", errorMessage)); if (context.failure() != null && displayExceptionDetails) { JsonArray stack = new JsonArray(); - for (StackTraceElement elem: context.failure().getStackTrace()) { + for (StackTraceElement elem : context.failure().getStackTrace()) { stack.add(elem.toString()); } jsonError.put("stack", stack); @@ -157,7 +157,7 @@ public class ErrorHandlerImpl implements ErrorHandler { sb.append(": "); sb.append(errorMessage); if (context.failure() != null && displayExceptionDetails) { - for (StackTraceElement elem: context.failure().getStackTrace()) { + for (StackTraceElement elem : context.failure().getStackTrace()) { sb.append("\\tat ").append(elem).append("\\n"); } } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java index f11afb8f8..8dc8f729e 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java @@ -163,7 +163,11 @@ public class RoutingContextImpl extends RoutingContextImplBase { @Override public void fail(Throwable t) { - this.fail(-1, t); + if (t instanceof HttpStatusException) { + this.fail(((HttpStatusException) t).getStatusCode(), t); + } else { + this.fail(500, t); + } } @Override diff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java index 354ce7837..fb10dc6db 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java @@ -616,7 +616,7 @@ public class RouterTest extends WebTestBase { String path = "/blah"; Throwable failure = new Throwable(); router.route(path).handler(rc -> rc.fail(failure)).failureHandler(frc -> { - assertEquals(-1, frc.statusCode()); + assertEquals(500, frc.statusCode()); assertSame(failure, frc.failure()); frc.response().setStatusCode(500).setStatusMessage("Internal Server Error").end(); }); @@ -627,7 +627,7 @@ public class RouterTest extends WebTestBase { public void testFailureWithNullThrowable() throws Exception { String path = "/blah"; router.route(path).handler(rc -> rc.fail(null)).failureHandler(frc -> { - assertEquals(-1, frc.statusCode()); + assertEquals(500, frc.statusCode()); assertTrue(frc.failure() instanceof NullPointerException); frc.response().setStatusCode(500).setStatusMessage("Internal Server Error").end(); }); @@ -2767,4 +2767,27 @@ public class RouterTest extends WebTestBase { testRequest(HttpMethod.MKCOL, "/", 200, "socks"); } + + @Test + public void testStatusCodeUncatchedException() throws Exception { + Route route1 = router.get("/somepath/path1"); + route1.handler(ctx -> { + // Let's say this throws a RuntimeException + throw new RuntimeException("something happened!"); + }); + +// Define a failure handler +// This will get called for any failures in the above handlers + Route route3 = router.get("/somepath/*"); + route3.failureHandler(failureRoutingContext -> { + int statusCode = failureRoutingContext.statusCode(); + // Status code should be 500 for the RuntimeException + assertEquals(500, statusCode); + HttpServerResponse response = failureRoutingContext.response(); + response.setStatusCode(statusCode).end("Sorry! Not today"); + }); + + testRequest(HttpMethod.GET, "/somepath/path1", 500, "Internal Server Error"); + + } } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java index 4b9e87aad..a6ee31031 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java @@ -310,7 +310,7 @@ public class SubRouterTest extends WebTestBase { }); router.route("/subpath/*").failureHandler(rc -> { - assertEquals(-1, rc.statusCode()); + assertEquals(500, rc.statusCode()); assertEquals("Balderdash!", rc.failure().getMessage()); rc.response().setStatusCode(555).setStatusMessage("Badgers").end(); }); @@ -329,7 +329,7 @@ public class SubRouterTest extends WebTestBase { }); subRouter.route("/foo/*").failureHandler(rc -> { - assertEquals(-1, rc.statusCode()); + assertEquals(500, rc.statusCode()); assertEquals("Balderdash!", rc.failure().getMessage()); rc.response().setStatusCode(555).setStatusMessage("Badgers").end(); });
    ['vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ErrorHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java']
    {'.java': 4}
    4
    4
    0
    0
    4
    1,648,974
    364,858
    51,080
    404
    2,837
    557
    62
    2
    870
    98
    193
    30
    0
    1
    1970-01-01T00:26:38
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,246
    vert-x3/vertx-web/2066/2065
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2065
    https://github.com/vert-x3/vertx-web/pull/2066
    https://github.com/vert-x3/vertx-web/pull/2066
    1
    fixes
    SecuritySchemeImpl returns null on bind call
    ### Version 4.1.5 ### Context When calling `RouterBuilder.securityScheme(String).bind(..)` the returned Future always return null due to a `.mapEmpty()` call.
    5b34cadd4a24b197ca2ac625393b8cf29f25f677
    f24d31766fda9b17c418b6403289212109d22941
    https://github.com/vert-x3/vertx-web/compare/5b34cadd4a24b197ca2ac625393b8cf29f25f677...f24d31766fda9b17c418b6403289212109d22941
    diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java index 2c8043fff..7df9cf046 100644 --- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java +++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java @@ -40,7 +40,7 @@ public class SecuritySchemeImpl implements SecurityScheme { if (securitySchemes.containsKey(securitySchemeId)) { return factory.apply(securitySchemes.getJsonObject(securitySchemeId)) .onSuccess(handler -> routerBuilder.securityHandler(securitySchemeId, handler)) - .mapEmpty(); + .map(routerBuilder); } } return diff --git a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java index 80d90e15b..d11b9db9c 100644 --- a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java +++ b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java @@ -1,11 +1,15 @@ package io.vertx.ext.web.openapi; +import static org.assertj.core.api.Assertions.assertThat; + +import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.ext.web.handler.APIKeyHandler; import io.vertx.ext.web.handler.OAuth2AuthHandler; import io.vertx.junit5.Timeout; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -68,4 +72,19 @@ public class RouterBuilderSecurityHandlerTest extends BaseRouterBuilderTest { } }); } + + @Test + public void asyncBindHandler(Vertx vertx, VertxTestContext testContext) { + RouterBuilder.create(vertx, SECURITY_TESTS) + .compose(routerBuilder -> + routerBuilder + .securityHandler("oauth") + .bind(config -> Future.succeededFuture(OAuth2AuthHandler.create(vertx, null))) + ) + .onSuccess(routerBuilder -> { + testContext.verify(() -> assertThat(routerBuilder).isNotNull()); + testContext.completeNow(); + }) + .onFailure(testContext::failNow); + } }
    ['vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/SecuritySchemeImpl.java', 'vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderSecurityHandlerTest.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,913,261
    424,136
    59,339
    474
    55
    11
    2
    1
    170
    19
    40
    8
    0
    0
    1970-01-01T00:27:13
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,268
    vert-x3/vertx-web/1492/1490
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1490
    https://github.com/vert-x3/vertx-web/pull/1492
    https://github.com/vert-x3/vertx-web/pull/1492
    2
    fixes
    FormLoginHandlerImpl should return status 401 on failed authentication
    ### Version * vert.x core: 3.8.4 * vert.x web: 3.8.4 ### Context I was using the FormLoginHandler to perform simple form-based login. The default implementation sets the status code to 403 ("Forbidden") which to me indicates that the user is not **allowed** to login. I think 401 ("Unauthorized") is more appropriate since it "[indicates that the request has not been applied because it lacks valid authentication credentials for the target resource](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401)" Also see https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses ### Do you have a reproducer? Just read the code at: https://github.com/vert-x3/vertx-web/blob/4c2ab04649c0ed306099abac1346f5fedea8c53b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java#L125 ### Steps to reproduce 1. Add FormLoginHandler to route 2. Submit wrong credentials via html form 3. observe
    70b4403c3b3a970167ebb101868ce2166ebf12d1
    357a8678ed88283b1b3112a91ebb691e51ed23be
    https://github.com/vert-x3/vertx-web/compare/70b4403c3b3a970167ebb101868ce2166ebf12d1...357a8678ed88283b1b3112a91ebb691e51ed23be
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java index 0fe34f8d6..71ed6f810 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java @@ -81,7 +81,7 @@ public class FormLoginHandlerImpl implements FormLoginHandler { public void handle(RoutingContext context) { HttpServerRequest req = context.request(); if (req.method() != HttpMethod.POST) { - context.fail(405); // Must be a POST + context.fail(new HttpStatusException(405)); // Must be a POST } else { if (!req.isExpectMultipart()) { throw new IllegalStateException("HttpServerRequest should have setExpectMultipart set to true, but it is currently set to false."); @@ -91,7 +91,7 @@ public class FormLoginHandlerImpl implements FormLoginHandler { String password = params.get(passwordParam); if (username == null || password == null) { log.warn("No username or password provided in form - did you forget to include a BodyHandler?"); - context.fail(400); + context.fail(new HttpStatusException(400)); } else { Session session = context.session(); JsonObject authInfo = new JsonObject().put("username", username).put("password", password); @@ -122,7 +122,7 @@ public class FormLoginHandlerImpl implements FormLoginHandler { req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE); } } else { - context.fail(403); // Failed login + context.fail(new HttpStatusException(401)); // Failed login } }); } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java index a0bdae237..1612a10cc 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java @@ -275,7 +275,7 @@ public class RedirectAuthHandlerTest extends AuthHandlerTestBase { req.putHeader("cookie", sessionCookie.get()); req.write(buffer); }, resp -> { - }, 403, "Forbidden", null); + }, 401, "Unauthorized", null); testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("cookie", sessionCookie.get()), resp -> { String location = resp.headers().get("location"); assertNotNull(location);
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/RedirectAuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/FormLoginHandlerImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,270,844
    283,807
    40,228
    298
    316
    67
    6
    1
    976
    104
    252
    23
    3
    0
    1970-01-01T00:26:16
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,261
    vert-x3/vertx-web/1765/1742
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1742
    https://github.com/vert-x3/vertx-web/pull/1765
    https://github.com/vert-x3/vertx-web/pull/1765
    1
    fixes
    ResponsePredicateResult::response returns null when requiresBody is false
    ### Version `3.9.3` ### Context I have a very simple `ErrorConverter` whose `ResponsePredicateResult` is returning `null` for `response()` when `requiresBody()` is set to `false`. It works fine (valid `HttpResponse` instance) if `requiresBody()` is set to `true`. I would expect to be able to assess all response properties _except_ `body()` by having `requiresBody` set to `false`. ### Do you have a reproducer? ~~No, if the report doesn't point to an obvious culprit I can see if I can create one.~~ https://github.com/pnsantos/vertx-predicate-npe-repro ### Steps to reproduce This is my error converter: ```java public class MyConverter implements ErrorConverter { @Override public Throwable apply(ResponsePredicateResult result) { int code = result.response().statusCode(); <--- result.response() is null (...) } } ``` And this is how I'm creating the response predicate: ``` ResponsePredicate.create(ResponsePredicate.SC_SUCCESS, new MyConverter()) ``` On "success" cases everything works fine. When the predicate fails (4xx/5xx responses), and the converter is called, if `requiresBody` is set to `true` everything works as expected. However if `requiresBody` is `false` the following exception happens (line 21 is where I'm doing (`result.response().statusCode()`): ``` java.lang.NullPointerException at com.example.error.MyErrorConverter.apply(MyErrorConverter.java:21) at io.vertx.ext.web.client.impl.predicate.PredicateInterceptor.failOnPredicate(PredicateInterceptor.java:88) at io.vertx.ext.web.client.impl.predicate.PredicateInterceptor.handle(PredicateInterceptor.java:55) at io.vertx.ext.web.client.impl.predicate.PredicateInterceptor.handle(PredicateInterceptor.java:32) at io.vertx.ext.web.client.impl.HttpContext.next(HttpContext.java:272) at io.vertx.ext.web.client.impl.HttpContext.fire(HttpContext.java:282) at io.vertx.ext.web.client.impl.HttpContext.receiveResponse(HttpContext.java:230) at io.vertx.ext.web.client.impl.HttpContext.lambda$handleSendRequest$7(HttpContext.java:420) at io.vertx.core.impl.FutureImpl.dispatch(FutureImpl.java:105) at io.vertx.core.impl.FutureImpl.tryComplete(FutureImpl.java:150) at io.vertx.core.http.impl.HttpClientRequestImpl.handleResponse(HttpClientRequestImpl.java:391) at io.vertx.core.http.impl.HttpClientRequestBase.checkHandleResponse(HttpClientRequestBase.java:159) at io.vertx.core.http.impl.HttpClientRequestBase.handleResponse(HttpClientRequestBase.java:140) at io.vertx.core.http.impl.Http1xClientConnection.handleResponseBegin(Http1xClientConnection.java:623) at io.vertx.core.http.impl.Http1xClientConnection.handleHttpMessage(Http1xClientConnection.java:593) at io.vertx.core.http.impl.Http1xClientConnection.handleMessage(Http1xClientConnection.java:575) at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:366) at io.vertx.core.impl.EventLoopContext.execute(EventLoopContext.java:43) at io.vertx.core.impl.ContextImpl.executeFromIO(ContextImpl.java:229) at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:163) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436) at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296) at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1518) at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1267) at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1314) at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501) at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:792) at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:475) at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:748) ``` I confirmed via logs that `result.response()` is returning `null`. ### Extra ``` netty: 4.1.49.Final --- openjdk version "1.8.0_265" OpenJDK Runtime Environment (Zulu 8.48.0.53-CA-linux64) (build 1.8.0_265-b11) OpenJDK 64-Bit Server VM (Zulu 8.48.0.53-CA-linux64) (build 25.265-b11, mixed mode) ```
    5e61e19dc35d74543b93bc7a19eb56802ac7d855
    d4260ec69ed3228dee793a0da19d243a37a57c69
    https://github.com/vert-x3/vertx-web/compare/5e61e19dc35d74543b93bc7a19eb56802ac7d855...d4260ec69ed3228dee793a0da19d243a37a57c69
    diff --git a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java index a4f5afe5e..8273ea14b 100644 --- a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java +++ b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java @@ -44,7 +44,7 @@ public class PredicateInterceptor implements Handler<HttpContext<?>> { for (ResponsePredicate expectation : expectations) { ResponsePredicateResultImpl predicateResult; try { - predicateResult = (ResponsePredicateResultImpl) expectation.apply(responseCopy(resp, httpContext,null)); + predicateResult = (ResponsePredicateResultImpl) expectation.apply(responseCopy(resp, httpContext, null)); } catch (Exception e) { httpContext.fail(e); return; @@ -52,6 +52,7 @@ public class PredicateInterceptor implements Handler<HttpContext<?>> { if (!predicateResult.succeeded()) { ErrorConverter errorConverter = expectation.errorConverter(); if (!errorConverter.requiresBody()) { + predicateResult.setHttpResponse(responseCopy(resp, httpContext, null)); failOnPredicate(httpContext, errorConverter, predicateResult); } else { resp.bodyHandler(buffer -> { diff --git a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java index 7e2396f6b..59052c32c 100644 --- a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java +++ b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java @@ -1775,6 +1775,29 @@ public class WebClientTest extends WebClientTestBase { }); } + @Test + public void testExpectCustomExceptionWithStatusCode() throws Exception { + UUID uuid = UUID.randomUUID(); + int statusCode = 400; + + ResponsePredicate predicate = ResponsePredicate.create(ResponsePredicate.SC_SUCCESS, ErrorConverter.create(result -> { + int code = result.response().statusCode(); + return new CustomException(uuid, String.valueOf(code)); + })); + + testExpectation(true, req -> req.expect(predicate), httpServerResponse -> { + httpServerResponse + .setStatusCode(statusCode) + .end(TestUtils.randomBuffer(2048)); + }, ar -> { + Throwable cause = ar.cause(); + assertThat(cause, instanceOf(CustomException.class)); + CustomException customException = (CustomException) cause; + assertEquals(String.valueOf(statusCode), customException.getMessage()); + assertEquals(uuid, customException.tag); + }); + } + @Test public void testExpectFunctionThrowsException() throws Exception { ResponsePredicate predicate = ResponsePredicate.create(r -> {
    ['vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java', 'vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/predicate/PredicateInterceptor.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,691,104
    374,258
    52,377
    411
    323
    55
    3
    1
    6,845
    318
    1,494
    106
    1
    4
    1970-01-01T00:26:44
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,253
    vert-x3/vertx-web/1978/1380
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1380
    https://github.com/vert-x3/vertx-web/pull/1978
    https://github.com/vert-x3/vertx-web/pull/1978
    1
    fix
    Race condition when using an event bus bridge hook (events handler), between socket closed event and other events
    ### Version * vert.x core: 3.7.1 (should apply to 3.8.1, master) * vert.x web: 3.7.1 (should apply to 3.8.1, master) ### Context We started to see that some messages were not delivered to the same event bus (bridge) address. After multiple re-connections, a client can't listen anymore to some particular address as it receives nothing or receives too few messages out of all the messages sent. The server needs to be restarted. When an event bus bridge hook (events handler) is used, it seems like there's a race condition where io.vertx.ext.web.handler.sockjs.impl.EventBusBridgeImpl.java may call handleSocketClosed while we're still in internalHandleRegister (or unregister, sendorpub). This can happen before checkCallHook's okAction is run as we're still waiting for the hook (event handlers) to accept the event... ### Do you have a reproducer? See steps below ### Steps to reproduce We reproduced this with custom tools but I think this scenario is sufficient to reproduce it: 1. ... Set an event bus bridge events handler 2. ... Intercept "REGISTER" event and wait enough time before accepting the event 3. ... Meanwhile, disconnect the client 4. ... A MessageConsumer is created for the given address although socket is already closed and any message sent to this address might now land into this MessageConsumer associated to nothing ### Extra Should apply to 3.8.1 and master as nothing was changed that could fix this issue in this file (EventBusBridgeImpl.java). We fixed this internally by just checking for `if (!sockInfos.containsKey(sock)) return;` at the beginning of checkCallHook's okAction handlers. It could probably explain https://github.com/vert-x3/vertx-web/issues/1327: the message consumer's handler references the closed socket when the race condition issue happens while a REGISTER event is being handled.
    7a8c6550ee5f4fdd9755ebfabb326765a6e52f3a
    e321e222b2086086b8901941f79acc3a90341af2
    https://github.com/vert-x3/vertx-web/compare/7a8c6550ee5f4fdd9755ebfabb326765a6e52f3a...e321e222b2086086b8901941f79acc3a90341af2
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java index 346b45b8e..51a98c417 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java @@ -97,8 +97,11 @@ public class EventBusBridgeImpl implements Handler<SockJSSocket> { // On close unregister any handlers that haven't been unregistered registrations.forEach((key, value) -> { value.unregister(); - checkCallHook(() -> new BridgeEventImpl(BridgeEventType.UNREGISTER, - new JsonObject().put("type", "unregister").put("address", value.address()), sock), null, null); + checkCallHook(() -> + new BridgeEventImpl( + BridgeEventType.UNREGISTER, + new JsonObject().put("type", "unregister").put("address", value.address()), + sock)); }); SockInfo info = sockInfos.remove(sock); @@ -109,8 +112,7 @@ public class EventBusBridgeImpl implements Handler<SockJSSocket> { } } - checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_CLOSED, null, sock), - null, null); + checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_CLOSED, null, sock)); } private void handleSocketData(SockJSSocket sock, Buffer data, Map<String, MessageConsumer<?>> registrations) { @@ -158,19 +160,35 @@ public class EventBusBridgeImpl implements Handler<SockJSSocket> { } + private void checkCallHook(Supplier<BridgeEventImpl> eventSupplier) { + checkCallHook(eventSupplier, null, null); + } + private void checkCallHook(Supplier<BridgeEventImpl> eventSupplier, Runnable okAction, Runnable rejectAction) { if (bridgeEventHandler == null) { if (okAction != null) { okAction.run(); } } else { - BridgeEventImpl event = eventSupplier.get(); + final BridgeEventImpl event = eventSupplier.get(); + final boolean before = sockInfos.containsKey(event.socket()); bridgeEventHandler.handle(event); - event.future().onComplete(res -> { - if (res.succeeded()) { - if (res.result()) { - if (okAction != null) { - okAction.run(); + event.future() + .onFailure(err -> LOG.error("Failure in bridge event handler", err)) + .onSuccess(ok -> { + if (ok) { + final boolean after = sockInfos.containsKey(event.socket()); + if (before != after) { + // even though the event check is valid, the socket info isn't valid anymore + if (rejectAction != null) { + rejectAction.run(); + } else { + LOG.debug("SockJSSocket state change prevented send or pub"); + } + } else { + if (okAction != null) { + okAction.run(); + } } } else { if (rejectAction != null) { @@ -179,10 +197,7 @@ public class EventBusBridgeImpl implements Handler<SockJSSocket> { LOG.debug("Bridge handler prevented send or pub"); } } - } else { - LOG.error("Failure in bridge event handler", res.cause()); - } - }); + }); } } @@ -261,7 +276,7 @@ public class EventBusBridgeImpl implements Handler<SockJSSocket> { registrations.put(address, reg); info.handlerCount++; // Notify registration completed - checkCallHook(() -> new BridgeEventImpl(BridgeEventType.REGISTERED, rawMsg, sock), null, null); + checkCallHook(() -> new BridgeEventImpl(BridgeEventType.REGISTERED, rawMsg, sock)); } else { // inbound match failed if (debug) { @@ -306,7 +321,7 @@ public class EventBusBridgeImpl implements Handler<SockJSSocket> { if (info != null) { info.pingInfo.lastPing = System.currentTimeMillis(); // Trigger an event to allow custom behavior after updating lastPing - checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_PING, null, sock), null, null); + checkCallHook(() -> new BridgeEventImpl(BridgeEventType.SOCKET_PING, null, sock)); } }
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/sockjs/impl/EventBusBridgeImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,757,323
    389,173
    54,407
    434
    2,238
    476
    47
    1
    1,881
    276
    416
    33
    1
    0
    1970-01-01T00:27:03
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,254
    vert-x3/vertx-web/1947/1890
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1890
    https://github.com/vert-x3/vertx-web/pull/1947
    https://github.com/vert-x3/vertx-web/pull/1947
    1
    fixes
    SessionHandler doesn't set SameSite cookie attribute when destroying the session and expiring the session cookie
    ### Questions When the session cookie needs to be removed on session logout, the SameSite attribute is not set. ### Version 3.9.2 ### Context If SameSite.None is set on the cookie while setting it for the duration of the session, It should also be present when the user sends a logout and the expiration of the cookie is set. The logout can be called from different locations where the SameSite.None is needed for it to function. Now because it's not set, the cookie remains, and the session is still available. ### Do you have a reproducer? It's on line 196 in io.vertx.ext.web.handler.impl.SessionHandlerImpl. The cookie is removed when the session gets destroyed. But the additional attributes are not there. I duplicated the SessionHandlerImpl class and added the following code to get it to work. I can add a pull request, to add the cookie handling in the SessionHandlerImpl itself. ``` ... } else { // invalidate the cookie as the session has been destroyed context.removeCookie(sessionCookieName); /* added from here*/ Cookie cookie = context.getCookie(sessionCookieName); if (cookie != null) { cookie.setPath(sessionCookiePath); cookie.setSecure(sessionCookieSecure); cookie.setHttpOnly(sessionCookieHttpOnly); cookie.setSameSite(cookieSameSite); context.addCookie(cookie); } /* until here*/ // if the session was regenerated in the request // the old id must also be removed if (session.isRegenerated()) { ... ```
    a4eb3dbe0f2dc167f1242c03282b14e37aeb13be
    48c3ede6747d7a65cb00478a57478b44125e59a0
    https://github.com/vert-x3/vertx-web/compare/a4eb3dbe0f2dc167f1242c03282b14e37aeb13be...48c3ede6747d7a65cb00478a57478b44125e59a0
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java index 367e27de1..c9934625c 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java @@ -146,14 +146,16 @@ public class SessionHandlerImpl implements SessionHandler { * * @param cookie the cookie to set */ - private void setCookieProperties(Cookie cookie) { + private void setCookieProperties(Cookie cookie, boolean expired) { cookie.setPath(sessionCookiePath); cookie.setSecure(sessionCookieSecure); cookie.setHttpOnly(sessionCookieHttpOnly); cookie.setSameSite(cookieSameSite); - // set max age if user requested it - else it's a session cookie - if (cookieMaxAge >= 0) { - cookie.setMaxAge(cookieMaxAge); + if (!expired) { + // set max age if user requested it - else it's a session cookie + if (cookieMaxAge >= 0) { + cookie.setMaxAge(cookieMaxAge); + } } } @@ -190,7 +192,7 @@ public class SessionHandlerImpl implements SessionHandler { // restore defaults session.setAccessed(); cookie.setValue(session.value()); - setCookieProperties(cookie); + setCookieProperties(cookie, false); } // we must invalidate the old id @@ -234,7 +236,10 @@ public class SessionHandlerImpl implements SessionHandler { } else { if (!cookieless) { // invalidate the cookie as the session has been destroyed - context.removeCookie(sessionCookieName); + final Cookie expiredCookie = context.removeCookie(sessionCookieName); + if (expiredCookie != null) { + setCookieProperties(expiredCookie, true); + } } // if the session was regenerated in the request // the old id must also be removed @@ -450,7 +455,7 @@ public class SessionHandlerImpl implements SessionHandler { return cookie; } cookie = Cookie.cookie(sessionCookieName, session.value()); - setCookieProperties(cookie); + setCookieProperties(cookie, false); context.addCookie(cookie); return cookie; } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java index 12bd307b3..e11505e8f 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java @@ -16,6 +16,7 @@ package io.vertx.ext.web.handler; +import io.vertx.core.http.CookieSameSite; import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.Session; import io.vertx.ext.web.WebTestBase; @@ -381,6 +382,7 @@ public abstract class SessionHandlerTestBase extends WebTestBase { testRequest(HttpMethod.GET, "/0", req -> { }, resp -> { String setCookie = resp.headers().get("set-cookie"); + System.out.println(setCookie); sessionID.set(setCookie); }, 200, "OK", null); CountDownLatch responseReceived = new CountDownLatch(1); @@ -393,6 +395,38 @@ public abstract class SessionHandlerTestBase extends WebTestBase { return MILLISECONDS.convert(System.nanoTime() - now, NANOSECONDS); } + @Test + public void testInvalidation() throws Exception { + router.route().handler(SessionHandler.create(store).setCookieSameSite(CookieSameSite.STRICT)); + AtomicReference<Session> rid = new AtomicReference<>(); + + router.get("/0").handler(rc -> { + rid.set(rc.session()); + rc.session().put("foo", "foo_value"); + rc.response().end(); + }); + router.get("/1").handler(rc -> { + rid.set(rc.session()); + assertEquals("foo_value", rc.session().get("foo")); + rc.session().destroy(); + rc.response().end(); + }); + + AtomicReference<String> sessionID = new AtomicReference<>(); + testRequest(HttpMethod.GET, "/0", req -> { + }, resp -> { + String setCookie = resp.headers().get("set-cookie"); + sessionID.set(setCookie); + }, 200, "OK", null); + CountDownLatch responseReceived = new CountDownLatch(1); + testRequest(HttpMethod.GET, "/1", req -> req.putHeader("cookie", sessionID.get()), resp -> { + // ensure that expired cookies still contain the the configured properties + assertTrue(resp.headers().get("set-cookie").contains("SameSite=Strict")); + responseReceived.countDown(); + }, 200, "OK", null); + awaitLatch(responseReceived); + } + @Test public void testSessionFixation() throws Exception {
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,749,425
    387,236
    54,129
    428
    833
    175
    19
    1
    1,663
    208
    326
    43
    0
    1
    1970-01-01T00:27:00
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,255
    vert-x3/vertx-web/1945/1933
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1933
    https://github.com/vert-x3/vertx-web/pull/1945
    https://github.com/vert-x3/vertx-web/pull/1945
    1
    fix
    CORS handling fails with "Origin: null" header
    ### Version Which version(s) did you encounter this bug ? 4.0.3 ### Context When issuing an HTTP request with the `Origin: null` header, the CorsHandler generates an HTTP 500 error (`CORS Rejected - Invalid origin`), even though it should allow the request to continue its normal processing. This happens whenever one creates a CorsHandler with either https://vertx.io/docs/apidocs/io/vertx/ext/web/handler/CorsHandler.html#create-- (which should allow any origin), or with https://vertx.io/docs/apidocs/io/vertx/ext/web/handler/CorsHandler.html#create-java.lang.String- and passing the `"*"` pattern (which should do the same as `.create()` and allow any origin.) The `Origin: null` header name and value is a valid origin, as per https://tools.ietf.org/html/rfc6454#section-7.1 ; the literal `null` is allowed; in that RFC it just happens to be phrased using its hex-encoded ascii values: ``` origin-list-or-null = %x6E %x75 %x6C %x6C / origin-list ``` This particular header value is sent automatically by browsers whenever they perform a cross-origin request, and the browser has to set an "opaque origin", like when the URL of the page is `file://` (see https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null ) ### Do you have a reproducer? Sort of; I noticed this issue in the https://github.com/yuzutech/kroki project; this project happens to have a publicly available instance which can demonstrate the issue; you can inspect how the CorsHandler is created, at https://github.com/yuzutech/kroki/blob/v0.12.1/server/src/main/java/io/kroki/server/Server.java#L92 To reproduce, just issue what should be a valid HTTP request with `Origin: null`, and notice that the API reports back an HTTP 500 error: * `curl https://kroki.io/graphviz/svg/eNpLyUwvSizIUHBXqPZIzcnJ17ULzy_KSanlAgB1EAjQ`, gives you HTTP 200, and a bunch of SVG, as expected. * `curl -H 'Origin: http://localhost' https://kroki.io/graphviz/svg/eNpLyUwvSizIUHBXqPZIzcnJ17ULzy_KSanlAgB1EAjQ`, also gives you HTTP 200, and a bunch of SVG. * `curl -H 'Origin: null' https://kroki.io/graphviz/svg/eNpLyUwvSizIUHBXqPZIzcnJ17ULzy_KSanlAgB1EAjQ` gives you an HTTP 500 with the error message `Error 500: CORS Rejected - Invalid origin` (which can be traced back to vertx-web). For that case, the stacktrace is this (reproduced in local environment): ``` java.lang.IllegalStateException: CORS Rejected - Invalid origin at io.vertx.ext.web.handler.impl.CorsHandlerImpl.handle(CorsHandlerImpl.java:211) at io.vertx.ext.web.handler.impl.CorsHandlerImpl.handle(CorsHandlerImpl.java:41) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1129) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:151) at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:133) at io.vertx.ext.web.impl.RouterImpl.handle(RouterImpl.java:55) at io.vertx.ext.web.impl.RouterImpl.handle(RouterImpl.java:37) at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:67) at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:30) at io.vertx.core.impl.EventLoopContext.emit(EventLoopContext.java:52) at io.vertx.core.impl.DuplicatedContext.emit(DuplicatedContext.java:194) at io.vertx.core.http.impl.Http1xServerConnection.handleMessage(Http1xServerConnection.java:140) at io.vertx.core.net.impl.ConnectionBase.read(ConnectionBase.java:153) at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:154) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:93) at io.netty.handler.codec.http.websocketx.extensions.WebSocketServerExtensionHandler.channelRead(WebSocketServerExtensionHandler.java:102) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.vertx.core.http.impl.Http1xUpgradeToH2CHandler.channelRead(Http1xUpgradeToH2CHandler.java:115) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.vertx.core.http.impl.Http1xOrH2CHandler.end(Http1xOrH2CHandler.java:61) at io.vertx.core.http.impl.Http1xOrH2CHandler.channelRead(Http1xOrH2CHandler.java:38) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Unknown Source) ``` ```
    f8e7bb17b6365b1f86f84fae0090102a48674205
    dce68f718a20d7c985a2175219c19c1507414f11
    https://github.com/vert-x3/vertx-web/compare/f8e7bb17b6365b1f86f84fae0090102a48674205...dce68f718a20d7c985a2175219c19c1507414f11
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java index f2aec90b5..5feada3f7 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java @@ -34,6 +34,7 @@ public final class Origin { private final String host; private final int port; private final String resource; + private final boolean isNull; // internal private final String base; @@ -41,6 +42,21 @@ public final class Origin { private final String optional; private Origin(String protocol, String host, String port, String resource) { + + if (protocol == null && host == null && port == null && resource == null) { + this.protocol = null; + this.host = null; + this.port = -1; + this.resource = null; + isNull = true; + this.base = null; + this.BASE = null; + this.optional = null; + return; + } else { + isNull = false; + } + String defaultPort; switch (protocol.toLowerCase()) { case "ftp": @@ -120,6 +136,12 @@ public final class Origin { public static Origin parse(String text) { + if (text.length() == 4) { + if ("null".equals(text)) { + return new Origin(null, null, null, null); + } + } + int sep0 = text.indexOf("://"); if (sep0 > 0) { @@ -168,6 +190,12 @@ public final class Origin { * https://tools.ietf.org/html/rfc6454#section-7 */ public static boolean isValid(String text) { + if (text.length() == 4) { + if ("null".equals(text)) { + return true; + } + } + int sep0 = text.indexOf("://"); if (sep0 > 0) { @@ -285,6 +313,11 @@ public final class Origin { } public boolean sameOrigin(String other) { + + if (isNull) { + return "null".equals(other); + } + // for each char of other // if any base chars != other abort // if more chars @@ -332,6 +365,10 @@ public final class Origin { } public String encode() { + if (isNull) { + return "<null>"; + } + switch (protocol) { case "http": return protocol + "://" + host + (port == 80 ? "" : ":" + port); @@ -346,6 +383,10 @@ public final class Origin { @Override public String toString() { + if (isNull) { + return "null"; + } + return base; } @@ -353,6 +394,10 @@ public final class Origin { * An hyperlink representation of this origin. Like on web browsers. */ public String href() { + if (isNull) { + return "null"; + } + return base + (resource == null ? "/" : resource); } } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java index a6daff696..96ee929c8 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java @@ -495,4 +495,12 @@ public class CORSHandlerTest extends WebTestBase { router.route().handler(context -> context.response().end()); testRequest(HttpMethod.GET, "/", req -> req.headers().add("origin", "https://www.vertx.io"), resp -> checkHeaders(resp, "https://www.vertx.io", null, null, null, "true", null), 200, "OK", null); } + + @Test + public void testAcceptNullOrigin() throws Exception { + router.route().handler(CorsHandler.create().addOrigin("*")); + router.route().handler(context -> context.response().end()); + testRequest(HttpMethod.GET, "/", req -> req.headers().add("origin", "null"), resp -> checkHeaders(resp, "*", null, null, null), 200, "OK", null); + } + } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java b/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java index 1f7929557..cb72dfb48 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java @@ -44,4 +44,11 @@ public class OriginTest { assertFalse(Origin.isValid(origin)); } } + + @Test + public void testNullOrigin() { + Origin.parse("null"); + assertTrue(Origin.isValid("null")); + } + }
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java', 'vertx-web/src/test/java/io/vertx/ext/web/impl/OriginTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Origin.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,748,628
    387,026
    54,084
    428
    841
    210
    45
    1
    8,731
    404
    1,718
    85
    10
    2
    1970-01-01T00:27:00
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,234
    vert-x3/vertx-web/2397/2315
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2315
    https://github.com/vert-x3/vertx-web/pull/2397
    https://github.com/vert-x3/vertx-web/pull/2397
    1
    fixes
    TenantHandler doesn't respect the order aware sub handler
    See: https://github.com/eclipse-vertx/vert.x/issues/4536 A possible use case is to implement SSO on the same endpoint, for this the IdP info is extracted from a param, however, OAuth2Handler implements `OrderListener` and depends on this information to properly mount the callback. On a Multi tenant environment, the order should be set to the handlers to avoid them being missed on the route.
    eae0a59cd95a68f1df51ac887b8f9631d26435ca
    d8f87ecca44446944a090d74e7c7a555ee2009dc
    https://github.com/vert-x3/vertx-web/compare/eae0a59cd95a68f1df51ac887b8f9631d26435ca...d8f87ecca44446944a090d74e7c7a555ee2009dc
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java index ccf8e8f22..d8d75c14a 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java @@ -18,6 +18,7 @@ package io.vertx.ext.web.handler.impl; import io.vertx.core.Handler; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.MultiTenantHandler; +import io.vertx.ext.web.impl.OrderListener; import java.util.Map; import java.util.Objects; @@ -27,7 +28,7 @@ import java.util.function.Function; /** * @author <a href="http://[email protected]">Paulo Lopes</a> */ -public class MultiTenantHandlerImpl implements MultiTenantHandler { +public class MultiTenantHandlerImpl implements MultiTenantHandler, OrderListener { private final Map<String, Handler<RoutingContext>> handlerMap = new ConcurrentHashMap<>(); @@ -87,4 +88,13 @@ public class MultiTenantHandlerImpl implements MultiTenantHandler { ctx.next(); } } + + @Override + public void onOrder(int order) { + for (Handler<RoutingContext> handler : handlerMap.values()) { + if (handler instanceof OrderListener) { + ((OrderListener) handler).onOrder(order); + } + } + } }
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/MultiTenantHandlerImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    2,020,426
    448,267
    62,389
    504
    434
    88
    12
    1
    399
    59
    89
    5
    1
    0
    1970-01-01T00:27:59
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,256
    vert-x3/vertx-web/1925/1919
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1919
    https://github.com/vert-x3/vertx-web/pull/1925
    https://github.com/vert-x3/vertx-web/pull/1925
    1
    fix
    Server eats exception and simply responds 500
    ### Description Server log doesn't contain any info about NPE error. I think it happens for other errors too. ### Version 4.0.3 ### Code sample ``` final HttpServer server = vertx .createHttpServer( new HttpServerOptions() .setLogActivity(true) ); final Router router = Router.router(vertx); router .route() .handler(ResponseContentTypeHandler.create()); router .get("/somepath") .produces("text/xml") .handler(ctx -> { final String foo = context.get("foo").toString(); ctx.response().end(); }); server .requestHandler(router) .listen(8080) .onSuccess(s -> System.out.format( "HTTP server is listening on port %s.", s.actualPort())); ``` ### Log sample ``` HTTP server is listening on port 8080. 14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096 14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2 14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16 14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8 14:06:09.544 [vert.x-eventloop-thread-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.delayedQueue.ratio: 8 14:06:09.550 [vert.x-eventloop-thread-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true 14:06:09.550 [vert.x-eventloop-thread-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true 14:06:09.551 [vert.x-eventloop-thread-1] DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@6f856194 14:06:09.588 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] READ: 86B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 47 45 54 20 2f 73 6f 6d 65 70 61 74 68 20 48 54 |GET /somepath HT| |00000010| 54 50 2f 31 2e 31 0d 0a 48 6f 73 74 3a 20 6c 6f |TP/1.1..Host: lo| |00000020| 63 61 6c 68 6f 73 74 3a 38 30 38 30 0d 0a 55 73 |calhost:8080..Us| |00000030| 65 72 2d 41 67 65 6e 74 3a 20 63 75 72 6c 2f 37 |er-Agent: curl/7| |00000040| 2e 36 34 2e 31 0d 0a 41 63 63 65 70 74 3a 20 2a |.64.1..Accept: *| |00000050| 2f 2a 0d 0a 0d 0a |/*.... | +--------+-------------------------------------------------+----------------+ 14:06:09.614 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.codec.compression.ZlibCodecFactory - -Dio.netty.noJdkZlibDecoder: false 14:06:09.614 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.codec.compression.ZlibCodecFactory - -Dio.netty.noJdkZlibEncoder: false 14:06:09.634 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] WRITE: 103B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 48 54 54 50 2f 31 2e 31 20 35 30 30 20 49 6e 74 |HTTP/1.1 500 Int| |00000010| 65 72 6e 61 6c 20 53 65 72 76 65 72 20 45 72 72 |ernal Server Err| |00000020| 6f 72 0d 0a 63 6f 6e 74 65 6e 74 2d 6c 65 6e 67 |or..content-leng| |00000030| 74 68 3a 20 32 31 0d 0a 63 6f 6e 74 65 6e 74 2d |th: 21..content-| |00000040| 74 79 70 65 3a 20 74 65 78 74 2f 78 6d 6c 0d 0a |type: text/xml..| |00000050| 0d 0a 49 6e 74 65 72 6e 61 6c 20 53 65 72 76 65 |..Internal Serve| |00000060| 72 20 45 72 72 6f 72 |r Error | +--------+-------------------------------------------------+----------------+ 14:06:09.635 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] READ COMPLETE 14:06:09.635 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] FLUSH 14:06:09.637 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 - R:/[0:0:0:0:0:0:0:1]:50225] READ COMPLETE 14:06:09.640 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 ! R:/[0:0:0:0:0:0:0:1]:50225] INACTIVE 14:06:09.640 [vert.x-eventloop-thread-1] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xc962bfb4, L:/[0:0:0:0:0:0:0:1]:8080 ! R:/[0:0:0:0:0:0:0:1]:50225] UNREGISTERED 14:06:15.228 [vert.x-eventloop-thread-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 2 thread-local buffer(s) from thread: vert.x-eventloop-thread-1 ```
    123b750b7995a20302bbeff92527344454f4894e
    1e0a374065cbdb3af9c43e953bf8833f3c226c8f
    https://github.com/vert-x3/vertx-web/compare/123b750b7995a20302bbeff92527344454f4894e...1e0a374065cbdb3af9c43e953bf8833f3c226c8f
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java index c7e87fce0..4432edcb6 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java @@ -180,9 +180,6 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal { } private void handleInHandlerRuntimeFailure(RouterImpl router, boolean failed, Throwable t) { - if (LOG.isTraceEnabled()) { - LOG.trace("Throwable thrown from handler", t); - } if (!failed) { if (LOG.isTraceEnabled()) { LOG.trace("Failing the routing"); @@ -199,6 +196,8 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal { protected void unhandledFailure(int statusCode, Throwable failure, RouterImpl router) { + LOG.error("Unhandled exception in router", failure); + int code = statusCode != -1 ? statusCode : (failure instanceof HttpException) ? diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java index 79da1fc79..9fdb3e145 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java @@ -115,7 +115,7 @@ public class BodyHandlerTest extends WebTestBase { req.setChunked(true); req.putHeader("content-type", "text/plain;charset=ISO-8859-1"); byte b = str.getBytes(StandardCharsets.ISO_8859_1)[0]; - req.write(Buffer.buffer(new byte[] { b })); + req.write(Buffer.buffer(new byte[]{b})); }, 200, "OK", null); } @@ -315,20 +315,20 @@ public class BodyHandlerTest extends WebTestBase { @Test public void testFileDeleteOnLargeUpload() throws Exception { - String uploadsDirectory = tempUploads.newFolder().getPath(); - router.clear(); - router.route().handler(BodyHandler.create() - .setDeleteUploadedFilesOnEnd(true) - .setBodyLimit(10000) - .setUploadsDirectory(uploadsDirectory)); - router.route().handler(ctx -> { - fail(); - ctx.fail(500); - }); + String uploadsDirectory = tempUploads.newFolder().getPath(); + router.clear(); + router.route().handler(BodyHandler.create() + .setDeleteUploadedFilesOnEnd(true) + .setBodyLimit(10000) + .setUploadsDirectory(uploadsDirectory)); + router.route().handler(ctx -> { + fail(); + ctx.fail(500); + }); - sendFileUploadRequest(TestUtils.randomBuffer(20000), 413, "Request Entity Too Large"); + sendFileUploadRequest(TestUtils.randomBuffer(20000), 413, "Request Entity Too Large"); - assertWaitUntil(() -> vertx.fileSystem().readDirBlocking(uploadsDirectory).isEmpty()); + assertWaitUntil(() -> vertx.fileSystem().readDirBlocking(uploadsDirectory).isEmpty()); } @Test @@ -392,8 +392,8 @@ public class BodyHandlerTest extends WebTestBase { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() - .setDeleteUploadedFilesOnEnd(deletedUploadedFilesOnEnd) - .setUploadsDirectory(uploadsDirectory)); + .setDeleteUploadedFilesOnEnd(deletedUploadedFilesOnEnd) + .setUploadsDirectory(uploadsDirectory)); router.route().handler(requestHandler); sendFileUploadRequest(TestUtils.randomBuffer(50), statusCode, statusMessage); @@ -500,13 +500,13 @@ public class BodyHandlerTest extends WebTestBase { for (int i = 0; i < uploads; i++) { String header = - "--" + boundary + "\\r\\n" + - "Content-Disposition: form-data; name=\\"file" + i + "\\"; filename=\\"file" + i + "\\"\\r\\n" + - "Content-Type: application/octet-stream\\r\\n" + - "Content-Transfer-Encoding: binary\\r\\n" + - "\\r\\n"; + "--" + boundary + "\\r\\n" + + "Content-Disposition: form-data; name=\\"file" + i + "\\"; filename=\\"file" + i + "\\"\\r\\n" + + "Content-Type: application/octet-stream\\r\\n" + + "Content-Transfer-Encoding: binary\\r\\n" + + "\\r\\n"; buffer.appendString(header); - buffer.appendBuffer(TestUtils.randomBuffer(4096*16)); + buffer.appendBuffer(TestUtils.randomBuffer(4096 * 16)); buffer.appendString("\\r\\n"); } buffer.appendString("--" + boundary + "\\r\\n"); @@ -543,10 +543,10 @@ public class BodyHandlerTest extends WebTestBase { Buffer buffer = Buffer.buffer(); String str = "--" + boundary + "\\r\\n" + - "Content-Disposition: form-data; name=\\"attr1\\"\\r\\n\\r\\nTim\\r\\n" + - "--" + boundary + "\\r\\n" + - "Content-Disposition: form-data; name=\\"attr2\\"\\r\\n\\r\\nJulien\\r\\n" + - "--" + boundary + "--\\r\\n"; + "Content-Disposition: form-data; name=\\"attr1\\"\\r\\n\\r\\nTim\\r\\n" + + "--" + boundary + "\\r\\n" + + "Content-Disposition: form-data; name=\\"attr2\\"\\r\\n\\r\\nJulien\\r\\n" + + "--" + boundary + "--\\r\\n"; buffer.appendString(str); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); @@ -561,7 +561,7 @@ public class BodyHandlerTest extends WebTestBase { router.clear(); router.route().handler(BodyHandler.create() - .setUploadsDirectory(uploadsDirectory)); + .setUploadsDirectory(uploadsDirectory)); router.route().handler(ctx -> { assertNull(ctx.getBody()); assertEquals(1, ctx.fileUploads().size()); @@ -575,11 +575,11 @@ public class BodyHandlerTest extends WebTestBase { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = - "--" + boundary + "\\r\\n" + - "Content-Disposition: form-data; name=\\"" + name + "\\"; filename=\\"" + fileName + "\\"\\r\\n" + - "Content-Type: " + contentType + "\\r\\n" + - "Content-Transfer-Encoding: binary\\r\\n" + - "\\r\\n"; + "--" + boundary + "\\r\\n" + + "Content-Disposition: form-data; name=\\"" + name + "\\"; filename=\\"" + fileName + "\\"\\r\\n" + + "Content-Type: " + contentType + "\\r\\n" + + "Content-Transfer-Encoding: binary\\r\\n" + + "\\r\\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); String footer = "\\r\\n--" + boundary + "--\\r\\n"; @@ -591,8 +591,7 @@ public class BodyHandlerTest extends WebTestBase { } @Test - public void testNoUploadDirMultiPartFormData() throws Exception - { + public void testNoUploadDirMultiPartFormData() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName)); @@ -612,7 +611,7 @@ public class BodyHandlerTest extends WebTestBase { @Test public void testFormMultipartFormDataWithAllowedFilesUploadFalse2() throws Exception { - testFormMultipartFormDataWithAllowedFilesUploadFalse(false); + testFormMultipartFormDataWithAllowedFilesUploadFalse(false); } private void testFormMultipartFormDataWithAllowedFilesUploadFalse(boolean mergeAttributes) throws Exception { @@ -645,7 +644,7 @@ public class BodyHandlerTest extends WebTestBase { Buffer buffer = Buffer.buffer(); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; String header = - "--" + boundary + "\\r\\n" + + "--" + boundary + "\\r\\n" + "Content-Disposition: form-data; name=\\"attr1\\"\\r\\n\\r\\nTim\\r\\n" + "--" + boundary + "\\r\\n" + "Content-Disposition: form-data; name=\\"attr2\\"\\r\\n\\r\\nTommaso\\r\\n" + @@ -654,8 +653,8 @@ public class BodyHandlerTest extends WebTestBase { "Content-Type: application/octet-stream\\r\\n" + "Content-Transfer-Encoding: binary\\r\\n" + "\\r\\n"; - buffer.appendString(header); - buffer.appendBuffer(TestUtils.randomBuffer(50)); + buffer.appendString(header); + buffer.appendBuffer(TestUtils.randomBuffer(50)); buffer.appendString("\\r\\n--" + boundary + "--\\r\\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); @@ -664,8 +663,7 @@ public class BodyHandlerTest extends WebTestBase { } @Test - public void testNoUploadDirFormURLEncoded() throws Exception - { + public void testNoUploadDirFormURLEncoded() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName)); @@ -676,16 +674,14 @@ public class BodyHandlerTest extends WebTestBase { } @Test - public void testBodyHandlerCreateTrueWorks() throws Exception - { + public void testBodyHandlerCreateTrueWorks() throws Exception { router.clear(); router.route().handler(BodyHandler.create(true)); testFormURLEncoded(); } @Test - public void testSetHandleFileUploads() throws Exception - { + public void testSetHandleFileUploads() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); @@ -709,8 +705,7 @@ public class BodyHandlerTest extends WebTestBase { } @Test - public void testRerouteWithHandleFileUploadsFalse() throws Exception - { + public void testRerouteWithHandleFileUploadsFalse() throws Exception { String fileName = "test.bin"; router.clear(); router.route().handler(BodyHandler.create(false).setMergeFormAttributes(true)); @@ -735,7 +730,7 @@ public class BodyHandlerTest extends WebTestBase { Buffer buffer = Buffer.buffer(); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; String header = - "--" + boundary + "\\r\\n" + + "--" + boundary + "\\r\\n" + "Content-Disposition: form-data; name=\\"attr1\\"\\r\\n\\r\\nTim\\r\\n" + "--" + boundary + "\\r\\n" + "Content-Disposition: form-data; name=\\"attr2\\"\\r\\n\\r\\nTommaso\\r\\n" + @@ -744,8 +739,8 @@ public class BodyHandlerTest extends WebTestBase { "Content-Type: application/octet-stream\\r\\n" + "Content-Transfer-Encoding: binary\\r\\n" + "\\r\\n"; - buffer.appendString(header); - buffer.appendBuffer(TestUtils.randomBuffer(50)); + buffer.appendString(header); + buffer.appendBuffer(TestUtils.randomBuffer(50)); buffer.appendString("\\r\\n--" + boundary + "--\\r\\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); @@ -754,8 +749,7 @@ public class BodyHandlerTest extends WebTestBase { } @Test - public void testBodyLimitWithHandleFileUploadsFalse() throws Exception - { + public void testBodyLimitWithHandleFileUploadsFalse() throws Exception { router.clear(); BodyHandler bodyHandler = BodyHandler.create(false).setBodyLimit(2048); @@ -768,8 +762,7 @@ public class BodyHandlerTest extends WebTestBase { sendFileUploadRequest(fileData, 413, "Request Entity Too Large"); } - private String getNotCreatedTemporaryFolderName() throws IOException - { + private String getNotCreatedTemporaryFolderName() throws IOException { File dir = tempUploads.newFolder(); dir.delete(); return dir.getPath(); @@ -882,24 +875,22 @@ public class BodyHandlerTest extends WebTestBase { router.clear(); router.route().handler(BodyHandler.create()); router.route().handler(rc -> { - MultiMap attrs = rc.request().formAttributes(); - assertNotNull(attrs); - int size = 0; - assertNotNull(attrs.get("attr1")); - size += attrs.get("attr1").length(); - assertNotNull(attrs.get("attr2")); - size += attrs.get("attr2").length(); - assertTrue(size > 2048); - rc.response().end(); + fail("Should not get here"); + }).failureHandler(ctx -> { + assertNotNull(ctx.failure()); + assertTrue(ctx.failure() instanceof IOException); + assertEquals("Size exceed allowed maximum capacity", ctx.failure().getMessage()); + ctx.next(); }); + testRequest(HttpMethod.POST, "/?p1=foo", req -> { Buffer buffer = Buffer.buffer(); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; String header = "--" + boundary + "\\r\\n" + - "Content-Disposition: form-data; name=\\"attr1\\"\\r\\n\\r\\n" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(1024).getBytes()) + "\\r\\n" + + "Content-Disposition: form-data; name=\\"attr1\\"\\r\\n\\r\\n" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(2048).getBytes()) + "\\r\\n" + "--" + boundary + "\\r\\n" + - "Content-Disposition: form-data; name=\\"attr2\\"\\r\\n\\r\\n" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(1024).getBytes()) + "\\r\\n" + + "Content-Disposition: form-data; name=\\"attr2\\"\\r\\n\\r\\n" + Base64.getUrlEncoder().encodeToString(TestUtils.randomBuffer(2048).getBytes()) + "\\r\\n" + "--" + boundary + "\\r\\n" + "Content-Disposition: form-data; name=\\"" + name + "\\"; filename=\\"file\\"\\r\\n" + "Content-Type: application/octet-stream\\r\\n" + @@ -911,7 +902,19 @@ public class BodyHandlerTest extends WebTestBase { req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); - }, 200, "OK", null); + }, 400, "Bad Request", null); + } + + @Test + public void testLogExceptions() throws Exception { + router.clear(); + router.route().handler(BodyHandler.create()); + + router.route().handler(ctx -> { + throw new NullPointerException(); + }); + testRequest(HttpMethod.GET, "/", req -> { + }, 500, "Internal Server Error", null); } }
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,746,216
    386,399
    53,997
    427
    153
    33
    5
    1
    5,157
    521
    1,950
    83
    0
    2
    1970-01-01T00:26:58
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,260
    vert-x3/vertx-web/1779/1778
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1778
    https://github.com/vert-x3/vertx-web/pull/1779
    https://github.com/vert-x3/vertx-web/pull/1779
    1
    fixes
    HTTP server file upload cleanup fail to delete
    The HTTP server file upload cleanup mechanism implemented in `BodyHandler` can fail to delete uploaded files because it does not ensure that the file upload is finished before deleting the file. Fixing this in vertx-web would bring lot of complexity and instead this has been implemented in vertx-core HTTP server file upload that will delete any stream not successfully completed.
    7d91fc4471655c3d57bb0ef7210079cf8b483145
    68dd64008a5312e67950bc7429a32a35b92f90ab
    https://github.com/vert-x3/vertx-web/compare/7d91fc4471655c3d57bb0ef7210079cf8b483145...68dd64008a5312e67950bc7429a32a35b92f90ab
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java b/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java index bc812f747..a95a2cb30 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java @@ -62,5 +62,11 @@ public interface FileUpload { */ String charSet(); + /** + * Try to cancel the file upload. + * + * @return {@code true} when the upload was cancelled, {@code false} when the upload is finished and the file is available + */ + boolean cancel(); } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java index 02b56382e..23457b62e 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java @@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.http.HttpHeaderValues; +import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.file.FileSystem; @@ -190,7 +191,7 @@ public class BodyHandlerImpl implements BodyHandler { long size = uploadSize + upload.size(); if (size > bodyLimit) { failed = true; - deleteFileUploads(); + cancelAndCleanupFileUploads(); context.fail(413); return; } @@ -199,20 +200,23 @@ public class BodyHandlerImpl implements BodyHandler { // we actually upload to a file with a generated filename uploadCount.incrementAndGet(); String uploadedFileName = new File(uploadsDir, UUID.randomUUID().toString()).getPath(); - upload.streamToFileSystem(uploadedFileName); FileUploadImpl fileUpload = new FileUploadImpl(uploadedFileName, upload); fileUploads.add(fileUpload); - upload.exceptionHandler(t -> { - deleteFileUploads(); - context.fail(t); + Future<Void> fut = upload.streamToFileSystem(uploadedFileName); + fut.onComplete(ar -> { + if (fut.succeeded()) { + uploadEnded(); + } else { + cancelAndCleanupFileUploads(); + context.fail(ar.cause()); + } }); - upload.endHandler(v -> uploadEnded()); } }); } context.request().exceptionHandler(t -> { - deleteFileUploads(); + cancelAndCleanupFileUploads(); if (t instanceof DecoderException) { // bad request context.fail(400, t.getCause()); @@ -253,7 +257,7 @@ public class BodyHandlerImpl implements BodyHandler { uploadSize += buff.length(); if (bodyLimit != -1 && uploadSize > bodyLimit) { failed = true; - deleteFileUploads(); + cancelAndCleanupFileUploads(); context.fail(413); } else { // multipart requests will not end up in the request body @@ -290,12 +294,12 @@ public class BodyHandlerImpl implements BodyHandler { void doEnd() { if (failed) { - deleteFileUploads(); + cancelAndCleanupFileUploads(); return; } if (deleteUploadedFilesOnEnd) { - context.addBodyEndHandler(x -> deleteFileUploads()); + context.addBodyEndHandler(x -> cancelAndCleanupFileUploads()); } HttpServerRequest req = context.request(); @@ -309,22 +313,21 @@ public class BodyHandlerImpl implements BodyHandler { context.next(); } - private void deleteFileUploads() { + /** + * Cancel all unfinished file upload in progress and delete all uploaded files. + */ + private void cancelAndCleanupFileUploads() { if (cleanup.compareAndSet(false, true) && handleFileUploads) { for (FileUpload fileUpload : context.fileUploads()) { FileSystem fileSystem = context.vertx().fileSystem(); - String uploadedFileName = fileUpload.uploadedFileName(); - fileSystem.exists(uploadedFileName, existResult -> { - if (existResult.failed()) { - log.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName, existResult.cause()); - } else if (existResult.result()) { - fileSystem.delete(uploadedFileName, deleteResult -> { - if (deleteResult.failed()) { - log.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause()); - } - }); - } - }); + if (!fileUpload.cancel()) { + String uploadedFileName = fileUpload.uploadedFileName(); + fileSystem.delete(uploadedFileName, deleteResult -> { + if (deleteResult.failed()) { + log.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause()); + } + }); + } } } } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java index 98d62b7c6..70c8fef42 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java @@ -67,4 +67,8 @@ public class FileUploadImpl implements FileUpload { return upload.charset(); } + @Override + public boolean cancel() { + return upload.cancelStreamToFileSystem(); + } }
    ['vertx-web/src/main/java/io/vertx/ext/web/FileUpload.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/FileUploadImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,698,077
    375,725
    52,586
    412
    2,487
    469
    59
    3
    383
    60
    70
    2
    0
    0
    1970-01-01T00:26:45
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,259
    vert-x3/vertx-web/1815/1814
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1814
    https://github.com/vert-x3/vertx-web/pull/1815
    https://github.com/vert-x3/vertx-web/pull/1815
    1
    fixes
    NPE when userAgentEnabled is set to false
    ### Version 4.0.0 (and in previous betas) ### Context I have a SecretsClient that is based on VaultConfigStore and like that code uses SlimVaultClient to access secrets in Vault. It only uses loginWithAppRole for creating/renewing the client token. The configuration passed thru to the SlimVaultClient includes the setting `userAgentEnabled = false`. When attempting to access the vault store, it will first attempt to get a token and it's at this point that the request fails with ``` java.lang.NullPointerException at io.vertx.ext.web.client.impl.HttpContext.handleSendRequest(HttpContext.java:469) at io.vertx.ext.web.client.impl.HttpContext.execute(HttpContext.java:332) at io.vertx.ext.web.client.impl.HttpContext.next(HttpContext.java:322) at io.vertx.ext.web.client.impl.HttpContext.fire(HttpContext.java:289) at io.vertx.ext.web.client.impl.HttpContext.sendRequest(HttpContext.java:193) at io.vertx.ext.web.client.impl.HttpContext.handlePrepareRequest(HttpContext.java:404) at io.vertx.ext.web.client.impl.HttpContext.execute(HttpContext.java:329) at io.vertx.ext.web.client.impl.HttpContext.next(HttpContext.java:322) at io.vertx.ext.web.client.impl.HttpContext.fire(HttpContext.java:289) at io.vertx.ext.web.client.impl.HttpContext.prepareRequest(HttpContext.java:180) at io.vertx.ext.web.client.impl.HttpRequestImpl.send(HttpRequestImpl.java:310) at io.vertx.ext.web.client.impl.HttpRequestImpl.sendJsonObject(HttpRequestImpl.java:290) at io.vertx.config.vault.client.SlimVaultClient.loginWithAppRole(SlimVaultClient.java:234) ``` If the setting is changed to `userAgentEnabled = true` then the request proceeds OK. Whilst the bug was found in the vertx-config project, I think the error is in the processing of requests via the underlying WebClient _within_ the SlimVaultClient. ```java // HttpContext line 459 private void handleSendRequest() { if (request.headers != null) { MultiMap headers = requestOptions.getHeaders(); if (headers == null) { headers = MultiMap.caseInsensitiveMultiMap(); requestOptions.setHeaders(headers); } headers.addAll(request.headers); } if (contentType != null) { // !! at this point the options headers is always null when userAgentEnabled = true !! String prev = requestOptions.getHeaders().get(HttpHeaders.CONTENT_TYPE); if (prev == null) { requestOptions.addHeader(HttpHeaders.CONTENT_TYPE, contentType); } else { contentType = prev; } } ``` ### Do you have a reproducer? ```java @test fun testSlimVaultClient() { runBlocking { val client = SlimVaultClient(vertx, JsonObject() .put("host", "localhost") .put("port", 8500) .put("ssl", false) .put("userAgentEnabled", false)) val promise = (vertx as VertxInternal).promise<Void>() println("Login") client.loginWithAppRole("some.role", "some.secret") { println("Handling") if (it.failed()) { promise.fail(it.cause()) } else { it.succeeded() } } println("Waiting") promise.await() } } ``` ### Steps to reproduce 1. attempt to run the test above 2. when `userAgentEnabled = true`, only _Login_ is printed 3. when `userAgentEnabled = false`, _Login_ _Waiting_ and _Handling_ are printed ### Extra * same code used to work in 4.0.0-milestone5
    b00221acf6a4809e87241e984a357bc5b20467b9
    dfee825ee22a2610978565ce5f8be5fa6897dff3
    https://github.com/vert-x3/vertx-web/compare/b00221acf6a4809e87241e984a357bc5b20467b9...dfee825ee22a2610978565ce5f8be5fa6897dff3
    diff --git a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java index b83629198..a2c760d77 100644 --- a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java +++ b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java @@ -79,6 +79,8 @@ public class HttpRequestImpl<T> implements HttpRequest<T> { this.options = options; if (options.isUserAgentEnabled()) { headers = HttpHeaders.set(HttpHeaders.USER_AGENT, options.getUserAgent()); + } else { + headers = HttpHeaders.headers(); } } @@ -92,7 +94,7 @@ public class HttpRequestImpl<T> implements HttpRequest<T> { this.host = other.host; this.timeout = other.timeout; this.uri = other.uri; - this.headers = other.headers != null ? HttpHeaders.headers().addAll(other.headers) : null; + this.headers = other.headers != null ? HttpHeaders.headers().addAll(other.headers) : HttpHeaders.headers(); this.params = other.params != null ? HttpHeaders.headers().addAll(other.params) : null; this.codec = other.codec; this.followRedirects = other.followRedirects; diff --git a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java index 3b0f6dabb..8f7912e44 100644 --- a/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java +++ b/vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java @@ -33,7 +33,6 @@ import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.net.ConnectException; -import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.*; @@ -135,6 +134,32 @@ public class WebClientTest extends WebClientTestBase { testRequest(client -> client.get("somehost", "somepath"), req -> assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT))); } + @Test + public void testSendingJsonWithUserAgentDisabled() throws Exception { + waitFor(2); + server.requestHandler(req -> { + assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT)); + try { + complete(); + } finally { + req.response().end(); + } + }); + startServer(); + + JsonObject payload = new JsonObject().put("meaning", 42); + + WebClientOptions clientOptions = new WebClientOptions() + .setDefaultHost(DEFAULT_HTTP_HOST) + .setDefaultPort(DEFAULT_HTTP_PORT) + .setUserAgentEnabled(false); + + WebClient agentFreeClient = WebClient.create(vertx, clientOptions); + HttpRequest<Buffer> builder = agentFreeClient.post("somehost", "somepath"); + builder.sendJson(payload, onSuccess(resp -> complete())); + await(); + } + @Test public void testUserAgentHeaderOverride() throws Exception { testRequest(client -> client.get("somehost", "somepath").putHeader(HttpHeaders.USER_AGENT.toString(), "smith"), req -> assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT)));
    ['vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java', 'vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,706,875
    377,581
    52,829
    416
    262
    49
    4
    1
    3,569
    309
    753
    92
    0
    3
    1970-01-01T00:26:47
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,258
    vert-x3/vertx-web/1834/1825
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1825
    https://github.com/vert-x3/vertx-web/pull/1834
    https://github.com/vert-x3/vertx-web/pull/1834
    1
    fix
    RoutingContext.isFresh() returns false for IF-NONE-MATCH single value Header
    Hi, while trying to use e-tag header for HTTP caching - I noticed the following behavior. ### Version 4.0.0 ### Context Given a simple HTTP server sample using `ctx.isFresh()` method: ```java package io.vertx.reproducer; import io.vertx.core.AbstractVerticle; import io.vertx.core.Promise; import io.vertx.ext.web.Router; public class HttpServerVerticle extends AbstractVerticle { @Override public void start(Promise<Void> startPromise) throws Exception { final Router router = Router.router(vertx); router.route("/check/e-tag").handler(ctx -> { ctx.etag("1234"); if (ctx.isFresh()) { ctx.response().setStatusCode(304).end("Not Modified"); } else { ctx.response().setStatusCode(200).end("OK"); } }); vertx.createHttpServer() .requestHandler(router) .listen(8080) .onFailure(startPromise::fail) .onSuccess(server -> startPromise.complete()); } } ``` When sending IF-NONE-MATCH header with value that is matching the ETag: ```shell > curl -v 'http://localhost:8080/check/e-tag' -H 'IF-NONE-MATCH: "1234"' * Trying ::1:8080... * Connected to localhost (::1) port 8080 (#0) > GET /check/e-tag HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.74.0 > Accept: */* > IF-NONE-MATCH: "1234" > * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < etag: "1234" < content-length: 2 < * Connection #0 to host localhost left intact OK% ``` I expect `ctx.isFresh()` to return `true` and my server to respond with Not Modified. Inspecting the [code](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java#L171) it seems to me, that the only way an e-tag is not marked as stale is to have a `,` character in it. That might work when you send multiple values, but am I supposed to send a trailing comma for single value? ```shell > curl -v 'http://localhost:8080/check/e-tag' -H 'IF-NONE-MATCH: "1234",' * Trying ::1:8080... * Connected to localhost (::1) port 8080 (#0) > GET /check/e-tag HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.74.0 > Accept: */* > IF-NONE-MATCH: "1234", > * Mark bundle as not supporting multiuse < HTTP/1.1 304 Not Modified < etag: "1234" < * Connection #0 to host localhost left intact ``` This one returns the expected result. Referring to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag it seems valid to not send trailing comma. Am I missing something? ### Do you have a reproducer? https://github.com/FrederikS/vertx-etag-none-match-reproducer
    2c0d3e6b84bc4c30dc3a384e6e9309d3b95f324b
    105040967214ab96d66ce29af48af4bf2ec2b4e2
    https://github.com/vert-x3/vertx-web/compare/2c0d3e6b84bc4c30dc3a384e6e9309d3b95f324b...105040967214ab96d66ce29af48af4bf2ec2b4e2
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java index 2425fe96b..572f02319 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java @@ -161,7 +161,8 @@ public class Utils extends io.vertx.core.impl.Utils { int end = 0; int start = 0; - loop: for (int i = 0; i < noneMatch.length(); i++) { + loop: + for (int i = 0; i < noneMatch.length(); i++) { switch (noneMatch.charAt(i)) { case ' ': if (start == end) { @@ -183,7 +184,11 @@ public class Utils extends io.vertx.core.impl.Utils { } if (etagStale) { - return false; + // the parser run out of bytes, need to check if the match is valid + String match = noneMatch.substring(start, end); + if (!match.equals(etag) && !match.equals("W/" + etag) && !("W/" + match).equals(etag)) { + return false; + } } } @@ -196,7 +201,7 @@ public class Utils extends io.vertx.core.impl.Utils { boolean modifiedStale = lastModified == -1 || !(lastModified <= parseRFC1123DateTime(modifiedSince)); - return !modifiedStale; + return !modifiedStale; } return true; diff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java index 590602dae..1f3db5547 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java @@ -2904,4 +2904,25 @@ public class RouterTest extends WebTestBase { testRequest(HttpMethod.GET, "/?u=" + utf8 + "&l=" + latin1, 200, "OK"); } + + @Test + public void testETag() throws Exception { + router.route("/check/e-tag").handler(ctx -> { + ctx.etag("1234"); + + if (ctx.isFresh()) { + ctx.response().setStatusCode(304).end("Not Modified"); + } else { + ctx.response().setStatusCode(200).end("OK"); + } + }); + + testRequest(HttpMethod.GET, "/check/e-tag", req -> { + req.putHeader("IF-NONE-MATCH", "\\"1234\\","); + }, 304, "Not Modified", ""); + + testRequest(HttpMethod.GET, "/check/e-tag", req -> { + req.putHeader("IF-NONE-MATCH", "\\"1234\\""); + }, 304, "Not Modified", ""); + } }
    ['vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,707,426
    377,707
    52,854
    416
    479
    126
    11
    1
    2,743
    307
    724
    95
    5
    3
    1970-01-01T00:26:49
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,236
    vert-x3/vertx-web/2300/2293
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2293
    https://github.com/vert-x3/vertx-web/pull/2300
    https://github.com/vert-x3/vertx-web/pull/2300
    1
    fixes
    "405 Method Not Allowed" response not adding allow header
    As per this document, https://vertx.io/docs/vertx-web/java/#_route_match_failures Vert.x-Web will signal a 405 error If a route matches the path but doesn’t match the HTTP Method, but as per Mozilla document https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 response should contain `allow` header. Is there any reason why it's not added in response? It only adds `content-length` header Version - 4.3.4
    1231eab65a061c9e6f9497049b86d3a3a21394e1
    8bcd7b50bd1a8bde897341df205121b4414e9287
    https://github.com/vert-x3/vertx-web/compare/1231eab65a061c9e6f9497049b86d3a3a21394e1...8bcd7b50bd1a8bde897341df205121b4414e9287
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java index c6959902b..07da73ab5 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java @@ -35,6 +35,7 @@ import io.vertx.ext.web.handler.impl.UserHolder; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.stream.Collectors; import static io.vertx.ext.web.handler.impl.SessionHandlerImpl.SESSION_USER_HOLDER_KEY; @@ -158,6 +159,10 @@ public class RoutingContextImpl extends RoutingContextImplBase { this.response() .putHeader(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8") .end(DEFAULT_404); + } else if (this.request().method() != HttpMethod.HEAD && matchFailure == 405) { + // If it's a 405 let's send a body too + this.response() + .putHeader(HttpHeaderNames.ALLOW, allowedMethods.stream().map(HttpMethod::name).collect(Collectors.joining(","))).end(); } else { this.response().end(); } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java index 58ff9d1f5..1e9860d95 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java @@ -18,6 +18,7 @@ package io.vertx.ext.web.impl; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.Handler; +import io.vertx.core.http.HttpMethod; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; import io.vertx.ext.web.Route; @@ -25,6 +26,7 @@ import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.HttpException; +import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; @@ -58,6 +60,8 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal { // internal runtime state private volatile long seen; + protected Set<HttpMethod> allowedMethods = new HashSet<>(); + RoutingContextImplBase(String mountPoint, Set<RouteImpl> routes, Router currentRouter) { this.mountPoint = mountPoint; this.routes = routes; @@ -179,6 +183,8 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal { } return true; } else if (matchResult == 405) { + //We need to add supported methods for route in case we need to send 405 at end + allowedMethods.addAll(routeState.getMethods()); // invalid method match, means that // we should "update" the failure if not found to be invalid method if (this.matchFailure == 404) { diff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java index d8eaa9b8d..fe0168e7d 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java @@ -2761,6 +2761,18 @@ public class RouterTest extends WebTestBase { testRequest(HttpMethod.PUT, "/path", HttpResponseStatus.METHOD_NOT_ALLOWED); } + @Test + public void testMethodNotAllowedHeader() throws Exception { + router.get("/path").handler(rc -> rc.response().end()); + router.post("/path").handler(rc -> rc.response().end()); + router.put("/hello").handler(rc -> rc.response().end()); + testRequest(HttpMethod.PUT, "/path", null, res -> { + assertEquals(2, res.getHeader("allow").split(",").length); + assertTrue(res.getHeader("allow").contains("GET")); + assertTrue(res.getHeader("allow").contains("POST")); + }, HttpResponseStatus.METHOD_NOT_ALLOWED.code(), HttpResponseStatus.METHOD_NOT_ALLOWED.reasonPhrase(), null); + } + @Test public void testNotAcceptableStatusCode() throws Exception { router.route().produces("text/html").handler(rc -> rc.response().end());
    ['vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,970,042
    437,391
    61,089
    482
    616
    132
    11
    2
    419
    52
    104
    5
    2
    0
    1970-01-01T00:27:47
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,230
    vert-x3/vertx-web/2347/2319
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2319
    https://github.com/vert-x3/vertx-web/pull/2347
    https://github.com/vert-x3/vertx-web/issues/2319#issuecomment-1406925163
    2
    resolve
    CORS headers not set on response for .* origin
    ### Version VertX 4.3.6 ### Context On a HTTP-Request without `Origin` i would expect the CORS-Handler to set `Vary:Origin` and this was the case with 3.4.5. I'm not 100% sure about the CORS spec itself but considering that the Requests could be cached and looking at -> https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches it seems to me that the previous behavior was the correct one. ### Do you have a reproducer? no ### Steps to reproduce 1. ` Router.router(vertx).route().handler(CorsHandler.create().addRelativeOrigin(".*").allowedMethod(GET))` 2. `router.get("/path").handler(rc -> rc.end("hello"));` 3. Call with a HttpClient asserting `ctx.assertNotNull(response.getHeaders().get(HttpHeaders.VARY))` ### Extra * OpenJDK 19
    79faa1baaa4e5292f945a56c30bfad60c3af6fb6
    26919f07ea3510cde0c08b51255531a22e4c939b
    https://github.com/vert-x3/vertx-web/compare/79faa1baaa4e5292f945a56c30bfad60c3af6fb6...26919f07ea3510cde0c08b51255531a22e4c939b
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java index 4df0ebfd5..1b938687d 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java @@ -234,7 +234,8 @@ public class CorsHandlerImpl implements CorsHandler { } else { // when it is possible to determine if only one origin is allowed, we can skip this extra caching header - if (!starOrigin() && !uniqueOrigin()) { + // If allow credentials is set, the response cannot be '*' thus we need to vary on origin + if (!(starOrigin() && !allowCredentials) && !uniqueOrigin()) { Utils.appendToMapIfAbsent(response.headers(), VARY, ",", ORIGIN); } addCredentialsAndOriginHeader(response, origin); diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java index 3dfe5dfc6..21c968b01 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java @@ -694,6 +694,30 @@ public class CORSHandlerTest extends WebTestBase { public void testCORSSetupStarOriginShouldNotHaveVary() throws Exception { // when we allow any origin, the response is not dependent on it, so we tell caches not to consider origin in // the cache key + router + .route() + .handler(CorsHandler.create() + .allowCredentials(false) + .allowedHeader("Content-Type") + .allowedMethod(HttpMethod.GET) + .allowedMethod(HttpMethod.POST) + .allowedMethod(HttpMethod.OPTIONS) + .allowedHeader("Access-Control-Allow-Origin")) + .handler(BodyHandler.create().setBodyLimit(1)) + .handler(context -> context.response().end()); + + testRequest(HttpMethod.POST, "/", req -> { + req.headers().add("origin", "https://mydomain.org:3000"); + }, resp -> { + assertNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertNotNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertNull(resp.getHeader(HttpHeaders.VARY)); + }, 200, "OK", null); + } + + @Test + public void testCORSSetupStarOriginWithAllowCredentialsShouldHaveVary() throws Exception { + // When allow credentials is set with any origin, the response is dependent on the origin router .route() .handler(CorsHandler.create() @@ -711,7 +735,7 @@ public class CORSHandlerTest extends WebTestBase { }, resp -> { assertNotNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); assertNotNull(resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull(resp.getHeader(HttpHeaders.VARY)); + assertEquals("origin", resp.getHeader(HttpHeaders.VARY)); }, 200, "OK", null); } }
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/CORSHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,985,499
    440,889
    61,525
    488
    219
    50
    3
    1
    772
    90
    198
    23
    1
    0
    1970-01-01T00:27:54
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,267
    vert-x3/vertx-web/1639/1619
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1619
    https://github.com/vert-x3/vertx-web/pull/1639
    https://github.com/vert-x3/vertx-web/pull/1639
    1
    fixes
    ApolloWS handler does not support messages sent in multiple frames
    GraphQL Subscriptions websocket uses a handler instead of textMessageHandler resulting in lost messages since handler will be called for all binary / text / continuation frames. In our case we should add a textMessageHandler since we want to concatenate messages when a continuation frame is received https://github.com/vert-x3/vertx-web/blob/13c10f88ec3b20e53950fd63ed740c9dc317f65a/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java#L71
    129fedc24157d84dadefde44cfd186274f3fddb9
    4eb7f7321e71f77c135311f171cd6727386eb72e
    https://github.com/vert-x3/vertx-web/compare/129fedc24157d84dadefde44cfd186274f3fddb9...4eb7f7321e71f77c135311f171cd6727386eb72e
    diff --git a/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java b/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java index abdd7e4ed..7394d8f96 100644 --- a/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java +++ b/vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java @@ -19,6 +19,7 @@ package io.vertx.ext.web.handler.graphql.impl; import graphql.ExecutionInput; import graphql.ExecutionResult; import io.vertx.core.Handler; +import io.vertx.core.buffer.Buffer; import io.vertx.core.http.ServerWebSocket; import io.vertx.core.impl.ContextInternal; import io.vertx.core.impl.logging.Logger; @@ -68,50 +69,52 @@ class ApolloWSConnectionHandler { ch.handle(serverWebSocket); } - serverWebSocket.handler(buffer -> { - JsonObject content = buffer.toJsonObject(); - String opId = content.getString("id"); - ApolloWSMessageType type = from(content.getString("type")); + serverWebSocket.binaryMessageHandler(this::handleBinaryMessage); + serverWebSocket.textMessageHandler(this::handleTextMessage); + serverWebSocket.closeHandler(this::close); + } - if (type == null) { - sendMessage(opId, ERROR, "Unknown message type: " + content.getString("type")); - return; - } + private void handleBinaryMessage(Buffer buffer) { + handleMessage(new JsonObject(buffer)); + } - ApolloWSMessage message = new ApolloWSMessageImpl(serverWebSocket, type, content); + private void handleTextMessage(String text) { + handleMessage(new JsonObject(text)); + } - Handler<ApolloWSMessage> mh = apolloWSHandler.getMessageHandler(); - if (mh != null) { - mh.handle(message); - } + private void handleMessage(JsonObject jsonObject) { + String opId = jsonObject.getString("id"); + ApolloWSMessageType type = from(jsonObject.getString("type")); - switch (type) { - case CONNECTION_INIT: - connect(); - break; - case CONNECTION_TERMINATE: - serverWebSocket.close(); - break; - case START: - start(message); - break; - case STOP: - stop(opId); - break; - default: - sendMessage(opId, ERROR, "Unsupported message type: " + type); - break; - } - }); + if (type == null) { + sendMessage(opId, ERROR, "Unknown message type: " + jsonObject.getString("type")); + return; + } - serverWebSocket.closeHandler(v -> { - subscriptions.values().forEach(Subscription::cancel); + ApolloWSMessage message = new ApolloWSMessageImpl(serverWebSocket, type, jsonObject); - Handler<ServerWebSocket> eh = apolloWSHandler.getEndHandler(); - if (eh != null) { - eh.handle(serverWebSocket); - } - }); + Handler<ApolloWSMessage> mh = apolloWSHandler.getMessageHandler(); + if (mh != null) { + mh.handle(message); + } + + switch (type) { + case CONNECTION_INIT: + connect(); + break; + case CONNECTION_TERMINATE: + serverWebSocket.close(); + break; + case START: + start(message); + break; + case STOP: + stop(opId); + break; + default: + sendMessage(opId, ERROR, "Unsupported message type: " + type); + break; + } } private void connect() { @@ -250,4 +253,13 @@ class ApolloWSConnectionHandler { } serverWebSocket.writeTextMessage(message.toString()); } + + private void close(Void v) { + subscriptions.values().forEach(Subscription::cancel); + + Handler<ServerWebSocket> eh = apolloWSHandler.getEndHandler(); + if (eh != null) { + eh.handle(serverWebSocket); + } + } } diff --git a/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java b/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java index d282ab59e..d09c4789d 100644 --- a/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java +++ b/vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java @@ -25,7 +25,10 @@ import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; +import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.WebSocket; +import io.vertx.core.http.WebSocketFrame; import io.vertx.core.json.JsonObject; import io.vertx.core.net.NetClientOptions; import io.vertx.core.net.NetServer; @@ -40,6 +43,7 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; import java.util.stream.IntStream; import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring; @@ -132,8 +136,8 @@ public class ApolloWSHandlerTest extends WebTestBase { AtomicReference<String> id = new AtomicReference<>(); AtomicInteger counter = new AtomicInteger(); - websocket.handler(buffer -> { - JsonObject obj = buffer.toJsonObject(); + websocket.textMessageHandler(text -> { + JsonObject obj = new JsonObject(text); int current = counter.getAndIncrement(); if (current >= 0 && current <= MAX_COUNT) { if (current == 0) { @@ -166,14 +170,30 @@ public class ApolloWSHandlerTest extends WebTestBase { @Test public void testQueryWsCall() { + testQueryWsCall((webSocket, message) -> webSocket.write(message.toBuffer())); + } + + @Test + public void testQueryWsCallMultipleFrames() { + testQueryWsCall((webSocket, message) -> { + Buffer buffer = message.toBuffer(); + int part = buffer.length() / 3; + if (part == 0) fail("Cannot perform test"); + webSocket.writeFrame(WebSocketFrame.binaryFrame(buffer.getBuffer(0, part), false)); + webSocket.writeFrame(WebSocketFrame.continuationFrame(buffer.getBuffer(part, 2 * part), false)); + webSocket.writeFrame(WebSocketFrame.continuationFrame(buffer.getBuffer(2 * part, buffer.length()), true)); + }); + } + + private void testQueryWsCall(BiConsumer<WebSocket, JsonObject> sender) { waitFor(2); client.webSocket("/graphql", onSuccess(websocket -> { websocket.exceptionHandler(this::fail); AtomicReference<String> id = new AtomicReference<>(); AtomicInteger counter = new AtomicInteger(); - websocket.handler(buffer -> { - JsonObject obj = buffer.toJsonObject(); + websocket.textMessageHandler(text -> { + JsonObject obj = new JsonObject(text); int current = counter.getAndIncrement(); if (current == 0) { assertTrue(id.compareAndSet(null, obj.getString("id"))); @@ -195,7 +215,7 @@ public class ApolloWSHandlerTest extends WebTestBase { .put("query", "query Query { staticCounter { count } }")) .put("type", "start") .put("id", "1"); - websocket.write(message.toBuffer()); + sender.accept(websocket, message); })); await(); } @@ -224,9 +244,9 @@ public class ApolloWSHandlerTest extends WebTestBase { websocket.exceptionHandler(this::fail); AtomicInteger counter = new AtomicInteger(0); - websocket.handler(buffer -> { + websocket.textMessageHandler(text -> { try { - JsonObject obj = buffer.toJsonObject(); + JsonObject obj = new JsonObject(text); if (counter.getAndIncrement() == 0) { assertEquals(ApolloWSMessageType.CONNECTION_ACK.getText(), obj.getString("type")); @@ -261,7 +281,7 @@ public class ApolloWSHandlerTest extends WebTestBase { websocket.exceptionHandler(this::fail); AtomicInteger counter = new AtomicInteger(); - websocket.handler(buffer -> { + websocket.textMessageHandler(text -> { if (counter.getAndIncrement() == MAX_COUNT) { if (subscriptionRef.get() == null) { fail("Expected a live subscription");
    ['vertx-web-graphql/src/test/java/io/vertx/ext/web/handler/graphql/ApolloWSHandlerTest.java', 'vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/impl/ApolloWSConnectionHandler.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,611,540
    355,944
    49,888
    402
    2,846
    568
    88
    1
    494
    47
    119
    5
    1
    0
    1970-01-01T00:26:32
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,232
    vert-x3/vertx-web/2406/1935
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1935
    https://github.com/vert-x3/vertx-web/pull/2406
    https://github.com/vert-x3/vertx-web/pull/2406
    1
    fix
    Log (LoggerHandlerImpl) swallows/loses log if client closes connection.
    As discussed from: https://github.com/eclipse-vertx/vert.x/issues/3902 Version 3.9.x Context Log is not logged Do you have a reproducer? No. Steps to reproduce This is coming from conversation here: https://groups.google.com/g/vertx/c/CZaPXYk2MA0 Add LoggerHandlerImpl to your route as early as possible. Make sure immediate is false, so that the log gets loged at the end of the request to ensure that context.addBodyEndHandler(v -> log(context, timestamp, remoteClient, version, method, uri)); is used. Have client connect and drop close the connection before response is returned.
    01794a9f52c06fb496916f3095a0174d8b57f352
    f2e96ec91594a83c019c40d9a2c6ae45301b3f10
    https://github.com/vert-x3/vertx-web/compare/01794a9f52c06fb496916f3095a0174d8b57f352...f2e96ec91594a83c019c40d9a2c6ae45301b3f10
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java index 5a5c8ca2e..a521f1500 100755 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java @@ -57,7 +57,6 @@ public class LoggerHandlerImpl implements LoggerHandler { */ private final LoggerFormat format; - private Function<HttpServerRequest, String> customFormatter; private LoggerFormatter logFormatter; public LoggerHandlerImpl(boolean immediate, LoggerFormat format) { @@ -147,11 +146,7 @@ public class LoggerHandlerImpl implements LoggerHandler { break; case CUSTOM: try { - if (logFormatter != null) { - message = logFormatter.format(context, (System.currentTimeMillis() - timestamp)); - } else { - message = customFormatter.apply(request); - } + message = logFormatter.format(context, (System.currentTimeMillis() - timestamp)); } catch (RuntimeException e) { // if an error happens at the user side // log it instead @@ -183,7 +178,7 @@ public class LoggerHandlerImpl implements LoggerHandler { if (immediate) { log(context, timestamp, remoteClient, version, method, uri); } else { - context.addBodyEndHandler(v -> log(context, timestamp, remoteClient, version, method, uri)); + context.addEndHandler(v -> log(context, timestamp, remoteClient, version, method, uri)); } context.next();
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,751,923
    391,757
    55,275
    443
    574
    109
    9
    1
    605
    78
    146
    17
    2
    0
    1970-01-01T00:28:00
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,252
    vert-x3/vertx-web/1984/1983
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1983
    https://github.com/vert-x3/vertx-web/pull/1984
    https://github.com/vert-x3/vertx-web/pull/1984
    1
    fixes
    Pause/Resume missing in AuthorizationHandlerImpl? IllegalStateException: Request has already been read
    ### Version 4.1.0 ### Context When using async operations in implementations of `AuthorizationProvider.getAuthorizations` then a `BodyHandler` added after an `AuthorizationHandler` that uses that `AuthorizationProvider` (created with `AuthorizationHandler.create`) causes that requests with body may fail due to: ``` java.lang.IllegalStateException: Request has already been read at io.vertx.core.http.impl.Http1xServerRequest.checkEnded(Http1xServerRequest.java:627) at io.vertx.core.http.impl.Http1xServerRequest.handler(Http1xServerRequest.java:287) at io.vertx.ext.web.impl.HttpServerRequestWrapper.handler(HttpServerRequestWrapper.java:97) at io.vertx.ext.web.handler.impl.BodyHandlerImpl.handle(BodyHandlerImpl.java:85) at io.vertx.ext.web.handler.impl.BodyHandlerImpl.handle(BodyHandlerImpl.java:44) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1127) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:114) at io.vertx.ext.web.impl.RoutingContextWrapper.next(RoutingContextWrapper.java:201) at io.vertx.ext.web.handler.impl.AuthorizationHandlerImpl.checkOrFetchAuthorizations(AuthorizationHandlerImpl.java:79) at io.vertx.ext.web.handler.impl.AuthorizationHandlerImpl.lambda$checkOrFetchAuthorizations$0(AuthorizationHandlerImpl.java:99) at io.vertx.core.impl.future.FutureImpl$3.onSuccess(FutureImpl.java:124) ``` I have noticed that counter measures have been taken in `AuthenticationHandlerImpl` with this [commit]( https://github.com/vert-x3/vertx-web/commit/937d1e73bda0e90789a9ced17ec2c5a800bdbf0b#diff-5b9edb22f0e308c1a7a43e62f17550732cea30ff9215305686994ff27674975d) where `request.pause()` and `request.resume()` are utilized. Unfortunately - as implementer of an `AuthorizationProvider` I have no way of adding this functionality by myself without copying/extending `AuthorizationHandlerImpl`.
    97917b0ad77ee80bfd6d65ca2f87b57ff3ad2d6a
    bc9a0366a6d09477b5d701d58029bc73dd622cd2
    https://github.com/vert-x3/vertx-web/compare/97917b0ad77ee80bfd6d65ca2f87b57ff3ad2d6a...bc9a0366a6d09477b5d701d58029bc73dd622cd2
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java index bdb61f542..d735cf00a 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java @@ -53,10 +53,22 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { if (routingContext.user() == null) { routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION); } else { - // create the authorization context - AuthorizationContext authorizationContext = getAuthorizationContext(routingContext); - // check or fetch authorizations - checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator()); + // before starting any potential async operation here + // pause parsing the request body. The reason is that + // we don't want to loose the body or protocol upgrades + // for async operations + routingContext.request().pause(); + + try { + // create the authorization context + AuthorizationContext authorizationContext = getAuthorizationContext(routingContext); + // check or fetch authorizations + checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator()); + } catch (RuntimeException e) { + // resume as the error handler may allow this request to become valid again + routingContext.request().resume(); + routingContext.fail(e); + } } } @@ -76,10 +88,14 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { */ private void checkOrFetchAuthorizations(RoutingContext routingContext, AuthorizationContext authorizationContext, Iterator<AuthorizationProvider> providers) { if (authorization.match(authorizationContext)) { + // resume the processing of the request + routingContext.request().resume(); routingContext.next(); return; } if (!providers.hasNext()) { + // resume as the error handler may allow this request to become valid again + routingContext.request().resume(); routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION); return; }
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,757,869
    389,260
    54,421
    434
    1,268
    221
    24
    1
    1,909
    107
    452
    25
    1
    1
    1970-01-01T00:27:04
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,248
    vert-x3/vertx-web/2035/1817
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1817
    https://github.com/vert-x3/vertx-web/pull/2035
    https://github.com/vert-x3/vertx-web/pull/2035
    1
    resolves
    Enable loading OpenAPI YAML from classpath
    #### Feature Description I'd like to load an OpenAPI YAML for router creation from a file that's bundled in a JAR. However, when using `getResource` to determine the URI to the bundled file, an exception is thrown: ``` io.vertx.ext.web.openapi.RouterBuilderException: Cannot load the spec in path file:/path/to/app.jar!/api/core_1.0.0.yaml ``` Ideally [RouterBuilder.create](https://vertx.io/docs/apidocs/io/vertx/ext/web/openapi/RouterBuilder.html#create-io.vertx.core.Vertx-java.lang.String-) should be adapted to be able to load any URI, even those pointing to files in the JAR. #### Contribution Not sure how much work this is. I'd think that it's something that can be implemented in a couple of minutes but maybe it needs some larger refactoring. If it's not too much work, I'm open to get acquainted with the codebase and implement it. However I'd appreciate if someone could give me a few pointers on possible approaches.
    faff38257bcf4c9608a645ca151ae8fe56d6f920
    51e13bbef6d7a52d7eb6019a87818163ced80ed1
    https://github.com/vert-x3/vertx-web/compare/faff38257bcf4c9608a645ca151ae8fe56d6f920...51e13bbef6d7a52d7eb6019a87818163ced80ed1
    diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java index c092f22bb..66cb0ebe1 100755 --- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java +++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java @@ -375,6 +375,7 @@ public class OpenAPIHolderImpl implements OpenAPIHolder { try { switch (uri.getScheme()) { case "http": + case "https": return Paths.get(uri.getPath()); case "file": return Paths.get(uri);
    ['vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,772,442
    392,555
    54,835
    436
    22
    5
    1
    1
    947
    128
    217
    14
    1
    1
    1970-01-01T00:27:10
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,249
    vert-x3/vertx-web/2031/2030
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2030
    https://github.com/vert-x3/vertx-web/pull/2031
    https://github.com/vert-x3/vertx-web/pull/2031
    1
    fixes
    HTTP/2, BodyHandler together with AuthorizationHandler - IllegalStateException Request has already been read
    ### Version vertx-web 4.1.0 - 4.2.0.Beta.1 (since this [commit](https://github.com/vert-x3/vertx-web/commit/bc9a0366a6d09477b5d701d58029bc73dd622cd2)) ### Context * BodyHandler together with a `AuthorizationHandler.create(RoleBasedAuthorization.create("operator"))` and Http 2 requests. ### Do you have a reproducer? https://github.com/DemonicTutor/vertx-web-aaa ### Extra * OpenJDK 16
    342982409d38e2defff1587c99c2ddcfd5c1aec3
    24b2c593bfdc491e24a18d5a68f7785c5f6a0f31
    https://github.com/vert-x3/vertx-web/compare/342982409d38e2defff1587c99c2ddcfd5c1aec3...24b2c593bfdc491e24a18d5a68f7785c5f6a0f31
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java index d735cf00a..28e51519e 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java @@ -18,6 +18,8 @@ import java.util.Iterator; import java.util.Objects; import java.util.function.BiConsumer; +import io.vertx.core.http.HttpHeaders; +import io.vertx.core.http.HttpServerRequest; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; import io.vertx.ext.auth.authorization.Authorization; @@ -57,16 +59,18 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { // pause parsing the request body. The reason is that // we don't want to loose the body or protocol upgrades // for async operations - routingContext.request().pause(); - + final boolean parseEnded = routingContext.request().isEnded(); + if (!parseEnded) { + routingContext.request().pause(); + } try { // create the authorization context AuthorizationContext authorizationContext = getAuthorizationContext(routingContext); // check or fetch authorizations - checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator()); + checkOrFetchAuthorizations(routingContext, parseEnded, authorizationContext, authorizationProviders.iterator()); } catch (RuntimeException e) { // resume as the error handler may allow this request to become valid again - routingContext.request().resume(); + resume(routingContext.request(), parseEnded); routingContext.fail(e); } } @@ -86,16 +90,16 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { * @param authorizationContext the current authorization context * @param providers the providers iterator */ - private void checkOrFetchAuthorizations(RoutingContext routingContext, AuthorizationContext authorizationContext, Iterator<AuthorizationProvider> providers) { + private void checkOrFetchAuthorizations(RoutingContext routingContext, boolean parseEnded, AuthorizationContext authorizationContext, Iterator<AuthorizationProvider> providers) { if (authorization.match(authorizationContext)) { // resume the processing of the request - routingContext.request().resume(); + resume(routingContext.request(), parseEnded); routingContext.next(); return; } if (!providers.hasNext()) { // resume as the error handler may allow this request to become valid again - routingContext.request().resume(); + resume(routingContext.request(), parseEnded); routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION); return; } @@ -112,7 +116,7 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { LOG.warn("An error occured getting authorization - providerId: " + provider.getId(), authorizationResult.cause()); // note that we don't 'record' the fact that we tried to fetch the authorization provider. therefore it will be re-fetched later-on } - checkOrFetchAuthorizations(routingContext, authorizationContext, providers); + checkOrFetchAuthorizations(routingContext, parseEnded, authorizationContext, providers); }); // get out right now as the callback will decide what to do next return; @@ -135,4 +139,10 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { this.authorizationProviders.add(authorizationProvider); return this; } + + private void resume(HttpServerRequest request, final boolean parseEnded) { + if (!parseEnded && !request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { + request.resume(); + } + } }
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,771,962
    392,449
    54,825
    436
    1,551
    280
    26
    1
    408
    33
    129
    16
    2
    0
    1970-01-01T00:27:10
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,245
    vert-x3/vertx-web/2124/2123
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2123
    https://github.com/vert-x3/vertx-web/pull/2124
    https://github.com/vert-x3/vertx-web/pull/2124
    1
    fix
    SessionHandler doesn't callback the handler of method flush in some cases
    ### Questions SessionHandler doesn't callback the handler of method flush in some cases, leaving some user defined actions uncomplished in the handler. ### Version vertx-web 3.9.12 ### Context Hi, we are developing website with Vert.x framework. When we tested the session feature based on the Vert.x `SessionHandler`, we find that sometimes the HTTP response has reached the browser while the session storage action is not finished.(We extended the `SessionStore` to put session into our cache server, sometime it may not act quickly) The root cause is the default logic of Vert.x `SessionHandler` is to flush session in the "HeadersEndHandler", and it does not ensure the response is sent after the session is flushed properly. After searching some issues, we find this is the expected behavior. So we decide to run the `flush` method manually and write the response after the flush action is done. But we find the `flush` method of `SessionHandlerImpl` does not always callback the `handler`. The `handler` are only called back when the session is actually stored. If the response indicates error(status code 4xx/5xx) or the session is not touched or some other cases, the session will not be actually written into the `SessionStore` and the `handler` is not called. This is a problem for those who want to do something after the session flush procedure ends. Because in some cases, the "end" is never shown to the caller of `flush` method. ### Do you have a reproducer? Here is a reproducer: ```java public class Demo { private static Vertx vertx = Vertx.vertx(); private static int flag = 0; public static void main(String[] args) { final HttpServer httpServer = vertx.createHttpServer(new HttpServerOptions() .setIdleTimeout(10)); final Router router = Router.router(vertx); final SessionHandler sessionHandler = SessionHandler.create(LocalSessionStore.create(vertx)) .setSessionTimeout(10_000) .setLazySession(true); router.route().handler(sessionHandler); router.route().handler(ctx -> { System.out.println("get request"); final HttpServerResponse response = ctx.response(); ctx.session(); if ((++flag & 1) == 0) { response.setStatusCode(500); } else { response.setStatusCode(200); } sessionHandler.flush(ctx, asyncResult -> { System.out.println("get session flush result: " + asyncResult.succeeded()); response.putHeader("Content-Type", "text/plain"); response.end("Hello World!"); ctx.next(); }); }); httpServer.requestHandler(router).listen(9999); } } ``` Only the vertx-web dependency is needed for this demo. ### Steps to reproduce 1. run the demo above 2. curl `http://localhost:9999/` I've made the server response `200` and `500` alternately. And when 200 is returned, the client will get response instantly, while when 500 should be returned, the server will hang the connection until the connection idle timed out. ### Extra I'm not sure whether this is the expected behavior of `SessionHandler`. But I guess people who want to ensure the order between "flush session" and some "finish action" may be troubled by this behavior. Is it possible to fix this problem? Looking forward to your reply, and thank you very much.
    91a1b2ade0d5af86aeb38231a919a5013a33ad99
    92fd0ac40396c9fdeff54e3c47801d22987ca5cf
    https://github.com/vert-x3/vertx-web/compare/91a1b2ade0d5af86aeb38231a919a5013a33ad99...92fd0ac40396c9fdeff54e3c47801d22987ca5cf
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java index 40d6efbdc..e07b7ac85 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java @@ -238,6 +238,8 @@ public class SessionHandlerImpl implements SessionHandler { } }); } + } else { + handler.handle(Future.failedFuture("Skipping session store: ignoreStatus || (currentStatusCode >= 200 && currentStatusCode < 400)")); } } else { if (!cookieless) { diff --git a/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java index 9b9fb7112..8b4948308 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java @@ -16,6 +16,8 @@ package io.vertx.ext.web.sstore; +import io.vertx.core.http.HttpMethod; +import io.vertx.ext.web.handler.SessionHandler; import io.vertx.ext.web.handler.SessionHandlerTestBase; import org.junit.Test; @@ -34,4 +36,25 @@ public class LocalSessionHandlerTest extends SessionHandlerTestBase { public void testRetryTimeout() throws Exception { assertTrue(doTestSessionRetryTimeout() < 3000); } + + @Test + public void test2123() throws Exception { + SessionHandler sessionHandler = SessionHandler.create(LocalSessionStore.create(vertx)) + .setSessionTimeout(10_000) + .setLazySession(true); + + router.clear(); + + router.route().handler(sessionHandler); + router.route().handler(ctx -> { + ctx.session(); + ctx.response().setStatusCode(500); + sessionHandler.flush(ctx, asyncResult -> { + assertTrue(asyncResult.failed()); + ctx.end(); + }); + }); + + testRequest(HttpMethod.GET, "/", 500, "Internal Server Error"); + } }
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java', 'vertx-web/src/test/java/io/vertx/ext/web/sstore/LocalSessionHandlerTest.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,906,750
    423,047
    59,207
    462
    158
    33
    2
    1
    3,532
    446
    735
    73
    1
    1
    1970-01-01T00:27:24
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,244
    vert-x3/vertx-web/2140/2136
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2136
    https://github.com/vert-x3/vertx-web/pull/2140
    https://github.com/vert-x3/vertx-web/pull/2140
    1
    fix
    Subrouter fails if mounted on another subrouter on path with path params
    ### Version 4.2.4 and 4.3.0-SNAPSHOT ### Context If subrouter is NOT mounted on root router (but instead on another subrouter) and its path contains parameters, then routing fails with 404 and well-known HTML output "Resource not found". ### Do you have a reproducer? By modifying [SubRouterTest#testSimpleWithParams](https://github.com/vert-x3/vertx-web/blob/8d1c667a6848ed71753d4dd7d314cb8492fb09a2/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java#L460) I constructed test that fails: ``` @Test // Fails! public void testHierarchicalWithParams() throws Exception { Router restRouter = Router.router(vertx); Router subRouter = Router.router(vertx); subRouter.get("/files").handler(ctx -> { // version is extracted from the root router assertEquals("1", ctx.pathParam("version")); ctx.response().end(); }); restRouter.mountSubRouter("/:version", subRouter); router.mountSubRouter("/rest", restRouter); testRequest(HttpMethod.GET, "/rest/1/files", 200, "OK"); } ``` Another interesting fact is that subrouter will work if it has path params too (!): ``` @Test // Passes public void testHierarchicalWithParamsInAllRouters() throws Exception { Router restRouter = Router.router(vertx); Router subRouter = Router.router(vertx); subRouter.get("/files/:id").handler(ctx -> { // version is extracted from the root router assertEquals("1", ctx.pathParam("version")); // id is extracted from this router assertEquals("2", ctx.pathParam("id")); ctx.response().end(); }); restRouter.mountSubRouter("/:version", subRouter); router.mountSubRouter("/rest", restRouter); testRequest(HttpMethod.GET, "/rest/1/files/2", 200, "OK"); } ``` ### Steps to reproduce 1. Add those tests to [SubRouterTest.java](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java) 2. Run tests with `mvn -Dtest=SubRouterTest test -pl vertx-web` ### Extra * OS: Ubuntu 21:10 * JVM: OpenJDK 11.0.13 2021-10-19
    8d1c667a6848ed71753d4dd7d314cb8492fb09a2
    0a998d8f269f8c12ec4980af8d1409b340f41b17
    https://github.com/vert-x3/vertx-web/compare/8d1c667a6848ed71753d4dd7d314cb8492fb09a2...0a998d8f269f8c12ec4980af8d1409b340f41b17
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java index efae8cccd..63db497d3 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java @@ -346,12 +346,14 @@ public class RouterImpl implements Router { } // regex if (ctx.matchRest != -1) { + // if we're on a sub router already we need to skip the matched path + int skip = ctx.mountPoint != null ? ctx.mountPoint.length() : 0; if (ctx.matchNormalized) { - return ctx.normalizedPath().substring(0, ctx.matchRest); + return ctx.normalizedPath().substring(skip, skip + ctx.matchRest); } else { String path = ctx.request().path(); if (path != null) { - return path.substring(0, ctx.matchRest); + return path.substring(skip, skip + ctx.matchRest); } return null; } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java index d0e6793e9..48700238a 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java @@ -647,5 +647,55 @@ public class SubRouterTest extends WebTestBase { router.route("/level1/*").handler(level2); testRequest(HttpMethod.GET, "/level1/level2/level3", 200, "ok"); } + + @Test + public void testHierarchicalWithParams() throws Exception { + + Router restRouter = Router.router(vertx); + Router subRouter = Router.router(vertx); + + subRouter.get("/files").handler(ctx -> { + // version is extracted from the root router + assertEquals("1", ctx.pathParam("version")); + ctx.response().end(); + }); + + restRouter.mountSubRouter("/:version", subRouter); + + router.mountSubRouter("/rest", restRouter); + + // router + // /rest -> restRouter + // /:version -> subRouter + // /files -> OK + + testRequest(HttpMethod.GET, "/rest/1/files", 200, "OK"); + } + + @Test + public void testHierarchicalWithParamsInAllRouters() throws Exception { + + Router restRouter = Router.router(vertx); + Router subRouter = Router.router(vertx); + + subRouter.get("/files/:id").handler(ctx -> { + // version is extracted from the root router + assertEquals("1", ctx.pathParam("version")); + // id is extracted from this router + assertEquals("2", ctx.pathParam("id")); + ctx.response().end(); + }); + + restRouter.mountSubRouter("/:version", subRouter); + + router.mountSubRouter("/rest", restRouter); + + // router + // /rest -> restRouter + // /:version -> subRouter + // /files/:id -> OK + + testRequest(HttpMethod.GET, "/rest/1/files/2", 200, "OK"); + } }
    ['vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,907,442
    423,206
    59,226
    462
    403
    89
    6
    1
    2,138
    191
    555
    67
    2
    2
    1970-01-01T00:27:26
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,243
    vert-x3/vertx-web/2159/2139
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2139
    https://github.com/vert-x3/vertx-web/pull/2159
    https://github.com/vert-x3/vertx-web/pull/2159
    1
    fix
    ConcurrentLRUCache shouldn't be named concurrent or LRU?
    Hey! I happened to notice `io.vertx.ext.web.impl.ConcurrentLRUCache` class in this project. Is this still being maintained and/or used somewhere? I couldn't find any references to this class in the codebase except in the tests here, or any discussions related to this. I was about to start using this for a simple cache, but after having done cursory review, it looks like this class doesn't do what the name implies. First and foremost, it is based on ConcurrentHashMap which is thread-safe, but it also relies internally on ArrayDeque, which is _not_ thread-safe. There doesn't seem to be any synchronization happening either. The "concurrent" in name would imply that this would be thread-safe. Second, it doesn't seem to be LRU either. If I read the code correctly, it deletes the earliest inserted item once reaching the max size, instead of the least recently used item. Not necessarily anything that needs to be done about this - just heads-up that the class name is quite confusing as it sets an expectation for something completely else.. :)
    8ed704182b18d459bd82c8bf2dc389d1a4edd8d5
    a6894b3407554f43db8fc07c579441e133d65ca8
    https://github.com/vert-x3/vertx-web/compare/8ed704182b18d459bd82c8bf2dc389d1a4edd8d5...a6894b3407554f43db8fc07c579441e133d65ca8
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java deleted file mode 100644 index e4b91f050..000000000 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2014 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.web.impl; - -import java.util.ArrayDeque; -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.BiFunction; - -/** - * Concurrent LRU cache. - * - * Note that remove operation on this structure is SLOW! Avoid using it. - * - * @author <a href="http://tfox.org">Tim Fox</a> - */ -public class ConcurrentLRUCache<K, V> extends ConcurrentHashMap<K, V> { - - private int maxSize; - private final Queue<K> queue = new ArrayDeque<>(); - - public ConcurrentLRUCache(int maxSize) { - this.maxSize = maxSize; - checkSize(); - } - - public ConcurrentLRUCache(int initialCapacity, int maxSize) { - super(initialCapacity); - this.maxSize = maxSize; - checkSize(); - } - - public ConcurrentLRUCache(Map<? extends K, ? extends V> m, int maxSize) { - super(m); - this.maxSize = maxSize; - checkSize(); - for (K k: m.keySet()) { - entryAdded(k); - } - checkRemoveOldest(); - } - - public ConcurrentLRUCache(int initialCapacity, float loadFactor, int maxSize) { - super(initialCapacity, loadFactor); - this.maxSize = maxSize; - checkSize(); - } - - public ConcurrentLRUCache(int initialCapacity, float loadFactor, int concurrencyLevel, int maxSize) { - super(initialCapacity, loadFactor, concurrencyLevel); - this.maxSize = maxSize; - checkSize(); - } - - public void setMaxSize(int maxSize) { - this.maxSize = maxSize; - checkRemoveOldest(); - } - - @Override - public V put(K key, V value) { - V v = super.put(key, value); - if (v == null) { - entryAdded(key); - } - checkRemoveOldest(); - return v; - } - - @Override - public void putAll(Map<? extends K, ? extends V> m) { - for (K k: m.keySet()) { - if (!super.containsKey(k)) { - entryAdded(k); - } - } - super.putAll(m); - checkRemoveOldest(); - } - - @Override - public V remove(Object key) { - V v = super.remove(key); - if (v != null) { - entryRemoved(key); - } - return v; - } - - @Override - public void clear() { - super.clear(); - queue.clear(); - } - - @Override - public V putIfAbsent(K key, V value) { - V v = super.putIfAbsent(key, value); - if (v == null) { - entryAdded(key); - } - checkRemoveOldest(); - return v; - } - - @Override - public boolean remove(Object key, Object value) { - boolean removed = super.remove(key, value); - if (removed) { - entryRemoved(value); - } - return removed; - } - - @Override - public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { - throw new UnsupportedOperationException(); - } - - private void entryAdded(K k) { - queue.add(k); - } - - private void entryRemoved(Object o) { - if (!queue.remove(o)) { - throw new IllegalStateException("Failed to remove"); - } - } - - private void checkRemoveOldest() { - while (queue.size() > maxSize) { - K k = queue.poll(); - if (k != null) { - super.remove(k); - } - } - } - - private void checkSize() { - if (maxSize < 1) { - throw new IllegalArgumentException("maxSize must be >= 1"); - } - } - - public int queueSize() { - return queue.size(); - } -} diff --git a/vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java b/vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java deleted file mode 100644 index 1ff39d68e..000000000 --- a/vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2014 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.web; - -import io.vertx.ext.web.impl.ConcurrentLRUCache; -import org.junit.Test; - -import java.util.Map; - -import static org.junit.Assert.*; - -/** - * @author <a href="http://tfox.org">Tim Fox</a> - */ -public class ConcurrentLRUCacheTest extends LRUCacheTestBase { - - @Override - protected Map<String, String> createCache() { - return new ConcurrentLRUCache<>(maxSize); - } - - @Test - public void testPut() { - super.testPut(); - assertEquals(maxSize, ((ConcurrentLRUCache)cache).queueSize()); - } - - @Test - public void testRemove() { - super.testRemove(); - assertEquals(0, ((ConcurrentLRUCache)cache).queueSize()); - } - - @Test(expected=IllegalArgumentException.class) - public void testCacheInvalidSize1() { - new ConcurrentLRUCache<>(0); - } - - @Test(expected=IllegalArgumentException.class) - public void testCacheInvalidSize2() { - new ConcurrentLRUCache<>(-1); - } - - @Test - public void testIncreaseMaxSize() { - for (int i = 0; i < maxSize; i++) { - cache.put("key" + i, "value" + i); - } - assertEquals(maxSize, cache.size()); - ConcurrentLRUCache<String, String> ccache = (ConcurrentLRUCache<String, String>)cache; - ccache.setMaxSize(maxSize + 10); - for (int i = maxSize; i < maxSize + 10; i++) { - cache.put("key" + i, "value" + i); - } - assertEquals(maxSize + 10, cache.size()); - } - -}
    ['vertx-web/src/test/java/io/vertx/ext/web/ConcurrentLRUCacheTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/ConcurrentLRUCache.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,930,111
    428,865
    59,963
    466
    3,834
    925
    163
    1
    1,065
    172
    221
    11
    0
    0
    1970-01-01T00:27:28
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,242
    vert-x3/vertx-web/2176/2169
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2169
    https://github.com/vert-x3/vertx-web/pull/2176
    https://github.com/vert-x3/vertx-web/pull/2176
    1
    fixes
    fileUploads are un-ordered
    ### Questions `fileUploads` are stored in an `HashSet`, thus we lose the order they were sent from. ### Version 4.3.0-SNAPSHOT ### Context I have a route which handle file uploads and it needs to retrieves the file names in the order they were sent. ### Do you have a reproducer? The `HashSet` is created here: https://github.com/vert-x3/vertx-web/blob/a60906bf3a88f944c47f324aa1f847b8cc367fea/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java#L538-L543 Could a `LinkedHashSet` be used here instead?
    4e2a4aca621884107ab1b0651acc76361ddb0b75
    c1f6e93ee0ddec39f3edb92d715b20d09db6af4e
    https://github.com/vert-x3/vertx-web/compare/4e2a4aca621884107ab1b0651acc76361ddb0b75...c1f6e93ee0ddec39f3edb92d715b20d09db6af4e
    diff --git a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java index d8428e232..5992cc391 100644 --- a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java +++ b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java @@ -44,7 +44,7 @@ public class OpenAPI3RequestValidationHandlerImpl extends HTTPOperationRequestVa this.isOptional = isOptional; } - private boolean existFileUpload(Set<FileUpload> files, String name, Pattern contentType) { + private boolean existFileUpload(List<FileUpload> files, String name, Pattern contentType) { for (FileUpload f : files) { if (f.name().equals(name) && contentType.matcher(f.contentType()).matches()) return true; } diff --git a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java index 4c83a015c..4c14462ba 100644 --- a/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java +++ b/vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java @@ -275,7 +275,7 @@ public abstract class BaseValidationHandler implements ValidationHandler { return parsedParams; } - private boolean existFileUpload(Set<FileUpload> files, String name, Pattern contentType) { + private boolean existFileUpload(List<FileUpload> files, String name, Pattern contentType) { for (FileUpload f : files) { if (f.name().equals(name) && contentType.matcher(f.contentType()).matches()) return true; } @@ -283,7 +283,7 @@ public abstract class BaseValidationHandler implements ValidationHandler { } private void validateFileUpload(RoutingContext routingContext) throws ValidationException { - Set<FileUpload> fileUploads = routingContext.fileUploads(); + List<FileUpload> fileUploads = routingContext.fileUploads(); for (Map.Entry<String, Pattern> expectedFile : multipartFileRules.entrySet()) { if (!existFileUpload(fileUploads, expectedFile.getKey(), expectedFile.getValue())) throw ValidationException.ValidationExceptionFactory.generateFileNotFoundValidationException(expectedFile diff --git a/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java b/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java index 6b04a31e6..e408838d7 100644 --- a/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java +++ b/vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java @@ -5,7 +5,7 @@ import io.vertx.core.http.HttpHeaders; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.RoutingContext; -import java.util.Set; +import java.util.List; import java.util.function.Function; import java.util.regex.Pattern; @@ -40,7 +40,7 @@ public interface RequestPredicate extends Function<RoutingContext, RequestPredic rc.request().headers().contains(HttpHeaders.CONTENT_TYPE) && rc.request().getHeader(HttpHeaders.CONTENT_TYPE).contains("multipart/form-data") ) { - Set<FileUpload> files = rc.fileUploads(); + List<FileUpload> files = rc.fileUploads(); for (FileUpload f : files) { if (f.name().equals(propertyName) && contentType.matcher(f.contentType()).matches()) return success(); } diff --git a/vertx-web/src/main/java/examples/WebExamples.java b/vertx-web/src/main/java/examples/WebExamples.java index 9dd9ad7f9..52c09446b 100644 --- a/vertx-web/src/main/java/examples/WebExamples.java +++ b/vertx-web/src/main/java/examples/WebExamples.java @@ -696,7 +696,7 @@ public class WebExamples { router.post("/some/path/uploads").handler(ctx -> { - Set<FileUpload> uploads = ctx.fileUploads(); + List<FileUpload> uploads = ctx.fileUploads(); // Do something with uploads.... }); diff --git a/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java b/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java index 9af928097..2fd2b1afe 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java @@ -378,10 +378,10 @@ public interface RoutingContext { RequestBody body(); /** - * @return a set of fileuploads (if any) for the request. The context must have first been routed to a + * @return a list of {@link FileUpload} (if any) for the request. The context must have first been routed to a * {@link io.vertx.ext.web.handler.BodyHandler} for this to work. */ - Set<FileUpload> fileUploads(); + List<FileUpload> fileUploads(); /** * Get the session. The context must have first been routed to a {@link io.vertx.ext.web.handler.SessionHandler} diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java index 9a286199f..0269e9cca 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java @@ -17,7 +17,7 @@ package io.vertx.ext.web.handler.impl; import java.io.File; -import java.util.Set; +import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -210,7 +210,7 @@ public class BodyHandlerImpl implements BodyHandler { initBodyBuffer(); } - Set<FileUpload> fileUploads = context.fileUploads(); + List<FileUpload> fileUploads = context.fileUploads(); final String contentType = context.request().getHeader(HttpHeaders.CONTENT_TYPE); if (contentType == null) { diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java index 819e11e39..9a2820107 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java @@ -133,7 +133,7 @@ public class RoutingContextDecorator implements RoutingContextInternal { } @Override - public Set<FileUpload> fileUploads() { + public List<FileUpload> fileUploads() { return decoratedContext.fileUploads(); } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java index 79413cb55..d7b7a1ae4 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java @@ -27,7 +27,6 @@ import io.vertx.core.impl.ContextInternal; import io.vertx.ext.auth.User; import io.vertx.ext.web.RequestBody; import io.vertx.ext.web.FileUpload; -import io.vertx.ext.web.RequestBody; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.Session; import io.vertx.ext.web.handler.HttpException; @@ -67,7 +66,7 @@ public class RoutingContextImpl extends RoutingContextImplBase { private String acceptableContentType; private ParsableHeaderValuesContainer parsedHeaders; - private Set<FileUpload> fileUploads; + private List<FileUpload> fileUploads; private Session session; private User user; @@ -304,8 +303,11 @@ public class RoutingContextImpl extends RoutingContextImplBase { } @Override - public Set<FileUpload> fileUploads() { - return getFileUploads(); + public List<FileUpload> fileUploads() { + if (fileUploads == null) { + fileUploads = new ArrayList<>(); + } + return fileUploads; } @Override @@ -535,13 +537,6 @@ public class RoutingContextImpl extends RoutingContextImplBase { return endHandlers; } - private Set<FileUpload> getFileUploads() { - if (fileUploads == null) { - fileUploads = new HashSet<>(); - } - return fileUploads; - } - private void doFail() { this.iter = router.iterator(); currentRoute = null; diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java index 22dca1361..4a4bfe546 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java @@ -279,7 +279,7 @@ public class RoutingContextWrapper extends RoutingContextImplBase { } @Override - public Set<FileUpload> fileUploads() { + public List<FileUpload> fileUploads() { return inner.fileUploads(); } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java index f49853c37..ba298bc1f 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java @@ -36,7 +36,7 @@ import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; -import java.util.Set; +import java.util.List; import java.util.function.Function; /** @@ -247,7 +247,7 @@ public class BodyHandlerTest extends WebTestBase { String contentType = "application/octet-stream"; Buffer fileData = TestUtils.randomBuffer(size); router.route().handler(rc -> { - Set<FileUpload> fileUploads = rc.fileUploads(); + List<FileUpload> fileUploads = rc.fileUploads(); assertNotNull(fileUploads); assertEquals(1, fileUploads.size()); FileUpload upload = fileUploads.iterator().next(); @@ -830,7 +830,7 @@ public class BodyHandlerTest extends WebTestBase { String contentType = "application/octet-stream"; Buffer fileData = TestUtils.randomBuffer(50); router.route().handler(rc -> { - Set<FileUpload> fileUploads = rc.fileUploads(); + List<FileUpload> fileUploads = rc.fileUploads(); assertNotNull(fileUploads); assertEquals(1, fileUploads.size()); FileUpload upload = fileUploads.iterator().next();
    ['vertx-web-validation/src/main/java/io/vertx/ext/web/validation/RequestPredicate.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java', 'vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/validation/impl/BaseValidationHandler.java', 'vertx-web/src/main/java/io/vertx/ext/web/RoutingContext.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java', 'vertx-web/src/main/java/examples/WebExamples.java', 'vertx-web-api-contract/src/main/java/io/vertx/ext/web/api/contract/openapi3/impl/OpenAPI3RequestValidationHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextWrapper.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java']
    {'.java': 10}
    10
    10
    0
    0
    10
    1,960,389
    435,305
    60,784
    481
    1,879
    441
    41
    9
    548
    63
    153
    20
    1
    0
    1970-01-01T00:27:32
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,241
    vert-x3/vertx-web/2186/2185
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2185
    https://github.com/vert-x3/vertx-web/pull/2186
    https://github.com/vert-x3/vertx-web/pull/2186
    1
    fixes
    Subrouter fails if mounted on another subrouter on path with path params
    ### Version 4.3.0 and 4.3.1-SNAPSHOT ### Context Follow up on #2136 which still fails in some cases. ### Do you have a reproducer? Add this to [SubRouterTest](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java): ``` @Test // FAILS! public void testHierarchicalWithParamsSimple() throws Exception { Router restRouter = Router.router(vertx); Router productRouter = Router.router(vertx); Router instanceRouter = Router.router(vertx); router.route("/rest*").subRouter(restRouter); restRouter.route("/product*").subRouter(productRouter); productRouter.route("/:id*").subRouter(instanceRouter); instanceRouter.get("/").handler(ctx -> { // id is extracted from the root router assertEquals("123", ctx.pathParam("id")); ctx.response().end(); }); // router // /rest -> restRouter // /product -> productRouter // /:id -> instanceRouter // / -> OK testRequest(HttpMethod.GET, "/rest/product/123", 200, "OK"); } ``` However, route is recognized if I add another path param to last sub-router: ``` @Test // succeeds public void testHierarchicalWithParamsSimpleWithDummy() throws Exception { Router restRouter = Router.router(vertx); Router productRouter = Router.router(vertx); Router instanceRouter = Router.router(vertx); router.route("/rest*").subRouter(restRouter); restRouter.route("/product*").subRouter(productRouter); productRouter.route("/:id*").subRouter(instanceRouter); instanceRouter.get("/:foo").handler(ctx -> { // id is extracted from the root router assertEquals("123", ctx.pathParam("id")); assertEquals("bar", ctx.pathParam("foo")); ctx.response().end(); }); // router // /rest -> restRouter // /product -> productRouter // /:id -> instanceRouter // /:foo -> OK testRequest(HttpMethod.GET, "/rest/product/123/bar", 200, "OK"); } ``` ### Steps to reproduce 1. Add those tests to [SubRouterTest.java](https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java) 2. Run tests with `mvn -Dtest=SubRouterTest test -pl vertx-web` ### Extra * OS: Ubuntu 21.10 * JVM: OpenJDK 64-Bit Server VM 11.0.14.1 2022-02-08
    f3e7c6e32632702bae3557c3da86fe8d35e23c5b
    ab2318af9ac0cab9129a35fa4b38c5e58affe286
    https://github.com/vert-x3/vertx-web/compare/f3e7c6e32632702bae3557c3da86fe8d35e23c5b...ab2318af9ac0cab9129a35fa4b38c5e58affe286
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java index b9833c6a3..7d54c0c76 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java @@ -1024,7 +1024,7 @@ final class RouteState { } context.matchRest = -1; - context.matchNormalized = useNormalizedPath; + context.normalizedMatch = useNormalizedPath; if (m.groupCount() > 0) { if (!exactPath) { diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java index 1fe9a7370..7f5e344fc 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java @@ -246,12 +246,14 @@ public class RouterImpl implements Router { @Override public void handleContext(RoutingContext ctx) { - new RoutingContextWrapper(getAndCheckRoutePath(ctx), state.getRoutes(), (RoutingContextInternal) ctx, this).next(); + final RoutingContextInternal ctxi = (RoutingContextInternal) ctx; + new RoutingContextWrapper(getAndCheckRoutePath(ctxi), state.getRoutes(), ctxi, this).next(); } @Override public void handleFailure(RoutingContext ctx) { - new RoutingContextWrapper(getAndCheckRoutePath(ctx), state.getRoutes(), (RoutingContextInternal) ctx, this).next(); + final RoutingContextInternal ctxi = (RoutingContextInternal) ctx; + new RoutingContextWrapper(getAndCheckRoutePath(ctxi), state.getRoutes(), ctxi, this).next(); } @Override @@ -333,8 +335,7 @@ public class RouterImpl implements Router { return state.getErrorHandler(statusCode); } - private String getAndCheckRoutePath(RoutingContext routingContext) { - final RoutingContextImplBase ctx = (RoutingContextImplBase) routingContext; + private String getAndCheckRoutePath(RoutingContextInternal ctx) { final Route route = ctx.currentRoute(); if (!route.isRegexPath()) { @@ -347,18 +348,9 @@ public class RouterImpl implements Router { } } // regex - if (ctx.matchRest != -1) { + if (ctx.restIndex() != -1) { // if we're on a sub router already we need to skip the matched path - int skip = ctx.mountPoint != null ? ctx.mountPoint.length() : 0; - if (ctx.matchNormalized) { - return ctx.normalizedPath().substring(skip, skip + ctx.matchRest); - } else { - String path = ctx.request().path(); - if (path != null) { - return path.substring(skip, skip + ctx.matchRest); - } - return null; - } + return ctx.basePath(); } else { // failure did not match throw new IllegalStateException("Sub routers must be mounted on paths (constant or parameterized)"); diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java index c072c25ae..70d3628a7 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java @@ -286,6 +286,16 @@ public class RoutingContextDecorator implements RoutingContextInternal { decoratedContext.setSession(session); } + @Override + public int restIndex() { + return decoratedContext.restIndex(); + } + + @Override + public boolean normalizedMatch() { + return decoratedContext.normalizedMatch(); + } + @Override public void setUser(User user) { decoratedContext.setUser(user); diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java index f043362c7..c6959902b 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java @@ -108,7 +108,6 @@ public class RoutingContextImpl extends RoutingContextImplBase { HeaderParser.sort(HeaderParser.convertToParsedHeaderValues(acceptLanguage, ParsableLanguageValue::new)), new ParsableMIMEValue(contentType) ); - } @Override diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java index 2a1261e0e..58ff9d1f5 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java @@ -54,7 +54,7 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal { int matchFailure; // the current path matched string int matchRest = -1; - boolean matchNormalized; + boolean normalizedMatch; // internal runtime state private volatile long seen; @@ -78,6 +78,16 @@ public abstract class RoutingContextImplBase implements RoutingContextInternal { return (seen & id) != 0; } + @Override + public int restIndex() { + return matchRest; + } + + @Override + public boolean normalizedMatch() { + return normalizedMatch; + } + @Override public synchronized RoutingContextInternal setMatchFailure(int matchFailure) { this.matchFailure = matchFailure; diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java index 34304fed4..f5a8b6b69 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java @@ -84,4 +84,25 @@ public interface RoutingContextInternal extends RoutingContext { * @param session the session */ void setSession(Session session); + + int restIndex(); + + boolean normalizedMatch(); + + default String basePath() { + // if we're on a sub router already we need to skip the matched path + String mountPoint = mountPoint(); + + int skip = mountPoint != null ? mountPoint.length() : 0; + if (normalizedMatch()) { + return normalizedPath().substring(skip, skip + restIndex()); + } else { + String path = request().path(); + if (path != null) { + return path.substring(skip, skip + restIndex()); + } + return null; + } + + }; } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java index 4d66c6b2c..6d32d22e4 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java @@ -690,5 +690,55 @@ public class SubRouterTest extends WebTestBase { testRequest(HttpMethod.GET, "/rest/1/files/2", 200, "OK"); } -} + @Test + public void testHierarchicalWithParamsSimple() throws Exception { + + Router restRouter = Router.router(vertx); + Router productRouter = Router.router(vertx); + Router instanceRouter = Router.router(vertx); + + router.route("/rest*").subRouter(restRouter); + restRouter.route("/product*").subRouter(productRouter); + productRouter.route("/:id*").subRouter(instanceRouter); + instanceRouter.get("/").handler(ctx -> { + // id is extracted from the root router + assertEquals("123", ctx.pathParam("id")); + ctx.response().end(); + }); + + // router + // /rest -> restRouter + // /product -> productRouter + // /:id -> instanceRouter + // / -> OK + + testRequest(HttpMethod.GET, "/rest/product/123", 200, "OK"); + } + + @Test + public void testHierarchicalWithParamsSimpleWithDummy() throws Exception { + + Router restRouter = Router.router(vertx); + Router productRouter = Router.router(vertx); + Router instanceRouter = Router.router(vertx); + + router.route("/rest*").subRouter(restRouter); + restRouter.route("/product*").subRouter(productRouter); + productRouter.route("/:id*").subRouter(instanceRouter); + instanceRouter.get("/:foo").handler(ctx -> { + // id is extracted from the root router + assertEquals("123", ctx.pathParam("id")); + assertEquals("bar", ctx.pathParam("foo")); + ctx.response().end(); + }); + + // router + // /rest -> restRouter + // /product -> productRouter + // /:id -> instanceRouter + // /:foo -> OK + + testRequest(HttpMethod.GET, "/rest/product/123/bar", 200, "OK"); + } +}
    ['vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextDecorator.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImplBase.java', 'vertx-web/src/test/java/io/vertx/ext/web/SubRouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RouterImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/RouteState.java']
    {'.java': 7}
    7
    7
    0
    0
    7
    1,965,720
    436,450
    60,969
    482
    2,332
    517
    68
    6
    2,445
    203
    613
    77
    2
    2
    1970-01-01T00:27:33
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,270
    vert-x3/vertx-web/1432/1429
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1429
    https://github.com/vert-x3/vertx-web/pull/1432
    https://github.com/vert-x3/vertx-web/pull/1432
    1
    fixes
    StaticHandlerImpl uses a shared DateFormat across threads causing issues with date parsing in header values
    Continuing on this curious issue in Quarkus https://github.com/quarkusio/quarkus/issues/4627, apart from the fix done yesterday here https://github.com/vert-x3/vertx-web/issues/1423, it would be really odd that Firefox (that too the latest version) would send incorrect values for a header like `If-Modified-Since`. The user attached the browser's request header screenshots here https://github.com/quarkusio/quarkus/issues/4627#issuecomment-543247193 and they show that Firefox is sending the right header values. So looking back into the code in `StaticHandlerImpl`, I think what's happening is multiple requests (across threads) are being handled by it and it uses a single instance of `DateFormat` to parse the header value. The `DateFormat` (`java.text.SimpleDateFormat`) is created once for that handler and stored as a member variable. The javadoc of `SimpleDateFormat` states: ``` * Date formats are not synchronized. * It is recommended to create separate format instances for each thread. * If multiple threads access a format concurrently, it must be synchronized * externally. ``` So what seems to be happening in that issue that is that its running into a race condition due to multiple threads using the same DateFormatter. I think the implementation in this `StaticHandlerImpl` should either create the DateFormat as and when needed or maybe have a `ThreadLocal`.
    32f6a489e9e53431a7051a6151977940150cb931
    7eae93b1dce3d6c916e85b8372b1eece8a3a9e7e
    https://github.com/vert-x3/vertx-web/compare/32f6a489e9e53431a7051a6151977940150cb931...7eae93b1dce3d6c916e85b8372b1eece8a3a9e7e
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java index a76a6513e..282e8e99a 100755 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java @@ -27,9 +27,6 @@ import io.vertx.ext.web.handler.LoggerHandler; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.impl.Utils; -import java.text.DateFormat; -import java.util.Date; - /** # Logger * * Logger for request. There are 3 formats included: @@ -48,10 +45,6 @@ public class LoggerHandlerImpl implements LoggerHandler { private final io.vertx.core.logging.Logger logger = LoggerFactory.getLogger(this.getClass()); - /** The Date formatter (UTC JS compatible format) - */ - private final DateFormat dateTimeFormat = Utils.createRFC1123DateTimeFormatter(); - /** log before request or after */ private final boolean immediate; @@ -119,7 +112,7 @@ public class LoggerHandlerImpl implements LoggerHandler { message = String.format("%s - - [%s] \\"%s %s %s\\" %d %d \\"%s\\" \\"%s\\"", remoteClient, - dateTimeFormat.format(new Date(timestamp)), + Utils.formatRFC1123DateTime(timestamp), method, uri, versionFormatted, diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java index b85df7d5c..14e34dd26 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java @@ -34,8 +34,6 @@ import io.vertx.ext.web.impl.Utils; import java.io.File; import java.nio.charset.Charset; -import java.text.DateFormat; -import java.text.ParseException; import java.util.*; import java.util.concurrent.Callable; import java.util.regex.Matcher; @@ -54,7 +52,6 @@ public class StaticHandlerImpl implements StaticHandler { private static final Logger log = LoggerFactory.getLogger(StaticHandlerImpl.class); - private final DateFormat dateTimeFormatter = Utils.createRFC1123DateTimeFormatter(); private String webRoot = DEFAULT_WEB_ROOT; private long maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS; // One day private boolean directoryListing = DEFAULT_DIRECTORY_LISTING; @@ -112,7 +109,7 @@ public class StaticHandlerImpl implements StaticHandler { // We use cache-control and last-modified // We *do not use* etags and expires (since they do the same thing - redundant) Utils.addToMapIfAbsent(headers, "cache-control", "public, max-age=" + maxAgeSeconds); - Utils.addToMapIfAbsent(headers, "last-modified", dateTimeFormatter.format(props.lastModifiedTime())); + Utils.addToMapIfAbsent(headers, "last-modified", Utils.formatRFC1123DateTime(props.lastModifiedTime())); // We send the vary header (for intermediate caches) // (assumes that most will turn on compression when using static handler) if (sendVaryHeader && request.headers().contains("accept-encoding")) { @@ -121,7 +118,7 @@ public class StaticHandlerImpl implements StaticHandler { } // date header is mandatory - headers.set("date", dateTimeFormatter.format(new Date())); + headers.set("date", Utils.formatRFC1123DateTime(System.currentTimeMillis())); } @Override @@ -742,14 +739,8 @@ public class StaticHandlerImpl implements StaticHandler { // Not a conditional request return false; } - Date ifModifiedSinceDate; - try { - ifModifiedSinceDate = dateTimeFormatter.parse(ifModifiedSince); - } catch (ParseException e) { - // Behave like the header is not present - return false; - } - boolean modifiedSince = Utils.secondsFactor(props.lastModifiedTime()) > ifModifiedSinceDate.getTime(); + long ifModifiedSinceDate = Utils.parseRFC1123DateTime(ifModifiedSince); + boolean modifiedSince = Utils.secondsFactor(props.lastModifiedTime()) > ifModifiedSinceDate; return !modifiedSince; } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java index 47ff09536..c2dff873a 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java @@ -32,6 +32,12 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Locale; import java.util.TimeZone; @@ -91,10 +97,19 @@ public class Utils extends io.vertx.core.impl.Utils { } } - public static DateFormat createRFC1123DateTimeFormatter() { - DateFormat dtf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - dtf.setTimeZone(TimeZone.getTimeZone("GMT")); - return dtf; + private static final ZoneId ZONE_GMT = ZoneId.of("GMT"); + + public static String formatRFC1123DateTime(final long time) { + return DateTimeFormatter.RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(time).atZone(ZONE_GMT)); + } + + public static long parseRFC1123DateTime(final String header) { + try { + return header == null || header.isEmpty() ? -1 : + LocalDateTime.parse(header, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant(ZoneOffset.UTC).toEpochMilli(); + } catch (DateTimeParseException ex) { + return -1; + } } public static String pathOffset(String path, RoutingContext context) { diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java index 7a2d3dd07..710fa3e14 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java @@ -22,7 +22,6 @@ import io.vertx.ext.web.impl.Utils; import io.vertx.ext.web.WebTestBase; import org.junit.Test; -import java.text.DateFormat; import java.util.*; /** @@ -137,8 +136,8 @@ public class CookieHandlerTest extends WebTestBase { int startPos = encoded.indexOf("Expires="); int endPos = encoded.indexOf(';', startPos); String expiresDate = encoded.substring(startPos + 8, endPos); - Date d = dateTimeFormat.parse(expiresDate); - assertTrue(d.getTime() - now >= maxAge); + long d = Utils.parseRFC1123DateTime(expiresDate); + assertTrue(d - now >= maxAge); cookie.setMaxAge(Long.MIN_VALUE); cookie.setSecure(true); @@ -146,6 +145,4 @@ public class CookieHandlerTest extends WebTestBase { cookie.setHttpOnly(true); assertEquals("foo=bar; Path=/somepath; Domain=foo.com; Secure; HTTPOnly", cookie.encode()); } - - private final DateFormat dateTimeFormat = Utils.createRFC1123DateTimeFormatter(); } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java index 375d48ee5..2134a80dd 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java @@ -19,13 +19,11 @@ package io.vertx.ext.web.handler; import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.Session; import io.vertx.ext.web.WebTestBase; -import io.vertx.ext.web.impl.Utils; import io.vertx.ext.web.sstore.AbstractSession; import io.vertx.ext.web.sstore.LocalSessionStore; import io.vertx.ext.web.sstore.SessionStore; import org.junit.Test; -import java.text.DateFormat; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -360,8 +358,6 @@ public abstract class SessionHandlerTestBase extends WebTestBase { resp -> assertNull(resp.headers().get("set-cookie")), 200, "OK", null); } - private final DateFormat dateTimeFormatter = Utils.createRFC1123DateTimeFormatter(); - protected long doTestSessionRetryTimeout() throws Exception { router.route().handler(SessionHandler.create(store)); AtomicReference<Session> rid = new AtomicReference<>(); diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java index da95bbee3..e10672e45 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java @@ -16,7 +16,6 @@ package io.vertx.ext.web.handler; -import io.vertx.core.Handler; import io.vertx.core.http.*; import io.vertx.core.json.JsonArray; import io.vertx.core.net.PemKeyCertOptions; @@ -29,7 +28,6 @@ import org.junit.Test; import java.io.File; import java.nio.file.Files; -import java.text.DateFormat; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; @@ -40,8 +38,6 @@ import java.util.function.BiConsumer; */ public class StaticHandlerTest extends WebTestBase { - private final DateFormat dateTimeFormatter = Utils.createRFC1123DateTimeFormatter(); - protected StaticHandler stat; @Override @@ -307,7 +303,7 @@ public class StaticHandlerTest extends WebTestBase { @Test public void testCacheGetNew() throws Exception { - testCacheReturnFromCache((lastModified, req) -> req.putHeader("if-modified-since", dateTimeFormatter.format(toDateTime(lastModified) - 1)), 200, "OK", "<html><body>Other page</body></html>"); + testCacheReturnFromCache((lastModified, req) -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(toDateTime(lastModified) - 1)), 200, "OK", "<html><body>Other page</body></html>"); } @Test @@ -442,7 +438,7 @@ public class StaticHandlerTest extends WebTestBase { String lastModified = res.headers().get("last-modified"); assertEquals(modified, toDateTime(lastModified)); }, 200, "OK", "<html><body>File system page</body></html>"); - testRequest(HttpMethod.GET, "/fspage.html", req -> req.putHeader("if-modified-since", dateTimeFormatter.format(modified)), null, 304, "Not Modified", null); + testRequest(HttpMethod.GET, "/fspage.html", req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), null, 304, "Not Modified", null); } @Test @@ -458,7 +454,7 @@ public class StaticHandlerTest extends WebTestBase { resource.setLastModified(modified + 1000); }, 200, "OK", "<html><body>File system page</body></html>"); // But it should still return not modified as the entry is cached - testRequest(HttpMethod.GET, "/fspage.html", req -> req.putHeader("if-modified-since", dateTimeFormatter.format(modified)), null, 304, "Not Modified", null); + testRequest(HttpMethod.GET, "/fspage.html", req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), null, 304, "Not Modified", null); } @Test @@ -481,7 +477,7 @@ public class StaticHandlerTest extends WebTestBase { }, 200, "OK", html); // But it should return a new entry as the entry is now old Thread.sleep(cacheEntryTimeout + 1); - testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", dateTimeFormatter.format(modified)), res -> { + testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), res -> { String lastModified = res.headers().get("last-modified"); assertEquals(modified + 1000, toDateTime(lastModified)); }, 200, "OK", html); @@ -489,7 +485,7 @@ public class StaticHandlerTest extends WebTestBase { // 304 must still work when cacheEntry.isOutOfDate() == true, https://github.com/vert-x3/vertx-web/issues/726 Thread.sleep(cacheEntryTimeout + 1); - testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", dateTimeFormatter.format(modified + 1000)), 304, "Not Modified", null); + testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified + 1000)), 304, "Not Modified", null); } @Test @@ -506,10 +502,10 @@ public class StaticHandlerTest extends WebTestBase { stat.setCacheEntryTimeout(3600 * 1000); long modified = Utils.secondsFactor(pageFile.lastModified()); - testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", dateTimeFormatter.format(modified)), null, 304, "Not Modified", null); + testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), null, 304, "Not Modified", null); pageFile.delete(); testRequest(HttpMethod.GET, page, 404, "Not Found"); - testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", dateTimeFormatter.format(modified)), null, 404, "Not Found", null); + testRequest(HttpMethod.GET, page, req -> req.putHeader("if-modified-since", Utils.formatRFC1123DateTime(modified)), null, 404, "Not Found", null); } @@ -855,8 +851,7 @@ public class StaticHandlerTest extends WebTestBase { private long toDateTime(String header) { try { - Date date = dateTimeFormatter.parse(header); - return date.getTime(); + return Utils.parseRFC1123DateTime(header); } catch (Exception e) { fail(e.getMessage()); return -1;
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/StaticHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/Utils.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/SessionHandlerTestBase.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/CookieHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/LoggerHandlerImpl.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/StaticHandlerTest.java']
    {'.java': 6}
    6
    6
    0
    0
    6
    1,211,345
    271,625
    38,526
    292
    2,339
    482
    49
    3
    1,389
    194
    298
    9
    3
    1
    1970-01-01T00:26:11
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,250
    vert-x3/vertx-web/1998/1996
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1996
    https://github.com/vert-x3/vertx-web/pull/1998
    https://github.com/vert-x3/vertx-web/pull/1998
    1
    fixes
    Hosted OpenAPI document relative `$ref` values replaced with absolute file paths
    ### Version 4.1.0 ### Context When hosting an OpenAPI document using `io.vertx.ext.web.openapi.RouterBuilder` with `io.vertx.ext.web.openapi.RouterBuilderOptions#setContractEndpoint`, the hosted document has absolute paths in `$ref` attribute values. It appears the relative references (i.e. to `#/components/...`) were replaced for the purposes of validation. However, the relative paths should still be present in the hosted document returned from HTTP GET at `/openapi` (or whatever the contract endpoint is configured to be). ### Do you have a reproducer? Not yet, but I can put something together if necessary. ### Extra N/A
    bb945a87766b61f2c5e62690305406a811cd9e55
    d427e10d3a696ace43360000ed8b2c1cdfee6777
    https://github.com/vert-x3/vertx-web/compare/bb945a87766b61f2c5e62690305406a811cd9e55...d427e10d3a696ace43360000ed8b2c1cdfee6777
    diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java index f227a422c..c092f22bb 100755 --- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java +++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java @@ -76,7 +76,7 @@ public class OpenAPIHolderImpl implements OpenAPIHolder { }) .compose(openapi -> { absolutePaths.put(initialScope, openapi); // Circular refs hell! - openapiRoot = openapi; + openapiRoot = openapi.copy(); return walkAndSolve(openapi, initialScope).map(openapi); }) .compose(openapi -> { diff --git a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java index b799caacb..2b92e6e9f 100755 --- a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java +++ b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java @@ -224,6 +224,20 @@ public class OpenAPIHolderTest { "src/test/resources/yaml/valid/local_refs.yaml#/components/schemas/Simple" ).toString()); + // Verify the OpenAPI object stored by the OpenAPIHolder retains local refs. + assertThat(loader.getOpenAPI()) + .extracting(JsonPointer.create() + .append("paths") + .append("/simple") + .append("post") + .append("requestBody") + .append("content") + .append("multipart/form-data") + .append("schema") + .append("$ref") + ) + .isEqualTo("#/components/schemas/Simple"); + assertThat(loader) .hasCached(resolveAbsoluteURIFromFS("src/test/resources/yaml/valid/refs/Simple.yaml")); @@ -645,7 +659,7 @@ public class OpenAPIHolderTest { )).append(Arrays.asList( "paths", "/test8", "post", "requestBody", "content", "application/json", "schema" )); - JsonObject resolved = (JsonObject) schemaPointer.query(loader.getOpenAPI(), + JsonObject resolved = (JsonObject) schemaPointer.query(l.result(), new JsonPointerIteratorWithLoader(loader)); Map<JsonPointer, JsonObject> additionalSchemasToRegister = new HashMap<>();
    ['vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderImpl.java', 'vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/impl/OpenAPIHolderTest.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,763,022
    390,341
    54,569
    436
    70
    17
    2
    1
    653
    85
    142
    16
    0
    0
    1970-01-01T00:27:06
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,273
    vert-x3/vertx-web/986/943
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/943
    https://github.com/vert-x3/vertx-web/pull/986
    https://github.com/vert-x3/vertx-web/pull/986
    1
    fixes
    ParsableHeaderValue::parameter does not call ensureHeaderProcessed
    `ParsableHeaderValue::parameter` does not call `ensureHeaderProcessed`. Because of this, the function will return `null` even though there is a parameter. Same goes for `parameters` Workaround is to call `value` first
    b1af8b3be4081a4a956853c5aa8c8a15685be6d2
    9a3e485bf68656793363d36e7aaaf52bbe1d1fa4
    https://github.com/vert-x3/vertx-web/compare/b1af8b3be4081a4a956853c5aa8c8a15685be6d2...9a3e485bf68656793363d36e7aaaf52bbe1d1fa4
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java index 596d7071e..b46cdfd77 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java @@ -54,10 +54,12 @@ public class ParsableHeaderValue implements ParsedHeaderValue { } public String parameter(String key) { + ensureHeaderProcessed(); return parameter.get(key); } public Map<String, String> parameters() { + ensureHeaderProcessed(); return Collections.unmodifiableMap(parameter); }
    ['vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValue.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    926,962
    209,607
    29,639
    223
    59
    10
    2
    1
    223
    29
    50
    5
    0
    0
    1970-01-01T00:25:32
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,240
    vert-x3/vertx-web/2187/2182
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2182
    https://github.com/vert-x3/vertx-web/pull/2187
    https://github.com/vert-x3/vertx-web/pull/2187
    1
    fixes
    Upgrading to 4.3.0 fails at the router Creation
    I just upgraded to 4.3.0 from 4.2.7 and now the router creation fails with Cannot add [SECURITY_POLICY] handler to route with [BODY] handler at index 0. java.lang.IllegalStateException: Cannot add [SECURITY_POLICY] handler to route with [BODY] handler at index 0 at io.vertx.ext.web.impl.RouteState.addContextHandler(RouteState.java:546) at io.vertx.ext.web.impl.RouteImpl.handler(RouteImpl.java:143) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at io.vertx.ext.web.openapi.impl.OpenAPI3RouterBuilderImpl.createRouter(OpenAPI3RouterBuilderImpl.java:268) Here is a projecto to reproduce the error, in the pom file you can swap from 4.2.7 and 4.3.0 https://github.com/yazalulloa/vertx-openapi-changes-4.3.0 Edit: After reading the changes in https://vertx.io/blog/whats-new-in-vert-x-4-3/#vertx-web I reordered the handlers according to the documentation: 1 - PLATFORM: plat­form han­dlers (LoggerHandler, FaviconHandler, etc.) 2 - SECURITY_POLICY: HTTP Se­cu­rity poli­cies (CSPHandler, CorsHandler, etc.) 3 - BODY: Body pars­ing (BodyHandler) 4 - AUTHENTICATION: Authn (JWTAuthHandler, APIKeyHandler, WebauthnHandler, etc.) 5 - INPUT_TRUST: Input ver­i­fi­ca­tion (CSRFHandler) 6 - AUTHORIZATION: Authz (AuthorizationHandler) But it still fails with Cannot add [PLATFORM] handler to route with [BODY] handler at index 0
    553c190b657a928af84fb5ffba0c6d3bfa70feba
    101f13f33b847ad8c70e47fbd889546c420103df
    https://github.com/vert-x3/vertx-web/compare/553c190b657a928af84fb5ffba0c6d3bfa70feba...101f13f33b847ad8c70e47fbd889546c420103df
    diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java index fc1395d2a..ffadb3128 100644 --- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java +++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java @@ -79,9 +79,15 @@ public interface RouterBuilder { * * @param bodyHandler * @return self + * + * @deprecated Use {@link #rootHandler(Handler)} instead. The order matters, so adding the body handler should + * happen after any {@code PLATFORM} or {@code SECURITY_POLICY} handler(s). */ @Fluent - RouterBuilder bodyHandler(@Nullable BodyHandler bodyHandler); + @Deprecated + default RouterBuilder bodyHandler(@Nullable BodyHandler bodyHandler) { + return rootHandler(bodyHandler); + } /** * Add global handler to be applied prior to {@link Router} being generated. <br/> diff --git a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java index 6b3f3bb43..6e8c648c2 100644 --- a/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java +++ b/vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java @@ -51,23 +51,21 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder { }; } - private Vertx vertx; - private OpenAPIHolder openapi; + private final Vertx vertx; + private final OpenAPIHolder openapi; private RouterBuilderOptions options; - private Map<String, OperationImpl> operations; - private BodyHandler bodyHandler; - private AuthenticationHandlersStore securityHandlers; - private List<Handler<RoutingContext>> globalHandlers; + private final Map<String, OperationImpl> operations; + private final AuthenticationHandlersStore securityHandlers; + private final List<Handler<RoutingContext>> globalHandlers; private Function<RoutingContext, JsonObject> serviceExtraPayloadMapper; - private SchemaRouter schemaRouter; - private OpenAPI3SchemaParser schemaParser; - private OpenAPI3ValidationHandlerGenerator validationHandlerGenerator; + private final SchemaRouter schemaRouter; + private final OpenAPI3SchemaParser schemaParser; + private final OpenAPI3ValidationHandlerGenerator validationHandlerGenerator; public OpenAPI3RouterBuilderImpl(Vertx vertx, HttpClient client, OpenAPIHolderImpl spec, OpenAPILoaderOptions options) { this.vertx = vertx; this.openapi = spec; this.options = new RouterBuilderOptions(); - this.bodyHandler = BodyHandler.create(); this.globalHandlers = new ArrayList<>(); this.schemaRouter = SchemaRouter.create(vertx, client, vertx.fileSystem(), options.toSchemaRouterOptions()); this.schemaParser = OpenAPI3SchemaParser.create(schemaRouter); @@ -75,7 +73,7 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder { this.schemaParser.withStringFormatValidator("binary", v -> true); this.validationHandlerGenerator = new OpenAPI3ValidationHandlerGenerator(spec, schemaParser); - spec.getAbsolutePaths().forEach((u, jo) -> schemaRouter.addJson(u, jo)); + spec.getAbsolutePaths().forEach(schemaRouter::addJson); // Load default generators this.validationHandlerGenerator @@ -181,12 +179,6 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder { return this.operations.get(operationId); } - @Override - public RouterBuilder bodyHandler(BodyHandler bodyHandler) { - this.bodyHandler = bodyHandler; - return this; - } - @Override public RouterBuilder rootHandler(Handler<RoutingContext> rootHandler) { this.globalHandlers.add(rootHandler); @@ -262,8 +254,9 @@ public class OpenAPI3RouterBuilderImpl implements RouterBuilder { public Router createRouter() { Router router = Router.router(vertx); Route globalRoute = router.route(); - if (bodyHandler != null) { - globalRoute.handler(bodyHandler); + if (globalHandlers.isEmpty()) { + // TODO: this is very opinionated + globalRoute.handler(BodyHandler.create()); } globalHandlers.forEach(globalRoute::handler); diff --git a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java index 2ce74cca8..89c87d624 100644 --- a/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java +++ b/vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java @@ -14,8 +14,7 @@ import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Route; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.handler.BodyHandler; -import io.vertx.ext.web.handler.StaticHandler; +import io.vertx.ext.web.handler.*; import io.vertx.ext.web.multipart.MultipartForm; import io.vertx.ext.web.validation.BodyProcessorException; import io.vertx.ext.web.validation.ParameterProcessorException; @@ -156,7 +155,6 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { RouterBuilder routerBuilder = routerBuilderAsyncResult.result(); routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - routerBuilder.bodyHandler(null); Router router = routerBuilder.createRouter(); @@ -205,15 +203,15 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { Checkpoint checkpoint = testContext.checkpoint(); loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); + routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - routerBuilder.operation("listPets").handler(routingContext -> - routingContext - .response() - .setStatusCode(200) - .end() - ); - }).onComplete(h -> + routerBuilder.operation("listPets").handler(routingContext -> + routingContext + .response() + .setStatusCode(200) + .end() + ); + }).onComplete(h -> testRequest(client, HttpMethod.GET, "/pets") .expect(statusCode(200)) .send(testContext, checkpoint) @@ -225,18 +223,18 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { Checkpoint checkpoint = testContext.checkpoint(); loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); + routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - routerBuilder - .operation("listPets") - .handler(routingContext -> routingContext.fail(null)) - .failureHandler(routingContext -> routingContext - .response() - .setStatusCode(500) - .setStatusMessage("ERROR") - .end() - ); - }).onComplete(h -> + routerBuilder + .operation("listPets") + .handler(routingContext -> routingContext.fail(null)) + .failureHandler(routingContext -> routingContext + .response() + .setStatusCode(500) + .setStatusMessage("ERROR") + .end() + ); + }).onComplete(h -> testRequest(client, HttpMethod.GET, "/pets") .expect(statusCode(500), statusMessage("ERROR")) .send(testContext, checkpoint) @@ -248,30 +246,30 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { Checkpoint checkpoint = testContext.checkpoint(); loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); + routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - routerBuilder - .operation("listPets") - .handler(routingContext -> - routingContext.put("message", "A").next() - ) - .handler(routingContext -> { - routingContext.put("message", routingContext.get("message") + "B"); - routingContext.fail(500); - }); - routerBuilder - .operation("listPets") - .failureHandler(routingContext -> - routingContext.put("message", routingContext.get("message") + "E").next() - ) - .failureHandler(routingContext -> - routingContext - .response() - .setStatusCode(500) - .setStatusMessage(routingContext.get("message")) - .end() - ); - }).onComplete(h -> + routerBuilder + .operation("listPets") + .handler(routingContext -> + routingContext.put("message", "A").next() + ) + .handler(routingContext -> { + routingContext.put("message", routingContext.get("message") + "B"); + routingContext.fail(500); + }); + routerBuilder + .operation("listPets") + .failureHandler(routingContext -> + routingContext.put("message", routingContext.get("message") + "E").next() + ) + .failureHandler(routingContext -> + routingContext + .response() + .setStatusCode(500) + .setStatusMessage(routingContext.get("message")) + .end() + ); + }).onComplete(h -> testRequest(client, HttpMethod.GET, "/pets") .expect(statusCode(500), statusMessage("ABE")) .send(testContext, checkpoint) @@ -287,29 +285,29 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { Checkpoint checkpoint = testContext.checkpoint(4); loadBuilderAndStartServer(vertx, "src/test/resources/specs/path_matching_order.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); + routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - routerBuilder - .operation("searchPets") - .handler(routingContext -> { - routingContext.response().setStatusMessage("searchPets").end(); - }); - routerBuilder - .operation("searchPetsInShop") - .handler(routingContext -> { - routingContext.response().setStatusMessage("searchPetsInShop").end(); - }); - routerBuilder - .operation("addPet") - .handler(routingContext -> { - routingContext.response().setStatusMessage("addPet").end(); - }); + routerBuilder + .operation("searchPets") + .handler(routingContext -> { + routingContext.response().setStatusMessage("searchPets").end(); + }); + routerBuilder + .operation("searchPetsInShop") + .handler(routingContext -> { + routingContext.response().setStatusMessage("searchPetsInShop").end(); + }); + routerBuilder + .operation("addPet") + .handler(routingContext -> { + routingContext.response().setStatusMessage("addPet").end(); + }); routerBuilder .operation("addPetToShop") .handler(routingContext -> { routingContext.response().setStatusMessage("addPetToShop").end(); }); - }).onComplete(h -> { + }).onComplete(h -> { testRequest(client, HttpMethod.POST, "/pets/wolfie") .expect(statusCode(200), statusMessage("addPet")) .sendJson(new JsonObject(), testContext, checkpoint); @@ -334,13 +332,13 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { Checkpoint checkpoint = testContext.checkpoint(); loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions( - new RouterBuilderOptions() - .setRequireSecurityHandlers(false) - .setMountNotImplementedHandler(true) - ); - routerBuilder.operation("showPetById").handler(RoutingContext::next); - }).onComplete(h -> + routerBuilder.setOptions( + new RouterBuilderOptions() + .setRequireSecurityHandlers(false) + .setMountNotImplementedHandler(true) + ); + routerBuilder.operation("showPetById").handler(RoutingContext::next); + }).onComplete(h -> testRequest(client, HttpMethod.GET, "/pets") .expect(statusCode(501), statusMessage("Not Implemented")) .send(testContext, checkpoint) @@ -353,15 +351,15 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions( - new RouterBuilderOptions() - .setRequireSecurityHandlers(false) - .setMountNotImplementedHandler(true) - ); + routerBuilder.setOptions( + new RouterBuilderOptions() + .setRequireSecurityHandlers(false) + .setMountNotImplementedHandler(true) + ); - routerBuilder.operation("deletePets").handler(RoutingContext::next); - routerBuilder.operation("createPets").handler(RoutingContext::next); - }).onComplete(rc -> + routerBuilder.operation("deletePets").handler(RoutingContext::next); + routerBuilder.operation("createPets").handler(RoutingContext::next); + }).onComplete(rc -> testRequest(client, HttpMethod.GET, "/pets") .expect(statusCode(405), statusMessage("Method Not Allowed")) .expect(resp -> @@ -375,23 +373,23 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { public void addGlobalHandlersTest(Vertx vertx, VertxTestContext testContext) { loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false)); - - routerBuilder.rootHandler(rc -> { - rc.response().putHeader("header-from-global-handler", "some dummy data"); - rc.next(); - }).rootHandler(rc -> { - rc.response().putHeader("header-from-global-handler", "some more dummy data"); - rc.next(); - }); + routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false)); + + routerBuilder.rootHandler(rc -> { + rc.response().putHeader("header-from-global-handler", "some dummy data"); + rc.next(); + }).rootHandler(rc -> { + rc.response().putHeader("header-from-global-handler", "some more dummy data"); + rc.next(); + }); - routerBuilder.operation("listPets").handler(routingContext -> routingContext - .response() - .setStatusCode(200) - .setStatusMessage("OK") - .end() - ); - }).onComplete(h -> + routerBuilder.operation("listPets").handler(routingContext -> routingContext + .response() + .setStatusCode(200) + .setStatusMessage("OK") + .end() + ); + }).onComplete(h -> testRequest(client, HttpMethod.GET, "/pets") .expect(statusCode(200)) .expect(responseHeader("header-from-global-handler", "some more dummy data")) @@ -405,22 +403,22 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setOperationModelKey( - "fooBarKey")); + routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setOperationModelKey( + "fooBarKey")); - routerBuilder.operation("listPets").handler(routingContext -> { - JsonObject operation = routingContext.get("fooBarKey"); + routerBuilder.operation("listPets").handler(routingContext -> { + JsonObject operation = routingContext.get("fooBarKey"); - routingContext - .response() - .setStatusCode(200) - .setStatusMessage(operation.getString("operationId")) - .end(); - }); - }).onComplete(h -> - testRequest(client, HttpMethod.GET, "/pets") - .expect(statusCode(200), statusMessage("listPets")) - .send(testContext, checkpoint) + routingContext + .response() + .setStatusCode(200) + .setStatusMessage(operation.getString("operationId")) + .end(); + }); + }).onComplete(h -> + testRequest(client, HttpMethod.GET, "/pets") + .expect(statusCode(200), statusMessage("listPets")) + .send(testContext, checkpoint) ); } @@ -430,24 +428,24 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { loadBuilderAndStartServer(vertx, "src/test/resources/specs/produces_consumes_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false)); + routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false)); - routerBuilder.operation("consumesTest").handler(routingContext -> { - RequestParameters params = routingContext.get("parsedParameters"); - if (params.body() != null && params.body().isJsonObject()) { - routingContext - .response() - .setStatusCode(200) - .putHeader("Content-Type", "application/json") - .end(params.body().getJsonObject().encode()); - } else { - routingContext - .response() + routerBuilder.operation("consumesTest").handler(routingContext -> { + RequestParameters params = routingContext.get("parsedParameters"); + if (params.body() != null && params.body().isJsonObject()) { + routingContext + .response() + .setStatusCode(200) + .putHeader("Content-Type", "application/json") + .end(params.body().getJsonObject().encode()); + } else { + routingContext + .response() .setStatusCode(200) .end(); } }); - }).onComplete(h -> { + }).onComplete(h -> { JsonObject obj = new JsonObject().put("name", "francesco"); testRequest(client, HttpMethod.POST, "/consumesTest") .expect(statusCode(200)) @@ -481,19 +479,19 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { loadBuilderAndStartServer(vertx, "src/test/resources/specs/produces_consumes_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false)); + routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false)); - routerBuilder.operation("producesTest").handler(routingContext -> { - if (((RequestParameters) routingContext.get("parsedParameters")).queryParameter("fail").getBoolean()) - routingContext - .response() - .putHeader("content-type", "text/plain") - .setStatusCode(500) - .end("Hate it"); - else - routingContext.response().setStatusCode(200).end("{}"); // ResponseContentTypeHandler does the job for me - }); - }).onComplete(h -> { + routerBuilder.operation("producesTest").handler(routingContext -> { + if (((RequestParameters) routingContext.get("parsedParameters")).queryParameter("fail").getBoolean()) + routingContext + .response() + .putHeader("content-type", "text/plain") + .setStatusCode(500) + .end("Hate it"); + else + routingContext.response().setStatusCode(200).end("{}"); // ResponseContentTypeHandler does the job for me + }); + }).onComplete(h -> { String acceptableContentTypes = String.join(", ", "application/json", "text/plain"); testRequest(client, HttpMethod.GET, "/producesTest") .with(requestHeader("Accept", acceptableContentTypes)) @@ -522,7 +520,7 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { routingContext.response().setStatusMessage(params.pathParameter("id").getInteger().toString()).end(); }); - testContext.completeNow(); + testContext.completeNow(); }).onComplete(h -> { testRequest(client, HttpMethod.GET, "/product/special") .expect(statusCode(200), statusMessage("special")) @@ -539,21 +537,21 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); + routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - routerBuilder.operation("encodedParamTest").handler(routingContext -> { - RequestParameters params = routingContext.get("parsedParameters"); - assertThat(params.pathParameter("p1").toString()).isEqualTo("a:b"); - assertThat(params.queryParameter("p2").toString()).isEqualTo("a:b"); - routingContext - .response() - .setStatusCode(200) - .setStatusMessage(params.pathParameter("p1").toString()) - .end(); - }); + routerBuilder.operation("encodedParamTest").handler(routingContext -> { + RequestParameters params = routingContext.get("parsedParameters"); + assertThat(params.pathParameter("p1").toString()).isEqualTo("a:b"); + assertThat(params.queryParameter("p2").toString()).isEqualTo("a:b"); + routingContext + .response() + .setStatusCode(200) + .setStatusMessage(params.pathParameter("p1").toString()) + .end(); + }); testContext.completeNow(); - }).onComplete(h -> + }).onComplete(h -> testRequest(client, HttpMethod.GET, "/foo/a%3Ab?p2=a%3Ab") .expect(statusCode(200), statusMessage("a:b")) .send(testContext, checkpoint) @@ -572,7 +570,7 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { BodyHandler bodyHandler = BodyHandler.create("my-uploads"); - routerBuilder.bodyHandler(bodyHandler); + routerBuilder.rootHandler(bodyHandler); routerBuilder.operation("upload").handler(routingContext -> routingContext.response().setStatusCode(201).end()); @@ -595,23 +593,23 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { loadBuilderAndStartServer(vertx, "src/test/resources/specs/shared_request_body.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); + routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS); - final Handler<RoutingContext> handler = routingContext -> { - RequestParameters params = routingContext.get("parsedParameters"); - RequestParameter body = params.body(); - JsonObject jsonBody = body.getJsonObject(); - routingContext - .response() - .setStatusCode(200) - .setStatusMessage("OK") - .putHeader("Content-Type", "application/json") - .end(jsonBody.toBuffer()); - }; + final Handler<RoutingContext> handler = routingContext -> { + RequestParameters params = routingContext.get("parsedParameters"); + RequestParameter body = params.body(); + JsonObject jsonBody = body.getJsonObject(); + routingContext + .response() + .setStatusCode(200) + .setStatusMessage("OK") + .putHeader("Content-Type", "application/json") + .end(jsonBody.toBuffer()); + }; - routerBuilder.operation("thisWayWorks").handler(handler); - routerBuilder.operation("thisWayBroken").handler(handler); - }).onComplete(h -> { + routerBuilder.operation("thisWayWorks").handler(handler); + routerBuilder.operation("thisWayBroken").handler(handler); + }).onComplete(h -> { JsonObject obj = new JsonObject().put("id", "aaa").put("name", "bla"); testRequest(client, HttpMethod.POST, "/v1/working") .expect(statusCode(200)) @@ -628,44 +626,44 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { public void pathResolverShouldNotCreateRegex(Vertx vertx, VertxTestContext testContext) { RouterBuilder.create(vertx, "src/test/resources/specs/produces_consumes_test.yaml", testContext.succeeding(routerBuilder -> { - routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false)); + routerBuilder.setOptions(new RouterBuilderOptions().setMountNotImplementedHandler(false)); - routerBuilder.operation("consumesTest").handler(routingContext -> - routingContext - .response() - .setStatusCode(200) - .setStatusMessage("OK") - ); + routerBuilder.operation("consumesTest").handler(routingContext -> + routingContext + .response() + .setStatusCode(200) + .setStatusMessage("OK") + ); - testContext.verify(() -> + testContext.verify(() -> assertThat(routerBuilder.createRouter().getRoutes()) .extracting(Route::getPath) .anyMatch("/consumesTest"::equals) ); testContext.completeNow(); - })); + })); } @Test public void testJsonEmptyBody(Vertx vertx, VertxTestContext testContext) { loadBuilderAndStartServer(vertx, "src/test/resources/specs/router_builder_test.yaml", testContext, routerBuilder -> { - routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setMountNotImplementedHandler(false)); + routerBuilder.setOptions(new RouterBuilderOptions().setRequireSecurityHandlers(false).setMountNotImplementedHandler(false)); - routerBuilder.operation("jsonEmptyBody").handler(routingContext -> { - RequestParameters params = routingContext.get("parsedParameters"); - RequestParameter body = params.body(); - routingContext - .response() - .setStatusCode(200) - .setStatusMessage("OK") - .putHeader("Content-Type", "application/json") - .end(new JsonObject().put("bodyEmpty", body == null).toBuffer()); - }); + routerBuilder.operation("jsonEmptyBody").handler(routingContext -> { + RequestParameters params = routingContext.get("parsedParameters"); + RequestParameter body = params.body(); + routingContext + .response() + .setStatusCode(200) + .setStatusMessage("OK") + .putHeader("Content-Type", "application/json") + .end(new JsonObject().put("bodyEmpty", body == null).toBuffer()); + }); testContext.completeNow(); - }).onComplete(h -> + }).onComplete(h -> testRequest(client, HttpMethod.POST, "/jsonBody/empty") .expect(statusCode(200), jsonBodyResponse(new JsonObject().put("bodyEmpty", true))) .send(testContext) @@ -1547,4 +1545,44 @@ public class RouterBuilderIntegrationTest extends BaseRouterBuilderTest { }); } + @Test + public void testProperOrderOfHandlers(Vertx vertx, VertxTestContext testContext) { + loadBuilderAndStartServer(vertx, VALIDATION_SPEC, testContext, routerBuilder -> { + + routerBuilder.rootHandler(LoggerHandler.create(true, LoggerHandler.DEFAULT_FORMAT)); + routerBuilder.rootHandler(TimeoutHandler.create(180000)); + routerBuilder.rootHandler(CorsHandler.create("*")); + routerBuilder.rootHandler(BodyHandler.create().setBodyLimit(40000000).setDeleteUploadedFilesOnEnd(true).setHandleFileUploads(true)); + + routerBuilder + .operation("listPets") + .handler(routingContext -> routingContext.response().setStatusMessage("ok").end()); + }).onComplete(h -> + testRequest(client, HttpMethod.GET, "/pets") + .expect(statusCode(200), statusMessage("ok")) + .send(testContext) + ); + } + + @Test + public void testIncorrectOrderOfHandlers(Vertx vertx, VertxTestContext testContext) { + + RouterBuilder.create(vertx, VALIDATION_SPEC, testContext.succeeding(routerBuilder -> { + routerBuilder.rootHandler(BodyHandler.create().setBodyLimit(40000000).setDeleteUploadedFilesOnEnd(true).setHandleFileUploads(true)); + routerBuilder.rootHandler(LoggerHandler.create(true, LoggerHandler.DEFAULT_FORMAT)); + routerBuilder.rootHandler(TimeoutHandler.create(180000)); + routerBuilder.rootHandler(CorsHandler.create("*")); + + routerBuilder + .operation("listPets") + .handler(routingContext -> routingContext.response().setStatusMessage("ok").end()); + + try { + routerBuilder.createRouter(); + testContext.failNow("Should not reach here"); + } catch (IllegalStateException ise) { + testContext.completeNow(); + } + })); + } }
    ['vertx-web-openapi/src/test/java/io/vertx/ext/web/openapi/RouterBuilderIntegrationTest.java', 'vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/RouterBuilder.java', 'vertx-web-openapi/src/main/java/io/vertx/ext/web/openapi/impl/OpenAPI3RouterBuilderImpl.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,966,252
    436,577
    61,001
    482
    1,762
    365
    39
    2
    1,371
    141
    371
    24
    2
    0
    1970-01-01T00:27:33
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,271
    vert-x3/vertx-web/1245/983
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/983
    https://github.com/vert-x3/vertx-web/pull/1245
    https://github.com/vert-x3/vertx-web/pull/1245
    1
    fixes
    */* produces does not limit AcceptableContentType based on Accept header
    ### Version * vert.x core: 3.6.0-SNAPSHOT * vert.x web: 3.6.0-SNAPSHOT ### Context When a route can produce `*/*` and the client specifies a specific content type via the Accept header, AcceptableContentType returns `*/*` instead of the client specified content type. To figure out what the client is requesting, you have to examine the parsed Accept header yourself. ### Steps to reproduce Sample code: ``` public static void main(String[] args) { Vertx vertx = Vertx.vertx(); HttpServer server = vertx.createHttpServer(); Router router = Router.router(vertx); router.route().produces("*/*").handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.end("Accept headers are:" + routingContext.parsedHeaders().accept().stream().map(ParsedHeaderValue::rawValue).collect(Collectors.toList()) + "\\nAcceptable Content Type is " + routingContext.getAcceptableContentType()); }); server.requestHandler(router).listen(8080); } ``` Start up above server. ``` curl -H "Accept: application/json" localhost:8080 Accept headers are:[application/json] Acceptable Content Type is */* ``` I would expect Acceptable Content Type to be `application/json`
    9147d85ad6b300f6b75cd56907f594043797003c
    d152aaf0aa21a99bc456adc733f992d759c8b483
    https://github.com/vert-x3/vertx-web/compare/9147d85ad6b300f6b75cd56907f594043797003c...d152aaf0aa21a99bc456adc733f992d759c8b483
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java b/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java index 54e1a1777..b54d8171b 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java @@ -1,11 +1,11 @@ package io.vertx.ext.web; -import java.util.Collection; -import java.util.List; - import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.VertxGen; +import java.util.Collection; +import java.util.List; + /** * A container with the request's headers that are meaningful enough to be parsed * Contains: @@ -54,5 +54,5 @@ public interface ParsedHeaderValues { * @return The first header that matched, otherwise empty if none matched */ @GenIgnore - <T extends ParsedHeaderValue> T findBestUserAcceptedIn(List<T> accepted, Collection<T> in); + MIMEHeader findBestUserAcceptedIn(List<MIMEHeader> accepted, Collection<MIMEHeader> in); } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java index a9c528c06..1ae8bf71a 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java @@ -1,13 +1,13 @@ package io.vertx.ext.web.impl; -import java.util.Collection; -import java.util.List; - import io.vertx.ext.web.LanguageHeader; import io.vertx.ext.web.MIMEHeader; import io.vertx.ext.web.ParsedHeaderValue; import io.vertx.ext.web.ParsedHeaderValues; +import java.util.Collection; +import java.util.List; + public class ParsableHeaderValuesContainer implements ParsedHeaderValues { private List<MIMEHeader> accept; @@ -48,11 +48,14 @@ public class ParsableHeaderValuesContainer implements ParsedHeaderValues { } @Override - public <T extends ParsedHeaderValue> T findBestUserAcceptedIn(List<T> userAccepted, Collection<T> in) { - for (T acceptableType: userAccepted) { - T acceptedType = acceptableType.findMatchedBy(in); - if(acceptedType != null){ - return acceptedType; + public MIMEHeader findBestUserAcceptedIn(List<MIMEHeader> userAccepted, Collection<MIMEHeader> in) { + for (MIMEHeader acceptableType: userAccepted) { + MIMEHeader acceptedType = acceptableType.findMatchedBy(in); + if (acceptedType != null) { + if ("*".equals(acceptedType.subComponent()) || "*".equals(acceptedType.component())) + return acceptableType; + else + return acceptedType; } } return null; diff --git a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java index 9019767d1..b469388ae 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java @@ -1088,6 +1088,33 @@ public class RouterTest extends WebTestBase { testRequestWithAccepts(HttpMethod.GET, "/foo", "application/*", 404, "Not Found"); } + @Test + public void testProducesSubtypeWildcardAcceptTextPlain() throws Exception { + router.route().produces("text/*").handler(rc -> { + rc.response().setStatusMessage(rc.getAcceptableContentType()); + rc.response().end(); + }); + testRequestWithAccepts(HttpMethod.GET, "/foo", "text/plain", 200, "text/plain"); + } + + @Test + public void testProducesComponentWildcardAcceptTextPlain() throws Exception { + router.route().produces("*/plain").handler(rc -> { + rc.response().setStatusMessage(rc.getAcceptableContentType()); + rc.response().end(); + }); + testRequestWithAccepts(HttpMethod.GET, "/foo", "text/plain", 200, "text/plain"); + } + + @Test + public void testProducesAllWildcard() throws Exception { + router.route().produces("*/*").handler(rc -> { + rc.response().setStatusMessage(rc.getAcceptableContentType()); + rc.response().end(); + }); + testRequestWithAccepts(HttpMethod.GET, "/foo", "text/plain", 200, "text/plain"); + } + @Test public void testProducesTopLevelTypeWildcard() throws Exception { router.route().produces("application/json").handler(rc -> {
    ['vertx-web/src/main/java/io/vertx/ext/web/ParsedHeaderValues.java', 'vertx-web/src/test/java/io/vertx/ext/web/RouterTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableHeaderValuesContainer.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,117,662
    250,532
    35,342
    278
    1,114
    243
    27
    2
    1,285
    134
    286
    40
    0
    2
    1970-01-01T00:25:55
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,233
    vert-x3/vertx-web/2399/2388
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2388
    https://github.com/vert-x3/vertx-web/pull/2399
    https://github.com/vert-x3/vertx-web/pull/2399
    1
    fix
    ParsableMIMEValue - component() and subComponent() do not ensure the header is parsed
    ### Version 4.3.7 ### Context The `io.vertx.ext.web.impl.ParsableMIMEValue.component()` and `io.vertx.ext.web.impl.ParsableMIMEValue.subComponent()` methods do not call the `ensureHeaderProcessed()` method. As a result, these methods may return `null`. A workaround exists: first call any other method that triggers parsing, e.g. `io.vertx.ext.web.impl.ParsableHeaderValue.value()`. There is also `io.vertx.ext.web.impl.ParsableHeaderValue.forceParse()` but that's an implementation class, i.e. not part of the public API.
    6ab7e72204338712bc1303bce252a9982721917b
    ec366d0056ea438e1aac497a4e66e128678ddf6f
    https://github.com/vert-x3/vertx-web/compare/6ab7e72204338712bc1303bce252a9982721917b...ec366d0056ea438e1aac497a4e66e128678ddf6f
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java index 01d24ed2f..dda7d80c9 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java @@ -17,11 +17,13 @@ public class ParsableMIMEValue extends ParsableHeaderValue implements MIMEHeader @Override public String component() { + ensureHeaderProcessed(); return component; } @Override public String subComponent() { + ensureHeaderProcessed(); return subComponent; }
    ['vertx-web/src/main/java/io/vertx/ext/web/impl/ParsableMIMEValue.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    2,020,811
    448,355
    62,401
    504
    59
    10
    2
    1
    539
    53
    129
    12
    0
    0
    1970-01-01T00:27:59
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,247
    vert-x3/vertx-web/2064/2063
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2063
    https://github.com/vert-x3/vertx-web/pull/2064
    https://github.com/vert-x3/vertx-web/pull/2064
    1
    fixes
    AuthorizationHandlerImpl: hanging requests - ctx.fail() is never called at denied request with all authorizations already cached in session
    ### Version 4.1.1 ### Context When `AuthorizationHandlerImpl` handles a denied request for a user with an active session where all authorizations are already fetched from all providers (at a previous request of the same user session) then `ctx.fail(...)` is never called, which causes the request to hang. ### Steps to reproduce _With sessions/session-cookies enabled:_ 1. Try to access an forbidden ressource -> forbidden is returned 2. Try to access an forbidden ressource again -> the request hangs
    ca67bd5de22f27d4389310c2fde293f9df161a94
    fad10340e34ffce9cdf34841f81301255ad0251c
    https://github.com/vert-x3/vertx-web/compare/ca67bd5de22f27d4389310c2fde293f9df161a94...fad10340e34ffce9cdf34841f81301255ad0251c
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java index 10d4a1b04..e794cea21 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java @@ -44,11 +44,13 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { private final Authorization authorization; private final Collection<AuthorizationProvider> authorizationProviders; + private final Collection<String> authorizationProviderIds; private BiConsumer<RoutingContext, AuthorizationContext> variableHandler; public AuthorizationHandlerImpl(Authorization authorization) { this.authorization = Objects.requireNonNull(authorization); this.authorizationProviders = new ArrayList<>(); + this.authorizationProviderIds = new ArrayList<>(); } @Override @@ -105,7 +107,7 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { final User user = ctx.user(); - if (user == null || !providers.hasNext()) { + if (user == null || !providers.hasNext() || allAuthorizationsFetched(user)) { // resume as the error handler may allow this request to become valid again resume(ctx.request(), parseEnded); ctx.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION); @@ -135,8 +137,8 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { @Override public AuthorizationHandler addAuthorizationProvider(AuthorizationProvider authorizationProvider) { Objects.requireNonNull(authorizationProvider); - this.authorizationProviders.add(authorizationProvider); + this.authorizationProviderIds.add(authorizationProvider.getId()); return this; } @@ -145,4 +147,17 @@ public class AuthorizationHandlerImpl implements AuthorizationHandler { request.resume(); } } + + /** + * Returns <code>true</code> when the authorizations of all available + * providers have been loaded for the given user which may have happened in a + * previous request of the current user session. + * + * @param user + * @return <code>true</code> when the authorizations of all available + * providers have been loaded for the user + */ + private boolean allAuthorizationsFetched(final User user) { + return user.authorizations().getProviderIds().containsAll(authorizationProviderIds); + } }
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthorizationHandlerImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,913,013
    424,082
    59,336
    474
    855
    181
    19
    1
    524
    77
    110
    16
    0
    0
    1970-01-01T00:27:13
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,231
    vert-x3/vertx-web/2413/2219
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2219
    https://github.com/vert-x3/vertx-web/pull/2413
    https://github.com/vert-x3/vertx-web/pull/2413
    1
    fix
    OAuth2AuthHandler.withScope returns new instance rather than updating current instance
    ### Version 4.3.1 ### Context I upgraded from 4.0.0. There were a few changes I needed to make, which went fine. But when testing OAuth with Webex, I got a message saying I was passing an invalid scope. I checked the URL, and no scope was being passed although I called `withScope()` Investigating further, I found OAuth2AuthImpl.withScope() and .withScopes both return a new instance rather than the current instance https://github.com/vert-x3/vertx-web/blob/4.3.1/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java#L240. Other fluent methods return the same instance. ### Do you have a reproducer? I don't have a reproducer that calls an external provider because Webex APIs only work with a paid account But you can review by looking at the example in the documentation, https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/main/java/examples/WebExamples.java#L1386. From what I've stepped through in my code, this won't work as expected, because on line 1402 it will pass a scope to add. But the method called doesn't update the current `oauth2` instance, instead is creates a new instance of the class and returns that. If you can debug the code, you should see at line 1405 `oauth2` does not have the scopes passed in line 1402. In order for the example to work, it would need to be changed to be `oauth2 = oauth2.withScope("profile");`. ### Steps to reproduce 1. If you can debug the example, you will see it calls `withScope()` at line 1402 2. After the method has been called, the `oauth2` instance at line 1405 won't have any scopes. ### Extra I'm not sure which is your preferred solution. I can work around it by reassigning my OAuth2AuthHandler. I just want to make sure the code I have is best for the future and that the documentation and code align.
    62c838ebe99883d38606e9eef3dcbec3025ae9db
    70efdb09de560528968a88750c47e0f1ef914b6a
    https://github.com/vert-x3/vertx-web/compare/62c838ebe99883d38606e9eef3dcbec3025ae9db...70efdb09de560528968a88750c47e0f1ef914b6a
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java index 9af0816ac..70cc1172c 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java @@ -32,7 +32,8 @@ import java.util.List; public interface JWTAuthHandler extends AuthenticationHandler { /** - * Create a JWT auth handler + * Create a JWT auth handler. When no scopes are explicit declared, the default scopes will be looked up from the + * route metadata. * * @param authProvider the auth provider to use * @return the auth handler @@ -42,7 +43,8 @@ public interface JWTAuthHandler extends AuthenticationHandler { } /** - * Create a JWT auth handler + * Create a JWT auth handler. When no scopes are explicit declared, the default scopes will be looked up from the + * route metadata. * * @param authProvider the auth provider to use * @return the auth handler @@ -52,32 +54,31 @@ public interface JWTAuthHandler extends AuthenticationHandler { } /** - * Return a new instance with the internal state copied from the caller but the scopes delimiter set - * to be unique to the instance. + * Set the scope delimiter. By default this is a space character. * * @param delimiter scope delimiter. - * @return new instance of this interface. + * @return fluent self. */ @Fluent JWTAuthHandler scopeDelimiter(String delimiter); /** * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token - * request are unique to the instance. + * request are unique to the instance. When scopes are applied to the handler, the default scopes from the route + * metadata will be ignored. * * @param scope scope. * @return new instance of this interface. */ - @Fluent JWTAuthHandler withScope(String scope); /** * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token - * request are unique to the instance. + * request are unique to the instance. When scopes are applied to the handler, the default scopes from the route + * metadata will be ignored. * * @param scopes scopes. * @return new instance of this interface. */ - @Fluent JWTAuthHandler withScopes(List<String> scopes); } diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java index 5b9f1df31..2f8439444 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java @@ -35,11 +35,14 @@ import java.util.List; public interface OAuth2AuthHandler extends AuthenticationHandler { /** - * Create a OAuth2 auth handler with host pinning + * Create a OAuth2 auth handler with host pinning. When no scopes are explicit declared, the default scopes will be + * looked up from the route metadata under the key {@code scopes} which can either be a single {@link String} or a + * {@link List<String>}. * * @param vertx the vertx instance * @param authProvider the auth provider to use - * @param callbackURL the callback URL you entered in your provider admin console, usually it should be something like: `https://myserver:8888/callback` + * @param callbackURL the callback URL you entered in your provider admin console, usually it should be something + * like: {@code https://myserver:8888/callback} * @return the auth handler */ static OAuth2AuthHandler create(Vertx vertx, OAuth2Auth authProvider, String callbackURL) { @@ -50,9 +53,10 @@ public interface OAuth2AuthHandler extends AuthenticationHandler { } /** - * Create a OAuth2 auth handler without host pinning. - * Most providers will not look to the redirect url but always redirect to - * the preconfigured callback. So this factory does not provide a callback url. + * Create a OAuth2 auth handler without host pinning.Most providers will not look to the redirect url but always + * redirect to the preconfigured callback. So this factory does not provide a callback url. When no scopes are + * explicit declared, the default scopes will be looked up from the route metadata under the key {@code scopes} + * which can either be a single {@link String} or a {@link List<String>}. * * @param vertx the vertx instance * @param authProvider the auth provider to use @@ -72,8 +76,9 @@ public interface OAuth2AuthHandler extends AuthenticationHandler { OAuth2AuthHandler extraParams(JsonObject extraParams); /** - * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token - * request are unique to the instance. + * Return a <b>new instance</b> with the internal state copied from the caller but the scopes to be requested during + * a token request are unique to the instance. When scopes are applied to the handler, the default scopes from the + * route metadata will be ignored. * * @param scope scope. * @return new instance of this interface. @@ -82,8 +87,9 @@ public interface OAuth2AuthHandler extends AuthenticationHandler { OAuth2AuthHandler withScope(String scope); /** - * Return a new instance with the internal state copied from the caller but the scopes to be requested during a token - * request are unique to the instance. + * Return a <b>new instance</b> with the internal state copied from the caller but the scopes to be requested during + * a token request are unique to the instance. When scopes are applied to the handler, the default scopes from the + * route metadata will be ignored. * * @param scopes scopes. * @return new instance of this interface. @@ -98,9 +104,14 @@ public interface OAuth2AuthHandler extends AuthenticationHandler { * * <ul> * <li><b>login</b> will force the user to enter their credentials on that request, negating single-sign on.</li> - * <li><b>none</b> is the opposite - it will ensure that the user isn't presented with any interactive prompt whatsoever. If the request can't be completed silently via single-sign on, the Microsoft identity platform endpoint will return an interaction_required error.</li> - * <li><b>consent</b> will trigger the OAuth consent dialog after the user signs in, asking the user to grant permissions to the app.</li> - * <li><b>select_account</b> will interrupt single sign-on providing account selection experience listing all the accounts either in session or any remembered account or an option to choose to use a different account altogether.</li> + * <li><b>none</b> is the opposite - it will ensure that the user isn't presented with any interactive prompt + * whatsoever. If the request can't be completed silently via single-sign on, the Microsoft identity platform + * endpoint will return an interaction_required error.</li> + * <li><b>consent</b> will trigger the OAuth consent dialog after the user signs in, asking the user to grant + * permissions to the app.</li> + * <li><b>select_account</b> will interrupt single sign-on providing account selection experience listing all the + * accounts either in session or any remembered account or an option to choose to use a different account + * altogether.</li> * <li><b></b></li> * </ul> * @@ -125,7 +136,7 @@ public interface OAuth2AuthHandler extends AuthenticationHandler { /** * add the callback handler to a given route. - * @param route a given route e.g.: `/callback` + * @param route a given route e.g.: {@code /callback} * @return self */ @Fluent diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java index a3f47bacd..5550c8501 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java @@ -29,7 +29,9 @@ import io.vertx.ext.web.handler.JWTAuthHandler; import io.vertx.ext.web.impl.RoutingContextInternal; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -39,17 +41,19 @@ import java.util.stream.Stream; public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler<JWTAuth> implements JWTAuthHandler, ScopedAuthentication<JWTAuthHandler> { private final List<String> scopes; - private final String delimiter; + private String delimiter; public JWTAuthHandlerImpl(JWTAuth authProvider, String realm) { super(authProvider, Type.BEARER, realm); - scopes = new ArrayList<>(); + scopes = Collections.emptyList(); this.delimiter = " "; } private JWTAuthHandlerImpl(JWTAuthHandlerImpl base, List<String> scopes, String delimiter) { super(base.authProvider, Type.BEARER, base.realm); + Objects.requireNonNull(scopes, "scopes cannot be null"); this.scopes = scopes; + Objects.requireNonNull(delimiter, "delimiter cannot be null"); this.delimiter = delimiter; } @@ -88,6 +92,7 @@ public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler<JWTAuth> implem @Override public JWTAuthHandler withScope(String scope) { + Objects.requireNonNull(scope, "scope cannot be null"); List<String> updatedScopes = new ArrayList<>(this.scopes); updatedScopes.add(scope); return new JWTAuthHandlerImpl(this, updatedScopes, delimiter); @@ -95,12 +100,15 @@ public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler<JWTAuth> implem @Override public JWTAuthHandler withScopes(List<String> scopes) { + Objects.requireNonNull(scopes, "scopes cannot be null"); return new JWTAuthHandlerImpl(this, scopes, delimiter); } @Override - public JWTAuthHandler scopeDelimiter(String delimeter) { - return new JWTAuthHandlerImpl(this, scopes, delimeter); + public JWTAuthHandler scopeDelimiter(String delimiter) { + Objects.requireNonNull(delimiter, "delimiter cannot be null"); + this.delimiter = delimiter; + return this; } /** @@ -115,6 +123,8 @@ public class JWTAuthHandlerImpl extends HTTPAuthorizationHandler<JWTAuth> implem return; } // the user is authenticated, however the user may not have all the required scopes + final List<String> scopes = getScopesOrSearchMetadata(this.scopes, ctx); + if (scopes.size() > 0) { final JsonObject jwt = user.get("accessToken"); if (jwt == null) { diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java index 0fc83daf2..62c8bfc7f 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java @@ -61,7 +61,6 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> private final MessageDigest sha256; private final List<String> scopes; - private final boolean openId; private JsonObject extraParams; private String prompt; private int pkce = -1; @@ -92,8 +91,7 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> this.callbackURL = null; } // scopes are empty by default - this.scopes = new ArrayList<>(); - this.openId = false; + this.scopes = Collections.emptyList(); } private OAuth2AuthHandlerImpl(OAuth2AuthHandlerImpl base, List<String> scopes) { @@ -117,8 +115,8 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> this.callback = base.callback; this.order = base.order; // apply the new scopes + Objects.requireNonNull(scopes, "scopes cannot be null"); this.scopes = scopes; - this.openId = scopes != null && scopes.contains("openid"); } @Override @@ -150,13 +148,15 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> // the redirect is processed as a failure to abort the chain String redirectUri = context.request().uri(); try { - return Future.failedFuture(new HttpException(302, authURI(context.session(), redirectUri))); + return Future.failedFuture(new HttpException(302, authURI(context, redirectUri))); } catch (IllegalStateException e) { return Future.failedFuture(e); } } } else { // continue + final List<String> scopes = getScopesOrSearchMetadata(this.scopes, context); + final Credentials credentials = scopes.size() > 0 ? new TokenCredentials(token).setScopes(scopes) : new TokenCredentials(token); @@ -170,12 +170,14 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> }); } - private String authURI(Session session, String redirectURL) { + private String authURI(RoutingContext context, String redirectURL) { String state = null; String codeVerifier = null; String loginHint = null; + final Session session = context.session(); + if (session == null) { if (pkce > 0) { // we can only handle PKCE with a session @@ -224,6 +226,8 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> config.setRedirectUri(callbackURL.href()); } + final List<String> scopes = getScopesOrSearchMetadata(this.scopes, context); + if (scopes.size() > 0) { config.setScopes(scopes); } @@ -248,6 +252,8 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> @Override public OAuth2AuthHandler withScope(String scope) { + Objects.requireNonNull(scope, "scope cannot be null"); + List<String> updatedScopes = new ArrayList<>(this.scopes); updatedScopes.add(scope); return new OAuth2AuthHandlerImpl(this, updatedScopes); @@ -255,6 +261,7 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> @Override public OAuth2AuthHandler withScopes(List<String> scopes) { + Objects.requireNonNull(scopes, "scopes cannot be null"); return new OAuth2AuthHandlerImpl(this, scopes); } @@ -329,7 +336,9 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> @Override public void postAuthentication(RoutingContext ctx) { // the user is authenticated, however the user may not have all the required scopes - if (scopes != null && scopes.size() > 0) { + final List<String> scopes = getScopesOrSearchMetadata(this.scopes, ctx); + + if (scopes.size() > 0) { final User user = ctx.user().get(); if (user == null) { // bad state @@ -338,22 +347,26 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> } if (user.principal().containsKey("scope")) { - final String scopes = user.principal().getString("scope"); - if (scopes != null) { + final String userScopes = user.principal().getString("scope"); + if (userScopes != null) { // user principal contains scope, a basic assertion is required to ensure that // the scopes present match the required ones - for (String scope : this.scopes) { + + // check if openid is active + final boolean openId = userScopes.contains("openid"); + + for (String scope : scopes) { // do not assert openid scopes if openid is active if (openId && OPENID_SCOPES.contains(scope)) { continue; } - int idx = scopes.indexOf(scope); + int idx = userScopes.indexOf(scope); if (idx != -1) { // match, but is it valid? if ( - (idx != 0 && scopes.charAt(idx -1) != ' ') || - (idx + scope.length() != scopes.length() && scopes.charAt(idx + scope.length()) != ' ')) { + (idx != 0 && userScopes.charAt(idx -1) != ' ') || + (idx + scope.length() != userScopes.length() && userScopes.charAt(idx + scope.length()) != ' ')) { // invalid scope assignment ctx.fail(403, new IllegalStateException("principal scope != handler scopes")); return; diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java index 853a74634..cf03a03ee 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java @@ -1,13 +1,18 @@ package io.vertx.ext.web.handler.impl; +import io.vertx.ext.web.Route; +import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.AuthenticationHandler; +import java.util.Collections; import java.util.List; +import java.util.Map; /** * Internal interface for scope aware Authentication handlers. - * @author <a href="mailto:[email protected]">Paulo Lopes</a> + * * @param <SELF> + * @author <a href="mailto:[email protected]">Paulo Lopes</a> */ public interface ScopedAuthentication<SELF extends AuthenticationHandler> { @@ -28,4 +33,39 @@ public interface ScopedAuthentication<SELF extends AuthenticationHandler> { * @return new instance of this interface. */ SELF withScopes(List<String> scopes); + + /** + * Return the list of scopes provided as the 1st argument, unless the list is empty. In this case, the list of scopes + * is obtained from the routing context metadata if possible. In case the metadata is not available, the list of + * scopes is always an empty list. + */ + default List<String> getScopesOrSearchMetadata(List<String> scopes, RoutingContext ctx) { + if (!scopes.isEmpty()) { + return scopes; + } + + final Route currentRoute = ctx.currentRoute(); + + if (currentRoute == null) { + return Collections.emptyList(); + } + + final Object value = currentRoute + .metadata() + .get("scopes"); + + if (value == null) { + return Collections.emptyList(); + } + + if (value instanceof List) { + return (List<String>) value; + } + + if (value instanceof String) { + return Collections.singletonList((String) value); + } + + throw new IllegalStateException("Invalid type for scopes metadata: " + value.getClass().getName()); + } } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java index 33069c484..fd688fa8d 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java @@ -160,4 +160,50 @@ public class JWTAuthHandlerTest extends WebTestBase { testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Bearer " + authProvider.generateToken(payloadB)), 200, "OK", null); } + + @Test + public void testLoginWithScopesFromMetadata() throws Exception { + + router.route() + .putMetadata("scopes", Arrays.asList("a", "b")) + .handler(JWTAuthHandler.create(authProvider)) + .handler(RoutingContext::end); + + // Payload as String list + final JsonObject payloadA = new JsonObject() + .put("sub", "Paulo") + .put("scope", String.join(" ", Arrays.asList("a", "b"))); + + testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Bearer " + authProvider.generateToken(payloadA)), 200, "OK", null); + + // Payload as Array + final JsonObject payloadB = new JsonObject() + .put("sub", "Paulo") + .put("scope", new JsonArray().add("a").add("b")); + + testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Bearer " + authProvider.generateToken(payloadB)), 200, "OK", null); + } + + @Test + public void testLoginWithScopesFromMetadataSingle() throws Exception { + + router.route() + .putMetadata("scopes", "a") + .handler(JWTAuthHandler.create(authProvider)) + .handler(RoutingContext::end); + + // Payload as String list + final JsonObject payloadA = new JsonObject() + .put("sub", "Paulo") + .put("scope", "a"); + + testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Bearer " + authProvider.generateToken(payloadA)), 200, "OK", null); + + // Payload as Array + final JsonObject payloadB = new JsonObject() + .put("sub", "Paulo") + .put("scope", new JsonArray().add("a")); + + testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Bearer " + authProvider.generateToken(payloadB)), 200, "OK", null); + } } diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java index 443350172..5db674edf 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java @@ -241,6 +241,130 @@ public class OAuth2AuthHandlerTest extends WebTestBase { server.close(); } + @Test + public void testAuthCodeFlowWithScopesFromMetadata() throws Exception { + + // lets mock an oauth2 server using code auth code flow + OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options() + .setClientId("client-id") + .setClientSecret("client-secret") + .setSite("http://localhost:10000")); + + final CountDownLatch latch = new CountDownLatch(1); + + HttpServer server = vertx.createHttpServer().requestHandler(req -> { + if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) { + req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader("Content-Type", "application/json").end(fixture.encode())); + } else if (req.method() == HttpMethod.POST && "/oauth/revoke".equals(req.path())) { + req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end()); + } else { + req.response().setStatusCode(400).end(); + } + }); + + server.listen(10000).onComplete(ready -> { + if (ready.failed()) { + throw new RuntimeException(ready.cause()); + } + // ready + latch.countDown(); + }); + + latch.await(); + + // create a oauth2 handler on our domain to the callback: "http://localhost:8080/callback" + OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler + .create(vertx, oauth2, "http://localhost:8080/callback"); + + // setup the callback handler for receiving the callback + oauth2Handler.setupCallback(router.route("/callback")); + + // protect everything under /protected + router.route("/protected/*") + .putMetadata("scopes", "read") + .handler(oauth2Handler); + // mount some handler under the protected zone + router.route("/protected/somepage").handler(rc -> { + assertNotNull(rc.user().get()); + rc.response().end("Welcome to the protected resource!"); + }); + + + testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> { + // in this case we should get a redirect + redirectURL = resp.getHeader("Location"); + assertNotNull(redirectURL); + }, 302, "Found", null); + + // fake the redirect + testRequest(HttpMethod.GET, "/callback?state=/protected/somepage&code=1", null, resp -> { + }, 200, "OK", "Welcome to the protected resource!"); + + server.close(); + } + + @Test + public void testAuthCodeFlowWithScopesFromMetadataNoMatch() throws Exception { + + // lets mock an oauth2 server using code auth code flow + OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options() + .setClientId("client-id") + .setClientSecret("client-secret") + .setSite("http://localhost:10000")); + + final CountDownLatch latch = new CountDownLatch(1); + + HttpServer server = vertx.createHttpServer().requestHandler(req -> { + if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) { + req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader("Content-Type", "application/json").end(fixture.encode())); + } else if (req.method() == HttpMethod.POST && "/oauth/revoke".equals(req.path())) { + req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end()); + } else { + req.response().setStatusCode(400).end(); + } + }); + + server.listen(10000).onComplete(ready -> { + if (ready.failed()) { + throw new RuntimeException(ready.cause()); + } + // ready + latch.countDown(); + }); + + latch.await(); + + // create a oauth2 handler on our domain to the callback: "http://localhost:8080/callback" + OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler + .create(vertx, oauth2, "http://localhost:8080/callback"); + + // setup the callback handler for receiving the callback + oauth2Handler.setupCallback(router.route("/callback")); + + // protect everything under /protected + router.route("/protected/*") + .putMetadata("scopes", "delete") + .handler(oauth2Handler); + // mount some handler under the protected zone + router.route("/protected/somepage").handler(rc -> { + assertNotNull(rc.user().get()); + rc.response().end("Welcome to the protected resource!"); + }); + + + testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> { + // in this case we should get a redirect + redirectURL = resp.getHeader("Location"); + assertNotNull(redirectURL); + }, 302, "Found", null); + + // fake the redirect + testRequest(HttpMethod.GET, "/callback?state=/protected/somepage&code=1", null, resp -> { + }, 403, "Forbidden", null); + + server.close(); + } + @Test public void testAuthCodeFlowBypass() throws Exception {
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/JWTAuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/ScopedAuthentication.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/OAuth2AuthHandler.java', 'vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/JWTAuthHandler.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/JWTAuthHandlerImpl.java']
    {'.java': 7}
    7
    7
    0
    0
    7
    1,755,892
    392,675
    55,397
    443
    8,764
    1,916
    155
    5
    1,838
    279
    458
    23
    2
    0
    1970-01-01T00:28:00
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,272
    vert-x3/vertx-web/1046/1044
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1044
    https://github.com/vert-x3/vertx-web/pull/1046
    https://github.com/vert-x3/vertx-web/pull/1046
    1
    fixes
    OAuth handler should not redirect the callback route
    when the oauth handle is set to protect everything e.g.: `router.route().handler(...` it always covers the `callback` handler and this will enter an infinite loop of redirects to the oauth provider and back. This needs to be whitelisted.
    19cfcfa8c421a207c430a8f3f3e301b0b2ffcb62
    0140c6910f3c5c599eee1827d57b921fbfe687ba
    https://github.com/vert-x3/vertx-web/compare/19cfcfa8c421a207c430a8f3f3e301b0b2ffcb62...0140c6910f3c5c599eee1827d57b921fbfe687ba
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java index 414f08356..fb18a2b86 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java @@ -23,6 +23,8 @@ import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; +import io.vertx.core.logging.Logger; +import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.auth.AuthProvider; import io.vertx.ext.auth.oauth2.OAuth2Auth; import io.vertx.ext.web.Route; @@ -43,6 +45,8 @@ import static io.vertx.ext.auth.oauth2.OAuth2FlowType.AUTH_CODE; */ public class OAuth2AuthHandlerImpl extends AuthorizationAuthHandler implements OAuth2AuthHandler { + private static final Logger log = LoggerFactory.getLogger(OAuth2AuthHandlerImpl.class); + /** * This is a verification step, it can abort the instantiation by * throwing a RuntimeException @@ -116,8 +120,22 @@ public class OAuth2AuthHandlerImpl extends AuthorizationAuthHandler implements O handler.handle(Future.failedFuture("callback route is not configured.")); return; } - // the redirect is processed as a failure to abort the chain - handler.handle(Future.failedFuture(new HttpStatusException(302, authURI(context.request().uri())))); + // when this handle is mounted as a catch all, the callback route must be configured before, + // as it would shade the callback route. When a request matches the callback path and has the + // method GET the exceptional case should not redirect to the oauth2 server as it would become + // an infinite redirect loop. In this case an exception must be raised. + if ( + context.request().method() == HttpMethod.GET && + context.normalisedPath().equals(callback.getPath())) { + + if (log.isWarnEnabled()) { + log.warn("The callback route is shaded by the OAuth2AuthHandler, ensure the callback route is added BEFORE the OAuth2AuthHandler route!"); + } + handler.handle(Future.failedFuture(new HttpStatusException(500, "Infinite redirect loop [oauth2 callback]"))); + } else { + // the redirect is processed as a failure to abort the chain + handler.handle(Future.failedFuture(new HttpStatusException(302, authURI(context.request().uri())))); + } } else { // attempt to decode the token and handle it as a user ((OAuth2Auth) authProvider).decodeToken(token, decodeToken -> { diff --git a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java index 68ae3631b..71e2256ef 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java @@ -109,6 +109,82 @@ public class OAuth2AuthHandlerTest extends WebTestBase { server.close(); } + @Test + public void testAuthCodeFlowBadSetup() throws Exception { + + // lets mock a oauth2 server using code auth code flow + OAuth2Auth oauth2 = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, new OAuth2ClientOptions() + .setClientID("client-id") + .setClientSecret("client-secret") + .setSite("http://localhost:10000")); + + final CountDownLatch latch = new CountDownLatch(1); + + HttpServer server = vertx.createHttpServer().requestHandler(req -> { + if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) { + req.setExpectMultipart(true).bodyHandler(buffer -> req.response().putHeader("Content-Type", "application/json").end(fixture.encode())); + } else if (req.method() == HttpMethod.POST && "/oauth/revoke".equals(req.path())) { + req.setExpectMultipart(true).bodyHandler(buffer -> req.response().end()); + } else { + req.response().setStatusCode(400).end(); + } + }).listen(10000, ready -> { + if (ready.failed()) { + throw new RuntimeException(ready.cause()); + } + // ready + latch.countDown(); + }); + + latch.await(); + + // protect everything. This has the bad sideffect that it will also shade the callback route which is computed + // after this handler, the proper way to fix this would be create the route before + router.route().handler(OAuth2AuthHandler.create(oauth2, "http://localhost:8080/callback").setupCallback(router.route())); + // mount some handler under the protected zone + router.route("/protected/somepage").handler(rc -> { + assertNotNull(rc.user()); + rc.response().end("Welcome to the protected resource!"); + }); + + + testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> { + // in this case we should get a redirect + redirectURL = resp.getHeader("Location"); + assertNotNull(redirectURL); + }, 302, "Found", null); + + // fake the redirect + testRequest(HttpMethod.GET, "/callback?state=/protected/somepage&code=1", null, resp -> { + }, 500, "Internal Server Error", "Internal Server Error"); + + // second attempt with proper config + router.clear(); + + // protect everything. + OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler.create(oauth2, "http://localhost:8080/callback").setupCallback(router.route()); + // now the callback is registered before as it should + router.route().handler(oauth2Handler); + // mount some handler under the protected zone + router.route("/protected/somepage").handler(rc -> { + assertNotNull(rc.user()); + rc.response().end("Welcome to the protected resource!"); + }); + + + testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> { + // in this case we should get a redirect + redirectURL = resp.getHeader("Location"); + assertNotNull(redirectURL); + }, 302, "Found", null); + + // fake the redirect + testRequest(HttpMethod.GET, "/callback?state=/protected/somepage&code=1", null, resp -> { + }, 200, "OK", "Welcome to the protected resource!"); + + server.close(); + } + @Test public void testPasswordFlow() throws Exception {
    ['vertx-web/src/test/java/io/vertx/ext/web/handler/OAuth2AuthHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    989,166
    222,491
    31,395
    246
    1,426
    274
    22
    1
    237
    37
    51
    1
    0
    0
    1970-01-01T00:25:41
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,237
    vert-x3/vertx-web/2287/2282
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2282
    https://github.com/vert-x3/vertx-web/pull/2287
    https://github.com/vert-x3/vertx-web/pull/2287
    1
    fixes
    BodyHandler Requires TRANSFER-ENCODING to react
    ### Version 4.3.4 ### Context https://netty.io/news/2022/09/08/4-1-81-Final.html > Connection related headers in HTTP/2 frames are now rejected, in compliance with the specification It is no longer allowed to set TRANSFER-ENCODING chunked on HTTP2 connections but we are currently doing this to allow BodyHandlerImpl to propagate the Body for us in RoutingContext. ### Reproducer https://github.com/DemonicTutor/vertx-434-issues https://github.com/DemonicTutor/vertx-434-issues/blob/main/src/test/java/com/noenv/vertx434issues/UploadTest.java ### Extra * openJdk 19
    9736694b3b65a3fda3afbb82d98aa601f13822a8
    bca6a416ee852b4c50f3203e6278efa13735cf55
    https://github.com/vert-x3/vertx-web/compare/9736694b3b65a3fda3afbb82d98aa601f13822a8...bca6a416ee852b4c50f3203e6278efa13735cf55
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java index 0269e9cca..2e674a2ef 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java @@ -87,8 +87,11 @@ public class BodyHandlerImpl implements BodyHandler { // or `content-length` headers set. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 final long parsedContentLength = parseContentLengthHeader(request); + // http2 never transmits a `transfer-encoding` as frames are chunks. + final boolean hasTransferEncoding = + request.version() == HttpVersion.HTTP_2 || request.headers().contains(HttpHeaders.TRANSFER_ENCODING); - if (!request.headers().contains(HttpHeaders.TRANSFER_ENCODING) && parsedContentLength == -1) { + if (!hasTransferEncoding && parsedContentLength == -1) { // there is no "body", so we can skip this handler context.next(); return; diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java index b85d3b15a..a88e50284 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java @@ -30,6 +30,7 @@ import io.vertx.ext.auth.VertxContextPRNG; import io.vertx.ext.auth.authentication.Credentials; import io.vertx.ext.auth.authentication.TokenCredentials; import io.vertx.ext.auth.oauth2.OAuth2Auth; +import io.vertx.ext.auth.oauth2.OAuth2FlowType; import io.vertx.ext.auth.oauth2.Oauth2Credentials; import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; @@ -434,6 +435,7 @@ public class OAuth2AuthHandlerImpl extends HTTPAuthorizationHandler<OAuth2Auth> } final Oauth2Credentials credentials = new Oauth2Credentials() + .setFlow(OAuth2FlowType.AUTH_CODE) .setCode(code); // the state that was passed to the IdP server. The state can be
    ['vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/OAuth2AuthHandlerImpl.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,970,649
    437,522
    61,100
    482
    487
    110
    7
    2
    597
    59
    158
    21
    3
    0
    1970-01-01T00:27:46
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,239
    vert-x3/vertx-web/2213/2196
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/2196
    https://github.com/vert-x3/vertx-web/pull/2213
    https://github.com/vert-x3/vertx-web/pull/2213
    1
    fixes
    SSL not set for secure Request
    ### Questions I'm currently encountering a strange bug. I'm not entirely sure whether its me, or whether something odd is happening in the vertx Code. I'm adding a secure cookie to a WebClientSession and then try to request a page from a server. However, the cookie is not added to the request, since the request does not set the ssl flag. I think I've found the problematic code in line 220 of HttpRequestImpl: ```java if (ssl != null && ssl != client.options.isSsl()) { requestOptions .setSsl(ssl); } ``` These lines will not set the ssl flag in the requestOptions if both the client.opentions.isSsl() and ssl are true. since the ssl flag on this is set to true before the line. I'm not sure, but I got the impression, that this should either be an `||` comparison, or something else is going on here. ### Version 4.3.1, the same code worked with 4.2.7 ### Context I had a test that tried to use a new session with an existing cookie but the cookie was not loaded, since the cookie was secure, but the request claimed to not have the ssl flag set. ### Do you have a reproducer? Somewhat: https://github.com/tpfau/vertx_issue By packaging the project you can see, that the Cookiestore gets a request for a non-ssl cookie, while the client options are set to be ssl. ### Steps to reproduce Run the Tests of the reproducer, this should show that the cookiestore gets a request for a non-ssl cookie while it should get one for an ssl cookie.
    c6aeabfae673afe2097ab799129b3dc21632d065
    0375b9b78dc5cb496e64e26e403481551292f661
    https://github.com/vert-x3/vertx-web/compare/c6aeabfae673afe2097ab799129b3dc21632d065...0375b9b78dc5cb496e64e26e403481551292f661
    diff --git a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java index 34313458b..da9290138 100644 --- a/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java +++ b/vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java @@ -217,7 +217,10 @@ public class HttpRequestImpl<T> implements HttpRequest<T> { .setHost(host) .setPort(port) .setURI(uri); - if (ssl != null && ssl != client.options.isSsl()) { + // if the user specified SSL we always enforce it + // even if the client has a default, because the default + // may have been used previously to compute the request options + if (ssl != null) { requestOptions .setSsl(ssl); }
    ['vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/HttpRequestImpl.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,970,063
    437,405
    61,125
    482
    276
    63
    5
    1
    1,518
    256
    362
    33
    1
    1
    1970-01-01T00:27:35
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,257
    vert-x3/vertx-web/1852/1830
    vert-x3
    vertx-web
    https://github.com/vert-x3/vertx-web/issues/1830
    https://github.com/vert-x3/vertx-web/pull/1852
    https://github.com/vert-x3/vertx-web/pull/1852
    1
    fixes
    SockJS websocket connections initially fail when combined with clustered infinispan-backed sessions
    ### Version 4.0.0.Beta3 - 4.0.0 Version 3.X.Y, 4.0.0.Beta1 and 4.0.0.Beta2 are not effected. ### Context Since vert.x stack version 4.0.0.Beta3 SockJS websocket connections are not established for load-balanced verticles until the same verticle processes the initial sockjs "/info" request and the websocket upgrade. After the first successful websocket upgrade the problem vanishes. This only occurs in combination with clustered sessions handled by an infinispan cluster manager and forced websocket connections. I have not found the root cause for this problem. ### Do you have a reproducer? Yes, it also includes a more detailed analysis of the problem: [vertx-4-infinispan-ws-sockjs-reproducer](https://github.com/trho/vertx-4-infinispan-ws-sockjs-reproducer) ### Steps to reproduce See [vertx-4-infinispan-ws-sockjs-reproducer](https://github.com/trho/vertx-4-infinispan-ws-sockjs-reproducer) ### Extra OS version, JVM version: MacOS 10.15.7, AdoptOpenJDK 11 (build 11.0.9.1+1)
    6c50bbde8119e6f3d104f47e2a1472b95e962706
    5c0dc3722174379c4bf594b8add03e0436d52ce1
    https://github.com/vert-x3/vertx-web/compare/6c50bbde8119e6f3d104f47e2a1472b95e962706...5c0dc3722174379c4bf594b8add03e0436d52ce1
    diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java index f3be81d40..f42f2013b 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java @@ -72,17 +72,15 @@ public abstract class AuthenticationHandlerImpl<T extends AuthenticationProvider // pause parsing the request body. The reason is that // we don't want to loose the body or protocol upgrades // for async operations - final boolean parseEnded = ctx.request().isEnded(); + HttpServerRequest request = ctx.request(); + final boolean parseEnded = request.isEnded(); if (!parseEnded) { - ctx.request().pause(); + request.pause(); } // parse the request in order to extract the credentials object parseCredentials(ctx, res -> { if (res.failed()) { - // resume as the error handler may allow this request to become valid again - if (!parseEnded) { - ctx.request().resume(); - } + resume(request, parseEnded); processException(ctx, res.cause()); return; } @@ -98,9 +96,7 @@ public abstract class AuthenticationHandlerImpl<T extends AuthenticationProvider session.regenerateId(); } // proceed with the router - if (!parseEnded) { - ctx.request().resume(); - } + resume(request, parseEnded); postAuthentication(ctx); } else { String header = authenticateHeader(ctx); @@ -109,24 +105,21 @@ public abstract class AuthenticationHandlerImpl<T extends AuthenticationProvider .putHeader("WWW-Authenticate", header); } // to allow further processing if needed - if (authN.cause() instanceof HttpStatusException) { - // resume as the error handler may allow this request to become valid again - if (!parseEnded) { - ctx.request().resume(); - } - processException(ctx, authN.cause()); - } else { - // resume as the error handler may allow this request to become valid again - if (!parseEnded) { - ctx.request().resume(); - } - processException(ctx, new HttpStatusException(401, authN.cause())); - } + resume(request, parseEnded); + Throwable cause = authN.cause(); + processException(ctx, cause instanceof HttpStatusException?cause:new HttpStatusException(401, cause)); } }); }); } + private void resume(HttpServerRequest request, boolean parseEnded) { + // resume as the error handler may allow this request to become valid again + if (!parseEnded && !request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { + request.resume(); + } + } + /** * This method is protected so custom auth handlers can override the default * error handling diff --git a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java index f6a453601..4f0736c0e 100644 --- a/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java +++ b/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java @@ -22,6 +22,8 @@ import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.Cookie; import io.vertx.core.http.CookieSameSite; +import io.vertx.core.http.HttpHeaders; +import io.vertx.core.http.HttpServerRequest; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; import io.vertx.ext.auth.AuthProvider; @@ -269,8 +271,9 @@ public class SessionHandlerImpl implements SessionHandler { @Override public void handle(RoutingContext context) { + HttpServerRequest request = context.request(); if (nagHttps && log.isDebugEnabled()) { - String uri = context.request().absoluteURI(); + String uri = request.absoluteURI(); if (!uri.startsWith("https:")) { log.debug( "Using session cookies without https could make you susceptible to session hijacking: " + uri); @@ -280,8 +283,19 @@ public class SessionHandlerImpl implements SessionHandler { // Look for existing session id String sessionID = getSessionId(context); if (sessionID != null && sessionID.length() > minLength) { + // before starting any potential async operation here + // pause parsing the request body. The reason is that + // we don't want to loose the body or protocol upgrades + // for async operations + final boolean parseEnded = request.isEnded(); + if (!parseEnded) { + request.pause(); + } // we passed the OWASP min length requirements getSession(context.vertx(), sessionID, res -> { + if (!parseEnded && !request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { + request.resume(); + } if (res.succeeded()) { Session session = res.result(); if (session != null) { diff --git a/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java b/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java index 400414af8..2e430f731 100644 --- a/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java +++ b/vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java @@ -175,4 +175,21 @@ public class ClusteredSessionHandlerTest extends SessionHandlerTestBase { long val = doTestSessionRetryTimeout(); assertTrue(String.valueOf(val), val >= 3000 && val < 5000); } + + @Test + public void testDelayedLookupWithRequestUpgrade() { + String sessionCookieName = "session"; + router.route().handler(SessionHandler.create(store).setSessionCookieName(sessionCookieName).setMinLength(0)); + router.route().handler(rc -> { + rc.request().toWebSocket(onSuccess(serverWebSocket -> serverWebSocket.textMessageHandler(msg -> { + assertEquals("foo", msg); + testComplete(); + }))); + }); + WebSocketConnectOptions options = new WebSocketConnectOptions() + .setURI("/") + .addHeader("cookie", sessionCookieName + "=" + TestUtils.randomAlphaString(32)); + client.webSocket(options, onSuccess(ws -> ws.writeTextMessage("foo"))); + await(); + } }
    ['vertx-web/src/test/java/io/vertx/ext/web/sstore/ClusteredSessionHandlerTest.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/SessionHandlerImpl.java', 'vertx-web/src/main/java/io/vertx/ext/web/handler/impl/AuthenticationHandlerImpl.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,711,255
    378,609
    52,958
    417
    2,311
    447
    53
    2
    1,023
    116
    287
    29
    2
    0
    1970-01-01T00:26:51
    1,049
    Java
    {'Java': 2911199, 'Python': 985896, 'HTML': 11069, 'JavaScript': 8466, 'Shell': 1414, 'Handlebars': 693, 'FreeMarker': 557, 'Batchfile': 249, 'Pug': 191, 'CSS': 113, 'Fluent': 27}
    Apache License 2.0
    1,342
    spring-cloud/spring-cloud-openfeign/202/189
    spring-cloud
    spring-cloud-openfeign
    https://github.com/spring-cloud/spring-cloud-openfeign/issues/189
    https://github.com/spring-cloud/spring-cloud-openfeign/pull/202
    https://github.com/spring-cloud/spring-cloud-openfeign/pull/202
    1
    closes
    Properly handle Pageable.unpaged() in PageableSpringEncoder
    Version `2.1.1.RELEASE` introduced support for Spring's `Pageable` (#26). However the associated Encoder (`PageableSpringEncoder`) crashes when faced with `Pageable.unpaged()`, since the latter throws an `UnsupportedOperationException` on `Pageable.getPageNumber(int)`. This will lead to the very unspecific error: `feign.codec.EncodeException: null` Possible enhancements: - Improve error handling in the above case or - Translate `Pageable.unpaged()` to a query with page number 0 and page size `Integer.MAX_VALUE` since this is close to an "unpaged" result
    eda905684de1007c7a65b378487b264b07b3da06
    ead4c47fcb42dc36106c2ceaf573fcfb97e2e28e
    https://github.com/spring-cloud/spring-cloud-openfeign/compare/eda905684de1007c7a65b378487b264b07b3da06...ead4c47fcb42dc36106c2ceaf573fcfb97e2e28e
    diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java index ddf631bb..4461f36b 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java @@ -81,8 +81,12 @@ public class PageableSpringEncoder implements Encoder { if (supports(object)) { if (object instanceof Pageable) { Pageable pageable = (Pageable) object; - template.query(pageParameter, pageable.getPageNumber() + ""); - template.query(sizeParameter, pageable.getPageSize() + ""); + + if (pageable.isPaged()) { + template.query(pageParameter, pageable.getPageNumber() + ""); + template.query(sizeParameter, pageable.getPageSize() + ""); + } + if (pageable.getSort() != null) { applySort(template, pageable.getSort()); } diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java index c3916507..cf94ec7c 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java @@ -64,13 +64,12 @@ public class PageableEncoderTests { encoder.encode(createPageAndSortRequest(), null, request); // Request queries shall contain three entries - assertThat(request.queries().size()).isEqualTo(3); + assertThat(request.queries()).hasSize(3); // Request page shall contain page assertThat(request.queries().get("page")).contains(String.valueOf(PAGE)); // Request size shall contain size - assertThat(request.queries().get("size")).contains(String.valueOf(SIZE)); - // Request sort size shall contain sort entries - assertThat(request.queries().get("sort").size()).isEqualTo(2); + assertThat(request.queries().get("size")).contains(String.valueOf(SIZE)); // Request sort size shall contain sort entries + assertThat(request.queries().get("sort")).hasSize(2); } private Pageable createPageAndSortRequest() { @@ -87,9 +86,8 @@ public class PageableEncoderTests { // Request page shall contain page assertThat(request.queries().get("page")).contains(String.valueOf(PAGE)); // Request size shall contain size - assertThat(request.queries().get("size")).contains(String.valueOf(SIZE)); - // Request sort size shall contain sort entries - assertThat(request.queries().containsKey("sort")).isEqualTo(false); + assertThat(request.queries().get("size")).contains(String.valueOf(SIZE)); // Request sort size shall contain sort entries + assertThat(request.queries()).doesNotContainKey("sort"); } private Pageable createPageAndRequest() { @@ -106,11 +104,22 @@ public class PageableEncoderTests { // Request queries shall contain three entries assertThat(request.queries().size()).isEqualTo(1); // Request sort size shall contain sort entries - assertThat(request.queries().get("sort").size()).isEqualTo(2); + assertThat(request.queries().get("sort")).hasSize(2); } private Sort createSort() { return Sort.by(SORT_1, SORT_2).ascending(); } + @Test + public void testUnpagedRequest() { + Encoder encoder = this.context.getInstance("foo", Encoder.class); + assertThat(encoder).isNotNull(); + RequestTemplate request = new RequestTemplate(); + + encoder.encode(Pageable.unpaged(), null, request); + // Request queries shall contain three entries + assertThat(request.queries()).isEmpty(); + } + }
    ['spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageableEncoderTests.java', 'spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageableSpringEncoder.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    181,316
    38,885
    5,790
    49
    307
    62
    8
    1
    567
    69
    129
    7
    0
    0
    1970-01-01T00:26:04
    1,041
    Java
    {'Java': 869956, 'CSS': 34264, 'Ruby': 481}
    Apache License 2.0
    1,341
    spring-cloud/spring-cloud-openfeign/843/842
    spring-cloud
    spring-cloud-openfeign
    https://github.com/spring-cloud/spring-cloud-openfeign/issues/842
    https://github.com/spring-cloud/spring-cloud-openfeign/pull/843
    https://github.com/spring-cloud/spring-cloud-openfeign/pull/843#issuecomment-1453933064
    1
    fixes
    SpringQueryMap is ignored when used with Pageable
    `@SpringQueryMap` is ignored when method includes `Pageable` `Page<Dto> list(@SpringQueryMap Pojo pojo, Pageable pageable)` this has been introduced in version 3.1.6 by https://github.com/spring-cloud/spring-cloud-openfeign/issues/753 `paramIndex` is set always to Pageable causing `PageableSpringQueryMapEncoder` to ignore `@SpringQueryMap`
    471c5c5cb11cf6d24dc49f0d4d94f003fc5b6c89
    5bc28fa1dd47be69c1269b6bf013e42bc6b27ff2
    https://github.com/spring-cloud/spring-cloud-openfeign/compare/471c5c5cb11cf6d24dc49f0d4d94f003fc5b6c89...5bc28fa1dd47be69c1269b6bf013e42bc6b27ff2
    diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java index 430bb44c..746cec5c 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java @@ -34,12 +34,14 @@ import feign.Contract; import feign.Feign; import feign.MethodMetadata; import feign.Param; +import feign.QueryMap; import feign.Request; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.cloud.openfeign.CollectionFormat; +import org.springframework.cloud.openfeign.SpringQueryMap; import org.springframework.cloud.openfeign.annotation.CookieValueParameterProcessor; import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor; import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor; @@ -67,6 +69,7 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; import static feign.Util.checkState; import static feign.Util.emptyToNull; @@ -158,7 +161,7 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource private static TypeDescriptor getElementTypeDescriptor(TypeDescriptor typeDescriptor) { TypeDescriptor elementTypeDescriptor = typeDescriptor.getElementTypeDescriptor(); - // that means it's not a collection but it is iterable, gh-135 + // that means it's not a collection, but it is iterable, gh-135 if (elementTypeDescriptor == null && Iterable.class.isAssignableFrom(typeDescriptor.getType())) { ResolvableType type = typeDescriptor.getResolvableType().as(Iterable.class).getGeneric(0); if (type.resolve() == null) { @@ -268,8 +271,12 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource try { if (Pageable.class.isAssignableFrom(data.method().getParameterTypes()[paramIndex])) { - data.queryMapIndex(paramIndex); - return false; + // do not set a Pageable as QueryMap if there's an actual QueryMap param + // present + if (!queryMapParamPresent(data)) { + data.queryMapIndex(paramIndex); + return false; + } } } catch (NoClassDefFoundError ignored) { @@ -304,6 +311,20 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource return isHttpAnnotation; } + private boolean queryMapParamPresent(MethodMetadata data) { + Annotation[][] paramsAnnotations = data.method().getParameterAnnotations(); + for (int i = 0; i < paramsAnnotations.length; i++) { + Annotation[] paramAnnotations = paramsAnnotations[i]; + Class<?> parameterType = data.method().getParameterTypes()[i]; + if (Arrays.stream(paramAnnotations).anyMatch( + annotation -> Map.class.isAssignableFrom(parameterType) && annotation instanceof RequestParam + || annotation instanceof SpringQueryMap || annotation instanceof QueryMap)) { + return true; + } + } + return false; + } + private void parseProduces(MethodMetadata md, Method method, RequestMapping annotation) { String[] serverProduces = annotation.produces(); String clientAccepts = serverProduces.length == 0 ? null : emptyToNull(serverProduces[0]); diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java index 919e85c8..e43983d4 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java @@ -117,7 +117,7 @@ class SpringMvcContractTests { Method isNamePresent = ReflectionUtils.findMethod(parameters[0].getClass(), "isNamePresent"); return Boolean.TRUE.equals(isNamePresent.invoke(parameters[0])); } - catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { + catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignored) { } } return false; @@ -631,10 +631,20 @@ class SpringMvcContractTests { void shouldNotFailWhenBothPageableAndRequestBodyParamsInPostRequest() { List<MethodMetadata> data = contract.parseAndValidateMetadata(TestTemplate_PageablePost.class); - assertThat(data.get(0).queryMapIndex().intValue()).isEqualTo(0); - assertThat(data.get(0).bodyIndex().intValue()).isEqualTo(1); - assertThat(data.get(1).queryMapIndex().intValue()).isEqualTo(1); - assertThat(data.get(1).bodyIndex().intValue()).isEqualTo(0); + assertThat(data.get(0).queryMapIndex()).isEqualTo(0); + assertThat(data.get(0).bodyIndex()).isEqualTo(1); + assertThat(data.get(1).queryMapIndex()).isEqualTo(1); + assertThat(data.get(1).bodyIndex()).isEqualTo(0); + } + + @Test + void shouldSetPageableAsBodyWhenQueryMapParamPresent() { + List<MethodMetadata> data = contract.parseAndValidateMetadata(TestTemplate_PageablePostWithQueryMap.class); + + assertThat(data.get(0).queryMapIndex()).isEqualTo(0); + assertThat(data.get(0).bodyIndex()).isEqualTo(1); + assertThat(data.get(1).queryMapIndex()).isEqualTo(1); + assertThat(data.get(1).bodyIndex()).isEqualTo(0); } private ConversionService getConversionService() { @@ -838,7 +848,7 @@ class SpringMvcContractTests { } - public interface TestTemplate_PageablePost { + interface TestTemplate_PageablePost { @PostMapping Page<String> getPage(Pageable pageable, @RequestBody String body); @@ -848,6 +858,16 @@ class SpringMvcContractTests { } + interface TestTemplate_PageablePostWithQueryMap { + + @PostMapping + Page<String> getPage(@SpringQueryMap TestObject pojo, Pageable pageable); + + @PostMapping + Page<String> getPage(Pageable pageable, @SpringQueryMap TestObject pojo); + + } + @JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE) public class TestObject {
    ['spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java', 'spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    315,256
    67,084
    9,243
    83
    1,143
    253
    27
    1
    352
    33
    93
    8
    1
    0
    1970-01-01T00:27:57
    1,041
    Java
    {'Java': 869956, 'CSS': 34264, 'Ruby': 481}
    Apache License 2.0
    659
    spring-cloud/spring-cloud-dataflow/1236/1235
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/1235
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1236
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1236
    1
    fixes
    Providing long deployment property values hangs
    Trying to set a property and if the value is too long it seems to hang - saw this from both shell and UI ``` dataflow:>stream deploy --name ticktock --properties "app.log.foo=FOOOOOOOOOOOBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar" ``` doesn't complete in a reasonable time.
    e80994edc2f36881ac9e12941a46e82e26e41c39
    ff2de24b4a61193237143284979fa7298b8cf696
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/e80994edc2f36881ac9e12941a46e82e26e41c39...ff2de24b4a61193237143284979fa7298b8cf696
    diff --git a/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java b/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java index 5ecc255e4..1494b4c2f 100644 --- a/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java +++ b/spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java @@ -46,11 +46,6 @@ public final class DeploymentPropertiesUtils { // prevent instantiation } - /** - * Pattern used for parsing a String of comma-delimited key=value pairs. - */ - private static final Pattern DEPLOYMENT_PROPERTIES_PATTERN = Pattern.compile("(?:,{0,1}\\\\s*)((\\\\.*(\\\\w|\\\\*|-)+)+)(\\\\s*=\\\\s*)"); - /** * Pattern used for parsing a String of command-line arguments. */ @@ -61,40 +56,40 @@ public final class DeploymentPropertiesUtils { * {@code app.[appname].[key]} or {@code deployer.[appname].[key]}. * Values may themselves contain commas, since the split points will be based upon the key pattern. * - * - * Logic of this pattern to find boundaries of valid key=value pairs is: - * 1. (?:,{0,1}\\s*) is a non-capturing group which takes characters before a key. - * Needed so that capturing groups later will capture key boundaries correctly. - * 2. ((\\.*(\\w|\\*|-)+)+) is a capturing group finding an actual key. There is a recursive - * capturing groups inside of it as we assume key is formed from dots and words and - * we capture those as many time as needed. We get groups 1, 2 and 3 but we only use 1. - * 3. (\\s*=\\s*) here we find boundary of '=' which may have empty characters around it. - * This becomes capturing group 4. - * 4. Now we know where is key with group 1 and start of value with group 4. - * 5. Now we can start to do matching. Need to match one ahead so that we - * know where next key possible is as that is then end of previous value. - * 6. Lastly we have one pair left which is a same case if we only have - * one pair to parse. + * Logic of parsing key/value pairs from a string is based on few rules and assumptions + * 1. keys will not have commas or equals. + * 2. First raw split is done by commas which will need to be fixed later + * if value is a comma-delimited list. * * @param s the string to parse * @return the Map of parsed key value pairs */ public static Map<String, String> parse(String s) { Map<String, String> deploymentProperties = new HashMap<String, String>(); - if (!StringUtils.isEmpty(s)) { - int start = 0; - int end = 0; - Matcher matcher = DEPLOYMENT_PROPERTIES_PATTERN.matcher(s); - while (matcher.find()) { - if (end > 0) { - // we don't know first value position until we've found second match - addKeyValuePairAsProperty(s.substring(start, matcher.start()), deploymentProperties); - } - start = matcher.start(1); - end = matcher.end(4); + ArrayList<String> pairs = new ArrayList<>(); + + // get raw candidates as simple comma split + String[] candidates = StringUtils.commaDelimitedListToStringArray(s); + for (int i = 0; i < candidates.length; i++) { + if (i > 0 && !candidates[i].contains("=")) { + // we don't have '=' so this has to be latter parts of + // a comma delimited value, append it to previously added + // key/value pair. + // we skip first as we would not have anything to append to. this + // would happen if dep prop string is malformed and first given + // key/value pair is not actually a key/value. + pairs.set(pairs.size()-1, pairs.get(pairs.size()-1) + "," + candidates[i]); + } + else { + // we have a key/value pair having '=', or malformed first pair + pairs.add(candidates[i]); } - // last match, we still have one left. - addKeyValuePairAsProperty(s.substring(start), deploymentProperties); + } + + // add what we got, addKeyValuePairAsProperty + // handles rest as trimming, etc + for (String pair : pairs) { + addKeyValuePairAsProperty(pair, deploymentProperties); } return deploymentProperties; } diff --git a/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java b/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java index 7e3a0b42e..24eaa0db7 100644 --- a/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java +++ b/spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java @@ -83,6 +83,22 @@ public class DeploymentPropertiesUtilsTests { props = DeploymentPropertiesUtils.parse("invalidkeyvalue1,foo=bar,invalidkeyvalue2"); assertThat(props.size(), is(1)); assertThat(props, hasEntry("foo", "bar,invalidkeyvalue2")); + + props = DeploymentPropertiesUtils.parse("foo.bar1=jee1,jee2,jee3,foo.bar2=jee4,jee5,jee6"); + assertThat(props, hasEntry("foo.bar1", "jee1,jee2,jee3")); + assertThat(props, hasEntry("foo.bar2", "jee4,jee5,jee6")); + + props = DeploymentPropertiesUtils.parse("foo.bar1=xxx=1,foo.bar2=xxx=2"); + assertThat(props, hasEntry("foo.bar1", "xxx=1")); + assertThat(props, hasEntry("foo.bar2", "xxx=2")); + } + + @Test + public void testLongDeploymentPropertyValues() { + Map<String, String> props = DeploymentPropertiesUtils.parse("app.foo.bar=FoooooooooooooooooooooBar,app.foo.bar2=FoooooooooooooooooooooBar"); + assertThat(props, hasEntry("app.foo.bar", "FoooooooooooooooooooooBar")); + props = DeploymentPropertiesUtils.parse("app.foo.bar=FooooooooooooooooooooooooooooooooooooooooooooooooooooBar"); + assertThat(props, hasEntry("app.foo.bar", "FooooooooooooooooooooooooooooooooooooooooooooooooooooBar")); } @Test
    ['spring-cloud-dataflow-rest-resource/src/main/java/org/springframework/cloud/dataflow/rest/util/DeploymentPropertiesUtils.java', 'spring-cloud-dataflow-rest-resource/src/test/java/org/springframework/cloud/dataflow/rest/job/support/DeploymentPropertiesUtilsTests.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,041,670
    222,165
    30,555
    327
    2,979
    771
    59
    1
    287
    38
    69
    7
    0
    1
    1970-01-01T00:24:49
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    648
    spring-cloud/spring-cloud-dataflow/2358/2353
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/2353
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/2358
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/2358
    1
    resolves
    Streams definitions search is broken
    _From @oodamien on August 3, 2018 20:52_ https://github.com/spring-cloud/spring-cloud-dataflow/commit/4cb9d85ff2d78d239df3b1b8541514e4780f4a84#diff-1b8ed5096382d31ece0a8397f1eb4cf2R135 The search parameter has changed. _Copied from original issue: spring-cloud/spring-cloud-dataflow-ui#875_
    042f28df7d5caf291bfb1831215f36398a7719b3
    3010f9607f1d728fe4cfa3886dd25105fa26b84a
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/042f28df7d5caf291bfb1831215f36398a7719b3...3010f9607f1d728fe4cfa3886dd25105fa26b84a
    diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java index 576c92897..bf2e1296f 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java @@ -132,14 +132,14 @@ public class StreamDefinitionController { * * @param pageable Pagination information * @param assembler assembler for {@link StreamDefinition} - * @param searchName optional findByNameLike parameter + * @param search optional findByNameLike parameter * @return list of stream definitions */ @RequestMapping(value = "", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public PagedResources<StreamDefinitionResource> list(Pageable pageable, - @RequestParam(required = false) String searchName, PagedResourcesAssembler<StreamDefinition> assembler) { - Page<StreamDefinition> streamDefinitions = this.streamService.findDefinitionByNameLike(pageable, searchName); + @RequestParam(required = false) String search, PagedResourcesAssembler<StreamDefinition> assembler) { + Page<StreamDefinition> streamDefinitions = this.streamService.findDefinitionByNameLike(pageable, search); return assembler.toResource(streamDefinitions, new Assembler(streamDefinitions)); } diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java index 346e769ad..9fc29dab6 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java @@ -100,10 +100,10 @@ public interface StreamService { /** * Find stream definitions where the findByNameLike parameter - * @param searchName the findByNameLike parameter to use + * @param search the findByNameLike parameter to use * @return Page of stream definitions */ - Page<StreamDefinition> findDefinitionByNameLike(Pageable pageable, String searchName); + Page<StreamDefinition> findDefinitionByNameLike(Pageable pageable, String search); /** * Find a stream definition by name. diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java index c0abe89e3..3f8b2ddc9 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java @@ -213,10 +213,10 @@ public abstract class AbstractStreamService implements StreamService { } @Override - public Page<StreamDefinition> findDefinitionByNameLike(Pageable pageable, String searchName) { + public Page<StreamDefinition> findDefinitionByNameLike(Pageable pageable, String search) { Page<StreamDefinition> streamDefinitions; - if (searchName != null) { - final SearchPageable searchPageable = new SearchPageable(pageable, searchName); + if (search != null) { + final SearchPageable searchPageable = new SearchPageable(pageable, search); searchPageable.addColumns("DEFINITION_NAME", "DEFINITION"); streamDefinitions = streamDefinitionRepository.findByNameLike(searchPageable); long count = streamDefinitions.getContent().size();
    ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/AbstractStreamService.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    1,442,279
    307,734
    41,542
    410
    1,241
    260
    16
    3
    295
    18
    109
    7
    1
    0
    1970-01-01T00:25:33
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    664
    spring-cloud/spring-cloud-dataflow/562/560
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/560
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/562
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/562
    1
    fixes
    module info doesn't work for Docker apps
    If I do `module info sink:log` I get the following exception - ``` dataflow:>module list ╔══════╤═════════╤════╤════╗ ║source│processor│sink│task║ ╠══════╪═════════╪════╪════╣ ║time │ │log │ ║ ╚══════╧═════════╧════╧════╝ dataflow:>module info sink:log Command failed org.springframework.cloud.dataflow.rest.client.DataFlowClientException: Exception trying to list configuration properties for module Docker Resource [docker:springcloudstream/log-sink-rabbit] Exception trying to list configuration properties for module Docker Resource [docker:springcloudstream/log-sink-rabbit] org.springframework.cloud.dataflow.rest.client.DataFlowClientException: Exception trying to list configuration properties for module Docker Resource [docker:springcloudstream/log-sink-rabbit] at org.springframework.cloud.dataflow.rest.client.VndErrorResponseErrorHandler.handleError(VndErrorResponseErrorHandler.java:52) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:264) at org.springframework.cloud.dataflow.rest.client.ModuleTemplate.info(ModuleTemplate.java:84) at org.springframework.cloud.dataflow.shell.command.ModuleCommands.info(ModuleCommands.java:100) 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:497) at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216) at org.springframework.shell.core.SimpleExecutionStrategy.invoke(SimpleExecutionStrategy.java:64) at org.springframework.shell.core.SimpleExecutionStrategy.execute(SimpleExecutionStrategy.java:57) at org.springframework.shell.core.AbstractShell.executeCommand(AbstractShell.java:130) at org.springframework.shell.core.JLineShell.promptLoop(JLineShell.java:533) at org.springframework.shell.core.JLineShell.run(JLineShell.java:179) at java.lang.Thread.run(Thread.java:745) ```
    d20999bbf76b7d82b86b2d332e305e8b12e24b94
    746f5ec294f0338908cd572816117af6afae46b9
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/d20999bbf76b7d82b86b2d332e305e8b12e24b94...746f5ec294f0338908cd572816117af6afae46b9
    diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java index fb8524b49..94da34645 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java @@ -114,10 +114,13 @@ public class ModuleController { DetailedModuleRegistrationResource result = new DetailedModuleRegistrationResource(moduleAssembler.toResource(registration)); Resource resource = registration.getResource(); - List<ConfigurationMetadataProperty> properties = metadataResolver.listProperties(resource); - for (ConfigurationMetadataProperty property : properties) { - result.addOption(property); - } + //TODO: Docker URIs will throw an exception, need another way to get the properties for them + try { + List<ConfigurationMetadataProperty> properties = metadataResolver.listProperties(resource); + for (ConfigurationMetadataProperty property : properties) { + result.addOption(property); + } + } catch (Exception ignore) {} return result; }
    ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/ModuleController.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    670,638
    142,603
    20,007
    206
    531
    105
    11
    1
    2,351
    102
    521
    37
    0
    1
    1970-01-01T00:24:21
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    658
    spring-cloud/spring-cloud-dataflow/1349/1241
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/1241
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1349
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1349
    1
    resolves
    Step Execution Count incorrect when same job is executed multiple times
    When executing a batch job (with same job name) multiple times the step execution count for for all instances are the same. i.e. if a job has 3 steps, the step execution count for the first run will be 3. The next time its run the step count for the current run and previous run will be 6. Steps to reproduce. Execute a batch job(task) and then rerun it. Then go to the shell and execute a job execution list.
    15a17aec39efb159698cdf12eba1956feb536d81
    f98b8a2e9d3860605686ce3a18e728779f8e582a
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/15a17aec39efb159698cdf12eba1956feb536d81...f98b8a2e9d3860605686ce3a18e728779f8e582a
    diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java index 9644bd213..91c521b15 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import org.slf4j.LoggerFactory; import org.springframework.batch.admin.service.JobService; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; +import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.launch.JobExecutionNotRunningException; import org.springframework.batch.core.launch.NoSuchJobException; @@ -52,6 +53,7 @@ import org.springframework.util.Assert; * @author Glenn Renfro. * @author Gunnar Hillert * @author Mark Fisher + * @author Ilayaperumal Gopinathan */ public class DefaultTaskJobService implements TaskJobService { @@ -91,8 +93,14 @@ public class DefaultTaskJobService implements TaskJobService { jobService.listJobExecutions(pageable.getOffset(), pageable.getPageSize())); for (JobExecution jobExecution : jobExecutions){ - jobExecution.addStepExecutions( - new ArrayList<StepExecution>(jobService.getStepExecutions(jobExecution.getId()))); + Collection<StepExecution> stepExecutions = jobService.getStepExecutions(jobExecution.getId()); + List<StepExecution> validStepExecutions = new ArrayList<>(); + for (StepExecution stepExecution: stepExecutions) { + if (stepExecution.getId() != null) { + validStepExecutions.add(stepExecution); + } + } + jobExecution.addStepExecutions(validStepExecutions); } return getTaskJobExecutionsForList(jobExecutions);
    ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskJobService.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,100,289
    234,991
    32,267
    339
    690
    156
    14
    1
    416
    80
    102
    3
    0
    0
    1970-01-01T00:24:52
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    663
    spring-cloud/spring-cloud-dataflow/564/563
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/563
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/564
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/564
    1
    resolves
    NPE when module info doesn't exist
    For the command `module info type:name` and if the app doesn't exist, then NPE is thrown. ``` dataflow:>module info processor:test Command failed java.lang.NullPointerException java.lang.NullPointerException at org.springframework.cloud.dataflow.shell.command.ModuleCommands.info(ModuleCommands.java:101) 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.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216) at org.springframework.shell.core.SimpleExecutionStrategy.invoke(SimpleExecutionStrategy.java:64) at org.springframework.shell.core.SimpleExecutionStrategy.execute(SimpleExecutionStrategy.java:57) at org.springframework.shell.core.AbstractShell.executeCommand(AbstractShell.java:130) at org.springframework.shell.core.JLineShell.promptLoop(JLineShell.java:533) at org.springframework.shell.core.JLineShell.run(JLineShell.java:179) at java.lang.Thread.run(Thread.java:745) ```
    746f5ec294f0338908cd572816117af6afae46b9
    119f173daba7f3bd176e4a77d5069745b416ec35
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/746f5ec294f0338908cd572816117af6afae46b9...119f173daba7f3bd176e4a77d5069745b416ec35
    diff --git a/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java b/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java index 3f507c9d3..868f7282d 100644 --- a/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java +++ b/spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java @@ -98,36 +98,41 @@ public class ModuleCommands implements CommandMarker, ResourceLoaderAware { help = "name of the module to query in the form of 'type:name'") QualifiedModuleName module) { DetailedModuleRegistrationResource info = moduleOperations().info(module.name, module.type); - List<ConfigurationMetadataProperty> options = info.getOptions(); List<Object> result = new ArrayList<>(); - result.add(String.format("Information about %s module '%s':", module.type, module.name)); + if (info != null) { + List<ConfigurationMetadataProperty> options = info.getOptions(); + result.add(String.format("Information about %s module '%s':", module.type, module.name)); - result.add(String.format("Resource URI: %s", info.getUri())); + result.add(String.format("Resource URI: %s", info.getUri())); - if (info.getShortDescription() != null) { - result.add(info.getShortDescription()); - } - if (options == null) { - result.add("Module options metadata is not available"); - } - else { - TableModelBuilder<Object> modelBuilder = new TableModelBuilder<>(); - modelBuilder.addRow() - .addValue("Option Name") - .addValue("Description") - .addValue("Default") - .addValue("Type"); - for (ConfigurationMetadataProperty option : options) { + if (info.getShortDescription() != null) { + result.add(info.getShortDescription()); + } + if (options == null) { + result.add("Module options metadata is not available"); + } + else { + TableModelBuilder<Object> modelBuilder = new TableModelBuilder<>(); modelBuilder.addRow() - .addValue(option.getId()) - .addValue(option.getDescription() == null ? "<unknown>" : option.getDescription()) - .addValue(prettyPrintDefaultValue(option)) - .addValue(option.getType() == null ? "<unknown>" : option.getType()); + .addValue("Option Name") + .addValue("Description") + .addValue("Default") + .addValue("Type"); + for (ConfigurationMetadataProperty option : options) { + modelBuilder.addRow() + .addValue(option.getId()) + .addValue(option.getDescription() == null ? "<unknown>" : option.getDescription()) + .addValue(prettyPrintDefaultValue(option)) + .addValue(option.getType() == null ? "<unknown>" : option.getType()); + } + TableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build())) + .on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30)) + .and(); + result.add(builder.build()); } - TableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build())) - .on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30)) - .and(); - result.add(builder.build()); + } + else { + result.add(String.format("Module info is not available for %s:%s", module.type, module.name)); } return result; } diff --git a/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java b/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java index 89021a4b9..8305078a7 100644 --- a/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java +++ b/spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java @@ -98,7 +98,13 @@ public class ModuleCommandsTests { assertThat(model.getValue(row, col), Matchers.is(expected[row][col])); } } - } + } + + @Test + public void testUnknownModule() { + List<Object> result = moduleCommands.info(new ModuleCommands.QualifiedModuleName("unknown", ArtifactType.processor)); + assertEquals((String) result.get(0), "Module info is not available for processor:unknown"); + } @Test public void register() {
    ['spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/command/ModuleCommandsTests.java', 'spring-cloud-dataflow-shell/src/main/java/org/springframework/cloud/dataflow/shell/command/ModuleCommands.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    670,777
    142,638
    20,010
    206
    2,491
    528
    55
    1
    1,198
    50
    245
    20
    0
    1
    1970-01-01T00:24:21
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    662
    spring-cloud/spring-cloud-dataflow/1067/923
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/923
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1067
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1067
    1
    fixes
    Stream parser permits unbalanced quotes
    You can create tasks such as: ``` `timestamp --format="asddd` ```
    60bb7939d53231a3d18a94b40c9dca4d3dad4aae
    9dd230c3006585320b0b78ab19a59770ae68f011
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/60bb7939d53231a3d18a94b40c9dca4d3dad4aae...9dd230c3006585320b0b78ab19a59770ae68f011
    diff --git a/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java b/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java index 524a33da2..b3c9b1581 100644 --- a/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java +++ b/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java @@ -25,6 +25,7 @@ import org.springframework.util.Assert; * Lex some input data into a stream of tokens that can then then be parsed. * * @author Andy Clement + * @author Eric Bottard */ class Tokenizer { @@ -272,7 +273,13 @@ class Tokenizer { } while (!isArgValueIdentifierTerminator(toProcess[pos], quoteOpen)); char[] subarray = null; - if (quoteClosedCount < 2 && sameQuotes(start, pos - 1)) { + if (quoteInUse != null && quoteInUse == '"' && quoteClosedCount == 0 ) { + throw new ParseException(expressionString, start, + DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING); + } else if (quoteInUse != null && quoteInUse == '\\'' && quoteClosedCount == 0) { + throw new ParseException(expressionString, start, + DSLMessage.NON_TERMINATING_QUOTED_STRING); + } else if (quoteClosedCount == 1 && sameQuotes(start, pos - 1)) { tokens.add(new Token(TokenKind.LITERAL_STRING, subArray(start, pos), start, pos)); } diff --git a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java index d56e43f63..e85ba0279 100644 --- a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java +++ b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java @@ -25,9 +25,7 @@ import static org.junit.Assert.fail; import java.util.List; import java.util.Properties; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Parse streams and verify either the correct abstract syntax tree is produced or the current exception comes out. @@ -36,12 +34,10 @@ import org.junit.rules.ExpectedException; * @author David Turanski * @author Ilayaperumal Gopinathan * @author Mark Fisher + * @author Eric Bottard */ public class StreamParserTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private StreamNode sn; @@ -243,6 +239,16 @@ public class StreamParserTests { assertEquals("new StringBuilder(payload).reverse()", props.get("expression")); } + @Test + public void testUnbalancedSingleQuotes() { + checkForParseError("foo | bar --expression='select foo", DSLMessage.NON_TERMINATING_QUOTED_STRING, 23); + } + + @Test + public void testUnbalancedDoubleQuotes() { + checkForParseError("foo | bar --expression=\\"select foo", DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 23); + } + @Test public void appArguments_xd1613() { StreamNode ast = null; @@ -534,20 +540,4 @@ public class StreamParserTests { } } } - - private void checkForParseError(String name, String stream, DSLMessage msg, int pos, String... inserts) { - try { - StreamNode sn = parse(name, stream); - fail("expected to fail but parsed " + sn.stringify()); - } - catch (ParseException e) { - assertEquals(msg, e.getMessageCode()); - assertEquals(pos, e.getPosition()); - if (inserts != null) { - for (int i = 0; i < inserts.length; i++) { - assertEquals(inserts[i], e.getInserts()[i]); - } - } - } - } } diff --git a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java index bf21be4de..77492e872 100644 --- a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java +++ b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java @@ -32,6 +32,7 @@ import org.junit.rules.ExpectedException; * @author Andy Clement * @author David Turanski * @author Michael Minella + * @author Eric Bottard */ public class TaskParserTests { @@ -246,6 +247,18 @@ public class TaskParserTests { assertEquals(appNode.getArgumentsAsProperties().get("expression"), "payload.replace(\\"abc\\", '')"); } + @Test + public void testUnbalancedSingleQuotes() { + checkForParseError("timestamp --format='YYYY", DSLMessage.NON_TERMINATING_QUOTED_STRING, 19); + } + + @Test + public void testUnbalancedDoubleQuotes() { + checkForParseError("timestamp --format=\\"YYYY", DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 19); + } + + + AppNode parse(String taskDefinition) { return new TaskParser(taskDefinition).parse(); } @@ -281,4 +294,4 @@ public class TaskParserTests { } } } -} \\ No newline at end of file +}
    ['spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/TaskParserTests.java', 'spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java', 'spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/dsl/Tokenizer.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    846,280
    177,655
    24,594
    284
    524
    144
    9
    1
    67
    10
    19
    5
    0
    1
    1970-01-01T00:24:41
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    661
    spring-cloud/spring-cloud-dataflow/1118/1070
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/1070
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1118
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/1118
    1
    resolves
    REST: Retrieving non-existing app details should return a 404
    The issue is in class `AppRegistryController#DetailedAppRegistrationResource` When executing a **GET** `/apps/{type}/{name}` a `200` HTTP Status is returned. But it should produce a `404`. We need to ensure that when making this minor **breaking change** that the shell and web UI are working.
    1131305790f5cea7d6d6ace57e171c2a6997f595
    56472c0d1da7632e0acba9584a53bdf4e9eea048
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/1131305790f5cea7d6d6ace57e171c2a6997f595...56472c0d1da7632e0acba9584a53bdf4e9eea048
    diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java index 092e4e259..51dd91e31 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java @@ -109,7 +109,7 @@ public class AppRegistryController { @PathVariable("name") String name) { AppRegistration registration = appRegistry.find(name, type); if (registration == null) { - return null; + throw new NoSuchAppRegistrationException(name, type); } DetailedAppRegistrationResource result = new DetailedAppRegistrationResource(assembler.toResource(registration)); Resource resource = registration.getResource(); diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java index 011c55384..25add9adf 100644 --- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java +++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -124,6 +124,13 @@ public class AppRegistryControllerTests { .andExpect(status().isOk()).andExpect(jsonPath("content", hasSize(4))); } + @Test + public void testFindNonExistentApp() throws Exception { + mockMvc.perform( + get("/apps/source/foo").accept(MediaType.APPLICATION_JSON)).andDo(print()) + .andExpect(status().is4xxClientError()).andReturn().getResponse().getContentAsString().contains("NoSuchAppRegistrationException"); + } + @Test public void testRegisterAndListApplications() throws Exception { mockMvc.perform( diff --git a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java index 2f7de5d9a..8a6b984e9 100644 --- a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java +++ b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java @@ -101,39 +101,44 @@ public class AppRegistryCommands implements CommandMarker, ResourceLoaderAware { key = {"", "id"}, help = "id of the application to query in the form of 'type:name'") QualifiedApplicationName application) { - DetailedAppRegistrationResource info = appRegistryOperations().info(application.name, application.type); List<Object> result = new ArrayList<>(); - if (info != null) { - List<ConfigurationMetadataProperty> options = info.getOptions(); - result.add(String.format("Information about %s application '%s':", application.type, application.name)); - result.add(String.format("Resource URI: %s", info.getUri())); - if (info.getShortDescription() != null) { - result.add(info.getShortDescription()); - } - if (options == null) { - result.add("Application options metadata is not available"); - } - else { - TableModelBuilder<Object> modelBuilder = new TableModelBuilder<>(); - modelBuilder.addRow() - .addValue("Option Name") - .addValue("Description") - .addValue("Default") - .addValue("Type"); - for (ConfigurationMetadataProperty option : options) { + try { + DetailedAppRegistrationResource info = appRegistryOperations().info(application.name, application.type); + if (info != null) { + List<ConfigurationMetadataProperty> options = info.getOptions(); + result.add(String.format("Information about %s application '%s':", application.type, application.name)); + result.add(String.format("Resource URI: %s", info.getUri())); + if (info.getShortDescription() != null) { + result.add(info.getShortDescription()); + } + if (options == null) { + result.add("Application options metadata is not available"); + } + else { + TableModelBuilder<Object> modelBuilder = new TableModelBuilder<>(); modelBuilder.addRow() - .addValue(option.getId()) - .addValue(option.getDescription() == null ? "<unknown>" : option.getDescription()) - .addValue(prettyPrintDefaultValue(option)) - .addValue(option.getType() == null ? "<unknown>" : option.getType()); + .addValue("Option Name") + .addValue("Description") + .addValue("Default") + .addValue("Type"); + for (ConfigurationMetadataProperty option : options) { + modelBuilder.addRow() + .addValue(option.getId()) + .addValue(option.getDescription() == null ? "<unknown>" : option.getDescription()) + .addValue(prettyPrintDefaultValue(option)) + .addValue(option.getType() == null ? "<unknown>" : option.getType()); + } + TableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build())) + .on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30)) + .and(); + result.add(builder.build()); } - TableBuilder builder = DataFlowTables.applyStyle(new TableBuilder(modelBuilder.build())) - .on(CellMatchers.table()).addSizer(new AbsoluteWidthSizeConstraints(30)) - .and(); - result.add(builder.build()); + } + else { + result.add(String.format("Application info is not available for %s:%s", application.type, application.name)); } } - else { + catch (Exception e) { result.add(String.format("Application info is not available for %s:%s", application.type, application.name)); } return result;
    ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/AppRegistryController.java', 'spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/AppRegistryCommands.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/AppRegistryControllerTests.java']
    {'.java': 3}
    3
    3
    0
    0
    3
    856,660
    179,835
    24,861
    286
    2,959
    602
    63
    2
    302
    42
    69
    7
    0
    0
    1970-01-01T00:24:44
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    643
    spring-cloud/spring-cloud-dataflow/3549/3546
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/3546
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/3549
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/3549
    1
    resolves
    SCDF fails to start with Scheduling disabled
    As a user, when deploying SCDF to CF without Scheduling (i.e., `SPRING_CLOUD_DATAFLOW_FEATURES_SCHEDULES_ENABLED=false`), I get the following error on `master` and on `2.3 M2`. ``` 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT *************************** 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT APPLICATION FAILED TO START 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT *************************** 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT Description: 2019-10-07T21:36:17.35-0700 [APP/PROC/WEB/0] OUT Parameter 8 of method deleteTaskService in org.springframework.cloud.dataflow.server.config.features.TaskConfiguration required a bean of type 'org.springframework.cloud.dataflow.server.service.SchedulerService' that could not be found. ``` The same error also appeared when deploying `master` on K8s, but it could have been due to a corrupted/unstable image.
    e466301ea38e0ab8ac8cba564214769fd97b9807
    7431604333d48d74f26ab8219308b02dd99c8e88
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/e466301ea38e0ab8ac8cba564214769fd97b9807...7431604333d48d74f26ab8219308b02dd99c8e88
    diff --git a/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java b/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java index 13752c791..e2f7dd354 100644 --- a/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java +++ b/spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java @@ -32,11 +32,15 @@ import org.junit.Rule; import org.mockito.ArgumentMatchers; import org.springframework.cloud.dataflow.core.ApplicationType; +import org.springframework.cloud.dataflow.core.Launcher; +import org.springframework.cloud.dataflow.core.TaskPlatform; import org.springframework.cloud.dataflow.server.controller.TaskSchedulerController; import org.springframework.cloud.dataflow.server.service.SchedulerService; import org.springframework.cloud.dataflow.server.single.LocalDataflowResource; import org.springframework.cloud.deployer.spi.app.AppDeployer; import org.springframework.cloud.deployer.spi.scheduler.ScheduleInfo; +import org.springframework.cloud.deployer.spi.scheduler.ScheduleRequest; +import org.springframework.cloud.deployer.spi.scheduler.Scheduler; import org.springframework.cloud.skipper.domain.AboutResource; import org.springframework.cloud.skipper.domain.Dependency; import org.springframework.cloud.skipper.domain.Deployer; @@ -129,7 +133,9 @@ public abstract class BaseDocumentation { this.dataSource = springDataflowServer.getWebApplicationContext().getBean(DataSource.class); TaskSchedulerController controller = this.springDataflowServer.getWebApplicationContext().getBean(TaskSchedulerController.class); ReflectionTestUtils.setField(controller, "schedulerService", schedulerService()); - + TaskPlatform taskPlatform = this.springDataflowServer.getWebApplicationContext().getBean(TaskPlatform.class); + Launcher launcher = taskPlatform.getLaunchers().stream().filter(launcherToFilter -> launcherToFilter.getName().equals("default")).findFirst().get(); + ReflectionTestUtils.setField(launcher, "scheduler", localTestScheduler()); } /** @@ -271,17 +277,41 @@ public abstract class BaseDocumentation { public ScheduleInfo getSchedule(String scheduleName) { return null; } + }; + } + + private List<ScheduleInfo> getSampleList() { + List<ScheduleInfo> result = new ArrayList<>(); + ScheduleInfo scheduleInfo = new ScheduleInfo(); + scheduleInfo.setScheduleName("FOO"); + scheduleInfo.setTaskDefinitionName("BAR"); + Map<String, String> props = new HashMap<>(1); + props.put("scheduler.AAA.spring.cloud.scheduler.cron.expression", "00 41 17 ? * *"); + scheduleInfo.setScheduleProperties(props); + result.add(scheduleInfo); + return result; + } + + public Scheduler localTestScheduler() { + return new Scheduler() { + @Override + public void schedule(ScheduleRequest scheduleRequest) { + throw new UnsupportedOperationException("Interface is not implemented for schedule method."); + } - private List<ScheduleInfo> getSampleList() { - List<ScheduleInfo> result = new ArrayList<>(); - ScheduleInfo scheduleInfo = new ScheduleInfo(); - scheduleInfo.setScheduleName("FOO"); - scheduleInfo.setTaskDefinitionName("BAR"); - Map<String, String> props = new HashMap<>(1); - props.put("scheduler.AAA.spring.cloud.scheduler.cron.expression", "00 41 17 ? * *"); - scheduleInfo.setScheduleProperties(props); - result.add(scheduleInfo); - return result; + @Override + public void unschedule(String scheduleName) { + throw new UnsupportedOperationException("Interface is not implemented for unschedule method."); + } + + @Override + public List<ScheduleInfo> list(String taskDefinitionName) { + throw new UnsupportedOperationException("Interface is not implemented for list method."); + } + + @Override + public List<ScheduleInfo> list() { + return getSampleList(); } }; } diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java index 079e86d18..956148484 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java @@ -15,9 +15,7 @@ */ package org.springframework.cloud.dataflow.server.config.features; -import java.util.Collections; import java.util.List; -import java.util.Map; import javax.sql.DataSource; @@ -61,15 +59,12 @@ import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskJobServ import org.springframework.cloud.dataflow.server.service.impl.DefaultTaskSaveService; import org.springframework.cloud.dataflow.server.service.impl.TaskAppDeploymentRequestCreator; import org.springframework.cloud.dataflow.server.service.impl.TaskConfigurationProperties; -import org.springframework.cloud.deployer.spi.scheduler.ScheduleInfo; import org.springframework.cloud.deployer.spi.scheduler.Scheduler; import org.springframework.cloud.task.repository.TaskExplorer; import org.springframework.cloud.task.repository.TaskRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; import org.springframework.data.map.repository.config.EnableMapRepositories; import org.springframework.lang.Nullable; import org.springframework.transaction.PlatformTransactionManager; @@ -97,6 +92,9 @@ public class TaskConfiguration { @Autowired DataSourceProperties dataSourceProperties; + @Autowired(required = false) + SchedulerService schedulerService; + @Value("${spring.cloud.dataflow.server.uri:}") private String dataflowServerUri; @@ -130,55 +128,6 @@ public class TaskConfiguration { return taskPlatform; } - /** - * The default profile is active when no other profiles are active. This is configured so - * that several tests will pass without having to explicitly enable the local profile. - * @return a no-op {@link SchedulerService} - */ - @Profile({ "local", "default" }) - @Bean - public SchedulerService schedulerService() { - return new SchedulerService() { - @Override - public void schedule(String scheduleName, String taskDefinitionName, Map<String, String> taskProperties, List<String> commandLineArgs) { - } - - @Override - public void unschedule(String scheduleName) { - } - - @Override - public void unscheduleForTaskDefinition(String taskDefinitionName) { - } - - @Override - public List<ScheduleInfo> list(Pageable pageable, String taskDefinitionName) { - return null; - } - - @Override - public Page<ScheduleInfo> list(Pageable pageable) { - return null; - } - - @Override - public List<ScheduleInfo> list(String taskDefinitionName) { - return Collections.emptyList(); - } - - @Override - public List<ScheduleInfo> list() { - return Collections.emptyList(); - } - - @Override - public ScheduleInfo getSchedule(String scheduleName) { - return null; - } - }; - } - - @Bean public TaskExecutionInfoService taskDefinitionRetriever(AppRegistryService registry, TaskExplorer taskExplorer, TaskDefinitionRepository taskDefinitionRepository, @@ -194,15 +143,14 @@ public class TaskConfiguration { AuditRecordService auditRecordService, DataflowTaskExecutionDao dataflowTaskExecutionDao, DataflowJobExecutionDao dataflowJobExecutionDao, - DataflowTaskExecutionMetadataDao dataflowTaskExecutionMetadataDao, - SchedulerService schedulerService) { + DataflowTaskExecutionMetadataDao dataflowTaskExecutionMetadataDao) { return new DefaultTaskDeleteService(taskExplorer, launcherRepository, taskDefinitionRepository, taskDeploymentRepository, auditRecordService, dataflowTaskExecutionDao, dataflowJobExecutionDao, dataflowTaskExecutionMetadataDao, - schedulerService); + this.schedulerService); } @Bean diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java index bb3d6907e..6c5c8f489 100644 --- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java +++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java @@ -114,7 +114,6 @@ public class DefaultTaskDeleteService implements TaskDeleteService { Assert.notNull(dataflowTaskExecutionDao, "DataflowTaskExecutionDao must not be null"); Assert.notNull(dataflowJobExecutionDao, "DataflowJobExecutionDao must not be null"); Assert.notNull(dataflowTaskExecutionMetadataDao, "DataflowTaskExecutionMetadataDao must not be null"); - Assert.notNull(schedulerService, "SchedulerService must not be null"); this.taskExplorer = taskExplorer; this.launcherRepository = launcherRepository; this.taskDefinitionRepository = taskDefinitionRepository; @@ -324,7 +323,9 @@ public class DefaultTaskDeleteService implements TaskDeleteService { private void deleteTaskDefinition(TaskDefinition taskDefinition) { TaskParser taskParser = new TaskParser(taskDefinition.getName(), taskDefinition.getDslText(), true, true); - schedulerService.unscheduleForTaskDefinition(taskDefinition.getTaskName()); + if (this.schedulerService != null) { + schedulerService.unscheduleForTaskDefinition(taskDefinition.getTaskName()); + } TaskNode taskNode = taskParser.parse(); // if composed-task-runner definition then destroy all child tasks associated with it. if (taskNode.isComposed()) { diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java index 420a90488..468ae9aab 100644 --- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java +++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java @@ -45,6 +45,7 @@ import org.springframework.cloud.dataflow.server.DockerValidatorProperties; import org.springframework.cloud.dataflow.server.config.VersionInfoProperties; import org.springframework.cloud.dataflow.server.config.apps.CommonApplicationProperties; import org.springframework.cloud.dataflow.server.config.features.FeaturesProperties; +import org.springframework.cloud.dataflow.server.config.features.SchedulerConfiguration; import org.springframework.cloud.dataflow.server.job.LauncherRepository; import org.springframework.cloud.dataflow.server.repository.DataflowJobExecutionDao; import org.springframework.cloud.dataflow.server.repository.DataflowTaskExecutionDao; @@ -82,6 +83,7 @@ import org.springframework.cloud.task.repository.support.SimpleTaskRepository; import org.springframework.cloud.task.repository.support.TaskExecutionDaoFactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; @@ -104,6 +106,7 @@ import static org.mockito.Mockito.when; * @author Glenn Renfro * @author David Turanski * @author Gunnar Hillert + * @author Ilayaperumal Gopinathan */ @Configuration @EnableSpringDataWebSupport @@ -234,7 +237,7 @@ public class TaskServiceDependencies extends WebMvcConfigurationSupport { DataflowTaskExecutionDao dataflowTaskExecutionDao, DataflowJobExecutionDao dataflowJobExecutionDao, DataflowTaskExecutionMetadataDao dataflowTaskExecutionMetadataDao, - SchedulerService schedulerService) { + @Autowired(required = false) SchedulerService schedulerService) { return new DefaultTaskDeleteService(taskExplorer, launcherRepository, taskDefinitionRepository, taskDeploymentRepository, @@ -296,6 +299,7 @@ public class TaskServiceDependencies extends WebMvcConfigurationSupport { } @Bean + @Conditional({ SchedulerConfiguration.SchedulerConfigurationPropertyChecker.class }) public SchedulerService schedulerService(CommonApplicationProperties commonApplicationProperties, TaskPlatform taskPlatform, TaskDefinitionRepository taskDefinitionRepository, AppRegistryService registry, ResourceLoader resourceLoader, diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java index 4fbdd7abb..df558a59f 100644 --- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java +++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java @@ -78,7 +78,8 @@ import static org.mockito.Mockito.when; "spring.cloud.dataflow.applicationProperties.task.globalkey=globalvalue", "spring.cloud.dataflow.applicationProperties.stream.globalstreamkey=nothere", "spring.main.allow-bean-definition-overriding=true", - "spring.cloud.dataflow.task.scheduler-task-launcher-url=https://test.test"}) + "spring.cloud.dataflow.task.scheduler-task-launcher-url=https://test.test", + "spring.cloud.dataflow.features.schedules-enabled=true"}) @EnableConfigurationProperties({ CommonApplicationProperties.class, TaskConfigurationProperties.class, DockerValidatorProperties.class}) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureTestDatabase(replace = Replace.ANY)
    ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultTaskDeleteService.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/configuration/TaskServiceDependencies.java', 'spring-cloud-dataflow-classic-docs/src/test/java/org/springframework/cloud/dataflow/server/rest/documentation/BaseDocumentation.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java']
    {'.java': 5}
    5
    5
    0
    0
    5
    1,971,577
    425,151
    56,411
    533
    2,050
    434
    67
    2
    906
    85
    281
    11
    0
    1
    1970-01-01T00:26:11
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    644
    spring-cloud/spring-cloud-dataflow/3274/3264
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/3264
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/3274
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/3274
    1
    resolves
    NPE when registering the app without the app resolution schema
    As a user, I copied the following app registration command from the [Microsite](https://dataflow.spring.io/docs/recipes/polyglot/processor/), but it failed with an NPE. register: ``` app register --type processor --name python-processor --uri springcloud/polyglot-python-processor:0.1 ``` error: ``` 2019-06-04 22:03:20.278 ERROR 1 --- [nio-8080-exec-9] o.s.c.d.s.c.RestControllerAdvice : Caught exception while handling a request │ │ │ │ java.lang.NullPointerException: null │ │ at org.springframework.cloud.dataflow.registry.support.AppResourceCommon.getResource(AppResourceCommon.java:154) │ │ at org.springframework.cloud.dataflow.registry.service.DefaultAppRegistryService.getResourceVersion(DefaultAppRegistryService.java:266) ``` 1) We need to add `docker:` schema in the microsite instructions 2) Handle the NPE gracefully
    ba7570c9443f58ca5784a5f4960841d6ed98a9d6
    64bb806f267a325f7e513b710d4a608489171816
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/ba7570c9443f58ca5784a5f4960841d6ed98a9d6...64bb806f267a325f7e513b710d4a608489171816
    diff --git a/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java b/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java index 4c5cc44ea..85a42e2ff 100644 --- a/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java +++ b/spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java @@ -151,7 +151,12 @@ public class AppResourceCommon { public Resource getResource(String resourceUri) { Assert.isTrue(StringUtils.hasText(resourceUri), "Resource URI must not be empty"); try { - String scheme = new URI(resourceUri).getScheme().toLowerCase(); + String scheme = new URI(resourceUri).getScheme(); + if (scheme == null) { + throw new IllegalArgumentException("Invalid URI schema for resource: " + resourceUri + + " Expected URI schema prefix like file://, http:// or classpath:// but got none"); + } + scheme = scheme.toLowerCase(); Assert.notNull(scheme, "a scheme (prefix) is required"); switch (scheme) { diff --git a/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java b/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java index c1d8e565f..6d4e87412 100644 --- a/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java +++ b/spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java @@ -70,6 +70,19 @@ public class AppResourceCommonTests { } } + @Test + public void testInvalidUriSchema() { + try { + appResourceCommon.getResource("springcloud/polyglot-python-processor:0.1"); + fail("Excepted IllegalArgumentException for an invalid URI schema prefix"); + } + catch (IllegalArgumentException iae) { + assertThat(iae.getMessage().equals("Invalid URI schema for resource: " + + "springcloud/polyglot-python-processor:0.1 Expected URI schema prefix like file://, " + + "http:// or classpath:// but got none")); + } + } + @Test public void testDefaultResource() { String classpathUri = "classpath:AppRegistryTests-importAll.properties";
    ['spring-cloud-dataflow-registry/src/test/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommonTests.java', 'spring-cloud-dataflow-registry/src/main/java/org/springframework/cloud/dataflow/registry/support/AppResourceCommon.java']
    {'.java': 2}
    2
    2
    0
    0
    2
    1,807,312
    390,577
    52,140
    503
    370
    82
    7
    1
    1,265
    77
    213
    18
    1
    2
    1970-01-01T00:25:59
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0
    646
    spring-cloud/spring-cloud-dataflow/2509/2508
    spring-cloud
    spring-cloud-dataflow
    https://github.com/spring-cloud/spring-cloud-dataflow/issues/2508
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/2509
    https://github.com/spring-cloud/spring-cloud-dataflow/pull/2509
    1
    resolves
    app info cmd throws exception for `app info <type:name>`
    Description: ``` dataflow:>app info source:http Command failed java.lang.IllegalArgumentException: The options [<type>:<name>] and [--name && --type] are mutually exclusive and one of these should be specified to uniquely identify the application ``` Release versions: Latest master, 1.7.0.RC1
    26ebafe6c0c44d059c79b582aa2805b4cb71f864
    6fab2419dcc3bed5e470dd8e92444278d0288345
    https://github.com/spring-cloud/spring-cloud-dataflow/compare/26ebafe6c0c44d059c79b582aa2805b4cb71f864...6fab2419dcc3bed5e470dd8e92444278d0288345
    diff --git a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java index 72c867037..0b3cf45be 100644 --- a/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java +++ b/spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java @@ -88,8 +88,7 @@ public class ClassicAppRegistryCommands extends AbstractAppRegistryCommands impl public List<Object> info( @CliOption(key = { "", "id" }, help = "id of the application to query in the form of 'type:name'") QualifiedApplicationName application, - @CliOption(key = { "", - "name" }, help = "name of the application to query") String applicationName, + @CliOption(key = { "", "name" }, help = "name of the application to query") String applicationName, @CliOption(key = { "type" }, help = "type of the application to query") ApplicationType applicationType, @CliOption(key = { "exhaustive" }, help = "return all metadata, including common Spring Boot properties", @@ -142,7 +141,7 @@ public class ClassicAppRegistryCommands extends AbstractAppRegistryCommands impl private boolean assertAppInfoOptions(QualifiedApplicationName application, String name, ApplicationType type) { if (application != null && StringUtils.hasText(application.name) && application.type != null) { - return !(StringUtils.hasText(name) || (type != null)); + return type == null; } else { return (StringUtils.hasText(name) && type != null);
    ['spring-cloud-dataflow-shell-core/src/main/java/org/springframework/cloud/dataflow/shell/command/classic/ClassicAppRegistryCommands.java']
    {'.java': 1}
    1
    1
    0
    0
    1
    1,555,448
    331,474
    44,779
    445
    297
    76
    5
    1
    306
    36
    69
    10
    0
    1
    1970-01-01T00:25:39
    1,007
    Java
    {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190}
    Apache License 2.0