{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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 }); }); } })(); \", toCompactString(result));\n }\n+\n+ @Test\n+ public void shouldKeepHrTags() throws Exception {\n+ String html = \"one
two
three\";\n+\n+ Document result = htmlSanitizer.sanitize(html);\n+\n+ assertEquals(\"one
two
three\", toCompactString(result));\n+ }\n }"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.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":3600094,"string":"3,600,094"},"repo_tokens_count":{"kind":"number","value":707876,"string":"707,876"},"repo_lines_count":{"kind":"number","value":98981,"string":"98,981"},"repo_files_without_tests_count":{"kind":"number","value":484,"string":"484"},"changed_symbols_count":{"kind":"number","value":73,"string":"73"},"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":1342,"string":"1,342"},"issue_words_count":{"kind":"number","value":148,"string":"148"},"issue_tokens_count":{"kind":"number","value":282,"string":"282"},"issue_lines_count":{"kind":"number","value":29,"string":"29"},"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:25:08","string":"1970-01-01T00:25:08"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1320,"cells":{"id":{"kind":"number","value":9642,"string":"9,642"},"text_id":{"kind":"string","value":"thundernest/k-9/2863/2861"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/2861"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2863"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2863"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"URL at the beginning of a line in plain text body isn't linkified"},"issue_body":{"kind":"string","value":"This happens because we first convert the plain text to HTML and end up with something like:\r\n\r\n```html\r\n
http://uri.example.org
\r\n```\r\n\r\nBut right now only supported schemes preceded by a space, a newline, or an opening parenthesis are candidates for linkifying.\r\n\r\nhttps://github.com/k9mail/k-9/blob/27bc562ebe37bc139b84c13142681dbfe5640688/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java#L16"},"base_sha":{"kind":"string","value":"27bc562ebe37bc139b84c13142681dbfe5640688"},"head_sha":{"kind":"string","value":"2e20ddf6a5a5783ee483a5070eadf4c8b98a1ee2"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/27bc562ebe37bc139b84c13142681dbfe5640688...2e20ddf6a5a5783ee483a5070eadf4c8b98a1ee2"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java b/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java\nindex 815acc5ce..3d2565f27 100644\n--- a/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java\n+++ b/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java\n@@ -13,7 +13,7 @@ import android.text.TextUtils;\n public class UriLinkifier {\n private static final Pattern URI_SCHEME;\n private static final Map SUPPORTED_URIS;\n- private static final String SCHEME_SEPARATORS = \" (\\\\\\\\n\";\n+ private static final String SCHEME_SEPARATORS = \" (\\\\\\\\n>\";\n private static final String ALLOWED_SEPARATORS_PATTERN = \"(?:^|[\" + SCHEME_SEPARATORS + \"])\";\n \n static {\ndiff --git a/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java\nindex 3b02dc035..81abbbb34 100644\n--- a/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java\n+++ b/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java\n@@ -136,4 +136,13 @@ public class UriLinkifierTest {\n \"http://uri2.example.org/path postfix\",\n outputBuffer.toString());\n }\n+\n+ @Test\n+ public void uriSurroundedByHtmlTags() {\n+ String text = \"
http://uri.example.org
\";\n+\n+ UriLinkifier.linkifyText(text, outputBuffer);\n+\n+ assertEquals(\"
http://uri.example.org
\", outputBuffer.toString());\n+ }\n }"},"changed_files":{"kind":"string","value":"['k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java', 'k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.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":3600094,"string":"3,600,094"},"repo_tokens_count":{"kind":"number","value":707876,"string":"707,876"},"repo_lines_count":{"kind":"number","value":98981,"string":"98,981"},"repo_files_without_tests_count":{"kind":"number","value":484,"string":"484"},"changed_symbols_count":{"kind":"number","value":124,"string":"124"},"changed_tokens_count":{"kind":"number","value":32,"string":"32"},"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":416,"string":"416"},"issue_words_count":{"kind":"number","value":41,"string":"41"},"issue_tokens_count":{"kind":"number","value":108,"string":"108"},"issue_lines_count":{"kind":"number","value":9,"string":"9"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:08","string":"1970-01-01T00:25:08"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1321,"cells":{"id":{"kind":"number","value":9648,"string":"9,648"},"text_id":{"kind":"string","value":"thundernest/k-9/2203/2143"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/2143"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2203"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2203"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Clear local messages -> freeze"},"issue_body":{"kind":"string","value":"### Expected behavior\r\n\"Clear local messages\" should clear the locally stored messages, allowing one to re-download the messages from the server.\r\n\r\n### Actual behavior\r\nFreeze.\r\n\r\n### Steps to reproduce\r\n1. Have a folder with some large amount of messages. A few hundred should suffice.\r\n2. Make sure it's NOT up-to-date with the server\r\n3. Clear its local messages.\r\n\r\n### Environment\r\nK-9 Mail version: 5.203\r\n\r\nAndroid version: 6.0.1\r\n\r\nAccount type (IMAP, POP3, WebDAV/Exchange): IMAP\r\n"},"base_sha":{"kind":"string","value":"c150bafac3aa1137376af532bba1b13dfac85fd2"},"head_sha":{"kind":"string","value":"4161b914415aef08ab645387893812d13356bda3"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/c150bafac3aa1137376af532bba1b13dfac85fd2...4161b914415aef08ab645387893812d13356bda3"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java\nindex 4235018bf..203b6eb54 100644\n--- a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java\n+++ b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java\n@@ -476,31 +476,9 @@ public class FolderList extends K9ListActivity {\n }\n \n private void onClearFolder(Account account, String folderName) {\n- // There has to be a cheaper way to get at the localFolder object than this\n- LocalFolder localFolder = null;\n- try {\n- if (account == null || folderName == null || !account.isAvailable(FolderList.this)) {\n- Log.i(K9.LOG_TAG, \"not clear folder of unavailable account\");\n- return;\n- }\n- localFolder = account.getLocalStore().getFolder(folderName);\n- localFolder.open(Folder.OPEN_MODE_RW);\n- localFolder.clearAllMessages();\n- } catch (Exception e) {\n- Log.e(K9.LOG_TAG, \"Exception while clearing folder\", e);\n- } finally {\n- if (localFolder != null) {\n- localFolder.close();\n- }\n- }\n-\n- onRefresh(!REFRESH_REMOTE);\n+ MessagingController.getInstance(getApplication()).clearFolder(account, folderName, mAdapter.mListener);\n }\n \n-\n-\n-\n-\n private void sendMail(Account account) {\n MessagingController.getInstance(getApplication()).sendPendingMessages(account, mAdapter.mListener);\n }\ndiff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java\nindex 3f0af1a22..51d1d8a23 100644\n--- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java\n+++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java\n@@ -53,6 +53,7 @@ import com.fsck.k9.K9;\n import com.fsck.k9.K9.Intents;\n import com.fsck.k9.Preferences;\n import com.fsck.k9.R;\n+import com.fsck.k9.activity.ActivityListener;\n import com.fsck.k9.activity.MessageReference;\n import com.fsck.k9.activity.setup.AccountSetupCheckSettings.CheckDirection;\n import com.fsck.k9.cache.EmailProviderCache;\n@@ -3513,6 +3514,36 @@ public class MessagingController {\n });\n }\n \n+ public void clearFolder(final Account account, final String folderName, final ActivityListener listener) {\n+ putBackground(\"clearFolder\", listener, new Runnable() {\n+ @Override\n+ public void run() {\n+ clearFolderSynchronous(account, folderName, listener);\n+ }\n+ });\n+ }\n+\n+ @VisibleForTesting\n+ protected void clearFolderSynchronous(Account account, String folderName, MessagingListener listener) {\n+ LocalFolder localFolder = null;\n+ try {\n+ localFolder = account.getLocalStore().getFolder(folderName);\n+ localFolder.open(Folder.OPEN_MODE_RW);\n+ localFolder.clearAllMessages();\n+ } catch (UnavailableStorageException e) {\n+ Log.i(K9.LOG_TAG, \"Failed to clear folder because storage is not available - trying again later.\");\n+ throw new UnavailableAccountException(e);\n+ } catch (Exception e) {\n+ Log.e(K9.LOG_TAG, \"clearFolder failed\", e);\n+ addErrorMessage(account, null, e);\n+ } finally {\n+ closeFolder(localFolder);\n+ }\n+\n+ listFoldersSynchronous(account, false, listener);\n+ }\n+\n+\n /**\n * Find out whether the account type only supports a local Trash folder.\n *\ndiff --git a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java\nindex e0254d7a1..8429a6cea 100644\n--- a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java\n+++ b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java\n@@ -13,6 +13,7 @@ import android.content.Context;\n \n import com.fsck.k9.Account;\n import com.fsck.k9.AccountStats;\n+import com.fsck.k9.K9;\n import com.fsck.k9.K9RobolectricTestRunner;\n import com.fsck.k9.Preferences;\n import com.fsck.k9.helper.Contacts;\n@@ -26,6 +27,7 @@ import com.fsck.k9.mail.Store;\n import com.fsck.k9.mailstore.LocalFolder;\n import com.fsck.k9.mailstore.LocalMessage;\n import com.fsck.k9.mailstore.LocalStore;\n+import com.fsck.k9.mailstore.UnavailableStorageException;\n import com.fsck.k9.notification.NotificationController;\n import com.fsck.k9.search.LocalSearch;\n import org.junit.After;\n@@ -51,6 +53,7 @@ import static org.mockito.Matchers.eq;\n import static org.mockito.Mockito.atLeast;\n import static org.mockito.Mockito.atLeastOnce;\n import static org.mockito.Mockito.doAnswer;\n+import static org.mockito.Mockito.doThrow;\n import static org.mockito.Mockito.mock;\n import static org.mockito.Mockito.never;\n import static org.mockito.Mockito.times;\n@@ -80,6 +83,8 @@ public class MessagingControllerTest {\n @Mock\n private LocalFolder localFolder;\n @Mock\n+ private LocalFolder errorFolder;\n+ @Mock\n private Folder remoteFolder;\n @Mock\n private LocalStore localStore;\n@@ -130,6 +135,62 @@ public class MessagingControllerTest {\n controller.stop();\n }\n \n+ @Test\n+ public void clearFolderSynchronous_shouldOpenFolderForWriting() throws MessagingException {\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+\n+ verify(localFolder).open(Folder.OPEN_MODE_RW);\n+ }\n+\n+ @Test\n+ public void clearFolderSynchronous_shouldClearAllMessagesInTheFolder() throws MessagingException {\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+\n+ verify(localFolder).clearAllMessages();\n+ }\n+\n+ @Test\n+ public void clearFolderSynchronous_shouldCloseTheFolder() throws MessagingException {\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+\n+ verify(localFolder, atLeastOnce()).close();\n+ }\n+\n+ @Test(expected = UnavailableAccountException.class)\n+ public void clearFolderSynchronous_whenStorageUnavailable_shouldThrowUnavailableAccountException() throws MessagingException {\n+ doThrow(new UnavailableStorageException(\"Test\")).when(localFolder).open(Folder.OPEN_MODE_RW);\n+\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+ }\n+\n+ @Test()\n+ public void clearFolderSynchronous_whenExceptionThrown_shouldAddErrorMessage() throws MessagingException {\n+ doThrow(new RuntimeException(\"Test\")).when(localFolder).open(Folder.OPEN_MODE_RW);\n+\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+\n+ verify(errorFolder).appendMessages(any(List.class));\n+ }\n+\n+ @Test()\n+ public void clearFolderSynchronous_whenExceptionThrown_shouldStillCloseFolder() throws MessagingException {\n+ doThrow(new RuntimeException(\"Test\")).when(localFolder).open(Folder.OPEN_MODE_RW);\n+\n+ try {\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+ } catch (Exception ignored){\n+ }\n+\n+ verify(localFolder, atLeastOnce()).close();\n+ }\n+\n+ @Test()\n+ public void clearFolderSynchronous_shouldListFolders() throws MessagingException {\n+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);\n+\n+ verify(listener, atLeastOnce()).listFoldersStarted(account);\n+ }\n+\n @Test\n public void listFoldersSynchronous_shouldNotifyTheListenerListingStarted() throws MessagingException {\n List folders = Collections.singletonList(localFolder);\n@@ -758,11 +819,15 @@ public class MessagingControllerTest {\n when(account.getLocalStore()).thenReturn(localStore);\n when(account.getStats(any(Context.class))).thenReturn(accountStats);\n when(account.getMaximumAutoDownloadMessageSize()).thenReturn(MAXIMUM_SMALL_MESSAGE_SIZE);\n+ when(account.getErrorFolderName()).thenReturn(K9.ERROR_FOLDER_NAME);\n+ when(account.getEmail()).thenReturn(\"user@host.com\");\n }\n \n- private void configureLocalStore() {\n+ private void configureLocalStore() throws MessagingException {\n when(localStore.getFolder(FOLDER_NAME)).thenReturn(localFolder);\n when(localFolder.getName()).thenReturn(FOLDER_NAME);\n+ when(localStore.getFolder(K9.ERROR_FOLDER_NAME)).thenReturn(errorFolder);\n+ when(localStore.getPersonalNamespaces(false)).thenReturn(Collections.singletonList(localFolder));\n }\n \n private void configureRemoteStoreWithFolder() throws MessagingException {"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/activity/FolderList.java', 'k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java', 'k9mail/src/main/java/com/fsck/k9/controller/MessagingController.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":3476576,"string":"3,476,576"},"repo_tokens_count":{"kind":"number","value":690051,"string":"690,051"},"repo_lines_count":{"kind":"number","value":95154,"string":"95,154"},"repo_files_without_tests_count":{"kind":"number","value":439,"string":"439"},"changed_symbols_count":{"kind":"number","value":2165,"string":"2,165"},"changed_tokens_count":{"kind":"number","value":412,"string":"412"},"changed_lines_count":{"kind":"number","value":55,"string":"55"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":491,"string":"491"},"issue_words_count":{"kind":"number","value":73,"string":"73"},"issue_tokens_count":{"kind":"number","value":120,"string":"120"},"issue_lines_count":{"kind":"number","value":18,"string":"18"},"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:46","string":"1970-01-01T00:24:46"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1322,"cells":{"id":{"kind":"number","value":9636,"string":"9,636"},"text_id":{"kind":"string","value":"thundernest/k-9/3174/2164"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/2164"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3174"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3174"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Drafts deleted when syncronizing with IMAP server"},"issue_body":{"kind":"string","value":"Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue\r\n\r\n### Expected behavior\r\nWhen \"Save as Draft\" is selected, draft should be remain saved either locally or on the server for future access. \r\n\r\n### Actual behavior\r\nEither draft is automatically completely deleted and no longer available upon server sync, or the draft remains in the \"drafts\" folder but when opening the compose window, the text is no longer available. It seems this is dependent on the encryption setting; everytime I re-open the draft I have to re-select \"Don't encrypt\" because the default is always \"encrypt if possible\". The last selection should be remembered. If \"encypt if possible\" or \"encrypt\" is selected, the draft is deleted upon sync. If not, I can often no longer access the draft text. This happens regardless of account, and only started after upgrading to the latest K9 version and adding my keys to OpenKeychain (I was using a much older version of K9 prior to this, not sure which).\r\n\r\n### Steps to reproduce\r\n1. Create a draft email with text in the body.\r\n2. Select \"don't encrypt\"\r\n3. Save draft by selecting either \"save draft\" or by pressing back and \"save draft\".\r\n4. Text is gone after server sync.\r\n\r\nOR\r\n\r\n1. Create a draft email with text in the body.\r\n2. Select \"encrypt\" or \"encrypt if possible\".\r\n3. Save draft by selecting either \"save draft\" or by pressing back and \"save draft\".\r\n4. Draft is gone after server sync. \r\n\r\n\r\n### Environment\r\nK-9 Mail version: 5.203\r\n\r\nAndroid version: 5.1.1\r\n\r\nAccount type (IMAP, POP3, WebDAV/Exchange): IMAP\r\n"},"base_sha":{"kind":"string","value":"3009752cac4a0f7ea6341bbef01e41cf4ab27963"},"head_sha":{"kind":"string","value":"f4147483e14bc42c7544a6336b2e40d34b43ebb4"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/3009752cac4a0f7ea6341bbef01e41cf4ab27963...f4147483e14bc42c7544a6336b2e40d34b43ebb4"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java\nindex 0f42badfa..718c6efe1 100644\n--- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java\n+++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java\n@@ -898,7 +898,7 @@ public class MessagingController {\n if (account.syncRemoteDeletions()) {\n List destroyMessageUids = new ArrayList<>();\n for (String localMessageUid : localUidMap.keySet()) {\n- if (remoteUidMap.get(localMessageUid) == null) {\n+ if (!localMessageUid.startsWith(K9.LOCAL_UID_PREFIX) && remoteUidMap.get(localMessageUid) == null) {\n destroyMessageUids.add(localMessageUid);\n }\n }\n@@ -1761,9 +1761,15 @@ public class MessagingController {\n localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);\n remoteFolder.appendMessages(Collections.singletonList(localMessage));\n \n- localFolder.changeUid(localMessage);\n- for (MessagingListener l : getListeners()) {\n- l.messageUidChanged(account, folder, oldUid, localMessage.getUid());\n+ if (localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {\n+ // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded\n+ // version will be downloaded during the next sync.\n+ localFolder.destroyMessages(Collections.singletonList(localMessage));\n+ } else {\n+ localFolder.changeUid(localMessage);\n+ for (MessagingListener l : getListeners()) {\n+ l.messageUidChanged(account, folder, oldUid, localMessage.getUid());\n+ }\n }\n } else {\n /*\n@@ -1796,10 +1802,17 @@ public class MessagingController {\n localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);\n \n remoteFolder.appendMessages(Collections.singletonList(localMessage));\n- localFolder.changeUid(localMessage);\n- for (MessagingListener l : getListeners()) {\n- l.messageUidChanged(account, folder, oldUid, localMessage.getUid());\n+ if (localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {\n+ // We didn't get the server UID of the uploaded message. Remove the local message now. The\n+ // uploaded version will be downloaded during the next sync.\n+ localFolder.destroyMessages(Collections.singletonList(localMessage));\n+ } else {\n+ localFolder.changeUid(localMessage);\n+ for (MessagingListener l : getListeners()) {\n+ l.messageUidChanged(account, folder, oldUid, localMessage.getUid());\n+ }\n }\n+\n if (remoteDate != null) {\n remoteMessage.setFlag(Flag.DELETED, true);\n if (Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) {\n@@ -3172,9 +3185,8 @@ public class MessagingController {\n private void deleteMessagesSynchronous(final Account account, final String folder,\n final List messages,\n MessagingListener listener) {\n- Folder localFolder = null;\n- Folder localTrashFolder = null;\n- List uids = getUidsFromMessages(messages);\n+ LocalFolder localFolder = null;\n+ LocalFolder localTrashFolder = null;\n try {\n //We need to make these callbacks before moving the messages to the trash\n //as messages get a new UID after being moved\n@@ -3183,13 +3195,32 @@ public class MessagingController {\n l.messageDeleted(account, folder, message);\n }\n }\n- Store localStore = account.getLocalStore();\n+\n+ List localOnlyMessages = new ArrayList<>();\n+ List syncedMessages = new ArrayList<>();\n+ List syncedMessageUids = new ArrayList<>();\n+ for (Message message : messages) {\n+ String uid = message.getUid();\n+ if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {\n+ localOnlyMessages.add(message);\n+ } else {\n+ syncedMessages.add(message);\n+ syncedMessageUids.add(uid);\n+ }\n+ }\n+\n+ LocalStore localStore = account.getLocalStore();\n localFolder = localStore.getFolder(folder);\n Map uidMap = null;\n if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) {\n Timber.d(\"Deleting messages in trash folder or trash set to -None-, not copying\");\n \n- localFolder.setFlags(messages, Collections.singleton(Flag.DELETED), true);\n+ if (!localOnlyMessages.isEmpty()) {\n+ localFolder.destroyMessages(localOnlyMessages);\n+ }\n+ if (!syncedMessages.isEmpty()) {\n+ localFolder.setFlags(syncedMessages, Collections.singleton(Flag.DELETED), true);\n+ }\n } else {\n localTrashFolder = localStore.getFolder(account.getTrashFolderName());\n if (!localTrashFolder.exists()) {\n@@ -3221,18 +3252,21 @@ public class MessagingController {\n queuePendingCommand(account, command);\n }\n processPendingCommands(account);\n- } else if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {\n- if (folder.equals(account.getTrashFolderName())) {\n- queueSetFlag(account, folder, true, Flag.DELETED, uids);\n+ } else if (!syncedMessageUids.isEmpty()) {\n+ if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {\n+ if (folder.equals(account.getTrashFolderName())) {\n+ queueSetFlag(account, folder, true, Flag.DELETED, syncedMessageUids);\n+ } else {\n+ queueMoveOrCopy(account, folder, account.getTrashFolderName(), false,\n+ syncedMessageUids, uidMap);\n+ }\n+ processPendingCommands(account);\n+ } else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) {\n+ queueSetFlag(account, folder, true, Flag.SEEN, syncedMessageUids);\n+ processPendingCommands(account);\n } else {\n- queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap);\n+ Timber.d(\"Delete policy %s prevents delete from server\", account.getDeletePolicy());\n }\n- processPendingCommands(account);\n- } else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) {\n- queueSetFlag(account, folder, true, Flag.SEEN, uids);\n- processPendingCommands(account);\n- } else {\n- Timber.d(\"Delete policy %s prevents delete from server\", account.getDeletePolicy());\n }\n \n unsuppressMessages(account, messages);\ndiff --git a/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java b/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java\nindex c16869c47..ebfa32872 100644\n--- a/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java\n+++ b/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java\n@@ -227,7 +227,7 @@ class ImapSync {\n if (account.syncRemoteDeletions()) {\n List destroyMessageUids = new ArrayList<>();\n for (String localMessageUid : localUidMap.keySet()) {\n- if (remoteUidMap.get(localMessageUid) == null) {\n+ if (!localMessageUid.startsWith(K9.LOCAL_UID_PREFIX) && remoteUidMap.get(localMessageUid) == null) {\n destroyMessageUids.add(localMessageUid);\n }\n }"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java', 'k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.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":3643983,"string":"3,643,983"},"repo_tokens_count":{"kind":"number","value":713898,"string":"713,898"},"repo_lines_count":{"kind":"number","value":99791,"string":"99,791"},"repo_files_without_tests_count":{"kind":"number","value":492,"string":"492"},"changed_symbols_count":{"kind":"number","value":5025,"string":"5,025"},"changed_tokens_count":{"kind":"number","value":882,"string":"882"},"changed_lines_count":{"kind":"number","value":80,"string":"80"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":1696,"string":"1,696"},"issue_words_count":{"kind":"number","value":276,"string":"276"},"issue_tokens_count":{"kind":"number","value":400,"string":"400"},"issue_lines_count":{"kind":"number","value":29,"string":"29"},"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:18","string":"1970-01-01T00:25:18"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1323,"cells":{"id":{"kind":"number","value":9637,"string":"9,637"},"text_id":{"kind":"string","value":"thundernest/k-9/3146/3004"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/3004"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3146"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3146"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Body in decrypted mails empty by reply or forwarding"},"issue_body":{"kind":"string","value":"### Expected behavior\r\nIf I click reply or forward, the body of the original mail should be filled with the whole original text and maybe attachments by forwarding .\r\n\r\n### Actual behavior\r\nThere is only the header (Mailadress and so on) and the subject line of the original mail\r\n\r\n### Steps to reproduce\r\n1. Receive a encrypted mail\r\n2. Decrypt this mail\r\n3. Click reply or forward\r\n4. See there is no quote and no attachment (by forwarding) \r\n\r\n### Environment\r\nK-9 Mail version: 5.400\r\n\r\nAndroid version: 7.0\r\n\r\nAccount type (IMAP, POP3, WebDAV/Exchange): IMAP\r\n"},"base_sha":{"kind":"string","value":"6767f41505e6e784af03befd1a122a99f771ead1"},"head_sha":{"kind":"string","value":"8b11a7284ee2e4c2dd1c9b43d05859bcd3468187"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/6767f41505e6e784af03befd1a122a99f771ead1...8b11a7284ee2e4c2dd1c9b43d05859bcd3468187"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java\nindex 6d6daccf7..bda32a1fc 100644\n--- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java\n+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java\n@@ -37,10 +37,10 @@ public class MessageViewInfo {\n this.extraAttachments = extraAttachments;\n }\n \n- static MessageViewInfo createWithExtractedContent(Message message, boolean isMessageIncomplete,\n+ static MessageViewInfo createWithExtractedContent(Message message, Part rootPart, boolean isMessageIncomplete,\n String text, List attachments, AttachmentResolver attachmentResolver) {\n return new MessageViewInfo(\n- message, isMessageIncomplete, message, text, attachments, null, attachmentResolver, null,\n+ message, isMessageIncomplete, rootPart, text, attachments, null, attachmentResolver, null,\n Collections.emptyList());\n }\n \ndiff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java\nindex 975b56686..9956c2b9b 100644\n--- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java\n+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java\n@@ -124,7 +124,7 @@ public class MessageViewInfoExtractor {\n !message.isSet(Flag.X_DOWNLOADED_FULL) || MessageExtractor.hasMissingParts(message);\n \n return MessageViewInfo.createWithExtractedContent(\n- message, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver);\n+ message, contentPart, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver);\n }\n \n private ViewableExtractedText extractViewableAndAttachments(List parts,\ndiff --git a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java\nindex a74910994..eae6f7aca 100644\n--- a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java\n+++ b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java\n@@ -406,6 +406,8 @@ public class MessageViewInfoExtractorTest {\n \n assertEquals(\"
text
\", messageViewInfo.text);\n assertSame(annotation, messageViewInfo.cryptoResultAnnotation);\n+ assertSame(message, messageViewInfo.message);\n+ assertSame(message, messageViewInfo.rootPart);\n assertTrue(messageViewInfo.attachments.isEmpty());\n assertTrue(messageViewInfo.extraAttachments.isEmpty());\n }\n@@ -427,6 +429,8 @@ public class MessageViewInfoExtractorTest {\n \n assertEquals(\"
replacement text
\", messageViewInfo.text);\n assertSame(annotation, messageViewInfo.cryptoResultAnnotation);\n+ assertSame(message, messageViewInfo.message);\n+ assertSame(replacementPart, messageViewInfo.rootPart);\n assertTrue(messageViewInfo.attachments.isEmpty());\n assertTrue(messageViewInfo.extraAttachments.isEmpty());\n }"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java', 'k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.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":3656715,"string":"3,656,715"},"repo_tokens_count":{"kind":"number","value":717769,"string":"717,769"},"repo_lines_count":{"kind":"number","value":100395,"string":"100,395"},"repo_files_without_tests_count":{"kind":"number","value":492,"string":"492"},"changed_symbols_count":{"kind":"number","value":643,"string":"643"},"changed_tokens_count":{"kind":"number","value":118,"string":"118"},"changed_lines_count":{"kind":"number","value":6,"string":"6"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":566,"string":"566"},"issue_words_count":{"kind":"number","value":93,"string":"93"},"issue_tokens_count":{"kind":"number","value":137,"string":"137"},"issue_lines_count":{"kind":"number","value":19,"string":"19"},"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:17","string":"1970-01-01T00:25:17"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1324,"cells":{"id":{"kind":"number","value":9638,"string":"9,638"},"text_id":{"kind":"string","value":"thundernest/k-9/3130/3129"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/3129"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3130"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3130"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"App crashes when I click on contact logo"},"issue_body":{"kind":"string","value":"Hi,\r\nI've not found a recent issue related to my issue.\r\n\r\nThanks for your answer\r\n\r\n### Expected behavior\r\nIt should be create a new message with the clicked contact, as recipient.\r\n\r\n### Actual behavior\r\nSince the update, the app crashes when I click on contact logo square.\r\n\r\n### Steps to reproduce\r\n1. Open the app\r\n2. Click on the logo square of any email\r\n3. The app will crash\r\n\r\n### Environment\r\nK-9 Mail version: 5.403\r\n\r\nAndroid version: 5.1 with Flyme 6.2.0.0A\r\n\r\nAccount type (IMAP, POP3, WebDAV/Exchange): IMAP with Gmail\r\n"},"base_sha":{"kind":"string","value":"7c3b90b356ffe045c27b2ab5ceb0a4db3381a7b9"},"head_sha":{"kind":"string","value":"2ec1b3fe29aa8ce745acd03169f70cf0978c5b20"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/7c3b90b356ffe045c27b2ab5ceb0a4db3381a7b9...2ec1b3fe29aa8ce745acd03169f70cf0978c5b20"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java b/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java\nindex fbea32426..6a09fedca 100644\n--- a/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java\n+++ b/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java\n@@ -1,6 +1,7 @@\n package com.fsck.k9.ui;\n \n \n+import android.content.ActivityNotFoundException;\n import android.content.AsyncQueryHandler;\n import android.content.ContentResolver;\n import android.content.Context;\n@@ -20,6 +21,9 @@ import android.view.View.OnClickListener;\n import android.view.accessibility.AccessibilityEvent;\n import android.view.accessibility.AccessibilityNodeInfo;\n import android.widget.ImageView;\n+import android.widget.Toast;\n+\n+import com.fsck.k9.R;\n \n \n /**\n@@ -207,10 +211,14 @@ public class ContactBadge extends ImageView implements OnClickListener {\n getContext(), ContactBadge.this, lookupUri, QuickContact.MODE_LARGE, null);\n } else if (createUri != null) {\n // Prompt user to add this person to contacts\n- final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri);\n- extras.remove(EXTRA_URI_CONTENT);\n- intent.putExtras(extras);\n- getContext().startActivity(intent);\n+ try {\n+ final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri);\n+ extras.remove(EXTRA_URI_CONTENT);\n+ intent.putExtras(extras);\n+ getContext().startActivity(intent);\n+ } catch (ActivityNotFoundException e) {\n+ Toast.makeText(getContext(), R.string.error_activity_not_found, Toast.LENGTH_LONG).show();\n+ }\n }\n }\n }"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.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":3656975,"string":"3,656,975"},"repo_tokens_count":{"kind":"number","value":718237,"string":"718,237"},"repo_lines_count":{"kind":"number","value":100405,"string":"100,405"},"repo_files_without_tests_count":{"kind":"number","value":492,"string":"492"},"changed_symbols_count":{"kind":"number","value":814,"string":"814"},"changed_tokens_count":{"kind":"number","value":131,"string":"131"},"changed_lines_count":{"kind":"number","value":16,"string":"16"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":537,"string":"537"},"issue_words_count":{"kind":"number","value":89,"string":"89"},"issue_tokens_count":{"kind":"number","value":140,"string":"140"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"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:16","string":"1970-01-01T00:25:16"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1325,"cells":{"id":{"kind":"number","value":9639,"string":"9,639"},"text_id":{"kind":"string","value":"thundernest/k-9/3073/3065"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/3065"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3073"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3073"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"tel URI links are stripped by HtmlSanitizer"},"issue_body":{"kind":"string","value":"Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue\r\n\r\n### Expected behavior\r\nTell us what should happen\r\nClick to call link does not work since a few weeks. A click to call link is a hyperlink which is opened by a dialer-application. For Exampel: `55555`\r\n\r\n### Actual behavior\r\nTell us what happens instead\r\nLink is shown as plain text\r\n\r\n### Steps to reproduce\r\n1. Create a new mail with html code` 55555` in it\r\n2. Check for new mails in an old version of k9, or in thunderbird and look for the link\r\n3. Check with current k9 mail, link is shown as plain-text.\r\n\r\n### Environment\r\nK-9 Mail version: current 5.403\r\n\r\nAndroid version:\r\n7.0 (motorola) and 7.1.2 (lineage) verified\r\n\r\nAccount type (IMAP, POP3, WebDAV/Exchange):\r\ndoes not matter\r\n "},"base_sha":{"kind":"string","value":"e4467ef959d5dc13d84afb9e49029cc6676fe6f5"},"head_sha":{"kind":"string","value":"11f6614a3b63371e2ce8b7d41623692990de2930"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/e4467ef959d5dc13d84afb9e49029cc6676fe6f5...11f6614a3b63371e2ce8b7d41623692990de2930"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java\nindex 63e9eaedb..2b197857a 100644\n--- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java\n+++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java\n@@ -25,7 +25,8 @@ public class HtmlSanitizer {\n \"align\", \"bgcolor\", \"colspan\", \"headers\", \"height\", \"nowrap\", \"rowspan\", \"scope\", \"valign\",\n \"width\")\n .addAttributes(\":all\", \"class\", \"style\", \"id\")\n- .addProtocols(\"img\", \"src\", \"http\", \"https\", \"cid\", \"data\");\n+ .addProtocols(\"img\", \"src\", \"http\", \"https\", \"cid\", \"data\")\n+ .addProtocols(\"a\", \"href\", \"tel\", \"sip\", \"bitcoin\", \"ethereum\", \"rtsp\");\n \n cleaner = new Cleaner(whitelist);\n headCleaner = new HeadCleaner();\ndiff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java\nindex 38d8d6e4f..3e9f6bf9c 100644\n--- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java\n+++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java\n@@ -213,4 +213,31 @@ public class HtmlSanitizerTest {\n \"
A
\" +\n \"\", toCompactString(result));\n }\n+\n+ @Test\n+ public void shouldKeepUris() {\n+ String html = \"\" +\n+ \"HTTP\" +\n+ \"HTTPS\" +\n+ \"Mailto\" +\n+ \"Telephone\" +\n+ \"SIP\" +\n+ \"Bitcoin\" +\n+ \"Ethereum\" +\n+ \"RTSP\" +\n+ \"\";\n+\n+ Document result = htmlSanitizer.sanitize(html);\n+\n+ assertEquals(\"\" +\n+ \"HTTP\" +\n+ \"HTTPS\" +\n+ \"Mailto\" +\n+ \"Telephone\" +\n+ \"SIP\" +\n+ \"Bitcoin\" +\n+ \"Ethereum\" +\n+ \"RTSP\" +\n+ \"\", toCompactString(result));\n+ }\n }"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.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":3654448,"string":"3,654,448"},"repo_tokens_count":{"kind":"number","value":717970,"string":"717,970"},"repo_lines_count":{"kind":"number","value":100340,"string":"100,340"},"repo_files_without_tests_count":{"kind":"number","value":492,"string":"492"},"changed_symbols_count":{"kind":"number","value":244,"string":"244"},"changed_tokens_count":{"kind":"number","value":73,"string":"73"},"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":952,"string":"952"},"issue_words_count":{"kind":"number","value":147,"string":"147"},"issue_tokens_count":{"kind":"number","value":256,"string":"256"},"issue_lines_count":{"kind":"number","value":24,"string":"24"},"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:15","string":"1970-01-01T00:25:15"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1326,"cells":{"id":{"kind":"number","value":9647,"string":"9,647"},"text_id":{"kind":"string","value":"thundernest/k-9/2215/1500"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/1500"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2215"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2215"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"Webdav (Exchange) sending email is broken since v5.109 (alpha)"},"issue_body":{"kind":"string","value":"Android version: 6.01\n\nUsing K-9 Mail v5.010 (stable) i could send emails using my old WEBDAV account.\nBut never delete emails on the server.\nThen Updated to K-9 Mail v5.109 (alpha) / and also to K-9 Mail v5.110 (alpha).\nNow I can delete emails on the server, but I can not send emails any more.\nThey end up on the outgoing folder.\nSorry I can't tell you the error message. The message text is too long so it's truncated...\n\nThen Downgraded (titanium Backup / also the database) and sending emails is working again.\n"},"base_sha":{"kind":"string","value":"c150bafac3aa1137376af532bba1b13dfac85fd2"},"head_sha":{"kind":"string","value":"2cec47491d963b0e7493469aba1bf9497ccf2678"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/c150bafac3aa1137376af532bba1b13dfac85fd2...2cec47491d963b0e7493469aba1bf9497ccf2678"},"diff":{"kind":"string","value":"diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java\nindex 7eda5d5b3..0f7d8da1b 100644\n--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java\n+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java\n@@ -27,6 +27,7 @@ import java.io.InputStreamReader;\n import java.net.URI;\n import java.net.URISyntaxException;\n import java.util.ArrayList;\n+import java.util.Collections;\n import java.util.Date;\n import java.util.HashMap;\n import java.util.List;\n@@ -678,28 +679,8 @@ class WebDavFolder extends Folder {\n \n Log.i(LOG_TAG, \"Uploading message as \" + messageURL);\n \n- httpmethod = new HttpGeneric(messageURL);\n- httpmethod.setMethod(\"PUT\");\n- httpmethod.setEntity(bodyEntity);\n+ store.sendRequest(messageURL, \"PUT\", bodyEntity, null, true);\n \n- String mAuthString = store.getAuthString();\n-\n- if (mAuthString != null) {\n- httpmethod.setHeader(\"Authorization\", mAuthString);\n- }\n-\n- response = httpclient.executeOverride(httpmethod, store.getContext());\n- statusCode = response.getStatusLine().getStatusCode();\n-\n- if (statusCode < 200 ||\n- statusCode > 300) {\n-\n- //TODO: Could we handle a login timeout here?\n-\n- throw new IOException(\"Error with status code \" + statusCode\n- + \" while sending/appending message. Response = \"\n- + response.getStatusLine().toString() + \" for message \" + messageURL);\n- }\n WebDavMessage retMessage = new WebDavMessage(message.getUid(), this);\n \n retMessage.setUrl(messageURL);\ndiff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java\nindex 3132904b3..44ed5fa04 100644\n--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java\n+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java\n@@ -830,7 +830,7 @@ public class WebDavStore extends RemoteStore {\n return mHttpClient;\n }\n \n- private InputStream sendRequest(String url, String method, StringEntity messageBody,\n+ protected InputStream sendRequest(String url, String method, StringEntity messageBody,\n Map headers, boolean tryAuth)\n throws MessagingException {\n if (url == null || method == null) {\ndiff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java\nindex 69b18552a..e9a6d1a25 100644\n--- a/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java\n+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java\n@@ -12,6 +12,7 @@ import org.apache.http.HttpResponse;\n import org.apache.http.StatusLine;\n import org.apache.http.client.methods.HttpUriRequest;\n import org.apache.http.entity.BasicHttpEntity;\n+import org.apache.http.entity.StringEntity;\n import org.apache.http.protocol.HttpContext;\n import org.junit.Before;\n import org.junit.Test;\n@@ -37,6 +38,7 @@ import static org.mockito.Matchers.anyInt;\n import static org.mockito.Matchers.anyMapOf;\n import static org.mockito.Matchers.anyString;\n import static org.mockito.Matchers.eq;\n+import static org.mockito.Matchers.isNull;\n import static org.mockito.Mockito.doThrow;\n import static org.mockito.Mockito.mock;\n import static org.mockito.Mockito.times;\n@@ -75,10 +77,16 @@ public class WebDavFolderTest {\n private StatusLine mockStatusLine;\n @Captor\n private ArgumentCaptor> headerCaptor;\n+ @Captor\n+ private ArgumentCaptor urlCaptor;\n+ @Captor\n+ private ArgumentCaptor entityCaptor;\n \n private WebDavFolder folder;\n \n private WebDavFolder destinationFolder;\n+ private String storeUrl = \"https://localhost/webDavStoreUrl\";\n+ private String folderName = \"testFolder\";\n private String moveOrCopyXml = \"MoveOrCopyXml\";\n private HashMap moveOrCopyHeaders;\n private List messages;\n@@ -86,10 +94,10 @@ public class WebDavFolderTest {\n @Before\n public void before() throws MessagingException, IOException {\n MockitoAnnotations.initMocks(this);\n- when(mockStore.getUrl()).thenReturn(\"https://localhost/webDavStoreUrl\");\n+ when(mockStore.getUrl()).thenReturn(storeUrl);\n when(mockStore.getHttpClient()).thenReturn(mockHttpClient);\n when(mockStore.getStoreConfig()).thenReturn(mockStoreConfig);\n- folder = new WebDavFolder(mockStore, \"testFolder\");\n+ folder = new WebDavFolder(mockStore, folderName);\n \n setupTempDirectory();\n }\n@@ -514,9 +522,6 @@ public class WebDavFolderTest {\n \n @Test\n public void appendWebDavMessages_replaces_messages_with_WebDAV_versions() throws MessagingException, IOException {\n- when(mockHttpClient.executeOverride(any(HttpUriRequest.class), any(HttpContext.class))).thenReturn(mockHttpResponse);\n- when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine);\n- when(mockStatusLine.getStatusCode()).thenReturn(200);\n List existingMessages = new ArrayList<>();\n Message existingMessage = mock(Message.class);\n existingMessages.add(existingMessage);\n@@ -529,4 +534,20 @@ public class WebDavFolderTest {\n assertEquals(WebDavMessage.class, response.get(0).getClass());\n assertEquals(messageUid, response.get(0).getUid());\n }\n+\n+ @Test\n+ public void appendWebDavMessages_sendsRequestUsingStore() throws MessagingException, IOException {\n+ List existingMessages = new ArrayList<>();\n+ Message existingMessage = mock(Message.class);\n+ existingMessages.add(existingMessage);\n+ String messageUid = \"testMessageUid\";\n+ when(existingMessage.getUid()).thenReturn(messageUid);\n+\n+ folder.appendWebDavMessages(existingMessages);\n+\n+ verify(mockStore).sendRequest(urlCaptor.capture(), eq(\"PUT\"), entityCaptor.capture(),\n+ Matchers.>eq(null), eq(true));\n+ assertTrue(urlCaptor.getValue().startsWith(storeUrl + \"/\" + folderName + \"/\" + messageUid));\n+ assertTrue(urlCaptor.getValue().endsWith(\".eml\"));\n+ }\n }"},"changed_files":{"kind":"string","value":"['k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.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":3476576,"string":"3,476,576"},"repo_tokens_count":{"kind":"number","value":690051,"string":"690,051"},"repo_lines_count":{"kind":"number","value":95154,"string":"95,154"},"repo_files_without_tests_count":{"kind":"number","value":439,"string":"439"},"changed_symbols_count":{"kind":"number","value":1247,"string":"1,247"},"changed_tokens_count":{"kind":"number","value":207,"string":"207"},"changed_lines_count":{"kind":"number","value":25,"string":"25"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":516,"string":"516"},"issue_words_count":{"kind":"number","value":93,"string":"93"},"issue_tokens_count":{"kind":"number","value":136,"string":"136"},"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:24:46","string":"1970-01-01T00:24:46"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1327,"cells":{"id":{"kind":"number","value":9646,"string":"9,646"},"text_id":{"kind":"string","value":"thundernest/k-9/2380/2282"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/2282"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2380"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2380"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Crash in 5.205: Bug in ParcelableUtil.unmarshall()?"},"issue_body":{"kind":"string","value":"Crash reported via Google Play.\r\n\r\nUser messages:\r\n* crash when opening from 1x1 widget\r\n* using inbox icon to start k9 results in crash\r\n* force closes on start from widget\r\n\r\n\r\n```\r\njava.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.NullPointerException: Attempt to get length of null array\r\n\tat android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)\r\n\tat android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)\r\n\tat android.app.ActivityThread.access$1100(ActivityThread.java:221)\r\n\tat android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)\r\n\tat android.os.Handler.dispatchMessage(Handler.java:102)\r\n\tat android.os.Looper.loop(Looper.java:158)\r\n\tat android.app.ActivityThread.main(ActivityThread.java:7224)\r\n\tat java.lang.reflect.Method.invoke(Native Method)\r\n\tat com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)\r\n\tat com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)\r\nCaused by: java.lang.NullPointerException: Attempt to get length of null array\r\n\tat com.fsck.k9.helper.ParcelableUtil.unmarshall(ParcelableUtil.java:27)\r\n\tat com.fsck.k9.helper.ParcelableUtil.unmarshall(ParcelableUtil.java:19)\r\n\tat com.fsck.k9.activity.MessageList.decodeExtras(MessageList.java:437)\r\n\tat com.fsck.k9.activity.MessageList.onCreate(MessageList.java:225)\r\n\tat android.app.Activity.performCreate(Activity.java:6876)\r\n\tat android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)\r\n\tat android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)\r\n\t... 9 more\r\n```"},"base_sha":{"kind":"string","value":"7880e8396e9f4674a3728543742eec64ad389242"},"head_sha":{"kind":"string","value":"5485f7a1bb8c5d816706e58b35a176cfd79c7de9"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/7880e8396e9f4674a3728543742eec64ad389242...5485f7a1bb8c5d816706e58b35a176cfd79c7de9"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java\nindex f1addf57f..28f4c0df3 100644\n--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java\n+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java\n@@ -72,8 +72,11 @@ public class MessageList extends K9Activity implements MessageListFragmentListen\n MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener,\n OnSwitchCompleteListener {\n \n- // for this activity\n- private static final String EXTRA_SEARCH = \"search\";\n+ @Deprecated\n+ //TODO: Remove after 2017-09-11\n+ private static final String EXTRA_SEARCH_OLD = \"search\";\n+\n+ private static final String EXTRA_SEARCH = \"search_bytes\";\n private static final String EXTRA_NO_THREADING = \"no_threading\";\n \n private static final String ACTION_SHORTCUT = \"shortcut\";\n@@ -431,6 +434,9 @@ public class MessageList extends K9Activity implements MessageListFragmentListen\n mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS);\n }\n }\n+ } else if (intent.hasExtra(EXTRA_SEARCH_OLD)) {\n+ mSearch = intent.getParcelableExtra(EXTRA_SEARCH_OLD);\n+ mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);\n } else {\n // regular LocalSearch object was passed\n mSearch = intent.hasExtra(EXTRA_SEARCH) ?"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/activity/MessageList.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":3498297,"string":"3,498,297"},"repo_tokens_count":{"kind":"number","value":692380,"string":"692,380"},"repo_lines_count":{"kind":"number","value":95953,"string":"95,953"},"repo_files_without_tests_count":{"kind":"number","value":446,"string":"446"},"changed_symbols_count":{"kind":"number","value":469,"string":"469"},"changed_tokens_count":{"kind":"number","value":104,"string":"104"},"changed_lines_count":{"kind":"number","value":10,"string":"10"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1647,"string":"1,647"},"issue_words_count":{"kind":"number","value":95,"string":"95"},"issue_tokens_count":{"kind":"number","value":371,"string":"371"},"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:24:49","string":"1970-01-01T00:24:49"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1328,"cells":{"id":{"kind":"number","value":9645,"string":"9,645"},"text_id":{"kind":"string","value":"thundernest/k-9/2521/2503"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/2503"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2521"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2521"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Export settings does not export 'Support signing of unecrypted mail' setting"},"issue_body":{"kind":"string","value":"If I set 'Support signing of unecrypted mail' option, then export the settings, then clear K9 mail app. data, then import the settings, the 'Support signing of unecrypted mail' option does not get set."},"base_sha":{"kind":"string","value":"231b46f27839f599d95ef3f62cd66f4a20e0e62e"},"head_sha":{"kind":"string","value":"35a29ec4560a031c6ada2849be987aee08108e60"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/231b46f27839f599d95ef3f62cd66f4a20e0e62e...35a29ec4560a031c6ada2849be987aee08108e60"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java b/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java\nindex 14c77e63e..f1a799ed9 100644\n--- a/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java\n+++ b/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java\n@@ -285,10 +285,10 @@ public class GlobalSettings {\n s.put(\"pgpSignOnlyDialogCounter\", Settings.versions(\n new V(45, new IntegerRangeSetting(0, Integer.MAX_VALUE, 0))\n ));\n- s.put(\"openpgpProvider\", Settings.versions(\n+ s.put(\"openPgpProvider\", Settings.versions(\n new V(46, new StringSetting(K9.NO_OPENPGP_PROVIDER))\n ));\n- s.put(\"openpgpSupportSignOnly\", Settings.versions(\n+ s.put(\"openPgpSupportSignOnly\", Settings.versions(\n new V(47, new BooleanSetting(false))\n ));\n "},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.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":3519596,"string":"3,519,596"},"repo_tokens_count":{"kind":"number","value":691880,"string":"691,880"},"repo_lines_count":{"kind":"number","value":96815,"string":"96,815"},"repo_files_without_tests_count":{"kind":"number","value":464,"string":"464"},"changed_symbols_count":{"kind":"number","value":225,"string":"225"},"changed_tokens_count":{"kind":"number","value":56,"string":"56"},"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":201,"string":"201"},"issue_words_count":{"kind":"number","value":34,"string":"34"},"issue_tokens_count":{"kind":"number","value":49,"string":"49"},"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:24:53","string":"1970-01-01T00:24:53"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1329,"cells":{"id":{"kind":"number","value":9640,"string":"9,640"},"text_id":{"kind":"string","value":"thundernest/k-9/3025/3018"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/3018"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3025"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/3025"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Bad
detection causes emails to appear empty"},"issue_body":{"kind":"string","value":"Some emails displayed empty, despite there is text in the email body. \r\nNote: Email preview in notification window shows (part) of body; but email body seems empty in K9.\r\n\r\nThis behavior has been introduced with the latest K9 update a few days ago.\r\n\r\n### Expected behavior\r\nEmail displayed correctly.\r\n\r\n### Actual behavior\r\nEmail shown empty. When using \"Reply\" on the mail, no email body is shown, the wait cursor is shown indefinitely.\r\n\r\n### Steps to reproduce\r\nNot sure why some emails get not displayed. I could provide the emails not correctly shown if needed.\r\n\r\n### Environment\r\nK-9 Mail version: 5.400\r\n\r\nAndroid version:\r\n7.1.1 and also 4.4.4\r\n\r\n\r\nAccount type (IMAP, POP3, WebDAV/Exchange): POP3\r\n"},"base_sha":{"kind":"string","value":"1506c6d4c028586da0cac60d0688f6a2493ed1e5"},"head_sha":{"kind":"string","value":"b49af84dc803c361244ece7e0333787d2e321573"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/1506c6d4c028586da0cac60d0688f6a2493ed1e5...b49af84dc803c361244ece7e0333787d2e321573"},"diff":{"kind":"string","value":"diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java\nindex 9d5d27aa4..fb618e80d 100644\n--- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java\n+++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java\n@@ -5,7 +5,6 @@ import java.util.Collections;\n import java.util.HashSet;\n import java.util.Locale;\n import java.util.Set;\n-import java.util.regex.Pattern;\n \n import android.text.Annotation;\n import android.text.Editable;\n@@ -179,11 +178,6 @@ public class HtmlConverter {\n \"style=\\\\\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid $$COLOR$$; padding-left: 1ex;\\\\\">\";\n private static final String HTML_BLOCKQUOTE_END = \"\";\n private static final String HTML_NEWLINE = \"
\";\n- private static final Pattern ASCII_PATTERN_FOR_HR = Pattern.compile(\n- \"(^|\\\\\\\\Q\" + HTML_NEWLINE + \"\\\\\\\\E)\\\\\\\\s*((\\\\\\\\Q\" + HTML_NEWLINE + \"\\\\\\\\E)*\" +\n- \"((((\\\\\\\\Q\" + HTML_NEWLINE + \"\\\\\\\\E){0,2}([-=_]{3,})(\\\\\\\\Q\" + HTML_NEWLINE +\n- \"\\\\\\\\E){0,2})|(([-=_]{2,} ?)(8&lt;|8|%&lt;|%)\" +\n- \"( ?[-=_]{2,})))+(\\\\\\\\Q\" + HTML_NEWLINE + \"\\\\\\\\E|$)))\");\n \n /**\n * Convert a text string into an HTML document.\n@@ -276,7 +270,7 @@ public class HtmlConverter {\n HTML_BLOCKQUOTE_END + \"$1\"\n );\n \n- text = ASCII_PATTERN_FOR_HR.matcher(text).replaceAll(\"
\");\n+ text = text.replaceAll(\"\\\\\\\\s*([-=_]{30,}+)\\\\\\\\s*\", \"
\");\n \n StringBuffer sb = new StringBuffer(text.length() + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH);\n \ndiff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java\nindex 9cd79b53d..b2dca89a9 100644\n--- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java\n+++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java\n@@ -8,6 +8,7 @@ import java.io.IOException;\n \n import com.fsck.k9.K9RobolectricTestRunner;\n import org.apache.commons.io.IOUtils;\n+import org.junit.Ignore;\n import org.junit.Test;\n import org.junit.runner.RunWith;\n import org.robolectric.annotation.Config;\n@@ -194,6 +195,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void issue2259Spec() {\n String text = \"text\\\\n\" +\n \"---------------------------\\\\n\" +\n@@ -225,6 +227,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void mergeConsecutiveBreaksIntoOne() {\n String text = \"hello\\\\n------------\\\\n---------------\\\\nfoo bar\";\n String result = HtmlConverter.textToHtml(text);\n@@ -260,6 +263,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void anyTripletIsHRuledOut() {\n String text = \"--=\\\\n-=-\\\\n===\\\\n___\\\\n\\\\n\";\n String result = HtmlConverter.textToHtml(text);\n@@ -267,6 +271,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void replaceSpaceSeparatedDashesWithHR() {\n String text = \"hello\\\\n---------------------------\\\\nfoo bar\";\n String result = HtmlConverter.textToHtml(text);\n@@ -274,6 +279,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void replacementWithHRAtBeginning() {\n String text = \"---------------------------\\\\nfoo bar\";\n String result = HtmlConverter.textToHtml(text);\n@@ -281,6 +287,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void replacementWithHRAtEnd() {\n String text = \"hello\\\\n__________________________________\";\n String result = HtmlConverter.textToHtml(text);\n@@ -288,6 +295,7 @@ public class HtmlConverterTest {\n }\n \n @Test\n+ @Ignore(\"Disabled due to temporary fix for issue #3018\")\n public void replacementOfScissorsByHR() {\n String text = \"hello\\\\n-- %< -------------- >8 --\\\\nworld\\\\n\";\n String result = HtmlConverter.textToHtml(text);"},"changed_files":{"kind":"string","value":"['k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.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":3599243,"string":"3,599,243"},"repo_tokens_count":{"kind":"number","value":707505,"string":"707,505"},"repo_lines_count":{"kind":"number","value":98930,"string":"98,930"},"repo_files_without_tests_count":{"kind":"number","value":484,"string":"484"},"changed_symbols_count":{"kind":"number","value":543,"string":"543"},"changed_tokens_count":{"kind":"number","value":178,"string":"178"},"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":711,"string":"711"},"issue_words_count":{"kind":"number","value":112,"string":"112"},"issue_tokens_count":{"kind":"number","value":166,"string":"166"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"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:14","string":"1970-01-01T00:25:14"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1330,"cells":{"id":{"kind":"number","value":9641,"string":"9,641"},"text_id":{"kind":"string","value":"thundernest/k-9/2885/2846"},"repo_owner":{"kind":"string","value":"thundernest"},"repo_name":{"kind":"string","value":"k-9"},"issue_url":{"kind":"string","value":"https://github.com/thundernest/k-9/issues/2846"},"pull_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2885"},"comment_url":{"kind":"string","value":"https://github.com/thundernest/k-9/pull/2885"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Parsing email address list with invalid base64 encoded word crashes the app"},"issue_body":{"kind":"string","value":"Test case:\r\n```java\r\nAddress.parse(\"=?utf-8?b?invalid#?= \");\r\n```\r\n\r\nException:\r\n```\r\njava.lang.Error: java.io.IOException: Unexpected base64 byte\r\n\r\n\tat org.apache.james.mime4j.codec.DecoderUtil.decodeBase64(DecoderUtil.java:89)\r\n\tat org.apache.james.mime4j.codec.DecoderUtil.decodeB(DecoderUtil.java:106)\r\n\tat org.apache.james.mime4j.codec.DecoderUtil.tryDecodeEncodedWord(DecoderUtil.java:233)\r\n\tat org.apache.james.mime4j.codec.DecoderUtil.decodeEncodedWords(DecoderUtil.java:187)\r\n\tat org.apache.james.mime4j.codec.DecoderUtil.decodeEncodedWords(DecoderUtil.java:143)\r\n\tat org.apache.james.mime4j.field.address.Builder.buildAddress(Builder.java:71)\r\n\tat org.apache.james.mime4j.field.address.Builder.buildAddressList(Builder.java:51)\r\n\tat org.apache.james.mime4j.field.address.DefaultAddressParser.parseAddressList(DefaultAddressParser.java:69)\r\n\tat org.apache.james.mime4j.field.address.DefaultAddressParser.parseAddressList(DefaultAddressParser.java:73)\r\n\tat com.fsck.k9.mail.Address.parse(Address.java:145)\r\n [...]\r\nCaused by: java.io.IOException: Unexpected base64 byte\r\n\tat org.apache.james.mime4j.codec.Base64InputStream.read0(Base64InputStream.java:193)\r\n\tat org.apache.james.mime4j.codec.Base64InputStream.read(Base64InputStream.java:87)\r\n\tat org.apache.james.mime4j.codec.DecoderUtil.decodeBase64(DecoderUtil.java:80)\r\n ... 39 more\r\n```\r\n\r\nI'm not sure what the best way to handle this is. Probably using the personal part as is. However, the options in MIME4J are somewhat limited. It's either crashing with an `Error` or ignoring invalid characters when decoding the base64 payload. Since we don't like crashes we should probably start out with the latter option."},"base_sha":{"kind":"string","value":"d696723023d8eb2c5dde223fdbcef1d67bd49bb9"},"head_sha":{"kind":"string","value":"ddcf1e257e43a9e08bb4bdcd237f93651c3651d5"},"diff_url":{"kind":"string","value":"https://github.com/thundernest/k-9/compare/d696723023d8eb2c5dde223fdbcef1d67bd49bb9...ddcf1e257e43a9e08bb4bdcd237f93651c3651d5"},"diff":{"kind":"string","value":"diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java b/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java\nindex 042fbbf44..eb8183768 100644\n--- a/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java\n+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java\n@@ -2,12 +2,14 @@\n package com.fsck.k9.mail;\n \n import android.support.annotation.VisibleForTesting;\n+\n import java.io.Serializable;\n import java.util.ArrayList;\n import java.util.List;\n import java.util.regex.Pattern;\n \n import org.apache.james.mime4j.MimeException;\n+import org.apache.james.mime4j.codec.DecodeMonitor;\n import org.apache.james.mime4j.codec.EncoderUtil;\n import org.apache.james.mime4j.dom.address.Mailbox;\n import org.apache.james.mime4j.dom.address.MailboxList;\n@@ -30,7 +32,6 @@ public class Address implements Serializable {\n \n private String mPersonal;\n \n-\n public Address(Address address) {\n mAddress = address.mAddress;\n mPersonal = address.mPersonal;\n@@ -142,7 +143,7 @@ public class Address implements Serializable {\n }\n List
addresses = new ArrayList<>();\n try {\n- MailboxList parsedList = DefaultAddressParser.DEFAULT.parseAddressList(addressList).flatten();\n+ MailboxList parsedList = DefaultAddressParser.DEFAULT.parseAddressList(addressList, DecodeMonitor.SILENT).flatten();\n \n for (int i = 0, count = parsedList.size(); i < count; i++) {\n Mailbox mailbox = parsedList.get(i);\ndiff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java\nindex 82a48be51..1fa329163 100644\n--- a/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java\n+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java\n@@ -180,4 +180,10 @@ public class AddressTest {\n \n assertNull(result);\n }\n+\n+ @Test\n+ public void handlesInvalidBase64Encoding() throws Exception {\n+ Address address = Address.parse(\"=?utf-8?b?invalid#?= \")[0];\n+ assertEquals(\"oops@example.com\", address.getAddress());\n+ }\n }"},"changed_files":{"kind":"string","value":"['k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/Address.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":3600355,"string":"3,600,355"},"repo_tokens_count":{"kind":"number","value":707916,"string":"707,916"},"repo_lines_count":{"kind":"number","value":98987,"string":"98,987"},"repo_files_without_tests_count":{"kind":"number","value":484,"string":"484"},"changed_symbols_count":{"kind":"number","value":296,"string":"296"},"changed_tokens_count":{"kind":"number","value":59,"string":"59"},"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":1711,"string":"1,711"},"issue_words_count":{"kind":"number","value":105,"string":"105"},"issue_tokens_count":{"kind":"number","value":408,"string":"408"},"issue_lines_count":{"kind":"number","value":28,"string":"28"},"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:09","string":"1970-01-01T00:25:09"},"repo_stars":{"kind":"number","value":8156,"string":"8,156"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1331,"cells":{"id":{"kind":"number","value":670,"string":"670"},"text_id":{"kind":"string","value":"apache/shardingsphere-elasticjob/368/367"},"repo_owner":{"kind":"string","value":"apache"},"repo_name":{"kind":"string","value":"shardingsphere-elasticjob"},"issue_url":{"kind":"string","value":"https://github.com/apache/shardingsphere-elasticjob/issues/367"},"pull_url":{"kind":"string","value":"https://github.com/apache/shardingsphere-elasticjob/pull/368"},"comment_url":{"kind":"string","value":"https://github.com/apache/shardingsphere-elasticjob/pull/368"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixed"},"issue_title":{"kind":"string","value":"Resuming Transient Job is abnormal"},"issue_body":{"kind":"string","value":"### Which version of Elastic-Job do you using?\r\n2.1.4\r\n\r\n### Expected behavior\r\nDisable the job and then resume the job, then triggered by cron expression. \r\n\r\n### Actual behavior\r\nDisable the job and then resume the job, immediately triggered several times.\r\n\r\n### Steps to reproduce the behavior\r\nDisable the transient job(cron 0/30 * * * * ?) with \"misfire\" parameter, wait several minutes, then resume it.\r\n"},"base_sha":{"kind":"string","value":"a3db7607ea9d33beb7b94c95ac0f56b7589d2b11"},"head_sha":{"kind":"string","value":"064eca0ab1804af654599bb06eae2ad6a1e59ea5"},"diff_url":{"kind":"string","value":"https://github.com/apache/shardingsphere-elasticjob/compare/a3db7607ea9d33beb7b94c95ac0f56b7589d2b11...064eca0ab1804af654599bb06eae2ad6a1e59ea5"},"diff":{"kind":"string","value":"diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java\nindex 0f9e58ae7..bccbb183a 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java\n@@ -70,7 +70,7 @@ public final class CloudJobConfigurationListener implements TreeCacheListener {\n if (!jobConfig.getTypeConfig().getCoreConfig().isMisfire()) {\n readyService.setMisfireDisabled(jobConfig.getJobName());\n }\n- producerManager.reschedule(jobConfig);\n+ producerManager.reschedule(jobConfig.getJobName());\n } else if (isJobConfigNode(event, path, Type.NODE_REMOVED)) {\n String jobName = path.substring(CloudJobConfigurationNode.ROOT.length() + 1, path.length());\n producerManager.unschedule(jobName);\ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java\nindex 527c58e1a..d27c36c53 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java\n@@ -172,12 +172,19 @@ public final class FacadeService {\n if (!jobConfigOptional.isPresent()) {\n return;\n }\n+ if (isDisable(jobConfigOptional.get())) {\n+ return;\n+ }\n CloudJobConfiguration jobConfig = jobConfigOptional.get();\n if (jobConfig.getTypeConfig().getCoreConfig().isFailover() || CloudJobExecutionType.DAEMON == jobConfig.getJobExecutionType()) {\n failoverService.add(taskContext);\n }\n }\n \n+ private boolean isDisable(final CloudJobConfiguration jobConfiguration) {\n+ return disableAppService.isDisabled(jobConfiguration.getAppName()) || disableJobService.isDisabled(jobConfiguration.getJobName());\n+ }\n+ \n /**\n * 将瞬时作业放入待执行队列.\n *\n@@ -223,6 +230,13 @@ public final class FacadeService {\n * @param jobName 作业名称\n */\n public void addDaemonJobToReadyQueue(final String jobName) {\n+ Optional jobConfigOptional = jobConfigService.load(jobName);\n+ if (!jobConfigOptional.isPresent()) {\n+ return;\n+ }\n+ if (isDisable(jobConfigOptional.get())) {\n+ return;\n+ }\n readyService.addDaemon(jobName);\n }\n \ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java\nindex 71d4c6d37..e681e656e 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java\n@@ -117,7 +117,7 @@ public final class ProducerManager {\n throw new JobConfigurationException(\"Cannot found job '%s', please register first.\", jobConfig.getJobName());\n }\n configService.update(jobConfig);\n- reschedule(jobConfig);\n+ reschedule(jobConfig.getJobName());\n }\n \n /**\n@@ -130,7 +130,6 @@ public final class ProducerManager {\n if (jobConfig.isPresent()) {\n disableJobService.remove(jobName);\n configService.remove(jobName);\n- transientProducerScheduler.deregister(jobConfig.get());\n }\n unschedule(jobName);\n }\n@@ -162,16 +161,23 @@ public final class ProducerManager {\n }\n runningService.remove(jobName);\n readyService.remove(Lists.newArrayList(jobName));\n+ Optional jobConfig = configService.load(jobName);\n+ if (jobConfig.isPresent()) {\n+ transientProducerScheduler.deregister(jobConfig.get());\n+ }\n }\n \n /**\n * 重新调度作业.\n *\n- * @param jobConfig 作业配置\n+ * @param jobName 作业名称\n */\n- public void reschedule(final CloudJobConfiguration jobConfig) {\n- unschedule(jobConfig.getJobName());\n- schedule(jobConfig);\n+ public void reschedule(final String jobName) {\n+ unschedule(jobName);\n+ Optional jobConfig = configService.load(jobName);\n+ if (jobConfig.isPresent()) {\n+ schedule(jobConfig.get());\n+ }\n }\n \n /**\ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java\nindex bfb793cc0..93d379f9d 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java\n@@ -112,7 +112,7 @@ final class TransientProducerScheduler {\n return TriggerBuilder.newTrigger().withIdentity(cron).withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()).build();\n }\n \n- void deregister(final CloudJobConfiguration jobConfig) {\n+ synchronized void deregister(final CloudJobConfiguration jobConfig) {\n repository.remove(jobConfig.getJobName());\n String cron = jobConfig.getTypeConfig().getCoreConfig().getCron();\n if (!repository.containsKey(buildJobKey(cron))) {\ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java\nindex 5c2c7f6a2..9d849510e 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java\n@@ -186,6 +186,11 @@ public final class CloudAppRestfulApi {\n public void enable(@PathParam(\"appName\") final String appName) throws JSONException {\n if (appConfigService.load(appName).isPresent()) {\n disableAppService.remove(appName);\n+ for (CloudJobConfiguration each : jobConfigService.loadAll()) {\n+ if (appName.equals(each.getAppName())) {\n+ producerManager.reschedule(each.getJobName());\n+ }\n+ }\n }\n }\n \ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java\nindex 2ad20f6db..2505b0435 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java\n@@ -184,8 +184,10 @@ public final class CloudJobRestfulApi {\n @DELETE\n @Path(\"/{jobName}/disable\")\n public void enable(@PathParam(\"jobName\") final String jobName) throws JSONException {\n- if (configService.load(jobName).isPresent()) {\n+ Optional configOptional = configService.load(jobName);\n+ if (configOptional.isPresent()) {\n facadeService.enableJob(jobName);\n+ producerManager.reschedule(jobName);\n }\n }\n \ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java\nindex 99f7ae93e..e8dc9213b 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java\n@@ -58,7 +58,7 @@ public final class CloudJobConfigurationListenerTest {\n public void assertChildEventWhenDataIsNull() throws Exception {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, null));\n verify(producerManager, times(0)).schedule(ArgumentMatchers.any());\n- verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n verify(producerManager, times(0)).unschedule(ArgumentMatchers.any());\n }\n \n@@ -66,7 +66,7 @@ public final class CloudJobConfigurationListenerTest {\n public void assertChildEventWhenIsNotConfigPath() throws Exception {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData(\"/other/test_job\", null, \"\".getBytes())));\n verify(producerManager, times(0)).schedule(ArgumentMatchers.any());\n- verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n verify(producerManager, times(0)).unschedule(ArgumentMatchers.any());\n }\n \n@@ -74,7 +74,7 @@ public final class CloudJobConfigurationListenerTest {\n public void assertChildEventWhenIsRootConfigPath() throws Exception {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_REMOVED, new ChildData(\"/config/job\", null, \"\".getBytes())));\n verify(producerManager, times(0)).schedule(ArgumentMatchers.any());\n- verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n verify(producerManager, times(0)).unschedule(ArgumentMatchers.any());\n }\n \n@@ -82,7 +82,7 @@ public final class CloudJobConfigurationListenerTest {\n public void assertChildEventWhenStateIsAddAndIsConfigPathAndInvalidData() throws Exception {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, new ChildData(\"/config/job/test_job\", null, \"\".getBytes())));\n verify(producerManager, times(0)).schedule(ArgumentMatchers.any());\n- verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.any());\n verify(producerManager, times(0)).unschedule(ArgumentMatchers.any());\n }\n \n@@ -96,7 +96,7 @@ public final class CloudJobConfigurationListenerTest {\n public void assertChildEventWhenStateIsUpdateAndIsConfigPathAndTransientJob() throws Exception {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData(\"/config/job/test_job\", null, CloudJsonConstants.getJobJson().getBytes())));\n verify(readyService, times(0)).remove(Collections.singletonList(\"test_job\"));\n- verify(producerManager).reschedule(ArgumentMatchers.any());\n+ verify(producerManager).reschedule(ArgumentMatchers.any());\n }\n \n @Test\n@@ -104,7 +104,7 @@ public final class CloudJobConfigurationListenerTest {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, \n new ChildData(\"/config/job/test_job\", null, CloudJsonConstants.getJobJson(CloudJobExecutionType.DAEMON).getBytes())));\n verify(readyService).remove(Collections.singletonList(\"test_job\"));\n- verify(producerManager).reschedule(ArgumentMatchers.any());\n+ verify(producerManager).reschedule(ArgumentMatchers.any());\n }\n \n @Test\n@@ -112,7 +112,7 @@ public final class CloudJobConfigurationListenerTest {\n cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED,\n new ChildData(\"/config/job/test_job\", null, CloudJsonConstants.getJobJson(false).getBytes())));\n verify(readyService).setMisfireDisabled(\"test_job\");\n- verify(producerManager).reschedule(ArgumentMatchers.any());\n+ verify(producerManager).reschedule(ArgumentMatchers.any());\n }\n \n @Test\ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java\nindex 35e44ccde..50cc09c4f 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java\n@@ -222,6 +222,7 @@ public final class FacadeServiceTest {\n \n @Test\n public void assertAddDaemonJobToReadyQueue() {\n+ when(jobConfigService.load(\"test_job\")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration(\"test_job\")));\n facadeService.addDaemonJobToReadyQueue(\"test_job\");\n verify(readyService).addDaemon(\"test_job\");\n }\ndiff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java\nindex e1c902886..1956a5da2 100644\n--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java\n+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java\n@@ -106,7 +106,7 @@ public final class CloudJobRestfulApiTest extends AbstractCloudRestfulApiTest {\n public void assertDeregister() throws Exception {\n when(getRegCenter().isExisted(\"/config/job/test_job\")).thenReturn(false);\n assertThat(sentRequest(\"http://127.0.0.1:19000/api/job/deregister\", \"DELETE\", \"test_job\"), is(204));\n- verify(getRegCenter(), times(2)).get(\"/config/job/test_job\");\n+ verify(getRegCenter(), times(3)).get(\"/config/job/test_job\");\n }\n \n @Test"},"changed_files":{"kind":"string","value":"['elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 9}"},"changed_files_count":{"kind":"number","value":9,"string":"9"},"java_changed_files_count":{"kind":"number","value":9,"string":"9"},"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":9,"string":"9"},"repo_symbols_count":{"kind":"number","value":841618,"string":"841,618"},"repo_tokens_count":{"kind":"number","value":188763,"string":"188,763"},"repo_lines_count":{"kind":"number","value":24229,"string":"24,229"},"repo_files_without_tests_count":{"kind":"number","value":277,"string":"277"},"changed_symbols_count":{"kind":"number","value":2092,"string":"2,092"},"changed_tokens_count":{"kind":"number","value":393,"string":"393"},"changed_lines_count":{"kind":"number","value":45,"string":"45"},"changed_files_without_tests_count":{"kind":"number","value":6,"string":"6"},"issue_symbols_count":{"kind":"number","value":411,"string":"411"},"issue_words_count":{"kind":"number","value":65,"string":"65"},"issue_tokens_count":{"kind":"number","value":93,"string":"93"},"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:24:58","string":"1970-01-01T00:24:58"},"repo_stars":{"kind":"number","value":7920,"string":"7,920"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2266368, 'Shell': 3428, 'Dockerfile': 1094, 'Batchfile': 861}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1332,"cells":{"id":{"kind":"number","value":115,"string":"115"},"text_id":{"kind":"string","value":"spring-projects/spring-security/13276/13243"},"repo_owner":{"kind":"string","value":"spring-projects"},"repo_name":{"kind":"string","value":"spring-security"},"issue_url":{"kind":"string","value":"https://github.com/spring-projects/spring-security/issues/13243"},"pull_url":{"kind":"string","value":"https://github.com/spring-projects/spring-security/pull/13276"},"comment_url":{"kind":"string","value":"https://github.com/spring-projects/spring-security/pull/13276"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"CasAuthenticationFilter.successfulAuthentication missing call to securityContextRepository.saveContext"},"issue_body":{"kind":"string","value":"**Describe the bug**\r\n`org.springframework.security.cas.web.CasAuthenticationFilter.successfulAuthentication` seems to be missing a call to `securityContextRepository.saveContext` as per [the Spring 6 migration document](https://docs.spring.io/spring-security/reference/migration/servlet/session-management.html). I think this makes the filter completely unusable on Spring6/Boot3 and begs to question if the `CasAuthenticationFilter` code is production ready for Spring 6 otherwise.\r\n\r\n**To Reproduce**\r\nUse the filter\r\n\r\n**Expected behavior**\r\nSecurityContext is saved between requests :)\r\n"},"base_sha":{"kind":"string","value":"537e10cf9c7feaf8c00d5523052823f3c469410d"},"head_sha":{"kind":"string","value":"52b87f339c36eaa95d835f456aadd37425bbad02"},"diff_url":{"kind":"string","value":"https://github.com/spring-projects/spring-security/compare/537e10cf9c7feaf8c00d5523052823f3c469410d...52b87f339c36eaa95d835f456aadd37425bbad02"},"diff":{"kind":"string","value":"diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java\nindex a951168f66..6f2920b3d0 100644\n--- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java\n+++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java\n@@ -42,6 +42,7 @@ import org.springframework.security.web.authentication.AbstractAuthenticationPro\n import org.springframework.security.web.authentication.AuthenticationFailureHandler;\n import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;\n import org.springframework.security.web.context.HttpSessionSecurityContextRepository;\n+import org.springframework.security.web.context.SecurityContextRepository;\n import org.springframework.security.web.util.matcher.AntPathRequestMatcher;\n import org.springframework.security.web.util.matcher.RequestMatcher;\n import org.springframework.util.Assert;\n@@ -192,10 +193,12 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil\n \n \tprivate AuthenticationFailureHandler proxyFailureHandler = new SimpleUrlAuthenticationFailureHandler();\n \n+\tprivate SecurityContextRepository securityContextRepository= new HttpSessionSecurityContextRepository();\n+\n \tpublic CasAuthenticationFilter() {\n \t\tsuper(\"/login/cas\");\n \t\tsetAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());\n-\t\tsetSecurityContextRepository(new HttpSessionSecurityContextRepository());\n+\t\tsetSecurityContextRepository(this.securityContextRepository);\n \t}\n \n \t@Override\n@@ -211,6 +214,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil\n \t\tSecurityContext context = SecurityContextHolder.createEmptyContext();\n \t\tcontext.setAuthentication(authResult);\n \t\tSecurityContextHolder.setContext(context);\n+\t\tthis.securityContextRepository.saveContext(context,request,response);\n \t\tif (this.eventPublisher != null) {\n \t\t\tthis.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));\n \t\t}"},"changed_files":{"kind":"string","value":"['cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.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":7476540,"string":"7,476,540"},"repo_tokens_count":{"kind":"number","value":1614247,"string":"1,614,247"},"repo_lines_count":{"kind":"number","value":200846,"string":"200,846"},"repo_files_without_tests_count":{"kind":"number","value":1671,"string":"1,671"},"changed_symbols_count":{"kind":"number","value":399,"string":"399"},"changed_tokens_count":{"kind":"number","value":56,"string":"56"},"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":592,"string":"592"},"issue_words_count":{"kind":"number","value":57,"string":"57"},"issue_tokens_count":{"kind":"number","value":118,"string":"118"},"issue_lines_count":{"kind":"number","value":9,"string":"9"},"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:28:05","string":"1970-01-01T00:28:05"},"repo_stars":{"kind":"number","value":7860,"string":"7,860"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 16395664, 'Kotlin': 860788, 'Groovy': 47907, 'AspectJ': 16776, 'Ruby': 7008, 'PLSQL': 3180, 'XSLT': 2369, 'Shell': 811, 'Python': 129, 'HTML': 80, 'JavaScript': 10}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1333,"cells":{"id":{"kind":"number","value":51,"string":"51"},"text_id":{"kind":"string","value":"dropwizard/metrics/505/444"},"repo_owner":{"kind":"string","value":"dropwizard"},"repo_name":{"kind":"string","value":"metrics"},"issue_url":{"kind":"string","value":"https://github.com/dropwizard/metrics/issues/444"},"pull_url":{"kind":"string","value":"https://github.com/dropwizard/metrics/pull/505"},"comment_url":{"kind":"string","value":"https://github.com/dropwizard/metrics/pull/505"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"Another ClassCastException in metrics-jetty9's InstrumentedHandler"},"issue_body":{"kind":"string","value":"I found another ClassCastException in metrics-jetty9. Commit 622ef9b which is included in 3.0.1 doesn't seem to completly fix issue #435 that I reported earlier.\n\n```\njava.lang.ClassCastException: org.atmosphere.cpr.AtmosphereRequest cannot be cast to org.eclipse.jetty.server.Request\n at com.codahale.metrics.jetty9.InstrumentedHandler$1.onComplete(InstrumentedHandler.java:140) ~[metrics-jetty9-3.0.1.jar:3.0.1]\n at org.eclipse.jetty.server.HttpChannelState.completed(HttpChannelState.java:470) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]\n at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:315) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]\n at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:228) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]\n at org.eclipse.jetty.server.handler.ContextHandler.handle(ContextHandler.java:1143) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]\n at org.eclipse.jetty.server.HttpChannelState.complete(HttpChannelState.java:432) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]\n at org.eclipse.jetty.server.AsyncContextState.complete(AsyncContextState.java:90) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]\n at org.atmosphere.container.Servlet30CometSupport.action(Servlet30CometSupport.java:157) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.container.Servlet30CometSupport.action(Servlet30CometSupport.java:79) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.cpr.AtmosphereResourceImpl.resume(AtmosphereResourceImpl.java:326) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.jersey.util.JerseyBroadcasterUtil.broadcast(JerseyBroadcasterUtil.java:161) ~[atmosphere-jersey-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.jersey.JerseyBroadcaster.invokeOnStateChange(JerseyBroadcaster.java:77) ~[atmosphere-jersey-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.cpr.DefaultBroadcaster.prepareInvokeOnStateChange(DefaultBroadcaster.java:1047) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.cpr.DefaultBroadcaster.executeAsyncWrite(DefaultBroadcaster.java:921) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at org.atmosphere.cpr.DefaultBroadcaster$3.run(DefaultBroadcaster.java:580) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]\n at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_25]\n at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) ~[na:1.7.0_25]\n at java.util.concurrent.FutureTask.run(FutureTask.java:166) ~[na:1.7.0_25]\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_25]\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_25]\n at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25]\n```\n"},"base_sha":{"kind":"string","value":"32f19d565b2883d91a9a9dbc52684891d58a8cd0"},"head_sha":{"kind":"string","value":"92f7d920deac3c0065ae504784a3b271d6b46fe7"},"diff_url":{"kind":"string","value":"https://github.com/dropwizard/metrics/compare/32f19d565b2883d91a9a9dbc52684891d58a8cd0...92f7d920deac3c0065ae504784a3b271d6b46fe7"},"diff":{"kind":"string","value":"diff --git a/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java b/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java\nindex 56805cdc9..503e7867f 100644\n--- a/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java\n+++ b/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java\n@@ -133,6 +133,8 @@ public class InstrumentedHandler extends HandlerWrapper {\n this.otherRequests = metricRegistry.timer(name(prefix, \"other-requests\"));\n \n this.listener = new AsyncListener() {\n+ private long startTime;\n+\n @Override\n public void onTimeout(AsyncEvent event) throws IOException {\n asyncTimeouts.mark();\n@@ -140,6 +142,7 @@ public class InstrumentedHandler extends HandlerWrapper {\n \n @Override\n public void onStartAsync(AsyncEvent event) throws IOException {\n+ startTime = System.currentTimeMillis();\n event.getAsyncContext().addListener(this);\n }\n \n@@ -150,8 +153,9 @@ public class InstrumentedHandler extends HandlerWrapper {\n @Override\n public void onComplete(AsyncEvent event) throws IOException {\n final AsyncContextState state = (AsyncContextState) event.getAsyncContext();\n- final Request request = (Request) state.getRequest();\n- updateResponses(request);\n+ final HttpServletRequest request = (HttpServletRequest) state.getRequest();\n+ final HttpServletResponse response = (HttpServletResponse) state.getResponse();\n+ updateResponses(request, response, startTime);\n if (!state.getHttpChannelState().isDispatched()) {\n activeSuspended.dec();\n }\n@@ -197,7 +201,7 @@ public class InstrumentedHandler extends HandlerWrapper {\n }\n activeSuspended.inc();\n } else if (state.isInitial()) {\n- updateResponses(request);\n+ updateResponses(httpRequest, httpResponse, start);\n }\n // else onCompletion will handle it.\n }\n@@ -233,13 +237,13 @@ public class InstrumentedHandler extends HandlerWrapper {\n }\n }\n \n- private void updateResponses(Request request) {\n- final int response = request.getResponse().getStatus() / 100;\n- if (response >= 1 && response <= 5) {\n- responses[response - 1].mark();\n+ private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start) {\n+ final int responseStatus = response.getStatus() / 100;\n+ if (responseStatus >= 1 && responseStatus <= 5) {\n+ responses[responseStatus - 1].mark();\n }\n activeRequests.dec();\n- final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp();\n+ final long elapsedTime = System.currentTimeMillis() - start;\n requests.update(elapsedTime, TimeUnit.MILLISECONDS);\n requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS);\n }\ndiff --git a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java\nindex 3c31cb66f..27b03900a 100644\n--- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java\n+++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java\n@@ -133,6 +133,8 @@ public class InstrumentedHandler extends HandlerWrapper {\n this.otherRequests = metricRegistry.timer(name(prefix, \"other-requests\"));\n \n this.listener = new AsyncListener() {\n+ private long startTime;\n+\n @Override\n public void onTimeout(AsyncEvent event) throws IOException {\n asyncTimeouts.mark();\n@@ -140,6 +142,7 @@ public class InstrumentedHandler extends HandlerWrapper {\n \n @Override\n public void onStartAsync(AsyncEvent event) throws IOException {\n+ startTime = System.currentTimeMillis();\n event.getAsyncContext().addListener(this);\n }\n \n@@ -150,8 +153,9 @@ public class InstrumentedHandler extends HandlerWrapper {\n @Override\n public void onComplete(AsyncEvent event) throws IOException {\n final AsyncContextState state = (AsyncContextState) event.getAsyncContext();\n- final Request request = (Request) state.getRequest();\n- updateResponses(request);\n+ final HttpServletRequest request = (HttpServletRequest) state.getRequest();\n+ final HttpServletResponse response = (HttpServletResponse) state.getResponse();\n+ updateResponses(request, response, startTime);\n if (state.getHttpChannelState().getState() != HttpChannelState.State.DISPATCHED) {\n activeSuspended.dec();\n }\n@@ -197,7 +201,7 @@ public class InstrumentedHandler extends HandlerWrapper {\n }\n activeSuspended.inc();\n } else if (state.isInitial()) {\n- updateResponses(request);\n+ updateResponses(httpRequest, httpResponse, start);\n }\n // else onCompletion will handle it.\n }\n@@ -233,13 +237,13 @@ public class InstrumentedHandler extends HandlerWrapper {\n }\n }\n \n- private void updateResponses(Request request) {\n- final int response = request.getResponse().getStatus() / 100;\n- if (response >= 1 && response <= 5) {\n- responses[response - 1].mark();\n+ private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start) {\n+ final int responseStatus = response.getStatus() / 100;\n+ if (responseStatus >= 1 && responseStatus <= 5) {\n+ responses[responseStatus - 1].mark();\n }\n activeRequests.dec();\n- final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp();\n+ final long elapsedTime = System.currentTimeMillis() - start;\n requests.update(elapsedTime, TimeUnit.MILLISECONDS);\n requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS);\n }"},"changed_files":{"kind":"string","value":"['metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java', 'metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.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":394935,"string":"394,935"},"repo_tokens_count":{"kind":"number","value":77392,"string":"77,392"},"repo_lines_count":{"kind":"number","value":11434,"string":"11,434"},"repo_files_without_tests_count":{"kind":"number","value":109,"string":"109"},"changed_symbols_count":{"kind":"number","value":2454,"string":"2,454"},"changed_tokens_count":{"kind":"number","value":400,"string":"400"},"changed_lines_count":{"kind":"number","value":40,"string":"40"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":2933,"string":"2,933"},"issue_words_count":{"kind":"number","value":96,"string":"96"},"issue_tokens_count":{"kind":"number","value":957,"string":"957"},"issue_lines_count":{"kind":"number","value":27,"string":"27"},"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:23:08","string":"1970-01-01T00:23:08"},"repo_stars":{"kind":"number","value":7744,"string":"7,744"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 1542841, 'Shell': 1659, 'Python': 351}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1334,"cells":{"id":{"kind":"number","value":102,"string":"102"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1579/1578"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1578"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1579"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1579"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"byte and binary properties are wrong"},"issue_body":{"kind":"string","value":"It looks like these two commits are backwards:\n\nAddition of `binary` property:\nhttps://github.com/swagger-api/swagger-core/commit/a18409eb69d9c69435bb2f0bbec7b2540b46616d\n\nAddition of `byte` property:\nhttps://github.com/swagger-api/swagger-core/commit/4e7a8014d14a8d0dd54f31f825858ae072be1061\n"},"base_sha":{"kind":"string","value":"05475b8552b8ac18864de841468f8665f8c3de10"},"head_sha":{"kind":"string","value":"deda3feafc61377ccf55883cca0e396a07615bc5"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/05475b8552b8ac18864de841468f8665f8c3de10...deda3feafc61377ccf55883cca0e396a07615bc5"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java b/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java\nindex 8c4980987..237c592c2 100644\n--- a/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java\n+++ b/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java\n@@ -1,19 +1,7 @@\n package io.swagger.util;\n \n import com.fasterxml.jackson.databind.type.TypeFactory;\n-import io.swagger.models.properties.BaseIntegerProperty;\n-import io.swagger.models.properties.BooleanProperty;\n-import io.swagger.models.properties.DateProperty;\n-import io.swagger.models.properties.DateTimeProperty;\n-import io.swagger.models.properties.DecimalProperty;\n-import io.swagger.models.properties.DoubleProperty;\n-import io.swagger.models.properties.FloatProperty;\n-import io.swagger.models.properties.IntegerProperty;\n-import io.swagger.models.properties.LongProperty;\n-import io.swagger.models.properties.ObjectProperty;\n-import io.swagger.models.properties.Property;\n-import io.swagger.models.properties.StringProperty;\n-import io.swagger.models.properties.UUIDProperty;\n+import io.swagger.models.properties.*;\n \n import java.lang.reflect.Type;\n import java.util.Collections;\n@@ -49,8 +37,17 @@ public enum PrimitiveType {\n */\n BYTE(Byte.class, \"byte\") {\n @Override\n- public StringProperty createProperty() {\n- return new StringProperty(StringProperty.Format.BYTE);\n+ public ByteArrayProperty createProperty() {\n+ return new ByteArrayProperty();\n+ }\n+ },\n+ /**\n+ * Binary\n+ */\n+ BINARY(Byte.class, \"binary\") {\n+ @Override\n+ public BinaryProperty createProperty() {\n+ return new BinaryProperty();\n }\n },\n /**\ndiff --git a/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java b/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java\nindex b043684b1..ef27bd4cf 100644\n--- a/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java\n+++ b/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java\n@@ -4,10 +4,17 @@ import io.swagger.converter.ModelConverters;\n import io.swagger.matchers.SerializationMatchers;\n import io.swagger.models.Model;\n \n+import io.swagger.models.ModelImpl;\n+import io.swagger.models.properties.ArrayProperty;\n+import io.swagger.models.properties.BinaryProperty;\n+import io.swagger.models.properties.ByteArrayProperty;\n+import io.swagger.util.Json;\n import org.testng.annotations.Test;\n \n import java.util.Map;\n \n+import static org.testng.Assert.assertEquals;\n+\n public class ByteConverterTest {\n \n @Test\n@@ -30,6 +37,54 @@ public class ByteConverterTest {\n SerializationMatchers.assertEqualsToJson(models, json);\n }\n \n+ @Test\n+ public void testByteProperty() {\n+ Model model = new ModelImpl()\n+ .property(\"byteProperty\", new ByteArrayProperty());\n+\n+ assertEquals(Json.pretty(model), \"{\\\\n\" +\n+ \" \\\\\"properties\\\\\" : {\\\\n\" +\n+ \" \\\\\"byteProperty\\\\\" : {\\\\n\" +\n+ \" \\\\\"type\\\\\" : \\\\\"string\\\\\",\\\\n\" +\n+ \" \\\\\"format\\\\\" : \\\\\"byte\\\\\"\\\\n\" +\n+ \" }\\\\n\" +\n+ \" }\\\\n\" +\n+ \"}\");\n+ }\n+\n+ @Test\n+ public void testDeserializeByteProperty() throws Exception {\n+ String json = \"{\\\\n\" +\n+ \" \\\\\"properties\\\\\" : {\\\\n\" +\n+ \" \\\\\"byteProperty\\\\\" : {\\\\n\" +\n+ \" \\\\\"type\\\\\" : \\\\\"string\\\\\",\\\\n\" +\n+ \" \\\\\"format\\\\\" : \\\\\"byte\\\\\"\\\\n\" +\n+ \" }\\\\n\" +\n+ \" }\\\\n\" +\n+ \"}\";\n+\n+ Model model = Json.mapper().readValue(json, Model.class);\n+ Json.prettyPrint(model);\n+ }\n+\n+ @Test\n+ public void testByteArray() {\n+ Model model = new ModelImpl()\n+ .property(\"byteArray\", new ArrayProperty(new BinaryProperty()));\n+\n+ assertEquals(Json.pretty(model), \"{\\\\n\" +\n+ \" \\\\\"properties\\\\\" : {\\\\n\" +\n+ \" \\\\\"byteArray\\\\\" : {\\\\n\" +\n+ \" \\\\\"type\\\\\" : \\\\\"array\\\\\",\\\\n\" +\n+ \" \\\\\"items\\\\\" : {\\\\n\" +\n+ \" \\\\\"type\\\\\" : \\\\\"string\\\\\",\\\\n\" +\n+ \" \\\\\"format\\\\\" : \\\\\"binary\\\\\"\\\\n\" +\n+ \" }\\\\n\" +\n+ \" }\\\\n\" +\n+ \" }\\\\n\" +\n+ \"}\");\n+ }\n+\n class ByteConverterModel {\n public Byte[] myBytes = new Byte[0];\n }\ndiff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java\nsimilarity index 74%\nrename from modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java\nrename to modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java\nindex c80d984b9..c1e20c5ac 100644\n--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java\n+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java\n@@ -2,73 +2,52 @@ package io.swagger.models.properties;\n \n import io.swagger.models.Xml;\n \n-import java.util.ArrayList;\n import java.util.List;\n \n-public class ByteProperty extends AbstractProperty implements Property {\n+public class BinaryProperty extends AbstractProperty implements Property {\n private static final String TYPE = \"string\";\n-\n- private static final String FORMAT = \"byte\";\n-\n protected List _enum;\n protected Integer minLength = null, maxLength = null;\n protected String pattern = null;\n protected String _default;\n \n- public ByteProperty() {\n- super.type = TYPE;\n- super.format = FORMAT;\n- }\n-\n- public ByteProperty _enum(String value) {\n- if (this._enum == null) {\n- this._enum = new ArrayList();\n- }\n- if (!_enum.contains(value)) {\n- _enum.add(value);\n- }\n- return this;\n- }\n-\n- public ByteProperty _enum(List value) {\n- this._enum = value;\n- return this;\n+ public BinaryProperty() {\n+ super.type = \"string\";\n+ super.format = \"binary\";\n }\n \n public static boolean isType(String type, String format) {\n- if (TYPE.equals(type) && FORMAT.equals(format)) {\n+ if (\"string\".equals(type) && \"binary\".equals(format))\n return true;\n- } else {\n- return false;\n- }\n+ else return false;\n }\n \n- public ByteProperty xml(Xml xml) {\n+ public BinaryProperty xml(Xml xml) {\n this.setXml(xml);\n return this;\n }\n \n- public ByteProperty minLength(Integer minLength) {\n+ public BinaryProperty minLength(Integer minLength) {\n this.setMinLength(minLength);\n return this;\n }\n \n- public ByteProperty maxLength(Integer maxLength) {\n+ public BinaryProperty maxLength(Integer maxLength) {\n this.setMaxLength(maxLength);\n return this;\n }\n \n- public ByteProperty pattern(String pattern) {\n+ public BinaryProperty pattern(String pattern) {\n this.setPattern(pattern);\n return this;\n }\n \n- public ByteProperty _default(String _default) {\n+ public BinaryProperty _default(String _default) {\n this._default = _default;\n return this;\n }\n \n- public ByteProperty vendorExtension(String key, Object obj) {\n+ public BinaryProperty vendorExtension(String key, Object obj) {\n this.setVendorExtension(key, obj);\n return this;\n }\n@@ -130,10 +109,10 @@ public class ByteProperty extends AbstractProperty implements Property {\n if (!super.equals(obj)) {\n return false;\n }\n- if (!(obj instanceof ByteProperty)) {\n+ if (!(obj instanceof BinaryProperty)) {\n return false;\n }\n- ByteProperty other = (ByteProperty) obj;\n+ BinaryProperty other = (BinaryProperty) obj;\n if (_default == null) {\n if (other._default != null) {\n return false;\ndiff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java\nindex 496a7ed05..c6ba49a34 100644\n--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java\n+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java\n@@ -2,18 +2,16 @@ package io.swagger.models.properties;\n \n import io.swagger.models.Xml;\n \n-import java.util.*;\n-\n public class ByteArrayProperty extends AbstractProperty implements Property {\n \n \n public ByteArrayProperty() {\n super.type = \"string\";\n- super.format = \"binary\";\n+ super.format = \"byte\";\n }\n \n public static boolean isType(String type, String format) {\n- if (\"string\".equals(type) && \"binary\".equals(format))\n+ if (\"string\".equals(type) && \"byte\".equals(format))\n return true;\n else return false;\n }\ndiff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java\nindex 750f788d2..8fb677dca 100644\n--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java\n+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java\n@@ -156,6 +156,17 @@ public class PropertyBuilder {\n return new ByteArrayProperty();\n }\n },\n+ BINARY(BinaryProperty.class) {\n+ @Override\n+ protected boolean isType(String type, String format) {\n+ return BinaryProperty.isType(type, format);\n+ }\n+\n+ @Override\n+ protected BinaryProperty create() {\n+ return new BinaryProperty();\n+ }\n+ },\n DATE(DateProperty.class) {\n @Override\n protected boolean isType(String type, String format) {\ndiff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java\nindex 0dbb65ced..920ab1b3e 100644\n--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java\n+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java\n@@ -17,7 +17,6 @@ public class StringProperty extends AbstractProperty implements Property {\n protected String _default;\n \n public enum Format {\n- BYTE(\"byte\"),\n URI(\"uri\"),\n URL(\"url\");\n \ndiff --git a/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java b/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java\nindex 19bf1ae6e..45be6930d 100644\n--- a/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java\n+++ b/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java\n@@ -1,21 +1,17 @@\n package io.swagger;\n \n-import static org.testng.Assert.assertEquals;\n-import static org.testng.Assert.assertNotEquals;\n-\n import io.swagger.models.properties.StringProperty;\n-\n import org.testng.annotations.Test;\n \n+import static org.testng.Assert.assertEquals;\n+import static org.testng.Assert.assertNotEquals;\n+\n public class StringPropertyTest {\n private static final String PROP_1 = \"prop1\";\n private static final String PROP_2 = \"prop2\";\n \n @Test\n public void testEquals() {\n- assertNotEquals(new StringProperty(StringProperty.Format.BYTE), new StringProperty(StringProperty.Format.URL));\n- assertEquals(new StringProperty(StringProperty.Format.BYTE), new StringProperty(StringProperty.Format.BYTE));\n-\n final StringProperty prop1 = new StringProperty();\n prop1.setName(PROP_1);\n prop1.setRequired(true);\ndiff --git a/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java b/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java\nindex d32f3dc27..3c0ff8b69 100644\n--- a/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java\n+++ b/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java\n@@ -1,17 +1,15 @@\n package io.swagger.models.properties;\n \n-import java.util.ArrayList;\n-import java.util.EnumMap;\n-import java.util.Iterator;\n-import java.util.List;\n-\n+import io.swagger.models.properties.PropertyBuilder.PropertyId;\n+import io.swagger.models.properties.StringProperty.Format;\n import org.testng.Assert;\n-\n import org.testng.annotations.DataProvider;\n import org.testng.annotations.Test;\n \n-import io.swagger.models.properties.PropertyBuilder.PropertyId;\n-import io.swagger.models.properties.StringProperty.Format;\n+import java.util.ArrayList;\n+import java.util.EnumMap;\n+import java.util.Iterator;\n+import java.util.List;\n \n public class PropertyBuilderTest {\n \n@@ -57,8 +55,8 @@ public class PropertyBuilderTest {\n {\"number\", \"float\", FloatProperty.class},\n {\"number\", \"double\", DoubleProperty.class},\n {\"string\", null, StringProperty.class},\n- {\"string\", \"byte\", StringProperty.class}, // are this and the next one correct?\n- {\"string\", \"binary\", ByteArrayProperty.class},\n+ {\"string\", \"byte\", ByteArrayProperty.class},\n+ {\"string\", \"binary\", BinaryProperty.class},\n {\"boolean\", null, BooleanProperty.class},\n {\"string\", \"date\", DateProperty.class},\n {\"string\", \"date-time\", DateTimeProperty.class},"},"changed_files":{"kind":"string","value":"['modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java', 'modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java', 'modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java', 'modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 8}"},"changed_files_count":{"kind":"number","value":8,"string":"8"},"java_changed_files_count":{"kind":"number","value":8,"string":"8"},"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":8,"string":"8"},"repo_symbols_count":{"kind":"number","value":578968,"string":"578,968"},"repo_tokens_count":{"kind":"number","value":111634,"string":"111,634"},"repo_lines_count":{"kind":"number","value":18293,"string":"18,293"},"repo_files_without_tests_count":{"kind":"number","value":165,"string":"165"},"changed_symbols_count":{"kind":"number","value":1727,"string":"1,727"},"changed_tokens_count":{"kind":"number","value":295,"string":"295"},"changed_lines_count":{"kind":"number","value":45,"string":"45"},"changed_files_without_tests_count":{"kind":"number","value":5,"string":"5"},"issue_symbols_count":{"kind":"number","value":293,"string":"293"},"issue_words_count":{"kind":"number","value":18,"string":"18"},"issue_tokens_count":{"kind":"number","value":96,"string":"96"},"issue_lines_count":{"kind":"number","value":8,"string":"8"},"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:24:10","string":"1970-01-01T00:24:10"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1335,"cells":{"id":{"kind":"number","value":101,"string":"101"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1678/1512"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1512"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1678"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1678"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"swagger-servlet generating non-unique operationIds"},"issue_body":{"kind":"string","value":"using swagger-servlet-1.5.4.\n\nfirst of all, @iushankin huuuge thanks for swagger-servlet migration with 1.5.4! works almost flawlessly.\n\ni noticed that swagger-servlet will use `@ApiOperation`s `nickname` attribute for path generation as well as for `operationId`.\nhowever, it may be necessary to have multiple operations with the same path (but different http methods).\nin this case, the `nickname` is correctly used multiple times as path for different operations but also as `operationId` which means the `operationId` is no longer unique.\n\nas a result, swagger editor - for example - shows errors:\n\n> Cannot have multiple operations with the same operationId: /myPath\n\nthanks, zyro\n"},"base_sha":{"kind":"string","value":"9e93afaf1ee7a9a0130b262fd2112b3c20bbb825"},"head_sha":{"kind":"string","value":"b2ae3198f993ac3d20446e4da7725153c19185b3"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/9e93afaf1ee7a9a0130b262fd2112b3c20bbb825...b2ae3198f993ac3d20446e4da7725153c19185b3"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java b/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java\nindex 5345b1a9f..5eaae4195 100644\n--- a/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java\n+++ b/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java\n@@ -222,7 +222,7 @@ public class ServletReaderExtension implements ReaderExtension {\n final String operationPath = apiOperation == null ? null : apiOperation.nickname();\n return PathUtils.collectPath(context.getParentPath(),\n apiAnnotation == null ? null : apiAnnotation.value(),\n- StringUtils.defaultIfBlank(operationPath, method.getName()));\n+ method.getName());\n }\n \n @Override\ndiff --git a/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java b/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java\nindex a48d65190..a36bacfe1 100644\n--- a/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java\n+++ b/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java\n@@ -43,12 +43,12 @@ public class ReaderTest {\n \n Assert.assertEquals(swagger.getHost(), \"host\");\n Assert.assertEquals(swagger.getBasePath(), \"/api\");\n- Assert.assertNotNull(swagger.getPath(\"/resources/users\"));\n+ Assert.assertNotNull(swagger.getPath(\"/resources/testMethod3\"));\n Assert.assertNotNull(swagger.getDefinitions().get(\"SampleData\"));\n Assert.assertEquals(swagger.getExternalDocs().getDescription(), \"docs\");\n Assert.assertEquals(swagger.getExternalDocs().getUrl(), \"url_to_docs\");\n \n- Path path = swagger.getPath(\"/resources/users\");\n+ Path path = swagger.getPath(\"/resources/testMethod3\");\n Assert.assertNotNull(path);\n Operation get = path.getGet();\n Assert.assertNotNull( get );\ndiff --git a/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java b/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java\nindex 4b643b073..3c1092335 100644\n--- a/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java\n+++ b/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java\n@@ -13,7 +13,7 @@ public class PathGetterTest extends BaseServletReaderExtensionTest {\n return new Object[][]{\n {\"testMethod1\", \"/tests/resources/testMethod1\"},\n {\"testMethod2\", \"/tests/resources/testMethod2\"},\n- {\"testMethod3\", \"/tests/resources/users\"},\n+ {\"testMethod3\", \"/tests/resources/testMethod3\"},\n {\"testMethod4\", \"/tests/resources/testMethod4\"},\n };\n }\n@@ -23,7 +23,7 @@ public class PathGetterTest extends BaseServletReaderExtensionTest {\n return new Object[][]{\n {\"testMethod1\", \"/tests/testMethod1\"},\n {\"testMethod2\", \"/tests/testMethod2\"},\n- {\"testMethod3\", \"/tests/users\"},\n+ {\"testMethod3\", \"/tests/testMethod3\"},\n {\"testMethod4\", \"/tests/testMethod4\"},\n };\n }"},"changed_files":{"kind":"string","value":"['modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java', 'modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java', 'modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.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":601624,"string":"601,624"},"repo_tokens_count":{"kind":"number","value":116159,"string":"116,159"},"repo_lines_count":{"kind":"number","value":18969,"string":"18,969"},"repo_files_without_tests_count":{"kind":"number","value":167,"string":"167"},"changed_symbols_count":{"kind":"number","value":114,"string":"114"},"changed_tokens_count":{"kind":"number","value":15,"string":"15"},"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":686,"string":"686"},"issue_words_count":{"kind":"number","value":100,"string":"100"},"issue_tokens_count":{"kind":"number","value":159,"string":"159"},"issue_lines_count":{"kind":"number","value":14,"string":"14"},"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:16","string":"1970-01-01T00:24:16"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1336,"cells":{"id":{"kind":"number","value":103,"string":"103"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1556/1526"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1526"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1556"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1556"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Example Value overwrites Parameter's DataType"},"issue_body":{"kind":"string","value":"Hi,\n\nI encountered the following unexpected behavior. When specifying an example value in a `@ApiImplicitParam` annotation the parameter's dataType will be set to the example value.\n\nFor instance annotation\n\n``` java\n@ApiImplicitParam(name=\"id\", paramType=\"path\", dataType=\"string\", example=\"123456\")\n```\n\nwill lead to JSON\n\n``` json\n\"parameters\":\n[{\"name\":\"id\",\n \"in\":\"path\",\n \"type\":\"123456\",\n \"x-example\":\"123456\"}]\n```\n\nThis behavior was observed on swagger 1.5.4.\n\nCause is the `ParameterProcessor.applyAnnotations()` method. The following code found in the method overwrites the parameter's dataType:\n\n``` java\n if (StringUtils.isNotEmpty(param.getExample())) {\n p.setType(param.getExample());\n }\n```\n\nI am not really sure about the original intention of the code but it does not look right to me. The code was introduced by commit 62c100f33a54d7688e859cd011abb89a907e02ef \"added example support for non-body params, implicits\".\n\nBest regards,\n\nphosn\n"},"base_sha":{"kind":"string","value":"436a9cb792be23fc835cf2dcbe1bdb087590f483"},"head_sha":{"kind":"string","value":"edeca227123e85ab03666f3d5e131d6e2c457663"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/436a9cb792be23fc835cf2dcbe1bdb087590f483...edeca227123e85ab03666f3d5e131d6e2c457663"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java b/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java\nindex b75656013..adb4106f0 100644\n--- a/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java\n+++ b/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java\n@@ -67,9 +67,6 @@ public class ParameterProcessor {\n p.setType(param.getDataType());\n }\n }\n- if (StringUtils.isNotEmpty(param.getExample())) {\n- p.setType(param.getExample());\n- }\n if (helper.getMinItems() != null) {\n p.setMinItems(helper.getMinItems());\n }\ndiff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java b/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java\nindex 63f6d5da6..fbf438d74 100644\n--- a/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java\n+++ b/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java\n@@ -13,7 +13,7 @@ public class ResourceWithImplicitFileParam {\n @POST\n @Path(\"/testString\")\n @ApiImplicitParams({\n- @ApiImplicitParam(name = \"sort\", paramType = \"form\", dataType = \"java.io.File\", required = false, value = \"file to upload\")\n+ @ApiImplicitParam(name = \"sort\", paramType = \"form\", dataType = \"java.io.File\", required = false, value = \"file to upload\")\n })\n @ApiOperation(\"Test operation with implicit parameters\")\n public void testImplicitFileParam() {"},"changed_files":{"kind":"string","value":"['modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java', 'modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.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":564498,"string":"564,498"},"repo_tokens_count":{"kind":"number","value":108724,"string":"108,724"},"repo_lines_count":{"kind":"number","value":17783,"string":"17,783"},"repo_files_without_tests_count":{"kind":"number","value":163,"string":"163"},"changed_symbols_count":{"kind":"number","value":125,"string":"125"},"changed_tokens_count":{"kind":"number","value":19,"string":"19"},"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":969,"string":"969"},"issue_words_count":{"kind":"number","value":116,"string":"116"},"issue_tokens_count":{"kind":"number","value":236,"string":"236"},"issue_lines_count":{"kind":"number","value":36,"string":"36"},"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:24:08","string":"1970-01-01T00:24:08"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1337,"cells":{"id":{"kind":"number","value":104,"string":"104"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1453/1440"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1440"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1453"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1453"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"The ApiOperation.nickname property does not work"},"issue_body":{"kind":"string","value":"The reason: please check this class: io.swagger.jaxrs.Reader, line 711\nI think there should be: operationId = apiOperation.nickname();\ninstead of: operationId = method.getName();\n\nSincerely yours\nNazar\n"},"base_sha":{"kind":"string","value":"4e6793564819457e5724464b27a782afad145e10"},"head_sha":{"kind":"string","value":"91a4dbef7c3756ecc69f334bd5d7a89ecf4b5737"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/4e6793564819457e5724464b27a782afad145e10...91a4dbef7c3756ecc69f334bd5d7a89ecf4b5737"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java\nindex 937ec0a52..464d77c2a 100644\n--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java\n+++ b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java\n@@ -714,7 +714,7 @@ public class Reader {\n return null;\n }\n if (!\"\".equals(apiOperation.nickname())) {\n- operationId = method.getName();\n+ operationId = apiOperation.nickname();\n }\n \n defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());"},"changed_files":{"kind":"string","value":"['modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.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":532171,"string":"532,171"},"repo_tokens_count":{"kind":"number","value":102641,"string":"102,641"},"repo_lines_count":{"kind":"number","value":16824,"string":"16,824"},"repo_files_without_tests_count":{"kind":"number","value":160,"string":"160"},"changed_symbols_count":{"kind":"number","value":104,"string":"104"},"changed_tokens_count":{"kind":"number","value":15,"string":"15"},"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":203,"string":"203"},"issue_words_count":{"kind":"number","value":25,"string":"25"},"issue_tokens_count":{"kind":"number","value":49,"string":"49"},"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:02","string":"1970-01-01T00:24:02"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1338,"cells":{"id":{"kind":"number","value":105,"string":"105"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1262/1175"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1175"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1262"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1262"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Change logging level to DEBUG for some messages in PropertyBuilder"},"issue_body":{"kind":"string","value":"Change logging level for [this](https://github.com/swagger-api/swagger-core/blob/400662d7253c0c2efb14316f8948ddc61a60069e/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java#L569) message to DEBUG as these messages look confusing for [codegen](https://github.com/swagger-api/swagger-codegen) users (https://github.com/swagger-api/swagger-parser/issues/60).\n"},"base_sha":{"kind":"string","value":"42056f20c52407e4c13283794a65d6d71b3a7e41"},"head_sha":{"kind":"string","value":"183a6fccd65bc0cd6de129aa2c7b35b13bfd2797"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/42056f20c52407e4c13283794a65d6d71b3a7e41...183a6fccd65bc0cd6de129aa2c7b35b13bfd2797"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java\nindex 41fbdf96a..660d11c86 100644\n--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java\n+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java\n@@ -566,7 +566,7 @@ public class PropertyBuilder {\n return item;\n }\n }\n- LOGGER.error(\"no property for \" + type + \", \" + format);\n+ LOGGER.debug(\"no property for \" + type + \", \" + format);\n return null;\n }\n "},"changed_files":{"kind":"string","value":"['modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.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":438099,"string":"438,099"},"repo_tokens_count":{"kind":"number","value":84995,"string":"84,995"},"repo_lines_count":{"kind":"number","value":14008,"string":"14,008"},"repo_files_without_tests_count":{"kind":"number","value":142,"string":"142"},"changed_symbols_count":{"kind":"number","value":139,"string":"139"},"changed_tokens_count":{"kind":"number","value":32,"string":"32"},"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":392,"string":"392"},"issue_words_count":{"kind":"number","value":17,"string":"17"},"issue_tokens_count":{"kind":"number","value":96,"string":"96"},"issue_lines_count":{"kind":"number","value":2,"string":"2"},"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:23:56","string":"1970-01-01T00:23:56"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1339,"cells":{"id":{"kind":"number","value":107,"string":"107"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1190/1185"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1185"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1190"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1190"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"'hidden' variable is not used"},"issue_body":{"kind":"string","value":"'hidden' variable is declared, but isn't used https://github.com/swagger-api/swagger-core/blob/9c67549cc4e30db916dac0165f0549485a6eb4c7/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java#L834-L837\n"},"base_sha":{"kind":"string","value":"8999c5b5a862cc4b9f533d1692ba9db7858b1d5f"},"head_sha":{"kind":"string","value":"a671881ac26a1df940012f2b2ff370d393f2dfee"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/8999c5b5a862cc4b9f533d1692ba9db7858b1d5f...a671881ac26a1df940012f2b2ff370d393f2dfee"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java\nindex 1657326ca..145416564 100644\n--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java\n+++ b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java\n@@ -829,11 +829,6 @@ public class Reader {\n operation.setDeprecated(true);\n }\n \n- boolean hidden = false;\n- if (apiOperation != null) {\n- hidden = apiOperation.hidden();\n- }\n-\n // process parameters\n for (Parameter globalParameter : globalParameters) {\n operation.parameter(globalParameter);"},"changed_files":{"kind":"string","value":"['modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.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":431150,"string":"431,150"},"repo_tokens_count":{"kind":"number","value":83484,"string":"83,484"},"repo_lines_count":{"kind":"number","value":13753,"string":"13,753"},"repo_files_without_tests_count":{"kind":"number","value":140,"string":"140"},"changed_symbols_count":{"kind":"number","value":127,"string":"127"},"changed_tokens_count":{"kind":"number","value":24,"string":"24"},"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":211,"string":"211"},"issue_words_count":{"kind":"number","value":8,"string":"8"},"issue_tokens_count":{"kind":"number","value":66,"string":"66"},"issue_lines_count":{"kind":"number","value":2,"string":"2"},"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:23:54","string":"1970-01-01T00:23:54"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1340,"cells":{"id":{"kind":"number","value":109,"string":"109"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1033/1000"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1000"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1033"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1033"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"NPE without any class with @Api annotation"},"issue_body":{"kind":"string","value":"If there is no class with `@Api` annotation trying to get `swagger.json` causes NPE. This may be very confusing at the beginning, when we are implementing Swagger step-by-step and get exception.\n\nStack:\n\n```\njava.lang.NullPointerException\n at com.wordnik.swagger.jaxrs.config.BeanConfig.configure(BeanConfig.java:196)\n at com.wordnik.swagger.jaxrs.listing.ApiListingResource.scan(ApiListingResource.java:52)\n at com.wordnik.swagger.jaxrs.listing.ApiListingResource.getListingJson(ApiListingResource.java:79)\n ...\n```\n\nSo we have to check for nulls somewhere in this area: https://github.com/swagger-api/swagger-core/blob/c4260bea041027f9887c67d5d6c6eb408c238969/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/config/BeanConfig.java#L197\n"},"base_sha":{"kind":"string","value":"e9cad60100c883f171b6d2a989ee6eb398fd3a25"},"head_sha":{"kind":"string","value":"e2e459b0a134e4310b91f60e2fb31625a40f57f0"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/e9cad60100c883f171b6d2a989ee6eb398fd3a25...e2e459b0a134e4310b91f60e2fb31625a40f57f0"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java\nindex 0574c9891..23aea9a17 100644\n--- a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java\n+++ b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java\n@@ -58,7 +58,7 @@ public class Reader {\n static ObjectMapper m = Json.mapper();\n \n public Reader(Swagger swagger) {\n- this.swagger = swagger;\n+ this.swagger = swagger == null ? new Swagger() : swagger;\n }\n \n public Swagger read(Set> classes) {\n@@ -76,8 +76,6 @@ public class Reader {\n }\n \n protected Swagger read(Class cls, String parentPath, String parentMethod, boolean readHidden, String[] parentConsumes, String[] parentProduces, Map parentTags, List parentParameters) {\n- if(swagger == null)\n- swagger = new Swagger();\n Api api = (Api) cls.getAnnotation(Api.class);\n Map globalScopes = new HashMap();\n "},"changed_files":{"kind":"string","value":"['modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.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":887167,"string":"887,167"},"repo_tokens_count":{"kind":"number","value":204437,"string":"204,437"},"repo_lines_count":{"kind":"number","value":29102,"string":"29,102"},"repo_files_without_tests_count":{"kind":"number","value":399,"string":"399"},"changed_symbols_count":{"kind":"number","value":148,"string":"148"},"changed_tokens_count":{"kind":"number","value":33,"string":"33"},"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":764,"string":"764"},"issue_words_count":{"kind":"number","value":54,"string":"54"},"issue_tokens_count":{"kind":"number","value":192,"string":"192"},"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:23:50","string":"1970-01-01T00:23:50"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1341,"cells":{"id":{"kind":"number","value":100,"string":"100"},"text_id":{"kind":"string","value":"swagger-api/swagger-core/1718/1714"},"repo_owner":{"kind":"string","value":"swagger-api"},"repo_name":{"kind":"string","value":"swagger-core"},"issue_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/issues/1714"},"pull_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1718"},"comment_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/pull/1718"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"jersey2 listing resource broken"},"issue_body":{"kind":"string","value":"1.5.8 seems to have broken the listing resource for jersey2. Now this class:\n\n``` java\npackage io.swagger.jersey.listing;\n\n/* */\n@Path(\"/\")\npublic class ApiListingResourceJSON\n extends ApiListingResource {\n}\n```\n\ncauses the swagger definition to appear only on `\"/\"` instead of `\"/swagger.{type:json|yaml}\"` as defined in the `io.swagger.jaxrs.listing.ApiListingResource` class\n\nThe solution is to use `io.swagger.jaxrs.listing.ApiListingResource`, but for previous uses (like swagger-generator), the 1.5.8 changes break the resource.\n\nWe should either fix the ApiListingResourceJSON, remove it, or make it clear how to update when going to 1.5.8.\n"},"base_sha":{"kind":"string","value":"3e5a7e613daaa95028f3aeb45cd8545c14deaa8c"},"head_sha":{"kind":"string","value":"2425b7f3aa36d7661777ca8819445180af792431"},"diff_url":{"kind":"string","value":"https://github.com/swagger-api/swagger-core/compare/3e5a7e613daaa95028f3aeb45cd8545c14deaa8c...2425b7f3aa36d7661777ca8819445180af792431"},"diff":{"kind":"string","value":"diff --git a/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java b/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java\nindex 05a54d0cf..dbe40f642 100644\n--- a/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java\n+++ b/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java\n@@ -2,9 +2,7 @@ package io.swagger.jersey.listing;\n \n import io.swagger.jaxrs.listing.ApiListingResource;\n \n-import javax.ws.rs.Path;\n-\n-@Path(\"/\")\n+@Deprecated\n public class ApiListingResourceJSON\n extends ApiListingResource {\n }\n\\\\ No newline at end of file"},"changed_files":{"kind":"string","value":"['modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.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":618360,"string":"618,360"},"repo_tokens_count":{"kind":"number","value":119346,"string":"119,346"},"repo_lines_count":{"kind":"number","value":19394,"string":"19,394"},"repo_files_without_tests_count":{"kind":"number","value":169,"string":"169"},"changed_symbols_count":{"kind":"number","value":52,"string":"52"},"changed_tokens_count":{"kind":"number","value":12,"string":"12"},"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":656,"string":"656"},"issue_words_count":{"kind":"number","value":83,"string":"83"},"issue_tokens_count":{"kind":"number","value":164,"string":"164"},"issue_lines_count":{"kind":"number","value":18,"string":"18"},"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:18","string":"1970-01-01T00:24:18"},"repo_stars":{"kind":"number","value":7244,"string":"7,244"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2870337, 'Shell': 9095, 'Python': 4538}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1342,"cells":{"id":{"kind":"number","value":8978,"string":"8,978"},"text_id":{"kind":"string","value":"karatelabs/karate/1556/1555"},"repo_owner":{"kind":"string","value":"karatelabs"},"repo_name":{"kind":"string","value":"karate"},"issue_url":{"kind":"string","value":"https://github.com/karatelabs/karate/issues/1555"},"pull_url":{"kind":"string","value":"https://github.com/karatelabs/karate/pull/1556"},"comment_url":{"kind":"string","value":"https://github.com/karatelabs/karate/pull/1556"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"`logPrettyResponse` configuration parameter is not considered"},"issue_body":{"kind":"string","value":"`logPrettyResponse` is not considered when configured, either in `karate-config.js` or in the feature itself.\r\nLooking at the code I found the issue and will submit a PR to fix it.\r\n"},"base_sha":{"kind":"string","value":"e2b4f3a875805da0a6f2531952af26540eb7c7c1"},"head_sha":{"kind":"string","value":"d5abda97bfcd507f7bd1fcd5b31a876f564b5bc5"},"diff_url":{"kind":"string","value":"https://github.com/karatelabs/karate/compare/e2b4f3a875805da0a6f2531952af26540eb7c7c1...d5abda97bfcd507f7bd1fcd5b31a876f564b5bc5"},"diff":{"kind":"string","value":"diff --git a/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java b/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java\nindex f6d7466cd..bc5464d12 100644\n--- a/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java\n+++ b/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java\n@@ -69,7 +69,7 @@ public class HttpLogger {\n }\n Variable v = new Variable(body);\n String text;\n- if (config != null && config.isLogPrettyRequest()) {\n+ if (config != null && needsPrettyLogging(config, request)) {\n text = v.getAsPrettyString();\n } else {\n text = v.getAsString();\n@@ -80,6 +80,18 @@ public class HttpLogger {\n sb.append(text);\n }\n \n+ private static boolean needsPrettyLogging(Config config, boolean request) {\n+ return logPrettyRequest(config, request) || logPrettyResponse(config, request);\n+ }\n+\n+ private static boolean logPrettyResponse(Config config, boolean request) {\n+ return !request && config.isLogPrettyResponse();\n+ }\n+\n+ private static boolean logPrettyRequest(Config config, boolean request) {\n+ return request && config.isLogPrettyRequest();\n+ }\n+\n private static HttpLogModifier logModifier(Config config, String uri) {\n HttpLogModifier logModifier = config.getLogModifier();\n return logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null;"},"changed_files":{"kind":"string","value":"['karate-core/src/main/java/com/intuit/karate/http/HttpLogger.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":1614061,"string":"1,614,061"},"repo_tokens_count":{"kind":"number","value":334168,"string":"334,168"},"repo_lines_count":{"kind":"number","value":47449,"string":"47,449"},"repo_files_without_tests_count":{"kind":"number","value":310,"string":"310"},"changed_symbols_count":{"kind":"number","value":601,"string":"601"},"changed_tokens_count":{"kind":"number","value":115,"string":"115"},"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":182,"string":"182"},"issue_words_count":{"kind":"number","value":30,"string":"30"},"issue_tokens_count":{"kind":"number","value":42,"string":"42"},"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:26:58","string":"1970-01-01T00:26:58"},"repo_stars":{"kind":"number","value":7226,"string":"7,226"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2164729, 'Gherkin': 262656, 'JavaScript': 70334, 'HTML': 44272, 'Scala': 13901, 'CSS': 7856, 'ANTLR': 4088, 'Shell': 3629, 'Dockerfile': 2919}"},"repo_license":{"kind":"string","value":"MIT License"}}},{"rowIdx":1343,"cells":{"id":{"kind":"number","value":8977,"string":"8,977"},"text_id":{"kind":"string","value":"karatelabs/karate/2376/2259"},"repo_owner":{"kind":"string","value":"karatelabs"},"repo_name":{"kind":"string","value":"karate"},"issue_url":{"kind":"string","value":"https://github.com/karatelabs/karate/issues/2259"},"pull_url":{"kind":"string","value":"https://github.com/karatelabs/karate/pull/2376"},"comment_url":{"kind":"string","value":"https://github.com/karatelabs/karate/pull/2376"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"Double Click and Right Click in Karate Robot framework for windows app"},"issue_body":{"kind":"string","value":"Double click doesnt work in Karate Robot framework for windows app\r\n```\r\nlocate('abc').doubleClick(0,0)\r\n```\r\nIt clicks twice but does it slowly such that the double click does not really work. I found doubleClick() method in RobotBase.Java which has a 40ms delay between the clicks and i'm not sure if that is the reason behind the lag in clicks.\r\n\r\nRight Click also doesnt work as there is no method in Element.java but there is a rightClick() method in RobotBase.Java which calls Click(3) internally "},"base_sha":{"kind":"string","value":"7e1f3b3bb0405847722f814d4ab8fed08e7f8832"},"head_sha":{"kind":"string","value":"7ee8b8bd272a7e12a7e2318a193ab84b4c45da6a"},"diff_url":{"kind":"string","value":"https://github.com/karatelabs/karate/compare/7e1f3b3bb0405847722f814d4ab8fed08e7f8832...7ee8b8bd272a7e12a7e2318a193ab84b4c45da6a"},"diff":{"kind":"string","value":"diff --git a/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java b/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java\nindex af420922a..0ee7dfbfc 100644\n--- a/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java\n+++ b/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java\n@@ -277,7 +277,7 @@ public abstract class RobotBase implements Robot, Plugin {\n \n @Override\n public Robot rightClick() {\n- return click(3);\n+ return click(2);\n }\n \n @Override\n@@ -299,9 +299,20 @@ public abstract class RobotBase implements Robot, Plugin {\n \n @Override\n public Robot doubleClick() {\n- click();\n- delay(40);\n- click();\n+ if (highlight) {\n+ getLocation().highlight(highlightDuration);\n+ int toDelay = highlightDuration;\n+ if (toDelay > 0) {\n+ RobotUtils.delay(toDelay);\n+ }\n+ }\n+ int clickType = mask(1);\n+ robot.mousePress(clickType);\n+ robot.mouseRelease(clickType);\n+ RobotUtils.delay(100);\n+ robot.mousePress(clickType);\n+ robot.mouseRelease(clickType);\n+\n return this;\n }\n "},"changed_files":{"kind":"string","value":"['karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.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":1727793,"string":"1,727,793"},"repo_tokens_count":{"kind":"number","value":357449,"string":"357,449"},"repo_lines_count":{"kind":"number","value":50168,"string":"50,168"},"repo_files_without_tests_count":{"kind":"number","value":307,"string":"307"},"changed_symbols_count":{"kind":"number","value":562,"string":"562"},"changed_tokens_count":{"kind":"number","value":110,"string":"110"},"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":504,"string":"504"},"issue_words_count":{"kind":"number","value":82,"string":"82"},"issue_tokens_count":{"kind":"number","value":115,"string":"115"},"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:28:11","string":"1970-01-01T00:28:11"},"repo_stars":{"kind":"number","value":7226,"string":"7,226"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 2164729, 'Gherkin': 262656, 'JavaScript': 70334, 'HTML': 44272, 'Scala': 13901, 'CSS': 7856, 'ANTLR': 4088, 'Shell': 3629, 'Dockerfile': 2919}"},"repo_license":{"kind":"string","value":"MIT License"}}},{"rowIdx":1344,"cells":{"id":{"kind":"number","value":3321,"string":"3,321"},"text_id":{"kind":"string","value":"apache/beam/27699/27670"},"repo_owner":{"kind":"string","value":"apache"},"repo_name":{"kind":"string","value":"beam"},"issue_url":{"kind":"string","value":"https://github.com/apache/beam/issues/27670"},"pull_url":{"kind":"string","value":"https://github.com/apache/beam/pull/27699"},"comment_url":{"kind":"string","value":"https://github.com/apache/beam/pull/27699"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"[Bug]: Storage Write API fails on Batch Pipelines on 2.49"},"issue_body":{"kind":"string","value":"### What happened?\r\n\r\nWhen writing to a BigQuery sink in a Batch pipeline using Storage Write API the pipeline fails due to the following error,\r\n\r\n```\r\njava.lang.RuntimeException: org.apache.beam.sdk.util.UserCodeException: java.lang.RuntimeException: Schema field not found: eventid\r\n\r\nat org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowsParDoFn.java:187 )\r\nat org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:108 )\r\nat org.apache.beam.runners.dataflow.worker.util.BatchGroupAlsoByWindowReshuffleFn.processElement ( org/apache.beam.runners.dataflow.worker.util/BatchGroupAlsoByWindowReshuffleFn.java:56 )\r\nat org.apache.beam.runners.dataflow.worker.util.BatchGroupAlsoByWindowReshuffleFn.processElement ( org/apache.beam.runners.dataflow.worker.util/BatchGroupAlsoByWindowReshuffleFn.java:39 )\r\nat org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:121 )\r\nat org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:73 )\r\nat org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowsParDoFn.java:117 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( org/apache.beam.runners.dataflow.worker.util.common.worker/ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( org/apache.beam.runners.dataflow.worker.util.common.worker/OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop ( org/apache.beam.runners.dataflow.worker.util.common.worker/ReadOperation.java:218 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start ( org/apache.beam.runners.dataflow.worker.util.common.worker/ReadOperation.java:169 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute ( org/apache.beam.runners.dataflow.worker.util.common.worker/MapTaskExecutor.java:83 )\r\nat org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.executeWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:319 )\r\nat org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.doWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:291 )\r\nat org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.getAndPerformWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:221 )\r\nat org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:147 )\r\nat org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:127 )\r\nat org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:114 )\r\nat java.util.concurrent.FutureTask.run ( java/util.concurrent/FutureTask.java:264 )\r\nat org.apache.beam.sdk.util.UnboundedScheduledExecutorService$ScheduledFutureTask.run ( org/apache.beam.sdk.util/UnboundedScheduledExecutorService.java:163 )\r\nat java.util.concurrent.ThreadPoolExecutor.runWorker ( java/util.concurrent/ThreadPoolExecutor.java:1128 )\r\nat java.util.concurrent.ThreadPoolExecutor$Worker.run ( java/util.concurrent/ThreadPoolExecutor.java:628 )\r\nat java.lang.Thread.run ( java/lang/Thread.java:834 )\r\nCaused by: org.apache.beam.sdk.util.UserCodeException\r\n\r\nat org.apache.beam.sdk.util.UserCodeException.wrap ( UserCodeException.java:39 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.StorageApiConvertMessages$ConvertMessagesDoFn$DoFnInvoker.invokeProcessElement\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.AssignWindowsParDoFnFactory$AssignWindowsParDoFn.processElement ( AssignWindowsParDoFnFactory.java:115 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement ( PrepareWrite.java:84 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1$DoFnInvoker.invokeProcessElement\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:185 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 )\r\nat org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn.processElement ( JdbcIO.java:1528 )\r\nat org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn$DoFnInvoker.invokeProcessElement\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )\r\nat org.apache.beam.sdk.transforms.DoFnOutputReceivers$WindowedContextOutputReceiver.output ( DoFnOutputReceivers.java:76 )\r\nat org.apache.beam.sdk.transforms.MapElements$2.processElement ( MapElements.java:151 )\r\nat org.apache.beam.sdk.transforms.MapElements$2$DoFnInvoker.invokeProcessElement\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 )\r\nat org.apache.beam.runners.dataflow.ReshuffleOverrideFactory$ReshuffleWithOnlyTrigger$1.processElement ( ReshuffleOverrideFactory.java:86 )\r\nat org.apache.beam.runners.dataflow.ReshuffleOverrideFactory$ReshuffleWithOnlyTrigger$1$DoFnInvoker.invokeProcessElement\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )\r\nat org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )\r\nat org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )\r\nat org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )\r\nat org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output ( GroupAlsoByWindowsParDoFn.java:185 )\r\nCaused by: java.lang.RuntimeException\r\n\r\nat org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto$SchemaInformation.getSchemaForField ( TableRowToStorageApiProto.java:371 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto.messageFromMap ( TableRowToStorageApiProto.java:472 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto.messageFromTableRow ( TableRowToStorageApiProto.java:625 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.StorageApiDynamicDestinationsTableRow$TableRowConverter.toMessage ( StorageApiDynamicDestinationsTableRow.java:170 )\r\nat org.apache.beam.sdk.io.gcp.bigquery.StorageApiConvertMessages$ConvertMessagesDoFn.processElement ( StorageApiConvertMessages.java:159 )\r\n```\r\n\r\nThe field `eventId` exists but for some reason the case of the field changes. \r\n\r\nThis does not occur in when using File Loads method. \r\n\r\n### Issue Priority\r\n\r\nPriority: 1 (data loss / total loss of function)\r\n\r\n### Issue Components\r\n\r\n- [ ] Component: Python SDK\r\n- [X] Component: Java SDK\r\n- [ ] Component: Go SDK\r\n- [ ] Component: Typescript SDK\r\n- [x] Component: IO connector\r\n- [ ] Component: Beam examples\r\n- [ ] Component: Beam playground\r\n- [ ] Component: Beam katas\r\n- [ ] Component: Website\r\n- [ ] Component: Spark Runner\r\n- [ ] Component: Flink Runner\r\n- [ ] Component: Samza Runner\r\n- [ ] Component: Twister2 Runner\r\n- [ ] Component: Hazelcast Jet Runner\r\n- [ ] Component: Google Cloud Dataflow Runner"},"base_sha":{"kind":"string","value":"f35a6365e8a6a67e74e933f29789f5bbf5f59315"},"head_sha":{"kind":"string","value":"2e958499e5d9060706d54b2fd99a347e48f3f1db"},"diff_url":{"kind":"string","value":"https://github.com/apache/beam/compare/f35a6365e8a6a67e74e933f29789f5bbf5f59315...2e958499e5d9060706d54b2fd99a347e48f3f1db"},"diff":{"kind":"string","value":"diff --git a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java\nindex d231d84aea..d98f9115cb 100644\n--- a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java\n+++ b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java\n@@ -344,7 +344,7 @@ public class TableRowToStorageApiProto {\n new SchemaInformation(\n field, Iterables.concat(this.parentSchemas, ImmutableList.of(this)));\n subFields.add(schemaInformation);\n- subFieldsByName.put(field.getName(), schemaInformation);\n+ subFieldsByName.put(field.getName().toLowerCase(), schemaInformation);\n }\n }\n \n@@ -365,9 +365,9 @@ public class TableRowToStorageApiProto {\n }\n \n public SchemaInformation getSchemaForField(String name) {\n- SchemaInformation schemaInformation = subFieldsByName.get(name);\n+ SchemaInformation schemaInformation = subFieldsByName.get(name.toLowerCase());\n if (schemaInformation == null) {\n- throw new RuntimeException(\"Schema field not found: \" + name);\n+ throw new RuntimeException(\"Schema field not found: \" + name.toLowerCase());\n }\n return schemaInformation;\n }\ndiff --git a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java\nindex 534c1b0c36..6405c0599e 100644\n--- a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java\n+++ b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java\n@@ -1824,7 +1824,7 @@ public class BigQueryIOWriteTest implements Serializable {\n new SimpleFunction() {\n @Override\n public TableRow apply(Long input) {\n- return new TableRow().set(\"name\", \"name \" + input).set(\"number\", input);\n+ return new TableRow().set(\"NaMe\", \"name \" + input).set(\"numBEr\", input);\n }\n }))\n .setCoder(TableRowJsonCoder.of());"},"changed_files":{"kind":"string","value":"['sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java', 'sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.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":26087797,"string":"26,087,797"},"repo_tokens_count":{"kind":"number","value":5616266,"string":"5,616,266"},"repo_lines_count":{"kind":"number","value":667143,"string":"667,143"},"repo_files_without_tests_count":{"kind":"number","value":3970,"string":"3,970"},"changed_symbols_count":{"kind":"number","value":461,"string":"461"},"changed_tokens_count":{"kind":"number","value":78,"string":"78"},"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":12687,"string":"12,687"},"issue_words_count":{"kind":"number","value":590,"string":"590"},"issue_tokens_count":{"kind":"number","value":2911,"string":"2,911"},"issue_lines_count":{"kind":"number","value":125,"string":"125"},"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:28:10","string":"1970-01-01T00:28:10"},"repo_stars":{"kind":"number","value":7039,"string":"7,039"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 44997581, 'Python': 11684345, 'Go': 6460783, 'TypeScript': 2009450, 'Dart': 1436710, 'Groovy': 981282, 'Shell': 411640, 'SCSS': 319433, 'Kotlin': 251827, 'HCL': 233427, 'HTML': 200724, 'JavaScript': 122178, 'Cython': 75277, 'Dockerfile': 73608, 'Jupyter Notebook': 61209, 'Sass': 27577, 'FreeMarker': 7933, 'CSS': 7584, 'Rust': 5168, 'C': 3869, 'Lua': 3620, 'Thrift': 3260, 'Smarty': 2618, 'ANTLR': 1598, 'Scala': 1429}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1345,"cells":{"id":{"kind":"number","value":516,"string":"516"},"text_id":{"kind":"string","value":"google/closure-compiler/1409/1407"},"repo_owner":{"kind":"string","value":"google"},"repo_name":{"kind":"string","value":"closure-compiler"},"issue_url":{"kind":"string","value":"https://github.com/google/closure-compiler/issues/1407"},"pull_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1409"},"comment_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1409"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Cannot use globs when running the compiler."},"issue_body":{"kind":"string","value":"Since 62ca536... I am no longer able to use globs for files when running the compiler:\n\nRunning this command used to work before that change:\n\n```\njava -jar ../../compiler/compiler.jar \\\\\n--flagfile=options/compile.ini \\\\\n--define \"goog.json.USE_NATIVE_JSON=true\" --define \"goog.ui.Component.ALLOW_DETACHED_DECORATION=true\" --define \"goog.NATIVE_ARRAY_PROTOTYPES=true\" --define \"goog.array.ASSUME_NATIVE_FUNCTIONS=true\" --define \"goog.Promise.UNHANDLED_REJECTION_DELAY=-1\" --define \"app.settings.RUN_AS_USER=false\" --externs=../externs/material.js --generate_exports --export_local_property_definitions --language_in=ECMASCRIPT6 --language_out=ES3 --use_types_for_optimization --output_wrapper=\"(function(){%output%})();\" \\\\\n--only_closure_dependencies \\\\\n--closure_entry_point=app \\\\\n--manage_closure_dependencies true \\\\\n--output_manifest build/app.filelist.txt \\\\\n--js_output_file /tmp/closure_compiler_build \\\\\n--js=\"js/**.js\" --js=\"tpl/en/**.js\" --js=\"../../templates/soyutils_usegoog.js\" --js=\"../../library/closure/goog/**.js\" --js=\"../../library/third_party/closure/goog/mochikit/async/deferred.js\" --js=\"../../library/third_party/closure/goog/mochikit/async/deferredlist.js\" --js=\"../pstj/animation/**.js\" --js=\"../pstj/app/**.js\" --js=\"../pstj/autogenerated/**.js\" --js=\"../pstj/cast/**.js\" --js=\"../pstj/color/**.js\" --js=\"../pstj/config/**.js\" --js=\"../pstj/control/**.js\" --js=\"../pstj/date/**.js\" --js=\"../pstj/debug/**.js\" --js=\"../pstj/ds/**.js\" --js=\"../pstj/element/**.js\" --js=\"../pstj/error/**.js\" --js=\"../pstj/fx/**.js\" --js=\"../pstj/graphics/**.js\" --js=\"../pstj/material/**.js\" --js=\"../pstj/math/**.js\" --js=\"../pstj/mvc/**.js\" --js=\"../pstj/ng/**.js\" --js=\"../pstj/object/**.js\" --js=\"../pstj/options/**.js\" --js=\"../pstj/resource/**.js\" --js=\"../pstj/sourcegen/**.js\" --js=\"../pstj/storage/**.js\" --js=\"../pstj/style/**.js\" --js=\"../pstj/themes/**.js\" --js=\"../pstj/ui/**.js\" --js=\"../smjs/ds/**.js\" --js=\"../smjs/element/**.js\" --js=\"../smjs/persistence/**.js\" --js=\"../smjs/player/**.js\" --js=\"../smjs/remotecontrol/**.js\" --js=\"../smjs/transport/**.js\" --js=\"../smjs/tv/**.js\" --js=\"../smjs/widgets/**.js\" --js=\"!**_test.js\"\n```\n\nNow (after the mentioned change) it gives this:\n\n```\nERROR - Cannot read: !**_test.js\n\nERROR - Cannot read: ../../library/closure/goog/**.js\n\nERROR - Cannot read: ../pstj/animation/**.js\n\nERROR - Cannot read: ../pstj/app/**.js\n\nERROR - Cannot read: ../pstj/autogenerated/**.js\n\nERROR - Cannot read: ../pstj/cast/**.js\n\nERROR - Cannot read: ../pstj/color/**.js\n\nERROR - Cannot read: ../pstj/config/**.js\n\nERROR - Cannot read: ../pstj/control/**.js\n\nERROR - Cannot read: ../pstj/date/**.js\n\nERROR - Cannot read: ../pstj/debug/**.js\n\nERROR - Cannot read: ../pstj/ds/**.js\n\nERROR - Cannot read: ../pstj/element/**.js\n\nERROR - Cannot read: ../pstj/error/**.js\n\nERROR - Cannot read: ../pstj/fx/**.js\n\nERROR - Cannot read: ../pstj/graphics/**.js\n\nERROR - Cannot read: ../pstj/material/**.js\n\nERROR - Cannot read: ../pstj/math/**.js\n\nERROR - Cannot read: ../pstj/mvc/**.js\n\nERROR - Cannot read: ../pstj/ng/**.js\n\nERROR - Cannot read: ../pstj/object/**.js\n\nERROR - Cannot read: ../pstj/options/**.js\n\nERROR - Cannot read: ../pstj/resource/**.js\n\nERROR - Cannot read: ../pstj/sourcegen/**.js\n\nERROR - Cannot read: ../pstj/storage/**.js\n\nERROR - Cannot read: ../pstj/style/**.js\n\nERROR - Cannot read: ../pstj/themes/**.js\n\nERROR - Cannot read: ../pstj/ui/**.js\n\nERROR - Cannot read: ../smjs/ds/**.js\n\nERROR - Cannot read: ../smjs/element/**.js\n\nERROR - Cannot read: ../smjs/persistence/**.js\n\nERROR - Cannot read: ../smjs/player/**.js\n\nERROR - Cannot read: ../smjs/remotecontrol/**.js\n\nERROR - Cannot read: ../smjs/transport/**.js\n\nERROR - Cannot read: ../smjs/tv/**.js\n\nERROR - Cannot read: ../smjs/widgets/**.js\n\nERROR - Cannot read: js/**.js\n\nERROR - Cannot read: tpl/en/**.js\n\nERROR - required entry point \"app\" never provided\n\n39 error(s), 0 warning(s)\n```\n"},"base_sha":{"kind":"string","value":"00adf761809e997aadadcf07050310d5d1dbad68"},"head_sha":{"kind":"string","value":"dfd1853feeb252fd57cf245816cef4305d3e1fe8"},"diff_url":{"kind":"string","value":"https://github.com/google/closure-compiler/compare/00adf761809e997aadadcf07050310d5d1dbad68...dfd1853feeb252fd57cf245816cef4305d3e1fe8"},"diff":{"kind":"string","value":"diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java\nindex 34c79d686..019b4d62e 100644\n--- a/src/com/google/javascript/jscomp/CommandLineRunner.java\n+++ b/src/com/google/javascript/jscomp/CommandLineRunner.java\n@@ -26,8 +26,6 @@ import com.google.common.collect.ImmutableList;\n import com.google.common.collect.ImmutableMap;\n import com.google.common.collect.ImmutableSet;\n import com.google.common.io.Files;\n-import com.google.javascript.jscomp.AbstractCommandLineRunner.FlagEntry;\n-import com.google.javascript.jscomp.AbstractCommandLineRunner.JsSourceType;\n import com.google.javascript.jscomp.SourceMap.LocationMapping;\n import com.google.javascript.rhino.TokenStream;\n import com.google.protobuf.TextFormat;\n@@ -47,8 +45,8 @@ import org.kohsuke.args4j.spi.StringOptionHandler;\n import java.io.BufferedReader;\n import java.io.File;\n import java.io.FileInputStream;\n-import java.io.InputStream;\n import java.io.IOException;\n+import java.io.InputStream;\n import java.io.OutputStreamWriter;\n import java.io.PrintStream;\n import java.lang.reflect.AnnotatedElement;\n@@ -64,10 +62,10 @@ import java.nio.file.attribute.BasicFileAttributes;\n import java.util.ArrayList;\n import java.util.Collection;\n import java.util.Collections;\n-import java.util.LinkedHashSet;\n import java.util.List;\n import java.util.Map;\n import java.util.Set;\n+import java.util.TreeSet;\n import java.util.logging.Level;\n import java.util.regex.Matcher;\n import java.util.regex.Pattern;\n@@ -732,6 +730,28 @@ public class CommandLineRunner extends\n return allJsInputs;\n }\n \n+ protected List> getMixedJsSources()\n+ throws CmdLineException, IOException {\n+ List> mixedSources = new ArrayList<>();\n+ for (FlagEntry source : Flags.mixedJsSources) {\n+ if (source.value.endsWith(\".zip\")) {\n+ mixedSources.add(source);\n+ } else {\n+ for (String filename : findJsFiles(Collections.singletonList(source.value))) {\n+ mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));\n+ }\n+ }\n+ }\n+ List fromArguments = findJsFiles(arguments);\n+ for (String filename : fromArguments) {\n+ mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));\n+ }\n+ if (!Flags.mixedJsSources.isEmpty() && !arguments.isEmpty() && mixedSources.isEmpty()) {\n+ throw new CmdLineException(parser, \"No inputs matched\");\n+ }\n+ return mixedSources;\n+ }\n+\n List getSourceMapLocationMappings() throws CmdLineException {\n ImmutableList.Builder locationMappings = ImmutableList.builder();\n \n@@ -1078,6 +1098,7 @@ public class CommandLineRunner extends\n Flags.mixedJsSources.clear();\n \n List jsFiles = null;\n+ List> mixedSources = null;\n List mappings = null;\n ImmutableMap sourceMapInputs = null;\n try {\n@@ -1089,6 +1110,7 @@ public class CommandLineRunner extends\n }\n \n jsFiles = flags.getJsFiles();\n+ mixedSources = flags.getMixedJsSources();\n mappings = flags.getSourceMapLocationMappings();\n sourceMapInputs = flags.getSourceMapInputs();\n } catch (CmdLineException e) {\n@@ -1207,7 +1229,7 @@ public class CommandLineRunner extends\n .setExterns(flags.externs)\n .setJs(jsFiles)\n .setJsZip(flags.jszip)\n- .setMixedJsSources(Flags.mixedJsSources)\n+ .setMixedJsSources(mixedSources)\n .setJsOutputFile(flags.jsOutputFile)\n .setModule(flags.module)\n .setVariableMapOutputFile(flags.variableMapOutputFile)\n@@ -1437,7 +1459,7 @@ public class CommandLineRunner extends\n * within the directory and sub-directories.\n */\n public static List findJsFiles(Collection patterns) throws IOException {\n- Set allJsInputs = new LinkedHashSet<>();\n+ Set allJsInputs = new TreeSet<>();\n for (String pattern : patterns) {\n if (!pattern.contains(\"*\") && !pattern.startsWith(\"!\")) {\n File matchedFile = new File(pattern);\n@@ -1458,7 +1480,9 @@ public class CommandLineRunner extends\n throws IOException {\n FileSystem fs = FileSystems.getDefault();\n final boolean remove = pattern.indexOf('!') == 0;\n- if (remove) pattern = pattern.substring(1);\n+ if (remove) {\n+ pattern = pattern.substring(1);\n+ }\n \n if (File.separator.equals(\"\\\\\\\\\")) {\n pattern = pattern.replace('\\\\\\\\', '/');\n@@ -1473,18 +1497,20 @@ public class CommandLineRunner extends\n if (i == 0) {\n break;\n } else {\n- prefix = Joiner.on(\"/\").join(patternParts.subList(0, i));\n- pattern = Joiner.on(\"/\").join(patternParts.subList(i, patternParts.size()));\n+ prefix = Joiner.on(File.separator).join(patternParts.subList(0, i));\n+ pattern = Joiner.on(File.separator).join(patternParts.subList(i, patternParts.size()));\n }\n }\n }\n \n- final PathMatcher matcher = fs.getPathMatcher(\"glob:\" + pattern);\n+ final PathMatcher matcher = fs.getPathMatcher(\"glob:\" + (prefix.equals(\".\")\n+ ? pattern\n+ : prefix + File.separator + pattern));\n java.nio.file.Files.walkFileTree(\n fs.getPath(prefix), new SimpleFileVisitor() {\n @Override public FileVisitResult visitFile(\n Path p, BasicFileAttributes attrs) {\n- if (matcher.matches(p)) {\n+ if (matcher.matches(p.normalize())) {\n if (remove) {\n allJsInputs.remove(p.toString());\n } else {\ndiff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\nindex fbee0ec4e..09463a96c 100644\n--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\n+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\n@@ -42,6 +42,7 @@ import java.io.File;\n import java.io.FileOutputStream;\n import java.io.IOException;\n import java.io.PrintStream;\n+import java.nio.file.Files;\n import java.util.ArrayList;\n import java.util.HashMap;\n import java.util.LinkedHashMap;\n@@ -1113,6 +1114,36 @@ public final class CommandLineRunnerTest extends TestCase {\n }\n }\n \n+ public void testGlobJs1() throws IOException {\n+ try {\n+ FlagEntry jsFile1 = createJsFile(\"test1\", \"var a;\");\n+ FlagEntry jsFile2 = createJsFile(\"test2\", \"var b;\");\n+ // Move test2 to the same directory as test1, also make the filename of test2\n+ // lexicographically larger than test1\n+ new File(jsFile2.value).renameTo(new File(\n+ new File(jsFile1.value).getParentFile() + File.separator + \"utest2.js\"));\n+ String glob = new File(jsFile1.value).getParent() + File.separator + \"**.js\";\n+ compileFiles(\n+ \"var a;var b;\", new FlagEntry<>(JsSourceType.JS, glob));\n+ } catch (FlagUsageException e) {\n+ fail(\"Unexpected exception\" + e);\n+ }\n+ }\n+\n+ public void testGlobJs2() throws IOException {\n+ try {\n+ FlagEntry jsFile1 = createJsFile(\"test1\", \"var a;\");\n+ FlagEntry jsFile2 = createJsFile(\"test2\", \"var b;\");\n+ new File(jsFile2.value).renameTo(new File(\n+ new File(jsFile1.value).getParentFile() + File.separator + \"utest2.js\"));\n+ String glob = new File(jsFile1.value).getParent() + File.separator + \"*test*.js\";\n+ compileFiles(\n+ \"var a;var b;\", new FlagEntry<>(JsSourceType.JS, glob));\n+ } catch (FlagUsageException e) {\n+ fail(\"Unexpected exception\" + e);\n+ }\n+ }\n+\n public void testSourceMapInputs() throws Exception {\n args.add(\"--js_output_file\");\n args.add(\"/path/to/out.js\");\n@@ -1875,7 +1906,8 @@ public final class CommandLineRunnerTest extends TestCase {\n \n private static FlagEntry createZipFile(Map entryContentsByName)\n throws IOException {\n- File tempZipFile = File.createTempFile(\"testdata\", \".js.zip\");\n+ File tempZipFile = File.createTempFile(\"testdata\", \".js.zip\",\n+ Files.createTempDirectory(\"jscomp\").toFile());\n \n try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempZipFile))) {\n for (Entry entry : entryContentsByName.entrySet()) {\n@@ -1889,9 +1921,11 @@ public final class CommandLineRunnerTest extends TestCase {\n \n private FlagEntry createJsFile(String filename, String fileContent)\n throws IOException {\n- File tempJsFile = File.createTempFile(filename, \".js\");\n- FileOutputStream fileOutputStream = new FileOutputStream(tempJsFile);\n- fileOutputStream.write(fileContent.getBytes(java.nio.charset.StandardCharsets.UTF_8));\n+ File tempJsFile = File.createTempFile(filename, \".js\",\n+ Files.createTempDirectory(\"jscomp\").toFile());\n+ try (FileOutputStream fileOutputStream = new FileOutputStream(tempJsFile)) {\n+ fileOutputStream.write(fileContent.getBytes(java.nio.charset.StandardCharsets.UTF_8));\n+ }\n \n return new FlagEntry<>(JsSourceType.JS, tempJsFile.getAbsolutePath());\n }"},"changed_files":{"kind":"string","value":"['src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.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":7125544,"string":"7,125,544"},"repo_tokens_count":{"kind":"number","value":1615261,"string":"1,615,261"},"repo_lines_count":{"kind":"number","value":217124,"string":"217,124"},"repo_files_without_tests_count":{"kind":"number","value":706,"string":"706"},"changed_symbols_count":{"kind":"number","value":2277,"string":"2,277"},"changed_tokens_count":{"kind":"number","value":480,"string":"480"},"changed_lines_count":{"kind":"number","value":48,"string":"48"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":3904,"string":"3,904"},"issue_words_count":{"kind":"number","value":319,"string":"319"},"issue_tokens_count":{"kind":"number","value":1206,"string":"1,206"},"issue_lines_count":{"kind":"number","value":100,"string":"100"},"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:24:13","string":"1970-01-01T00:24:13"},"repo_stars":{"kind":"number","value":7031,"string":"7,031"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1346,"cells":{"id":{"kind":"number","value":515,"string":"515"},"text_id":{"kind":"string","value":"google/closure-compiler/1469/1407"},"repo_owner":{"kind":"string","value":"google"},"repo_name":{"kind":"string","value":"closure-compiler"},"issue_url":{"kind":"string","value":"https://github.com/google/closure-compiler/issues/1407"},"pull_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1469"},"comment_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1469"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Cannot use globs when running the compiler."},"issue_body":{"kind":"string","value":"Since 62ca536... I am no longer able to use globs for files when running the compiler:\n\nRunning this command used to work before that change:\n\n```\njava -jar ../../compiler/compiler.jar \\\\\n--flagfile=options/compile.ini \\\\\n--define \"goog.json.USE_NATIVE_JSON=true\" --define \"goog.ui.Component.ALLOW_DETACHED_DECORATION=true\" --define \"goog.NATIVE_ARRAY_PROTOTYPES=true\" --define \"goog.array.ASSUME_NATIVE_FUNCTIONS=true\" --define \"goog.Promise.UNHANDLED_REJECTION_DELAY=-1\" --define \"app.settings.RUN_AS_USER=false\" --externs=../externs/material.js --generate_exports --export_local_property_definitions --language_in=ECMASCRIPT6 --language_out=ES3 --use_types_for_optimization --output_wrapper=\"(function(){%output%})();\" \\\\\n--only_closure_dependencies \\\\\n--closure_entry_point=app \\\\\n--manage_closure_dependencies true \\\\\n--output_manifest build/app.filelist.txt \\\\\n--js_output_file /tmp/closure_compiler_build \\\\\n--js=\"js/**.js\" --js=\"tpl/en/**.js\" --js=\"../../templates/soyutils_usegoog.js\" --js=\"../../library/closure/goog/**.js\" --js=\"../../library/third_party/closure/goog/mochikit/async/deferred.js\" --js=\"../../library/third_party/closure/goog/mochikit/async/deferredlist.js\" --js=\"../pstj/animation/**.js\" --js=\"../pstj/app/**.js\" --js=\"../pstj/autogenerated/**.js\" --js=\"../pstj/cast/**.js\" --js=\"../pstj/color/**.js\" --js=\"../pstj/config/**.js\" --js=\"../pstj/control/**.js\" --js=\"../pstj/date/**.js\" --js=\"../pstj/debug/**.js\" --js=\"../pstj/ds/**.js\" --js=\"../pstj/element/**.js\" --js=\"../pstj/error/**.js\" --js=\"../pstj/fx/**.js\" --js=\"../pstj/graphics/**.js\" --js=\"../pstj/material/**.js\" --js=\"../pstj/math/**.js\" --js=\"../pstj/mvc/**.js\" --js=\"../pstj/ng/**.js\" --js=\"../pstj/object/**.js\" --js=\"../pstj/options/**.js\" --js=\"../pstj/resource/**.js\" --js=\"../pstj/sourcegen/**.js\" --js=\"../pstj/storage/**.js\" --js=\"../pstj/style/**.js\" --js=\"../pstj/themes/**.js\" --js=\"../pstj/ui/**.js\" --js=\"../smjs/ds/**.js\" --js=\"../smjs/element/**.js\" --js=\"../smjs/persistence/**.js\" --js=\"../smjs/player/**.js\" --js=\"../smjs/remotecontrol/**.js\" --js=\"../smjs/transport/**.js\" --js=\"../smjs/tv/**.js\" --js=\"../smjs/widgets/**.js\" --js=\"!**_test.js\"\n```\n\nNow (after the mentioned change) it gives this:\n\n```\nERROR - Cannot read: !**_test.js\n\nERROR - Cannot read: ../../library/closure/goog/**.js\n\nERROR - Cannot read: ../pstj/animation/**.js\n\nERROR - Cannot read: ../pstj/app/**.js\n\nERROR - Cannot read: ../pstj/autogenerated/**.js\n\nERROR - Cannot read: ../pstj/cast/**.js\n\nERROR - Cannot read: ../pstj/color/**.js\n\nERROR - Cannot read: ../pstj/config/**.js\n\nERROR - Cannot read: ../pstj/control/**.js\n\nERROR - Cannot read: ../pstj/date/**.js\n\nERROR - Cannot read: ../pstj/debug/**.js\n\nERROR - Cannot read: ../pstj/ds/**.js\n\nERROR - Cannot read: ../pstj/element/**.js\n\nERROR - Cannot read: ../pstj/error/**.js\n\nERROR - Cannot read: ../pstj/fx/**.js\n\nERROR - Cannot read: ../pstj/graphics/**.js\n\nERROR - Cannot read: ../pstj/material/**.js\n\nERROR - Cannot read: ../pstj/math/**.js\n\nERROR - Cannot read: ../pstj/mvc/**.js\n\nERROR - Cannot read: ../pstj/ng/**.js\n\nERROR - Cannot read: ../pstj/object/**.js\n\nERROR - Cannot read: ../pstj/options/**.js\n\nERROR - Cannot read: ../pstj/resource/**.js\n\nERROR - Cannot read: ../pstj/sourcegen/**.js\n\nERROR - Cannot read: ../pstj/storage/**.js\n\nERROR - Cannot read: ../pstj/style/**.js\n\nERROR - Cannot read: ../pstj/themes/**.js\n\nERROR - Cannot read: ../pstj/ui/**.js\n\nERROR - Cannot read: ../smjs/ds/**.js\n\nERROR - Cannot read: ../smjs/element/**.js\n\nERROR - Cannot read: ../smjs/persistence/**.js\n\nERROR - Cannot read: ../smjs/player/**.js\n\nERROR - Cannot read: ../smjs/remotecontrol/**.js\n\nERROR - Cannot read: ../smjs/transport/**.js\n\nERROR - Cannot read: ../smjs/tv/**.js\n\nERROR - Cannot read: ../smjs/widgets/**.js\n\nERROR - Cannot read: js/**.js\n\nERROR - Cannot read: tpl/en/**.js\n\nERROR - required entry point \"app\" never provided\n\n39 error(s), 0 warning(s)\n```\n"},"base_sha":{"kind":"string","value":"f98608a07dc43fb3e950a730ca59906179386ffb"},"head_sha":{"kind":"string","value":"16d143d67f4c27aa1435d3561a64acbe039dc972"},"diff_url":{"kind":"string","value":"https://github.com/google/closure-compiler/compare/f98608a07dc43fb3e950a730ca59906179386ffb...16d143d67f4c27aa1435d3561a64acbe039dc972"},"diff":{"kind":"string","value":"diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java\nindex fbdc565a5..87f9c2037 100644\n--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java\n+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java\n@@ -2542,6 +2542,16 @@ public abstract class AbstractCommandLineRunner that = (FlagEntry) o;\n+ return that.flag.equals(this.flag)\n+ && that.value.equals(this.value);\n+ }\n+ return false;\n+ }\n }\n \n /**\ndiff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java\nindex 47c87615d..1f83037d4 100644\n--- a/src/com/google/javascript/jscomp/CommandLineRunner.java\n+++ b/src/com/google/javascript/jscomp/CommandLineRunner.java\n@@ -61,6 +61,7 @@ import java.nio.file.attribute.BasicFileAttributes;\n import java.util.ArrayList;\n import java.util.Collection;\n import java.util.Collections;\n+import java.util.HashSet;\n import java.util.List;\n import java.util.Map;\n import java.util.Set;\n@@ -745,12 +746,21 @@ public class CommandLineRunner extends\n protected List> getMixedJsSources()\n throws CmdLineException, IOException {\n List> mixedSources = new ArrayList<>();\n+ Set excludes = new HashSet<>();\n for (FlagEntry source : Flags.mixedJsSources) {\n if (source.value.endsWith(\".zip\")) {\n mixedSources.add(source);\n+ } else if (source.value.startsWith(\"!\")) {\n+ for (String filename : findJsFiles(\n+ Collections.singletonList(source.value.substring(1)))) {\n+ excludes.add(filename);\n+ mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename));\n+ }\n } else {\n for (String filename : findJsFiles(Collections.singletonList(source.value))) {\n- mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));\n+ if (!excludes.contains(filename)) {\n+ mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));\n+ }\n }\n }\n }\n@@ -1475,23 +1485,25 @@ public class CommandLineRunner extends\n */\n public static List findJsFiles(Collection patterns) throws IOException {\n Set allJsInputs = new TreeSet<>();\n+ Set excludes = new HashSet<>();\n for (String pattern : patterns) {\n if (!pattern.contains(\"*\") && !pattern.startsWith(\"!\")) {\n File matchedFile = new File(pattern);\n if (matchedFile.isDirectory()) {\n- matchPaths(new File(matchedFile, \"**.js\").toString(), allJsInputs);\n- } else {\n+ matchPaths(new File(matchedFile, \"**.js\").toString(), allJsInputs, excludes);\n+ } else if (!excludes.contains(pattern)) {\n allJsInputs.add(pattern);\n }\n } else {\n- matchPaths(pattern, allJsInputs);\n+ matchPaths(pattern, allJsInputs, excludes);\n }\n }\n \n return new ArrayList<>(allJsInputs);\n }\n \n- private static void matchPaths(String pattern, final Set allJsInputs)\n+ private static void matchPaths(String pattern, final Set allJsInputs,\n+ final Set excludes)\n throws IOException {\n FileSystem fs = FileSystems.getDefault();\n final boolean remove = pattern.indexOf('!') == 0;\n@@ -1526,10 +1538,12 @@ public class CommandLineRunner extends\n @Override public FileVisitResult visitFile(\n Path p, BasicFileAttributes attrs) {\n if (matcher.matches(p.normalize())) {\n+ String pathString = p.toString();\n if (remove) {\n- allJsInputs.remove(p.toString());\n- } else {\n- allJsInputs.add(p.toString());\n+ excludes.add(pathString);\n+ allJsInputs.remove(pathString);\n+ } else if (!excludes.contains(pathString)) {\n+ allJsInputs.add(pathString);\n }\n }\n return FileVisitResult.CONTINUE;\ndiff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\nindex 66b8ec811..0af52d6cb 100644\n--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\n+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\n@@ -1139,6 +1139,34 @@ public final class CommandLineRunnerTest extends TestCase {\n }\n }\n \n+ public void testGlobJs3() throws IOException, FlagUsageException {\n+ FlagEntry jsFile1 = createJsFile(\"test1\", \"var a;\");\n+ FlagEntry jsFile2 = createJsFile(\"test2\", \"var b;\");\n+ new File(jsFile2.value).renameTo(new File(\n+ new File(jsFile1.value).getParentFile() + File.separator + \"test2.js\"));\n+ // Make sure test2.js is excluded from the inputs when the exclusion\n+ // comes after the inclusion\n+ String glob1 = new File(jsFile1.value).getParent() + File.separator + \"**.js\";\n+ String glob2 = \"!\" + new File(jsFile1.value).getParent() + File.separator + \"**test2.js\";\n+ compileFiles(\n+ \"var a;\", new FlagEntry<>(JsSourceType.JS, glob1),\n+ new FlagEntry<>(JsSourceType.JS, glob2));\n+ }\n+\n+ public void testGlobJs4() throws IOException, FlagUsageException {\n+ FlagEntry jsFile1 = createJsFile(\"test1\", \"var a;\");\n+ FlagEntry jsFile2 = createJsFile(\"test2\", \"var b;\");\n+ new File(jsFile2.value).renameTo(new File(\n+ new File(jsFile1.value).getParentFile() + File.separator + \"test2.js\"));\n+ // Make sure test2.js is excluded from the inputs when the exclusion\n+ // comes before the inclusion\n+ String glob1 = \"!\" + new File(jsFile1.value).getParent() + File.separator + \"**test2.js\";\n+ String glob2 = new File(jsFile1.value).getParent() + File.separator + \"**.js\";\n+ compileFiles(\n+ \"var a;\", new FlagEntry<>(JsSourceType.JS, glob1),\n+ new FlagEntry<>(JsSourceType.JS, glob2));\n+ }\n+\n public void testSourceMapInputs() throws Exception {\n args.add(\"--js_output_file\");\n args.add(\"/path/to/out.js\");"},"changed_files":{"kind":"string","value":"['src/com/google/javascript/jscomp/AbstractCommandLineRunner.java', 'src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.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":7155232,"string":"7,155,232"},"repo_tokens_count":{"kind":"number","value":1622150,"string":"1,622,150"},"repo_lines_count":{"kind":"number","value":217888,"string":"217,888"},"repo_files_without_tests_count":{"kind":"number","value":708,"string":"708"},"changed_symbols_count":{"kind":"number","value":1800,"string":"1,800"},"changed_tokens_count":{"kind":"number","value":354,"string":"354"},"changed_lines_count":{"kind":"number","value":40,"string":"40"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":3904,"string":"3,904"},"issue_words_count":{"kind":"number","value":319,"string":"319"},"issue_tokens_count":{"kind":"number","value":1206,"string":"1,206"},"issue_lines_count":{"kind":"number","value":100,"string":"100"},"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:24:14","string":"1970-01-01T00:24:14"},"repo_stars":{"kind":"number","value":7031,"string":"7,031"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1347,"cells":{"id":{"kind":"number","value":514,"string":"514"},"text_id":{"kind":"string","value":"google/closure-compiler/1549/1548"},"repo_owner":{"kind":"string","value":"google"},"repo_name":{"kind":"string","value":"closure-compiler"},"issue_url":{"kind":"string","value":"https://github.com/google/closure-compiler/issues/1548"},"pull_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1549"},"comment_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1549"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"File order not maintained"},"issue_body":{"kind":"string","value":"I call the closure compiler like:\n\n```\njava.exe -jar dev\\\\jars\\\\closure\\\\compiler.jar --compilation_level WHITESPACE_ONLY --formatting PRETTY_PRINT --formatting PRINT_INPUT_DELIMITER --formatting SINGLE_QUOTES --js_output_file jQuery_a52d83c3.min.js --js jquery.js ui\\\\core.js ui\\\\widget.js ui\\\\mouse.js ui\\\\draggable.js ui\\\\droppable.js ui\\\\resizable.js ui\\\\selectable.js ui\\\\sortable.js ui\\\\button.js ui\\\\position.js\n```\n\nWhen I use the `compiler.jar` from github binary downloads `compiler-20151216.tar.gz` everything is fine. When I use `compiler-20160208.tar.gz` the file originial order is not maintained in the compressed file which breaks the code, as the js files have to be included in a specific order.\nI tried the new parameter `--dependency_mode NONE` but it changed nothing. According to the docs should NONE be the default.\n\nI'm on Windows 10, 64 bit JAVA 8 as provided by Oracle.\n"},"base_sha":{"kind":"string","value":"4544359bba2cac67e0ff13fda514b6e52d9d29cb"},"head_sha":{"kind":"string","value":"b193c1b5b10c1246877c384526fc01d9f0db448b"},"diff_url":{"kind":"string","value":"https://github.com/google/closure-compiler/compare/4544359bba2cac67e0ff13fda514b6e52d9d29cb...b193c1b5b10c1246877c384526fc01d9f0db448b"},"diff":{"kind":"string","value":"diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java\nindex 65e615bdd..cd1896c4a 100644\n--- a/src/com/google/javascript/jscomp/CommandLineRunner.java\n+++ b/src/com/google/javascript/jscomp/CommandLineRunner.java\n@@ -62,6 +62,7 @@ import java.util.ArrayList;\n import java.util.Collection;\n import java.util.Collections;\n import java.util.HashSet;\n+import java.util.LinkedHashSet;\n import java.util.List;\n import java.util.Map;\n import java.util.Set;\n@@ -757,7 +758,7 @@ public class CommandLineRunner extends\n mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename));\n }\n } else {\n- for (String filename : findJsFiles(Collections.singletonList(source.value))) {\n+ for (String filename : findJsFiles(Collections.singletonList(source.value), true)) {\n if (!excludes.contains(filename)) {\n mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));\n }\n@@ -1503,7 +1504,20 @@ public class CommandLineRunner extends\n * within the directory and sub-directories.\n */\n public static List findJsFiles(Collection patterns) throws IOException {\n- Set allJsInputs = new TreeSet<>();\n+ return findJsFiles(patterns, false);\n+ }\n+\n+ /**\n+ * Returns all the JavaScript files from the set of patterns.\n+ *\n+ * @param patterns A collection of filename patterns.\n+ * @param sortAlphabetically Whether the output filenames should be in alphabetical order.\n+ * @return The list of JS filenames found by expanding the patterns.\n+ */\n+ private static List findJsFiles(Collection patterns, boolean sortAlphabetically)\n+ throws IOException {\n+ Set allJsInputs = sortAlphabetically\n+ ? new TreeSet() : new LinkedHashSet();\n Set excludes = new HashSet<>();\n for (String pattern : patterns) {\n if (!pattern.contains(\"*\") && !pattern.startsWith(\"!\")) {\ndiff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\nindex 114df7d5e..e270af668 100644\n--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\n+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java\n@@ -1094,9 +1094,11 @@ public final class CommandLineRunnerTest extends TestCase {\n }\n \n public void testInputMultipleJsFilesWithOneJsFlag() throws IOException, FlagUsageException {\n+ // Test that file order is preserved with --js test3.js test2.js test1.js\n FlagEntry jsFile1 = createJsFile(\"test1\", \"var a;\");\n FlagEntry jsFile2 = createJsFile(\"test2\", \"var b;\");\n- compileJsFiles(\"var a;var b;\", jsFile1, jsFile2);\n+ FlagEntry jsFile3 = createJsFile(\"test3\", \"var c;\");\n+ compileJsFiles(\"var c;var b;var a;\", jsFile3, jsFile2, jsFile1);\n }\n \n public void testGlobJs1() throws IOException, FlagUsageException {"},"changed_files":{"kind":"string","value":"['src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.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":7185495,"string":"7,185,495"},"repo_tokens_count":{"kind":"number","value":1629249,"string":"1,629,249"},"repo_lines_count":{"kind":"number","value":218744,"string":"218,744"},"repo_files_without_tests_count":{"kind":"number","value":712,"string":"712"},"changed_symbols_count":{"kind":"number","value":865,"string":"865"},"changed_tokens_count":{"kind":"number","value":174,"string":"174"},"changed_lines_count":{"kind":"number","value":18,"string":"18"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":883,"string":"883"},"issue_words_count":{"kind":"number","value":109,"string":"109"},"issue_tokens_count":{"kind":"number","value":223,"string":"223"},"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:24:15","string":"1970-01-01T00:24:15"},"repo_stars":{"kind":"number","value":7031,"string":"7,031"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1348,"cells":{"id":{"kind":"number","value":517,"string":"517"},"text_id":{"kind":"string","value":"google/closure-compiler/1322/1314"},"repo_owner":{"kind":"string","value":"google"},"repo_name":{"kind":"string","value":"closure-compiler"},"issue_url":{"kind":"string","value":"https://github.com/google/closure-compiler/issues/1314"},"pull_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1322"},"comment_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/1322"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Unlike var statements, const statements do not support multiple types"},"issue_body":{"kind":"string","value":"Code -\n\n```\n// ==ClosureCompiler==\n// @output_file_name default.js\n// @compilation_level ADVANCED_OPTIMIZATIONS\n// @language ECMASCRIPT6_STRICT\n// ==/ClosureCompiler==\n\"use strict\";\nconst\n /** @const {string} */ foo = \"1\",\n /** @const {number} */ bar = 1;\n\nconst\n /** @type {string} */ baz = \"1\",\n /** @type {number} */ taz = 1;\n```\n\nWarnings -\n\n```\nJSC_MULTIPLE_VAR_DEF: declaration of multiple variables with shared type information at line 2 character 0\nconst\n^\nJSC_MULTIPLE_VAR_DEF: declaration of multiple variables with shared type information at line 6 character 0\nconst\n^\n```\n\nNote - changing them to `var` avoids the warnings, of course.\n"},"base_sha":{"kind":"string","value":"0767ef6c3863cd188d1f5fe61b73967ea9e3c912"},"head_sha":{"kind":"string","value":"7de586e22e0663c275f2320ad4ddac4e23abb145"},"diff_url":{"kind":"string","value":"https://github.com/google/closure-compiler/compare/0767ef6c3863cd188d1f5fe61b73967ea9e3c912...7de586e22e0663c275f2320ad4ddac4e23abb145"},"diff":{"kind":"string","value":"diff --git a/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java b/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java\nindex 291ff9a2e..bf678d067 100644\n--- a/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java\n+++ b/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java\n@@ -132,17 +132,26 @@ public final class Es6RewriteBlockScopedDeclaration extends AbstractPostOrderCal\n if (!letConsts.isEmpty()) {\n for (Node n : letConsts) {\n if (n.isConst()) {\n- JSDocInfo existingInfo = n.getJSDocInfo();\n- if (existingInfo == null) {\n- existingInfo = n.getFirstChild().getJSDocInfo();\n- n.getFirstChild().setJSDocInfo(null);\n+ // Normalize declarations like \"const x = 1, y = 2;\" so that inline\n+ // type annotations are preserved.\n+ for (Node child : n.children()) {\n+ Node declaration = IR.var(child.detachFromParent());\n+ declaration.useSourceInfoFrom(n);\n+ JSDocInfo existingInfo = n.getJSDocInfo();\n+ if (existingInfo == null) {\n+ existingInfo = child.getJSDocInfo();\n+ child.setJSDocInfo(null);\n+ }\n+ JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo);\n+ builder.recordConstancy();\n+ JSDocInfo info = builder.build();\n+ declaration.setJSDocInfo(info);\n+ n.getParent().addChildAfter(declaration, n);\n }\n- JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo);\n- builder.recordConstancy();\n- JSDocInfo info = builder.build();\n- n.setJSDocInfo(info);\n+ n.detachFromParent();\n+ } else {\n+ n.setType(Token.VAR);\n }\n- n.setType(Token.VAR);\n }\n compiler.reportCodeChange();\n }\ndiff --git a/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java b/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java\nindex fcc8c663c..270c277b4 100644\n--- a/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java\n+++ b/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java\n@@ -778,6 +778,10 @@ public final class Es6RewriteBlockScopedDeclarationTest extends CompilerTestCase\n testWarning(\"/** @type {number} */ const x = 'str';\", TypeValidator.TYPE_MISMATCH_WARNING);\n testWarning(\"const /** number */ x = 'str';\", TypeValidator.TYPE_MISMATCH_WARNING);\n testWarning(\"const /** @type {number} */ x = 'str';\", TypeValidator.TYPE_MISMATCH_WARNING);\n+ testWarning(\"const /** @type {string} */ x = 3, /** @type {number} */ y = 3;\",\n+ TypeValidator.TYPE_MISMATCH_WARNING);\n+ testWarning(\"const /** @type {string} */ x = 'str', /** @type {string} */ y = 3;\",\n+ TypeValidator.TYPE_MISMATCH_WARNING);\n }\n \n public void testDoWhileForOfCapturedLetAnnotated() {"},"changed_files":{"kind":"string","value":"['test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java', 'src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.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":7100552,"string":"7,100,552"},"repo_tokens_count":{"kind":"number","value":1609557,"string":"1,609,557"},"repo_lines_count":{"kind":"number","value":216424,"string":"216,424"},"repo_files_without_tests_count":{"kind":"number","value":705,"string":"705"},"changed_symbols_count":{"kind":"number","value":1284,"string":"1,284"},"changed_tokens_count":{"kind":"number","value":278,"string":"278"},"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":651,"string":"651"},"issue_words_count":{"kind":"number","value":96,"string":"96"},"issue_tokens_count":{"kind":"number","value":182,"string":"182"},"issue_lines_count":{"kind":"number","value":31,"string":"31"},"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:24:10","string":"1970-01-01T00:24:10"},"repo_stars":{"kind":"number","value":7031,"string":"7,031"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1349,"cells":{"id":{"kind":"number","value":513,"string":"513"},"text_id":{"kind":"string","value":"google/closure-compiler/3988/3840"},"repo_owner":{"kind":"string","value":"google"},"repo_name":{"kind":"string","value":"closure-compiler"},"issue_url":{"kind":"string","value":"https://github.com/google/closure-compiler/issues/3840"},"pull_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/3988"},"comment_url":{"kind":"string","value":"https://github.com/google/closure-compiler/pull/3988"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"--create_source_map throws exception on windows when using input source maps and chunks"},"issue_body":{"kind":"string","value":"Closure throws an exception when I try to build source maps for chunks:\r\njava.io.FileNotFoundException: .\\\\dist\\\\closure\\\\common.js.map (The system cannot find the path specified)\r\nIt seems like there's a race condition issue if the source map of a depending module is built before the dependency. It seems to work properly if I run the build without `--create_source_map`, and then run it again _with_ `--create_source_map`.\r\n\r\nReproducer is available here: https://github.com/DerGernTod/ts-esbuild-closure-reproducer/blob/main/index.js\r\n\r\nThe used flags:\r\n--chunk common:2\r\n--chunk_wrapper common:(function(){%s})()\r\n--source_map_input dist/esbuild/chunk-7THFJKJQ.js|dist/esbuild/chunk-7THFJKJQ.js.map\r\n--js dist/esbuild/chunk-7THFJKJQ.js\r\n--source_map_input dist/esbuild/filecommon.js|dist/esbuild/filecommon.js.map\r\n--js dist/esbuild/filecommon.js\r\n--chunk filea:1:common\r\n--chunk_wrapper filea:(function(){%s})()\r\n--source_map_input dist/esbuild/filea.js|dist/esbuild/filea.js.map\r\n--js dist/esbuild/filea.js\r\n--chunk fileb:1:common\r\n--chunk_wrapper fileb:(function(){%s})()\r\n--source_map_input dist/esbuild/fileb.js|dist/esbuild/fileb.js.map\r\n--js dist/esbuild/fileb.js\r\n--language_in ECMASCRIPT_2017\r\n--language_out ECMASCRIPT_2017\r\n--chunk_output_path_prefix ./dist/closure/\r\n--rename_prefix_namespace myNamespace\r\n--compilation_level ADVANCED_OPTIMIZATIONS\r\n--create_source_map %outname%.map\r\n\r\nI also tried `--source_map_include_content`, but that doesn't seem to work either (even if you build it once without source maps to prevent the error mentioned above, and then build it with source maps). The source is not embedded at all.\r\n\r\n"},"base_sha":{"kind":"string","value":"3784fba4f48519472ca66792d0ed318ee443d44a"},"head_sha":{"kind":"string","value":"55e3c557a2d9aae7cffefdad42140911130c8551"},"diff_url":{"kind":"string","value":"https://github.com/google/closure-compiler/compare/3784fba4f48519472ca66792d0ed318ee443d44a...55e3c557a2d9aae7cffefdad42140911130c8551"},"diff":{"kind":"string","value":"diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java\nindex e27089744..ad4fdaff2 100644\n--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java\n+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java\n@@ -1139,12 +1139,9 @@ public abstract class AbstractCommandLineRunner implements Validatable {\n private final ConfigErrors configErrors = new ConfigErrors();\n- private Map>> packageToPipelineMap;\n- private Map>> pluggableSCMMaterialToPipelineMap;\n+ private volatile Map>> packageToPipelineMap;\n+ private volatile Map>> pluggableSCMMaterialToPipelineMap;\n \n public PipelineGroups() {\n }\n@@ -235,10 +233,7 @@ public class PipelineGroups extends BaseCollection implements V\n \n public boolean canDeletePluggableSCMMaterial(SCM scmConfig) {\n Map>> packageUsageInPipelines = getPluggableSCMMaterialUsageInPipelines();\n- if (packageUsageInPipelines.containsKey(scmConfig.getId())) {\n- return false;\n- }\n- return true;\n+ return !packageUsageInPipelines.containsKey(scmConfig.getId());\n }\n \n public PipelineGroups getLocal() {\ndiff --git a/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java b/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java\nindex 553ea6019b..93b5f1315f 100644\n--- a/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java\n+++ b/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java\n@@ -22,6 +22,7 @@ import com.thoughtworks.go.util.command.CommandArgument;\n import com.thoughtworks.go.util.command.UrlArgument;\n import org.apache.commons.io.FileUtils;\n import org.apache.commons.io.IOUtils;\n+import org.jetbrains.annotations.VisibleForTesting;\n import org.slf4j.Logger;\n import org.slf4j.LoggerFactory;\n \n@@ -30,7 +31,6 @@ import java.io.FileOutputStream;\n import java.io.IOException;\n import java.io.OutputStream;\n import java.lang.reflect.Constructor;\n-import java.net.URISyntaxException;\n import java.net.URL;\n import java.nio.file.Paths;\n import java.util.jar.JarEntry;\n@@ -44,16 +44,13 @@ class TfsSDKCommandBuilder {\n private static final Logger LOGGER = LoggerFactory.getLogger(TfsSDKCommandBuilder.class);\n private final File tempFolder = new File(\"data/tfs-sdk\");\n private final ClassLoader sdkLoader;\n- private static TfsSDKCommandBuilder ME;\n+ private static volatile TfsSDKCommandBuilder ME;\n \n- private TfsSDKCommandBuilder() throws IOException, URISyntaxException {\n+ private TfsSDKCommandBuilder() throws IOException {\n this.sdkLoader = initSdkLoader();\n }\n \n- /*\n- * Used in tests\n- */\n- @Deprecated\n+ @VisibleForTesting\n TfsSDKCommandBuilder(ClassLoader sdkLoader) {\n this.sdkLoader = sdkLoader;\n }\n@@ -61,7 +58,7 @@ class TfsSDKCommandBuilder {\n TfsCommand buildTFSSDKCommand(String materialFingerPrint, UrlArgument url, String domain, String userName,\n String password, final String computedWorkspaceName, String projectPath) {\n try {\n- return instantitateAdapter(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath);\n+ return instantiateAdapter(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath);\n } catch (Exception e) {\n String message = \"[TFS SDK] Could not create TFS SDK Command \";\n LOGGER.error(message, e);\n@@ -69,7 +66,7 @@ class TfsSDKCommandBuilder {\n }\n }\n \n- private TfsCommand instantitateAdapter(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, String computedWorkspaceName, String projectPath) throws ReflectiveOperationException {\n+ private TfsCommand instantiateAdapter(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, String computedWorkspaceName, String projectPath) throws ReflectiveOperationException {\n Class adapterClass = Class.forName(tfsSdkCommandTCLAdapterClassName(), true, sdkLoader);\n Constructor constructor = adapterClass.getConstructor(String.class, CommandArgument.class, String.class, String.class, String.class, String.class, String.class);\n return (TfsCommand) constructor.newInstance(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath);\n@@ -79,7 +76,7 @@ class TfsSDKCommandBuilder {\n return \"com.thoughtworks.go.tfssdk.TfsSDKCommandTCLAdapter\";\n }\n \n- static TfsSDKCommandBuilder getBuilder() throws IOException, URISyntaxException {\n+ static TfsSDKCommandBuilder getBuilder() throws IOException {\n if (ME == null) {\n synchronized (TfsSDKCommandBuilder.class) {\n if (ME == null) {"},"changed_files":{"kind":"string","value":"['domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java', 'config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.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":15875936,"string":"15,875,936"},"repo_tokens_count":{"kind":"number","value":3177194,"string":"3,177,194"},"repo_lines_count":{"kind":"number","value":374335,"string":"374,335"},"repo_files_without_tests_count":{"kind":"number","value":3354,"string":"3,354"},"changed_symbols_count":{"kind":"number","value":2008,"string":"2,008"},"changed_tokens_count":{"kind":"number","value":393,"string":"393"},"changed_lines_count":{"kind":"number","value":28,"string":"28"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":523,"string":"523"},"issue_words_count":{"kind":"number","value":48,"string":"48"},"issue_tokens_count":{"kind":"number","value":119,"string":"119"},"issue_lines_count":{"kind":"number","value":6,"string":"6"},"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:18","string":"1970-01-01T00:27:18"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1351,"cells":{"id":{"kind":"number","value":408,"string":"408"},"text_id":{"kind":"string","value":"gocd/gocd/1052/1045"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/1045"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/1052"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/1052"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixed"},"issue_title":{"kind":"string","value":"Temporary console log issues"},"issue_body":{"kind":"string","value":"1) ~~Even though console logs are available in 'Artifacts' tab, yet i see following message there which should not be happen~~\n\n~~\"Artifacts for this job instance are unavailable as they may have been purged by Go or deleted externally. Re-run the stage or job to generate them again.\"~~\n\nThis is not an issue [@arikagoyal]\n\n2) a) When a job is cancelled, its o/p looks like this -\n\n[go] Job Completed Console-testing/8/defaultStage/1/job213:30:25.194 [go] Start to execute cancel task: Kills child processes\n13:30:25.383 [go] Task is cancelled\n\nExpected : \"[go] Job Completed Console-testing/8/defaultStage/1/job2\" should show up in the end of console log\n\nb) Also on specifying job timeout, the console o/p looks like this -\n\n[go] Job Completed Simple-console-testing/3/defaultStage/1/defaultJobGo cancelled this job as it has not generated any console output for more than 2 minute(s)10:15:54.829 [go] Start to execute cancel task: Kills child processes\n10:15:54.891 [go] Task is cancelled\n\nExpected o/p :\n\nGo cancelled this job as it has not generated any console output for more than 1 minute(s)\n[go] Start to execute cancel task: Kills child processes\n\n[go] Task is cancelled\n\n[go] Job completed test/4/defaultStage/1/defaultJob on f9c423f70d26 [/var/lib/cruise-agent] at Wed Apr 15 20:43:26 UTC 2015\n\nAlso at times when a job is cancelled, sometimes logs do not get moved to the final artifact location.\n\n3) ~~If temporary console logs fails to make to the final artifact location due to disk space issue or permissions issue, they continue to lie in the temporary location forever. There should be a way to get these temp logs moved over to the actual location once the issue is resolved with the actual artifact location. Some automatic retry mechanism or on demand retry mechanism should be in place ?? Maybe in later releases ?~~ Moved this to #1057\n"},"base_sha":{"kind":"string","value":"dd9050b6c43282dfcb1d7684038ea9cd9934d819"},"head_sha":{"kind":"string","value":"81080bc7ced42ef543338721f9ca582e85ac8aef"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/dd9050b6c43282dfcb1d7684038ea9cd9934d819...81080bc7ced42ef543338721f9ca582e85ac8aef"},"diff":{"kind":"string","value":"diff --git a/common/src/com/thoughtworks/go/remote/work/BuildWork.java b/common/src/com/thoughtworks/go/remote/work/BuildWork.java\nindex 2732b8543e..b6bc734e87 100644\n--- a/common/src/com/thoughtworks/go/remote/work/BuildWork.java\n+++ b/common/src/com/thoughtworks/go/remote/work/BuildWork.java\n@@ -94,6 +94,8 @@ public class BuildWork implements Work {\n LOGGER.error(\"Agent UUID changed in the middle of the build.\", e);\n } catch (Exception e) {\n reportFailure(e);\n+ } finally {\n+ goPublisher.stop();\n }\n }\n \n@@ -110,9 +112,9 @@ public class BuildWork implements Work {\n private void reportCompletion(JobResult result) {\n try {\n builders.waitForCancelTasks();\n- goPublisher.stop();\n if (result == null) {\n goPublisher.reportCurrentStatus(JobState.Completed);\n+ goPublisher.reportCompletedAction();\n } else {\n goPublisher.reportCompleted(result);\n }\ndiff --git a/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java b/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java\nindex 36aece3d2d..b7d3e8b71e 100644\n--- a/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java\n+++ b/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java\n@@ -16,11 +16,13 @@\n \n package com.thoughtworks.go.work;\n \n+import java.io.File;\n+\n+import com.thoughtworks.go.domain.builder.FetchArtifactBuilder;\n import com.thoughtworks.go.domain.JobIdentifier;\n import com.thoughtworks.go.domain.JobResult;\n import com.thoughtworks.go.domain.JobState;\n import com.thoughtworks.go.domain.Property;\n-import com.thoughtworks.go.domain.builder.FetchArtifactBuilder;\n import com.thoughtworks.go.publishers.GoArtifactsManipulator;\n import com.thoughtworks.go.remote.AgentIdentifier;\n import com.thoughtworks.go.remote.BuildRepositoryRemote;\n@@ -32,8 +34,6 @@ import com.thoughtworks.go.util.TimeProvider;\n import org.apache.commons.logging.Log;\n import org.apache.commons.logging.LogFactory;\n \n-import java.io.File;\n-\n import static java.lang.String.format;\n \n public class DefaultGoPublisher implements GoPublisher {\n@@ -107,6 +107,11 @@ public class DefaultGoPublisher implements GoPublisher {\n LOG.info(String.format(\"%s is reporting build result [%s] to Go Server for %s\", agentIdentifier, result,\n jobIdentifier.toFullString()));\n remoteBuildRepository.reportCompleted(agentRuntimeInfo, jobIdentifier, result);\n+ reportCompletedAction();\n+ }\n+\n+ public void reportCompletedAction() {\n+ reportAction(\"Job completed\");\n }\n \n public boolean isIgnored() {\ndiff --git a/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java b/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java\nindex 9a39151595..38643b1547 100644\n--- a/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java\n+++ b/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java\n@@ -22,12 +22,9 @@ import com.thoughtworks.go.domain.JobIdentifier;\n import com.thoughtworks.go.domain.JobInstance;\n import com.thoughtworks.go.server.domain.JobStatusListener;\n import com.thoughtworks.go.server.service.ConsoleService;\n-import com.thoughtworks.go.util.GoConstants;\n import org.springframework.beans.factory.annotation.Autowired;\n import org.springframework.stereotype.Component;\n \n-import static java.lang.String.format;\n-\n @Component\n public class ConsoleLogArtifactHandler implements JobStatusListener {\n private ConsoleService consoleService;\n@@ -43,9 +40,6 @@ public class ConsoleLogArtifactHandler implements JobStatusListener {\n try {\n JobIdentifier identifier = job.getIdentifier();\n consoleService.moveConsoleArtifacts(identifier);\n- // TODO: Put correct timestamp of job completion the agent and the server maybe on different timezones.\n- consoleService.appendToConsoleLog(identifier, format(\"[%s] %s %s\", GoConstants.PRODUCT_NAME, \"Job Completed\"\n- , identifier.buildLocatorForDisplay()));\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\ndiff --git a/server/src/com/thoughtworks/go/server/service/ConsoleService.java b/server/src/com/thoughtworks/go/server/service/ConsoleService.java\nindex 74609d7b3a..c55be1ec99 100644\n--- a/server/src/com/thoughtworks/go/server/service/ConsoleService.java\n+++ b/server/src/com/thoughtworks/go/server/service/ConsoleService.java\n@@ -173,6 +173,7 @@ public class ConsoleService {\n public void moveConsoleArtifacts(LocatableEntity locatableEntity) {\n try {\n File from = chooser.temporaryConsoleFile(locatableEntity);\n+ from.createNewFile(); // Job cancellation skips temporary file creation. Force create one if it does not exist.\n File to = chooser.findArtifact(locatableEntity, getConsoleOutputFolderAndFileName());\n FileUtils.moveFile(from, to);\n } catch (IOException e) {\ndiff --git a/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java b/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java\nindex a7e297e068..86ab26af52 100644\n--- a/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java\n+++ b/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java\n@@ -35,12 +35,6 @@ public class ConsoleLogArtifactHandlerTest {\n verify(consoleService, never()).moveConsoleArtifacts(buildingJobInstance.getIdentifier());\n }\n \n- @Test\n- public void shouldReportJobAsCompletedOnConsole() throws Exception {\n- handler.jobStatusChanged(completedJobInstance);\n- verify(consoleService).appendToConsoleLog(completedJobInstance.getIdentifier(), \"[go] Job Completed pipeline/label-1/stage/1/job\");\n- }\n-\n @Test\n public void shouldReportJobAsCompletedOnConsoleOnlyWhenStatusIsCompleted() throws Exception {\n handler.jobStatusChanged(buildingJobInstance);"},"changed_files":{"kind":"string","value":"['server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java', 'common/src/com/thoughtworks/go/work/DefaultGoPublisher.java', 'server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java', 'common/src/com/thoughtworks/go/remote/work/BuildWork.java', 'server/src/com/thoughtworks/go/server/service/ConsoleService.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":7843133,"string":"7,843,133"},"repo_tokens_count":{"kind":"number","value":1575547,"string":"1,575,547"},"repo_lines_count":{"kind":"number","value":204493,"string":"204,493"},"repo_files_without_tests_count":{"kind":"number","value":1780,"string":"1,780"},"changed_symbols_count":{"kind":"number","value":967,"string":"967"},"changed_tokens_count":{"kind":"number","value":172,"string":"172"},"changed_lines_count":{"kind":"number","value":22,"string":"22"},"changed_files_without_tests_count":{"kind":"number","value":4,"string":"4"},"issue_symbols_count":{"kind":"number","value":1861,"string":"1,861"},"issue_words_count":{"kind":"number","value":292,"string":"292"},"issue_tokens_count":{"kind":"number","value":454,"string":"454"},"issue_lines_count":{"kind":"number","value":31,"string":"31"},"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:23:49","string":"1970-01-01T00:23:49"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1352,"cells":{"id":{"kind":"number","value":409,"string":"409"},"text_id":{"kind":"string","value":"gocd/gocd/1003/1000"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/1000"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/1003"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/1003"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"handle special characters in material name in pipeline label template"},"issue_body":{"kind":"string","value":"In XSD [here](https://github.com/gocd/gocd/blob/master/config/config-server/resources/cruise-config.xsd#L715) the label template allows special characters like `-` in material name inside `${ }`. But [here](https://github.com/gocd/gocd/blob/master/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java#L45) we don't match them in material name.\n\ncauses `${git-repo}` to not get resolved to revision.\n"},"base_sha":{"kind":"string","value":"0e31f680841b78cc06d851d731ff7da9ee1493ae"},"head_sha":{"kind":"string","value":"ee180c73421285ee93905caa7c0db27166df1219"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/0e31f680841b78cc06d851d731ff7da9ee1493ae...ee180c73421285ee93905caa7c0db27166df1219"},"diff":{"kind":"string","value":"diff --git a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java\nindex 36e2d48f34..7a834ee52a 100644\n--- a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java\n+++ b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java\n@@ -19,6 +19,7 @@ package com.thoughtworks.go.domain;\n import com.thoughtworks.go.config.CaseInsensitiveString;\n import com.thoughtworks.go.config.materials.ScmMaterial;\n import com.thoughtworks.go.config.materials.mercurial.HgMaterial;\n+import com.thoughtworks.go.config.materials.svn.SvnMaterial;\n import com.thoughtworks.go.domain.label.PipelineLabel;\n import com.thoughtworks.go.domain.materials.Modification;\n import com.thoughtworks.go.helper.MaterialsMother;\n@@ -221,7 +222,7 @@ public class PipelineLabelTest {\n public void canMatchWithOneTruncationAsFirstRevision() throws Exception {\n final String[][] expectedGroups = { {\"git\", \"4\"}, { \"svn\" } };\n String res = assertLabelGroupsMatchingAndReplace(\"release-${git[:4]}-${svn}\", expectedGroups);\n- assertThat(res, is(\"release-\" + GIT_REVISION.substring(0, 4) + \"-\" + SVN_REVISION));\n+ assertThat(res, is(\"release-\" + GIT_REVISION.substring(0, 4) + \"-\" + SVN_REVISION));\n }\n \n @Test\n@@ -231,6 +232,36 @@ public class PipelineLabelTest {\n assertThat(res, is(\"release-\" + GIT_REVISION.substring(0, 5) + \"-\" + SVN_REVISION.substring(0, 3)));\n }\n \n+ @Test\n+ public void canNotMatchWithTruncationWhenMaterialNameHasAColon() throws Exception {\n+ final String[][] expectedGroups = { { \"git:one\", \"7\" } };\n+ String res = assertLabelGroupsMatchingAndReplace(\"release-${git:one[:7]}\", expectedGroups);\n+ assertThat(res, is(\"release-${git:one[:7]}\"));\n+ }\n+\n+ @Test\n+ public void shouldReplaceTheTemplateWithSpecialCharacters() throws Exception {\n+ ensureLabelIsReplaced(\"SVNMaterial\");\n+ ensureLabelIsReplaced(\"SVN-Material\");\n+ ensureLabelIsReplaced(\"SVN_Material\");\n+ ensureLabelIsReplaced(\"SVN!Material\");\n+ ensureLabelIsReplaced(\"SVN__##Material_1023_WithNumbers\");\n+ ensureLabelIsReplaced(\"SVN_Material-_!!_\");\n+ ensureLabelIsReplaced(\"svn_Material'WithQuote\");\n+ ensureLabelIsReplaced(\"SVN_Material.With.Period\");\n+ ensureLabelIsReplaced(\"SVN_Material#With#Hash\");\n+ ensureLabelIsReplaced(\"SVN_Material:With:Colon\");\n+ ensureLabelIsReplaced(\"SVN_Material~With~Tilde\");\n+\n+ ensureLabelIsNOTReplaced(\"SVN*MATERIAL\");\n+ ensureLabelIsNOTReplaced(\"SVN+Material\");\n+ ensureLabelIsNOTReplaced(\"SVN^Material\");\n+ ensureLabelIsNOTReplaced(\"SVN_Material(With)Parentheses\");\n+ ensureLabelIsNOTReplaced(\"SVN_Material{With}Braces\");\n+ ensureLabelIsNOTReplaced(\"SVN**Material\");\n+ ensureLabelIsNOTReplaced(\"SVN\\\\\\\\Material_With_Backslash\");\n+ }\n+\n @BeforeClass\n public static void setup() {\n MATERIAL_REVISIONS.put(new CaseInsensitiveString(\"svnRepo.verynice\"), SVN_REVISION);\n@@ -285,4 +316,23 @@ public class PipelineLabelTest {\n }\n return builder.toString();\n }\n+\n+ private void ensureLabelIsReplaced(String name) {\n+ PipelineLabel label = getReplacedLabelFor(name, String.format(\"release-${%s}\", name));\n+ assertThat(label.toString(), is(\"release-\" + ModificationsMother.currentRevision()));\n+ }\n+\n+ private void ensureLabelIsNOTReplaced(String name) {\n+ String labelFormat = String.format(\"release-${%s}\", name);\n+ PipelineLabel label = getReplacedLabelFor(name, labelFormat);\n+ assertThat(label.toString(), is(labelFormat));\n+ }\n+\n+ private PipelineLabel getReplacedLabelFor(String name, String labelFormat) {\n+ MaterialRevisions materialRevisions = ModificationsMother.oneUserOneFile();\n+ PipelineLabel label = PipelineLabel.create(labelFormat);\n+ ((SvnMaterial) materialRevisions.getRevisions().get(0).getMaterial()).setName(new CaseInsensitiveString(name));\n+ label.updateLabel(materialRevisions.getNamedRevisions());\n+ return label;\n+ }\n }\ndiff --git a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java\nindex 0b77ba92da..132a09b249 100644\n--- a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java\n+++ b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java\n@@ -42,7 +42,7 @@ public class PipelineLabel implements Serializable {\n return label;\n }\n \n- public static final Pattern PATTERN = Pattern.compile(\"(?i)\\\\\\\\$\\\\\\\\{([\\\\\\\\w\\\\\\\\.]+)(\\\\\\\\[:(\\\\\\\\d+)\\\\\\\\])?\\\\\\\\}\");\n+ public static final Pattern PATTERN = Pattern.compile(\"(?i)\\\\\\\\$\\\\\\\\{([a-zA-Z0-9_\\\\\\\\-\\\\\\\\.!~'#:]+)(\\\\\\\\[:(\\\\\\\\d+)\\\\\\\\])?\\\\\\\\}\");\n \n private String replaceRevisionsInLabel(Map materialRevisions) {\n final Matcher matcher = PATTERN.matcher(this.label);"},"changed_files":{"kind":"string","value":"['config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java', 'common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.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":7829565,"string":"7,829,565"},"repo_tokens_count":{"kind":"number","value":1572877,"string":"1,572,877"},"repo_lines_count":{"kind":"number","value":204139,"string":"204,139"},"repo_files_without_tests_count":{"kind":"number","value":1777,"string":"1,777"},"changed_symbols_count":{"kind":"number","value":222,"string":"222"},"changed_tokens_count":{"kind":"number","value":81,"string":"81"},"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":420,"string":"420"},"issue_words_count":{"kind":"number","value":34,"string":"34"},"issue_tokens_count":{"kind":"number","value":106,"string":"106"},"issue_lines_count":{"kind":"number","value":4,"string":"4"},"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:23:48","string":"1970-01-01T00:23:48"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1353,"cells":{"id":{"kind":"number","value":405,"string":"405"},"text_id":{"kind":"string","value":"gocd/gocd/9899/9889"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/9889"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/9899"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/9899"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Unreleased Resource: Streams in business continuity ViewResolver"},"issue_body":{"kind":"string","value":"https://github.com/gocd/gocd/blob/86b555e57daccec6b53b246f0dcdd4d0090566ef/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java#L40\r\n\r\nThe program can potentially fail to release a system resource."},"base_sha":{"kind":"string","value":"c83d03b8ff7b4dd04915476f409c7625ce0c7602"},"head_sha":{"kind":"string","value":"750effbf9f204a1c9203f4caefa7a9f5a768e483"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/c83d03b8ff7b4dd04915476f409c7625ce0c7602...750effbf9f204a1c9203f4caefa7a9f5a768e483"},"diff":{"kind":"string","value":"diff --git a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java\nindex d45bf86971..edd169b2c2 100644\n--- a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java\n+++ b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java\n@@ -21,6 +21,7 @@ import org.apache.commons.io.IOUtils;\n import java.io.File;\n import java.io.FileOutputStream;\n import java.io.InputStream;\n+import java.util.Objects;\n \n import static java.text.MessageFormat.format;\n \n@@ -68,33 +69,20 @@ public class FileValidator implements Validator {\n String message = format(\"File {0} is not readable or writeable.\", file.getAbsolutePath());\n return validation.addError(new RuntimeException(message));\n }\n- } else {\n- // Pull out the file from the class path\n- InputStream input = this.getClass().getResourceAsStream(srcDir + \"/\" + fileName);\n+ }\n+ // Pull out the file from the class path\n+ try (InputStream input = this.getClass().getResourceAsStream(srcDir + \"/\" + fileName)) {\n if (input == null) {\n String message = format(\"Resource {0}/{1} does not exist in the classpath\", srcDir, fileName);\n return validation.addError(new RuntimeException(message));\n- } else {\n- FileOutputStream output = null;\n- try {\n- // Make sure the dir exists\n- file.getParentFile().mkdirs();\n- output = new FileOutputStream(file);\n- IOUtils.copy(input, output);\n- } catch (Exception e) {\n- return handleExceptionDuringFileHandling(validation, e);\n- } finally {\n- try {\n- input.close();\n- if (output != null) {\n- output.flush();\n- output.close();\n- }\n- } catch (Exception e) {\n- return handleExceptionDuringFileHandling(validation, e);\n- }\n- }\n }\n+ // Make sure the dir exists\n+ file.getParentFile().mkdirs();\n+ try (FileOutputStream output = new FileOutputStream(file)) {\n+ IOUtils.copy(input, output);\n+ }\n+ } catch (Exception e) {\n+ return handleExceptionDuringFileHandling(validation, e);\n }\n return Validation.SUCCESS;\n }\n@@ -112,9 +100,9 @@ public class FileValidator implements Validator {\n FileValidator that = (FileValidator) o;\n \n if (shouldReplace != that.shouldReplace) return false;\n- if (fileName != null ? !fileName.equals(that.fileName) : that.fileName != null) return false;\n- if (srcDir != null ? !srcDir.equals(that.srcDir) : that.srcDir != null) return false;\n- return destDir != null ? destDir.equals(that.destDir) : that.destDir == null;\n+ if (!Objects.equals(fileName, that.fileName)) return false;\n+ if (!Objects.equals(srcDir, that.srcDir)) return false;\n+ return Objects.equals(destDir, that.destDir);\n }\n \n @Override\ndiff --git a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java\nindex f49ae008d3..63b4aed02d 100644\n--- a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java\n+++ b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java\n@@ -23,7 +23,6 @@ import org.jdom2.input.SAXBuilder;\n import org.junit.jupiter.api.Test;\n \n import java.io.IOException;\n-import java.io.InputStream;\n import java.text.ParseException;\n import java.util.HashMap;\n import java.util.List;\n@@ -69,10 +68,7 @@ public class SvnLogXmlParserTest {\n \n @Test\n public void shouldParseSvnLogContainingNullComments() throws IOException {\n- String xml;\n- try (InputStream stream = getClass().getResourceAsStream(\"jemstep_svn_log.xml\")) {\n- xml = IOUtils.toString(stream, UTF_8);\n- }\n+ String xml = IOUtils.toString(getClass().getResource(\"jemstep_svn_log.xml\"), UTF_8);\n SvnLogXmlParser parser = new SvnLogXmlParser();\n List revisions = parser.parse(xml, \"\", new SAXBuilder());\n \ndiff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java\nindex 807a0edd83..f504b22c22 100644\n--- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java\n+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java\n@@ -35,7 +35,10 @@ import com.thoughtworks.go.config.remote.PartialConfig;\n import com.thoughtworks.go.config.rules.Allow;\n import com.thoughtworks.go.config.rules.Deny;\n import com.thoughtworks.go.config.rules.Rules;\n-import com.thoughtworks.go.config.validation.*;\n+import com.thoughtworks.go.config.validation.ArtifactDirValidator;\n+import com.thoughtworks.go.config.validation.GoConfigValidator;\n+import com.thoughtworks.go.config.validation.ServerIdImmutabilityValidator;\n+import com.thoughtworks.go.config.validation.TokenGenerationKeyImmutabilityValidator;\n import com.thoughtworks.go.domain.*;\n import com.thoughtworks.go.domain.config.*;\n import com.thoughtworks.go.domain.label.PipelineLabel;\n@@ -1690,15 +1693,6 @@ public class MagicalGoConfigXmlLoaderTest {\n ConfigMigrator.loadWithMigration(content); // should not fail with a validation exception\n }\n \n- @Test\n- void shouldLoadLargeConfigFileInReasonableTime() throws Exception {\n- String content = IOUtils.toString(getClass().getResourceAsStream(\"/data/big-cruise-config.xml\"), UTF_8);\n-// long start = System.currentTimeMillis();\n- GoConfigHolder configHolder = ConfigMigrator.loadWithMigration(content);\n-// assertThat(System.currentTimeMillis() - start, lessThan(new Long(2000)));\n- assertThat(configHolder.config.schemaVersion()).isEqualTo(CONFIG_SCHEMA_VERSION);\n- }\n-\n @Test\n void shouldLoadConfigWithPipelinesMatchingUpWithPipelineDefinitionCaseInsensitively() {\n String content = configWithEnvironments(\n@@ -3884,7 +3878,7 @@ public class MagicalGoConfigXmlLoaderTest {\n \n final CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(configXml).configForEdit;\n final ArtifactTypeConfigs artifactTypeConfigs = cruiseConfig.pipelineConfigByName(\n- new CaseInsensitiveString(\"up42\")).getStage(\"up42_stage\")\n+ new CaseInsensitiveString(\"up42\")).getStage(\"up42_stage\")\n .getJobs().getJob(new CaseInsensitiveString(\"up42_job\")).artifactTypeConfigs();\n \n assertThat(artifactTypeConfigs).hasSize(1);\n@@ -4224,7 +4218,7 @@ public class MagicalGoConfigXmlLoaderTest {\n ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfo(pluginDescriptor, storeConfigSettings, publishArtifactSettings, fetchArtifactSettings, null, new Capabilities());\n ArtifactMetadataStore.instance().setPluginInfo(artifactPluginInfo);\n \n- String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n+ String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n \n CruiseConfig config = xmlLoader.loadConfigHolder(content).configForEdit;\n PipelineConfig ancestor = config.pipelineConfigByName(new CaseInsensitiveString(\"ancestor\"));\n@@ -4484,7 +4478,7 @@ public class MagicalGoConfigXmlLoaderTest {\n MaterialConfig materialConfig = config\n .getPipelineConfigByName(new CaseInsensitiveString(\"pipeline\"))\n .materialConfigs().get(0);\n- \n+\n assertThat(materialConfig).isInstanceOf(PluggableSCMMaterialConfig.class);\n assertThat(materialConfig.isInvertFilter()).isTrue();\n }\ndiff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java\nindex de03835525..94a55028ba 100644\n--- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java\n+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java\n@@ -55,14 +55,15 @@ import javax.xml.transform.stream.StreamSource;\n import javax.xml.validation.SchemaFactory;\n import java.io.ByteArrayInputStream;\n import java.io.ByteArrayOutputStream;\n+import java.io.InputStream;\n \n import static com.thoughtworks.go.helper.MaterialConfigsMother.git;\n import static com.thoughtworks.go.helper.MaterialConfigsMother.tfs;\n import static com.thoughtworks.go.util.DataStructureUtils.m;\n import static com.thoughtworks.go.util.GoConstants.CONFIG_SCHEMA_VERSION;\n import static java.nio.charset.StandardCharsets.UTF_8;\n-import static org.hamcrest.Matchers.*;\n import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.*;\n import static org.junit.jupiter.api.Assertions.fail;\n \n @ExtendWith(ResetCipher.class)\n@@ -321,7 +322,9 @@ public class MagicalGoConfigXmlWriterTest {\n @Test\n public void shouldBeAValidXSD() throws Exception {\n SchemaFactory factory = SchemaFactory.newInstance(\"http://www.w3.org/2001/XMLSchema\");\n- factory.newSchema(new StreamSource(getClass().getResourceAsStream(\"/cruise-config.xsd\")));\n+ try (InputStream xsdStream = getClass().getResourceAsStream(\"/cruise-config.xsd\")) {\n+ factory.newSchema(new StreamSource(xsdStream));\n+ }\n }\n \n @Test\ndiff --git a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java\nindex 6c96c73262..2ab651bece 100644\n--- a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java\n+++ b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java\n@@ -40,9 +40,9 @@ public class ConfigRepoMigrator {\n }\n \n private Chainr getTransformerFor(int targetVersion) {\n+ String targetVersionFile = String.format(\"/config-repo/migrations/%s.json\", targetVersion);\n try {\n- String targetVersionFile = String.format(\"/config-repo/migrations/%s.json\", targetVersion);\n- String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(targetVersionFile), StandardCharsets.UTF_8);\n+ String transformJSON = IOUtils.toString(this.getClass().getResource(targetVersionFile), StandardCharsets.UTF_8);\n return Chainr.fromSpec(JsonUtils.jsonToList(transformJSON));\n } catch (Exception e) {\n throw new RuntimeException(\"Failed to migrate to version \" + targetVersion, e);\n@@ -50,9 +50,9 @@ public class ConfigRepoMigrator {\n }\n \n private Map getContextMap(int targetVersion) {\n+ String contextFile = String.format(\"/config-repo/contexts/%s.json\", targetVersion);\n try {\n- String contextFile = String.format(\"/config-repo/contexts/%s.json\", targetVersion);\n- String contextJSON = IOUtils.toString(this.getClass().getResourceAsStream(contextFile), StandardCharsets.UTF_8);\n+ String contextJSON = IOUtils.toString(this.getClass().getResource(contextFile), StandardCharsets.UTF_8);\n return JsonUtils.jsonToMap(contextJSON);\n } catch (Exception e) {\n LOGGER.debug(String.format(\"No context file present for target version '%s'.\", targetVersion));\ndiff --git a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java\nindex 90885bd189..2cf16d1836 100644\n--- a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java\n+++ b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java\n@@ -18,6 +18,7 @@ package com.thoughtworks.go.plugin.access.configrepo;\n import com.bazaarvoice.jolt.JsonUtils;\n import org.apache.commons.io.IOUtils;\n \n+import java.nio.charset.StandardCharsets;\n import java.util.Map;\n \n import static com.bazaarvoice.jolt.utils.JoltUtils.remove;\n@@ -41,7 +42,7 @@ class ConfigRepoDocumentMother {\n \n private Map getJSONFor(String fileName) {\n try {\n- String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(fileName), \"UTF-8\");\n+ String transformJSON = IOUtils.toString(this.getClass().getResource(fileName), StandardCharsets.UTF_8);\n return JsonUtils.jsonToMap(transformJSON);\n } catch (Exception e) {\n throw new RuntimeException(e);\ndiff --git a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java\nindex 44c809ffd6..d16eaadece 100644\n--- a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java\n+++ b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java\n@@ -22,6 +22,7 @@ import org.springframework.stereotype.Component;\n \n import java.io.IOException;\n import java.io.InputStream;\n+import java.nio.charset.StandardCharsets;\n import java.util.Map;\n \n import static java.lang.String.format;\n@@ -36,9 +37,8 @@ public class ViewResolver {\n }\n \n public String resolveView(String viewName, Map modelMap) {\n- try {\n- InputStream resourceAsStream = getResourceAsStream(viewName);\n- String template = IOUtils.toString(resourceAsStream, \"UTF-8\");\n+ try (InputStream resourceAsStream = getResourceAsStream(viewName)) {\n+ String template = IOUtils.toString(resourceAsStream, StandardCharsets.UTF_8);\n for (String modelKey : modelMap.keySet()) {\n template = template.replaceAll(format(\"<<<%s>>>\", modelKey), modelMap.get(modelKey));\n }\ndiff --git a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java\nindex b2ae2982cb..0a66781184 100644\n--- a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java\n+++ b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java\n@@ -118,7 +118,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin\n \n try {\n byte[] payload = Base64.getDecoder().decode(data.getBytes());\n- byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResourceAsStream(\"/\" + PLUGIN_ENDPOINT_JS));\n+ byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResource(\"/\" + PLUGIN_ENDPOINT_JS));\n \n try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(payload))) {\n String assetsHash = calculateHash(payload, pluginEndpointJsContent);\n@@ -139,7 +139,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin\n \n private void safeCopyExternalAssetsToPluginAssetRoot(final String pluginAssetsRoot) {\n Path externalAssetsPath = Paths.get(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS));\n- if (externalAssetsPath == null || !Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) {\n+ if (!Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) {\n LOGGER.debug(\"Analytics plugin external assets path ({}) does not exist or is not a directory. Not loading any assets.\", externalAssetsPath);\n return;\n }\n@@ -184,9 +184,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin\n LOGGER.info(\"Deleting cached static assets for plugin: {}\", pluginId);\n try {\n FileUtils.deleteDirectory(new File(pluginStaticAssetsRootDir(pluginId)));\n- if (pluginAssetPaths.containsKey(pluginId)) {\n- pluginAssetPaths.remove(pluginId);\n- }\n+ pluginAssetPaths.remove(pluginId);\n } catch (Exception e) {\n LOGGER.error(\"Failed to delete cached static assets for plugin: {}\", pluginId, e);\n ExceptionUtils.bomb(e);\ndiff --git a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java\nindex 4e750c430a..c71e9091a0 100644\n--- a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java\n+++ b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java\n@@ -3,6 +3,7 @@ package com.thoughtworks.go.addon.businesscontinuity;\n import org.apache.commons.io.IOUtils;\n import org.junit.jupiter.api.Test;\n \n+import java.nio.charset.StandardCharsets;\n import java.util.HashMap;\n \n import static org.hamcrest.MatcherAssert.assertThat;\n@@ -20,7 +21,7 @@ class ViewResolverTest {\n modelMap.put(\"key2\", \"value2\");\n \n ViewResolver viewResolverSpy = spy(new ViewResolver());\n- doReturn(IOUtils.toInputStream(template)).when(viewResolverSpy).getResourceAsStream(\"sample\");\n+ doReturn(IOUtils.toInputStream(template, StandardCharsets.UTF_8)).when(viewResolverSpy).getResourceAsStream(\"sample\");\n String resolvedView = viewResolverSpy.resolveView(\"sample\", modelMap);\n \n assertThat(resolvedView, is(\"\"));\ndiff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java\nindex 283cdda954..52e4ce6b62 100644\n--- a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java\n+++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java\n@@ -24,7 +24,6 @@ import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;\n import com.thoughtworks.go.util.SystemEnvironment;\n import org.apache.commons.io.FileUtils;\n import org.apache.commons.io.IOUtils;\n-import org.junit.jupiter.api.AfterEach;\n import org.junit.jupiter.api.BeforeEach;\n import org.junit.jupiter.api.Test;\n import org.junit.jupiter.api.extension.ExtendWith;\n@@ -35,7 +34,6 @@ import org.mockito.junit.jupiter.MockitoExtension;\n import javax.servlet.ServletContext;\n import java.io.File;\n import java.io.IOException;\n-import java.nio.charset.StandardCharsets;\n import java.nio.file.Files;\n import java.nio.file.Path;\n import java.nio.file.Paths;\n@@ -76,7 +74,7 @@ public class AnalyticsPluginAssetsServiceTest {\n }\n \n @Test\n- public void shouldBeAPluginMetadataChangeListener() throws Exception {\n+ public void shouldBeAPluginMetadataChangeListener() {\n verify(analyticsMetadataLoader).registerListeners(assetsService);\n }\n \n@@ -165,7 +163,7 @@ public class AnalyticsPluginAssetsServiceTest {\n \n assertTrue(pluginDirPath.toFile().exists());\n assertTrue(actualPath.toFile().exists());\n- byte[] expected = IOUtils.toByteArray(getClass().getResourceAsStream(\"/plugin-endpoint.js\"));\n+ byte[] expected = IOUtils.toByteArray(getClass().getResource(\"/plugin-endpoint.js\"));\n assertArrayEquals(expected, Files.readAllBytes(actualPath), \"Content of plugin-endpoint.js should be preserved\");\n }\n \n@@ -178,8 +176,8 @@ public class AnalyticsPluginAssetsServiceTest {\n when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());\n \n when(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS)).thenReturn(externalAssetsDir.getAbsolutePath());\n- Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), \"a.js\"), \"a\".getBytes(StandardCharsets.UTF_8));\n- Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), \"b.js\"), \"b\".getBytes(StandardCharsets.UTF_8));\n+ Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), \"a.js\"), \"a\");\n+ Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), \"b.js\"), \"b\");\n \n \n assetsService.onPluginMetadataCreate(PLUGIN_ID);\n@@ -241,7 +239,7 @@ public class AnalyticsPluginAssetsServiceTest {\n }\n \n private String testDataZipArchive() throws IOException {\n- return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResourceAsStream(\"/plugin_cache_test.zip\"))));\n+ return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResource(\"/plugin_cache_test.zip\"))));\n }\n \n private void addAnalyticsPluginInfoToStore(String pluginId) {\ndiff --git a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java\nindex 6c83d9839b..ed7c1caab2 100644\n--- a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java\n+++ b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java\n@@ -32,7 +32,6 @@ import javax.servlet.FilterChain;\n import javax.servlet.ServletException;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n-import java.io.InputStream;\n import java.io.PrintWriter;\n import java.util.Optional;\n \n@@ -48,7 +47,6 @@ public class BackupFilterTest {\n private FilterChain chain;\n private BackupService backupService;\n private PrintWriter writer;\n- private InputStream inputStream;\n \n @BeforeEach\n public void setUp() throws ServletException, IOException {\n@@ -57,7 +55,6 @@ public class BackupFilterTest {\n res = mock(HttpServletResponse.class);\n backupService = mock(BackupService.class);\n chain = mock(FilterChain.class);\n- inputStream = BackupFilter.class.getClassLoader().getResourceAsStream(\"backup_in_progress.html\");\n writer = mock(PrintWriter.class);\n when(res.getWriter()).thenReturn(writer);\n this.backupFilter = new BackupFilter(backupService);\n@@ -99,7 +96,7 @@ public class BackupFilterTest {\n when(backupService.backupRunningSinceISO8601()).thenReturn(BACKUP_STARTED_AT);\n when(backupService.backupStartedBy()).thenReturn(BACKUP_STARTED_BY);\n \n- String content = IOUtils.toString(inputStream, UTF_8);\n+ String content = IOUtils.toString(BackupFilter.class.getClassLoader().getResource(\"backup_in_progress.html\"), UTF_8);\n content = backupFilter.replaceStringLiterals(content);\n Request request = request(HttpMethod.GET, \"\", \"/go/agents\");\n \ndiff --git a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java\nindex e0a00b18b0..7417d7b1d6 100644\n--- a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java\n+++ b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java\n@@ -54,7 +54,10 @@ import com.thoughtworks.go.serverhealth.HealthStateType;\n import com.thoughtworks.go.serverhealth.ServerHealthService;\n import com.thoughtworks.go.serverhealth.ServerHealthState;\n import com.thoughtworks.go.service.ConfigRepository;\n-import com.thoughtworks.go.util.*;\n+import com.thoughtworks.go.util.GoConstants;\n+import com.thoughtworks.go.util.ReflectionUtil;\n+import com.thoughtworks.go.util.SystemEnvironment;\n+import com.thoughtworks.go.util.TempDirUtils;\n import com.thoughtworks.go.util.command.CommandLine;\n import com.thoughtworks.go.util.command.ConsoleResult;\n import org.apache.commons.io.FileUtils;\n@@ -1200,7 +1203,7 @@ public class CachedGoConfigIntegrationTest {\n ArtifactStore artifactStore = new ArtifactStore(\"dockerhub\", \"cd.go.artifact.docker.registry\");\n artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult());\n File configFile = new File(new SystemEnvironment().getCruiseConfigFile());\n- String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n+ String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n FileUtils.writeStringToFile(configFile, config, UTF_8);\n \n cachedGoConfig.forceReload();\n@@ -1221,7 +1224,7 @@ public class CachedGoConfigIntegrationTest {\n ArtifactStore artifactStore = new ArtifactStore(\"dockerhub\", \"cd.go.artifact.docker.registry\");\n artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult());\n File configFile = new File(new SystemEnvironment().getCruiseConfigFile());\n- String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n+ String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n FileUtils.writeStringToFile(configFile, config, UTF_8);\n \n cachedGoConfig.forceReload();\ndiff --git a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java\nindex 2668a2a71e..32236b8585 100644\n--- a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java\n+++ b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java\n@@ -41,8 +41,8 @@ import java.util.ArrayList;\n \n import static java.nio.charset.StandardCharsets.UTF_8;\n import static java.util.Arrays.asList;\n-import static org.hamcrest.Matchers.*;\n import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.*;\n \n @ExtendWith(SpringExtension.class)\n @ContextConfiguration(locations = {\n@@ -70,7 +70,7 @@ public abstract class FullConfigSaveFlowTestBase {\n public void setUp() throws Exception {\n configHelper = new GoConfigFileHelper(goConfigDao);\n configHelper.onSetUp();\n- xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n+ xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource(\"/data/pluggable_artifacts_with_params.xml\"), UTF_8));\n loader = new MagicalGoConfigXmlLoader(configCache, registry);\n setupMetadataForPlugin();\n }\ndiff --git a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java\nindex 6910f8d923..f9d8272ca5 100644\n--- a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java\n+++ b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java\n@@ -27,7 +27,9 @@ import com.thoughtworks.go.security.ResetCipher;\n import com.thoughtworks.go.server.service.GoConfigService;\n import com.thoughtworks.go.serverhealth.ServerHealthService;\n import com.thoughtworks.go.service.ConfigRepository;\n-import com.thoughtworks.go.util.*;\n+import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother;\n+import com.thoughtworks.go.util.SystemEnvironment;\n+import com.thoughtworks.go.util.TimeProvider;\n import org.apache.commons.io.IOUtils;\n import org.apache.commons.lang3.StringUtils;\n import org.jdom2.Document;\n@@ -112,7 +114,7 @@ public class GoConfigMigrationIntegrationTest {\n \n @Test\n public void shouldMigrateToRevision22() throws Exception {\n- final String content = IOUtils.toString(getClass().getResourceAsStream(\"cruise-config-escaping-migration-test-fixture.xml\"), UTF_8);\n+ final String content = IOUtils.toString(getClass().getResource(\"cruise-config-escaping-migration-test-fixture.xml\"), UTF_8);\n \n String migratedContent = ConfigMigrator.migrate(content, 21, 22);\n \n@@ -122,7 +124,7 @@ public class GoConfigMigrationIntegrationTest {\n \n @Test\n public void shouldMigrateToRevision28() throws Exception {\n- final String content = IOUtils.toString(getClass().getResourceAsStream(\"no-tracking-tool-group-holder-config.xml\"), UTF_8);\n+ final String content = IOUtils.toString(getClass().getResource(\"no-tracking-tool-group-holder-config.xml\"), UTF_8);\n \n String migratedContent = migrateXmlString(content, 27);\n \n@@ -132,7 +134,7 @@ public class GoConfigMigrationIntegrationTest {\n \n @Test\n public void shouldMigrateToRevision34() throws Exception {\n- final String content = IOUtils.toString(getClass().getResourceAsStream(\"svn-p4-with-parameterized-passwords.xml\"), UTF_8);\n+ final String content = IOUtils.toString(getClass().getResource(\"svn-p4-with-parameterized-passwords.xml\"), UTF_8);\n \n String migratedContent = ConfigMigrator.migrate(content, 22, 34);\n \n@@ -144,7 +146,7 @@ public class GoConfigMigrationIntegrationTest {\n \n @Test\n public void shouldMigrateToRevision35_escapeHash() throws Exception {\n- final String content = IOUtils.toString(getClass().getResourceAsStream(\"escape_param_for_nant_p4.xml\"), UTF_8).trim();\n+ final String content = IOUtils.toString(getClass().getResource(\"escape_param_for_nant_p4.xml\"), UTF_8).trim();\n \n String migratedContent = ConfigMigrator.migrate(content, 22, 35);\n \ndiff --git a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java\nindex d8aba694df..d215589cb0 100644\n--- a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java\n+++ b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java\n@@ -71,7 +71,7 @@ public class PipelineConfigsServiceIntegrationTest {\n @BeforeEach\n public void setUp() throws Exception {\n configHelper = new GoConfigFileHelper();\n- xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream(\"/data/config_with_pluggable_artifacts_store.xml\"), UTF_8));\n+ xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource(\"/data/config_with_pluggable_artifacts_store.xml\"), UTF_8));\n setupMetadataForPlugin();\n \n configHelper.usingCruiseConfigDao(goConfigDao);\n@@ -201,7 +201,7 @@ public class PipelineConfigsServiceIntegrationTest {\n }\n \n private String groupSnippetWithSecurePropertiesBeforeEncryption() throws IOException {\n- return IOUtils.toString(getClass().getResourceAsStream(\"/data/pipeline_group_snippet_with_pluggable_artifacts.xml\"), UTF_8);\n+ return IOUtils.toString(getClass().getResource(\"/data/pipeline_group_snippet_with_pluggable_artifacts.xml\"), UTF_8);\n }\n \n }"},"changed_files":{"kind":"string","value":"['server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java', 'plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java', 'server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java', 'base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java', 'server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java', 'server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java', 'server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java', 'plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java', 'config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java', 'common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java', 'config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java', 'server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java', 'server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 15}"},"changed_files_count":{"kind":"number","value":15,"string":"15"},"java_changed_files_count":{"kind":"number","value":15,"string":"15"},"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":15,"string":"15"},"repo_symbols_count":{"kind":"number","value":15876612,"string":"15,876,612"},"repo_tokens_count":{"kind":"number","value":3177279,"string":"3,177,279"},"repo_lines_count":{"kind":"number","value":374348,"string":"374,348"},"repo_files_without_tests_count":{"kind":"number","value":3354,"string":"3,354"},"changed_symbols_count":{"kind":"number","value":8706,"string":"8,706"},"changed_tokens_count":{"kind":"number","value":1665,"string":"1,665"},"changed_lines_count":{"kind":"number","value":111,"string":"111"},"changed_files_without_tests_count":{"kind":"number","value":11,"string":"11"},"issue_symbols_count":{"kind":"number","value":228,"string":"228"},"issue_words_count":{"kind":"number","value":11,"string":"11"},"issue_tokens_count":{"kind":"number","value":67,"string":"67"},"issue_lines_count":{"kind":"number","value":3,"string":"3"},"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:18","string":"1970-01-01T00:27:18"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1354,"cells":{"id":{"kind":"number","value":403,"string":"403"},"text_id":{"kind":"string","value":"gocd/gocd/10087/10086"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/10086"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/10087"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/10087"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Test Drive/standalone GoCD fails to start when commit GPG signing is enabled at system/user level"},"issue_body":{"kind":"string","value":"##### Issue Type\r\n\r\n- Bug Report\r\n\r\n##### Summary\r\nWhen I run Test Drive 21.4.0 (`gocd-21.4.0-13469-1477-osx`) which is current stable version, GoCD server couldn't be started.\r\n\r\n##### Environment\r\n\r\nOn my macbook\r\n\r\n###### Basic environment details\r\n\r\n* Go Version: `21.4.0`\r\n* JAVA Version: `openjdk 15.0.4`\r\n* OS: `macOS 11.6`\r\n\r\n##### Steps to Reproduce\r\n\r\n1. Run `curl -fsSL 'https://www.gocd.org/test-drive-gocd/try.sh' | bash -s 'https://download.gocd.org/test-drive/installers/21.4.0/13469/gocd-21.4.0-13469-1477-osx.zip'` \r\n2. Server hung with `Wating for the GoCD server to finish initializing.....`\r\n\r\n##### Expected Results\r\nGoCD Server launched\r\n\r\n##### Actual Results\r\nStarting server failed.\r\n\r\n##### Log snippets\r\n```\r\norg.eclipse.jgit.api.errors.ServiceUnavailableException: Signing service is not available\r\n\tat org.eclipse.jgit.api.CommitCommand.sign(CommitCommand.java:290)\r\n\tat org.eclipse.jgit.api.CommitCommand.call(CommitCommand.java:247)\r\n\tat com.thoughtworks.go.service.ConfigRepository$1.run(ConfigRepository.java:125)\r\n\tat com.thoughtworks.go.util.VoidThrowingFn.call(VoidThrowingFn.java:25)\r\n\tat com.thoughtworks.go.service.ConfigRepository.doLocked(ConfigRepository.java:136)\r\n\tat com.thoughtworks.go.service.ConfigRepository.checkin(ConfigRepository.java:121)\r\n\tat com.thoughtworks.go.config.FullConfigSaveFlow.checkinToConfigRepo(FullConfigSaveFlow.java:79)\r\n\tat com.thoughtworks.go.config.FullConfigSaveNormalFlow.execute(FullConfigSaveNormalFlow.java:67)\r\n\tat com.thoughtworks.go.config.GoConfigMigrator.upgradeConfigFile(GoConfigMigrator.java:110)\r\n\tat com.thoughtworks.go.config.GoConfigMigrator.upgrade(GoConfigMigrator.java:96)\r\n\tat com.thoughtworks.go.config.GoConfigMigrator.migrate(GoConfigMigrator.java:87)\r\n\tat com.thoughtworks.go.config.CachedGoConfig.upgradeConfig(CachedGoConfig.java:149)\r\n\tat com.thoughtworks.go.server.initializers.ApplicationInitializer.onApplicationEvent(ApplicationInitializer.java:112)\r\n\tat com.thoughtworks.go.server.initializers.ApplicationInitializer.onApplicationEvent(ApplicationInitializer.java:49)\r\n\tat org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)\r\n\tat org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)\r\n\tat org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)\r\n\tat org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)\r\n\tat org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)\r\n\tat org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)\r\n\tat org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)\r\n\tat org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)\r\n\tat org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)\r\n\tat org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)\r\n\tat org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1067)\r\n\tat org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:572)\r\n\tat org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:996)\r\n\tat org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:746)\r\n\tat org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:379)\r\n\tat org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449)\r\n\tat org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414)\r\n\tat org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:910)\r\n\tat org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288)\r\n\tat org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)\r\n\tat org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)\r\n\tat org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46)\r\n\tat org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188)\r\n\tat org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:517)\r\n\tat org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:157)\r\n\tat com.thoughtworks.go.server.Jetty9Server.startHandlers(Jetty9Server.java:179)\r\n\tat com.thoughtworks.go.server.Jetty9Server.start(Jetty9Server.java:129)\r\n\tat com.thoughtworks.go.server.GoServer.startServer(GoServer.java:62)\r\n\tat com.thoughtworks.go.server.GoServer.go(GoServer.java:54)\r\n\tat com.thoughtworks.go.server.util.GoLauncher.main(GoLauncher.java:42)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:567)\r\n\tat com.thoughtworks.gocd.Boot.run(Boot.java:90)\r\n\tat com.thoughtworks.gocd.Boot.main(Boot.java:56)\r\n2022-01-14 20:54:16,934 WARN [main] GoConfigMigrator:98 - Error upgrading config file, trying to upgrade using the versioned config file.\r\n2022-01-14 20:54:16,935 WARN [main] ConfigRepository:196 - [CONFIG REPOSITORY] No head exists in the config repository.\r\n2022-01-14 20:54:16,935 WARN [main] GoConfigMigrator:116 - There is no versioned configuration to fallback for migration.\r\n2022-01-14 20:54:16,944 ERROR [main] GoConfigMigrator:64 - There are errors in the Cruise config file. Please read the error message and correct the errors.\r\nOnce fixed, please restart GoCD.\r\nError: Signing service is not available\r\n```\r\n"},"base_sha":{"kind":"string","value":"fb73c589ce0052f30d576f115a8bafe101d1c1c3"},"head_sha":{"kind":"string","value":"2db3a23f2bd8f4836e3db34bf7d80b7b242221e9"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/fb73c589ce0052f30d576f115a8bafe101d1c1c3...2db3a23f2bd8f4836e3db34bf7d80b7b242221e9"},"diff":{"kind":"string","value":"diff --git a/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java b/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java\nindex 8eb6f587f3..9f2520ca6b 100644\n--- a/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java\n+++ b/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java\n@@ -78,10 +78,14 @@ public class ConfigRepository {\n workingDir = this.systemEnvironment.getConfigRepoDir();\n File configRepoDir = new File(workingDir, \".git\");\n gitRepo = new FileRepositoryBuilder().setGitDir(configRepoDir).build();\n- gitRepo.getConfig().setInt(\"gc\", null, \"auto\", 0);\n+ updateWithDefaults(gitRepo.getConfig());\n git = new Git(gitRepo);\n }\n \n+ private void updateWithDefaults(StoredConfig config) {\n+ config.setInt(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_AUTO, 0);\n+ config.setBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_GPGSIGN, false);\n+ }\n \n public Repository getGitRepo() {\n return gitRepo;\ndiff --git a/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java b/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java\nindex 25fbac99ae..b40abe1b64 100644\n--- a/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java\n+++ b/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java\n@@ -24,8 +24,11 @@ import com.thoughtworks.go.util.SystemEnvironment;\n import com.thoughtworks.go.util.TimeProvider;\n import org.eclipse.jgit.api.ListBranchCommand;\n import org.eclipse.jgit.api.errors.GitAPIException;\n+import org.eclipse.jgit.lib.ConfigConstants;\n import org.eclipse.jgit.lib.Ref;\n+import org.eclipse.jgit.lib.StoredConfig;\n import org.eclipse.jgit.revwalk.RevCommit;\n+import org.eclipse.jgit.util.SystemReader;\n import org.junit.jupiter.api.AfterEach;\n import org.junit.jupiter.api.BeforeEach;\n import org.junit.jupiter.api.Test;\n@@ -35,6 +38,7 @@ import java.io.File;\n import java.io.IOException;\n import java.util.Iterator;\n import java.util.List;\n+import java.util.function.Consumer;\n \n import static org.hamcrest.MatcherAssert.assertThat;\n import static org.hamcrest.Matchers.*;\n@@ -70,6 +74,33 @@ public class ConfigRepositoryTest {\n assertThat(configRepo.getRevision(\"md5-v2\").getContent(), is(\"v1 v2\"));\n }\n \n+ @Test\n+ public void shouldBeAbleToCheckInWithGlobalGpgSigningEnabled() throws Exception {\n+ try (UndoableUserGitConfig ignored = new UndoableUserGitConfig(c -> c.setBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_GPGSIGN, true))) {\n+ configRepo = new ConfigRepository(systemEnvironment);\n+ configRepo.initialize();\n+ configRepo.checkin(new GoConfigRevision(\"v1\", \"md5-v1\", \"user-name\", \"100.3.9\", new TimeProvider()));\n+ assertThat(configRepo.getRevision(\"md5-v1\").getContent(), is(\"v1\"));\n+ assertThat(configRepo.getCurrentRevCommit().getRawGpgSignature(), nullValue());\n+ }\n+ }\n+\n+ private static class UndoableUserGitConfig implements AutoCloseable {\n+ private final String originalConfig;\n+\n+ public UndoableUserGitConfig(Consumer configConsumer) throws Exception {\n+ StoredConfig config = SystemReader.getInstance().getUserConfig();\n+ originalConfig = config.toText();\n+ configConsumer.accept(config);\n+ }\n+\n+ @Override\n+ public void close() throws Exception {\n+ StoredConfig config = SystemReader.getInstance().getUserConfig();\n+ config.fromText(originalConfig);\n+ }\n+ }\n+\n @Test\n public void shouldGetCommitsCorrectly() throws Exception {\n configRepo.checkin(new GoConfigRevision(\"v1\", \"md5-v1\", \"user-name\", \"100.3.9\", new TimeProvider()));\n@@ -110,7 +141,7 @@ public class ConfigRepositoryTest {\n }\n \n @Test\n- public void shouldReturnNullWhenThereAreNoCheckIns() throws GitAPIException, IOException {\n+ public void shouldReturnNullWhenThereAreNoCheckIns() throws Exception {\n assertThat(configRepo.getRevision(\"current\"), is(nullValue()));\n }\n \n@@ -317,7 +348,7 @@ public class ConfigRepositoryTest {\n }\n \n @Test\n- public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception, GitAPIException {\n+ public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception {\n configRepo.checkin(goConfigRevision(\"v1\", \"md5-1\"));\n configRepo.createBranch(ConfigRepository.BRANCH_AT_HEAD, configRepo.getCurrentRevCommit());\n configRepo.createBranch(ConfigRepository.BRANCH_AT_REVISION, configRepo.getCurrentRevCommit());\n@@ -376,10 +407,10 @@ public class ConfigRepositoryTest {\n public void shouldPerformGC() throws Exception {\n configRepo.checkin(goConfigRevision(\"v1\", \"md5-1\"));\n Long numberOfLooseObjects = (Long) configRepo.git().gc().getStatistics().get(\"sizeOfLooseObjects\");\n- assertThat(numberOfLooseObjects > 0l, is(true));\n+ assertThat(numberOfLooseObjects > 0L, is(true));\n configRepo.garbageCollect();\n numberOfLooseObjects = (Long) configRepo.git().gc().getStatistics().get(\"sizeOfLooseObjects\");\n- assertThat(numberOfLooseObjects, is(0l));\n+ assertThat(numberOfLooseObjects, is(0L));\n }\n \n @Test\n@@ -411,7 +442,7 @@ public class ConfigRepositoryTest {\n return new GoConfigRevision(fileContent, md5, \"user-1\", \"13.2\", new TimeProvider());\n }\n \n- private String getLatestConfigAt(String branchName) throws GitAPIException, IOException {\n+ private String getLatestConfigAt(String branchName) throws GitAPIException {\n configRepo.git().checkout().setName(branchName).call();\n \n String content = configRepo.getCurrentRevision().getContent();"},"changed_files":{"kind":"string","value":"['config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java', 'config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.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":15850828,"string":"15,850,828"},"repo_tokens_count":{"kind":"number","value":3172153,"string":"3,172,153"},"repo_lines_count":{"kind":"number","value":373812,"string":"373,812"},"repo_files_without_tests_count":{"kind":"number","value":3347,"string":"3,347"},"changed_symbols_count":{"kind":"number","value":393,"string":"393"},"changed_tokens_count":{"kind":"number","value":83,"string":"83"},"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":6058,"string":"6,058"},"issue_words_count":{"kind":"number","value":278,"string":"278"},"issue_tokens_count":{"kind":"number","value":1380,"string":"1,380"},"issue_lines_count":{"kind":"number","value":89,"string":"89"},"issue_links_count":{"kind":"number","value":2,"string":"2"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:22","string":"1970-01-01T00:27:22"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1355,"cells":{"id":{"kind":"number","value":402,"string":"402"},"text_id":{"kind":"string","value":"gocd/gocd/10649/10648"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/10648"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/10649"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/10649"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Plugin admin page can display stale plugin information after plugin upgrades"},"issue_body":{"kind":"string","value":"##### Issue Type\r\n\r\n- Bug Report\r\n\r\n##### Summary\r\n\r\n\r\nWhen plugins are updated to new versions without changing which plugins are installed, `/go/admin/plugins` will display stale data in the browser until browser cache expiry.\r\n\r\n\r\n###### Basic environment details\r\n\r\n\r\n\r\n* Go Version: `22.1.0`\r\n\r\n##### Steps to Reproduce\r\n\r\n\r\n\r\n1. Load the plugins admin page\r\n2. Update a plugin to a new version while changing nothing else\r\n3. Bounce the server\r\n4. Re-load the plugins admin page, not the old version.\r\n5. Clear cache and/or force refresh and notice it changing.\r\n\r\n##### Expected Results\r\n\r\nThe page should be updated reliably when plugins are updated.\r\n\r\n##### Actual Results\r\n\r\nStale data displayed for some indeterminate amount of time.\r\n\r\n##### Possible Fix\r\n\r\nIt looks like the below defines a custom hash algorithm for `PluginInfo` which excludes `version`, `name` and other aspects of the plugin descriptor so if they are updated it won't cause a refresh. At the very least the `version` should be included so when a new version is released (which may have new values for other fields) the hash changes, and thus the entity `ETag`.\r\n\r\nhttps://github.com/gocd/gocd/blob/5c7c6c226dc2caa1fe729f5142536634912e795a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java#L107-L113"},"base_sha":{"kind":"string","value":"c2293bcb6397761bc052789ae59facf315afbfe2"},"head_sha":{"kind":"string","value":"85d5ba31393959d8328f5d0dec8e33b27afce6ce"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/c2293bcb6397761bc052789ae59facf315afbfe2...85d5ba31393959d8328f5d0dec8e33b27afce6ce"},"diff":{"kind":"string","value":"diff --git a/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java b/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java\nindex a75120a5a9..1568613acb 100644\n--- a/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java\n+++ b/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java\n@@ -18,7 +18,6 @@ package com.thoughtworks.go.apiv7.plugininfos;\n import com.thoughtworks.go.api.ApiController;\n import com.thoughtworks.go.api.ApiVersion;\n import com.thoughtworks.go.api.spring.ApiAuthenticationHelper;\n-import com.thoughtworks.go.api.spring.ToggleRegisterLatest;\n import com.thoughtworks.go.apiv7.plugininfos.representers.PluginInfoRepresenter;\n import com.thoughtworks.go.apiv7.plugininfos.representers.PluginInfosRepresenter;\n import com.thoughtworks.go.config.exceptions.RecordNotFoundException;\ndiff --git a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java b/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java\nindex ebdffb96bd..870f071742 100644\n--- a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java\n+++ b/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java\n@@ -107,6 +107,7 @@ public class EntityHashes implements DigestMixin {\n JsonSerializer PLUGIN_INFO = (src, typeOfSrc, context) -> {\n final JsonObject result = new JsonObject();\n result.addProperty(\"id\", src.getDescriptor().id());\n+ result.addProperty(\"version\", src.getDescriptor().version());\n result.addProperty(\"extension\", src.getExtensionName());\n result.add(\"settings\", context.serialize(src.getPluginSettings()));\n return result;\ndiff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java\nindex 3459ec986a..ff9b142ec9 100644\n--- a/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java\n+++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java\n@@ -41,6 +41,7 @@ import java.util.List;\n \n import static com.thoughtworks.go.server.service.EntityHashingService.ETAG_CACHE_KEY;\n import static org.apache.commons.lang3.StringUtils.isNotBlank;\n+import static org.assertj.core.api.Assertions.assertThat;\n import static org.junit.jupiter.api.Assertions.*;\n import static org.mockito.Mockito.*;\n \n@@ -72,29 +73,35 @@ public class EntityHashingServiceTest {\n \n @Test\n void digestsCombinedPluginInfoAndCollection() {\n- final CombinedPluginInfo info1 = new CombinedPluginInfo(new NotificationPluginInfo(\n- GoPluginDescriptor.builder().id(\"foo\").build(),\n- new PluggableInstanceSettings(List.of(new PluginConfiguration(\"user\", null)))\n- ));\n- final CombinedPluginInfo info2 = new CombinedPluginInfo(new NotificationPluginInfo(\n- GoPluginDescriptor.builder().id(\"bar\").build(),\n- new PluggableInstanceSettings(List.of(new PluginConfiguration(\"user\", null)))\n- ));\n+ PluggableInstanceSettings testSettings = new PluggableInstanceSettings(List.of(new PluginConfiguration(\"user\", null)));\n+ final CombinedPluginInfo info1 = new CombinedPluginInfo(\n+ new NotificationPluginInfo(GoPluginDescriptor.builder().id(\"foo\").build(), testSettings)\n+ );\n+ final CombinedPluginInfo info2 = new CombinedPluginInfo(\n+ new NotificationPluginInfo(GoPluginDescriptor.builder().id(\"bar\").build(), testSettings)\n+ );\n final Collection many = List.of(info1, info2);\n \n final String actual = service.hashForEntity(many);\n assertTrue(actual.matches(\"[a-f0-9]{64}\"));\n \n assertEquals(digests.digest(\n- service.hashForEntity(info1),\n- service.hashForEntity(info2)\n+ service.hashForEntity(info1),\n+ service.hashForEntity(info2)\n ), actual);\n+\n+ final CombinedPluginInfo info2v2 = new CombinedPluginInfo(\n+ new NotificationPluginInfo(GoPluginDescriptor.builder().id(\"bar\").version(\"2\").build(), testSettings)\n+ );\n+\n+ assertThat(service.hashForEntity(info2v2)).isNotEqualTo(service.hashForEntity(info2));\n+\n }\n \n @Test\n @DisplayName(\"when plugin settings contain secret properties, the digest used for\" +\n- \"ETags should not change as long as the decrypted values remain the same, \" +\n- \"even if the crypto salt changes between requests\")\n+ \"ETags should not change as long as the decrypted values remain the same, \" +\n+ \"even if the crypto salt changes between requests\")\n void digestIsConsistentForPluginSettingsWithSecretPropertiesEvenWhenCryptoSaltChanges() {\n TestIVProvider.with(new ProductionIVProvider(), () -> {\n final String id = \"com.foo.plugin\";\n@@ -106,9 +113,9 @@ public class EntityHashingServiceTest {\n final PluginSettings p2 = pluginSettings(id, key, secret);\n \n assertNotEquals(\n- p1.getPluginSettingsProperties().get(0).getEncryptedValue(),\n- p2.getPluginSettingsProperties().get(0).getEncryptedValue(),\n- \"both entities should have different cipherTexts even though the input values are equal\"\n+ p1.getPluginSettingsProperties().get(0).getEncryptedValue(),\n+ p2.getPluginSettingsProperties().get(0).getEncryptedValue(),\n+ \"both entities should have different cipherTexts even though the input values are equal\"\n );\n \n final String expected = service.hashForEntity(p1);\n@@ -162,7 +169,7 @@ public class EntityHashingServiceTest {\n \n @Test\n @DisplayName(\"hashForEntity() can determine the proper overloaded method for implementations of \" +\n- \"EnvironmentConfig and List without ambiguity\")\n+ \"EnvironmentConfig and List without ambiguity\")\n void hashesEnvironmentConfigsWithoutClassAmbiguityIssues() {\n // important to test these when typed as the non-specific parent interface\n final EnvironmentConfig basic = new BasicEnvironmentConfig(new CaseInsensitiveString(\"hello\"));\n@@ -175,11 +182,11 @@ public class EntityHashingServiceTest {\n // resolving the wrong overload might result in an exception indicating that the object \"does not\n // have a ConfigTag\"\n assertDoesNotThrow(() -> {\n- assertTrue(isNotBlank(service.hashForEntity(basic)));\n- assertTrue(isNotBlank(service.hashForEntity(merged)));\n- assertTrue(isNotBlank(service.hashForEntity(mult)));\n- assertTrue(isNotBlank(service.hashForEntity(nested)));\n- }\n+ assertTrue(isNotBlank(service.hashForEntity(basic)));\n+ assertTrue(isNotBlank(service.hashForEntity(merged)));\n+ assertTrue(isNotBlank(service.hashForEntity(mult)));\n+ assertTrue(isNotBlank(service.hashForEntity(nested)));\n+ }\n );\n }\n \n@@ -190,8 +197,8 @@ public class EntityHashingServiceTest {\n MergeEnvironmentConfig merged = new MergeEnvironmentConfig(env1, env2);\n \n when(goCache.get(ETAG_CACHE_KEY, \"com.thoughtworks.go.config.BasicEnvironmentConfig.env\")).\n- thenReturn(\"foo\").\n- thenReturn(\"bar\");\n+ thenReturn(\"foo\").\n+ thenReturn(\"bar\");\n \n final String type = MergeEnvironmentConfig.class.getSimpleName();\n assertEquals(digests.digest(type, \"foo\", \"bar\"), service.hashForEntity(merged));"},"changed_files":{"kind":"string","value":"['server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java', 'api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java', 'server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.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":15791732,"string":"15,791,732"},"repo_tokens_count":{"kind":"number","value":3160232,"string":"3,160,232"},"repo_lines_count":{"kind":"number","value":372429,"string":"372,429"},"repo_files_without_tests_count":{"kind":"number","value":3334,"string":"3,334"},"changed_symbols_count":{"kind":"number","value":3440,"string":"3,440"},"changed_tokens_count":{"kind":"number","value":626,"string":"626"},"changed_lines_count":{"kind":"number","value":55,"string":"55"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":1709,"string":"1,709"},"issue_words_count":{"kind":"number","value":257,"string":"257"},"issue_tokens_count":{"kind":"number","value":382,"string":"382"},"issue_lines_count":{"kind":"number","value":39,"string":"39"},"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:39","string":"1970-01-01T00:27:39"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1356,"cells":{"id":{"kind":"number","value":401,"string":"401"},"text_id":{"kind":"string","value":"gocd/gocd/10676/10036"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/10036"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/10676"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/10676"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"HTTP 500 when using external authorization plugins and GoCD site urls are blank"},"issue_body":{"kind":"string","value":"##### Issue Type\r\n\r\n- Bug Report\r\n\r\n##### Summary\r\n\r\nWhen using GoCD GitLab or GitHub authentication plugins, the server site URLs must be set properly in the server configuration, otherwise the GoCD will fail with HTTP 500.\r\n\r\n##### Environment\r\n\r\nDiscovered on 21.2.0, Java 15.\r\nI suppose it is not related to the GoCD or Java version.\r\n\r\n###### Basic environment details\r\n\r\n* Go Version: 21.2.0 \r\n* JAVA Version: 15.0.2\r\n* OS: Linux 4.19.0-17-amd64\r\n\r\n##### Steps to Reproduce\r\n\r\n1. Put a GitLab or GitHub plugin JAR into the appropriate folder and restart the server\r\n2. Create a new authorization configuration with the desired plugin\r\n3. Make sure that both server site urls are not set OR at least the second one (Secure site URL) is not set\r\n4. Try to login via plugin\r\n\r\n##### Expected Results\r\n\r\nShould be redirected to the external IDP properly\r\n\r\n##### Actual Results\r\n\r\nGoCD throws an HTTP500\r\n\r\n##### Possible Fix\r\n\r\nUse at least the site url which is set or something default, like http://localhost:8153\r\n\r\n##### Log snippets\r\n\r\nIn the go-server.log you can see following:\r\n\r\n```\r\n2022-01-03 10:25:48,470 WARN [qtp679525351-29] HttpChannel:673 - handleException /go/plugin/cd.go.authorization.gitlab/login java.net.MalformedURLException: no protocol:\r\n```\r\n\r\n"},"base_sha":{"kind":"string","value":"4fae75d5c7e6e6dcfcacaea0577eafb193e6f29b"},"head_sha":{"kind":"string","value":"5b7c362731eae1fd8deec665bc025c2e99cba3be"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/4fae75d5c7e6e6dcfcacaea0577eafb193e6f29b...5b7c362731eae1fd8deec665bc025c2e99cba3be"},"diff":{"kind":"string","value":"diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java\nindex 0fef04a87e..51f01b601b 100644\n--- a/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java\n+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java\n@@ -294,15 +294,12 @@ public class ServerConfig implements Validatable {\n \n \n public ServerSiteUrlConfig getSiteUrlPreferablySecured() {\n- SiteUrl siteUrl = getSiteUrl();\n- SecureSiteUrl secureSiteUrlConfig = getSecureSiteUrl();\n- if (secureSiteUrlConfig.hasNonNullUrl()) {\n- return secureSiteUrlConfig;\n- }\n- if (!secureSiteUrlConfig.hasNonNullUrl()) {\n- return siteUrl;\n+ SecureSiteUrl secureSiteUrl = getSecureSiteUrl();\n+ if (!secureSiteUrl.isBlank()) {\n+ return secureSiteUrl;\n+ } else {\n+ return getSiteUrl();\n }\n- return new SiteUrl();\n }\n \n public ServerSiteUrlConfig getHttpsUrl() {\n@@ -311,7 +308,7 @@ public class ServerConfig implements Validatable {\n }\n \n public boolean hasAnyUrlConfigured() {\n- return getSiteUrl().hasNonNullUrl() || getSecureSiteUrl().hasNonNullUrl();\n+ return !getSiteUrl().isBlank() || !getSecureSiteUrl().isBlank();\n }\n \n public Double getPurgeStart() {\ndiff --git a/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java\nindex b350abcc9b..c978d4c873 100644\n--- a/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java\n+++ b/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java\n@@ -16,6 +16,7 @@\n package com.thoughtworks.go.domain;\n \n import com.thoughtworks.go.config.ConfigValue;\n+import org.apache.commons.lang3.StringUtils;\n \n import java.net.URI;\n import java.net.URISyntaxException;\n@@ -32,8 +33,8 @@ public abstract class ServerSiteUrlConfig {\n this.url = url;\n }\n \n- public boolean hasNonNullUrl() {\n- return getUrl() != null;\n+ public boolean isBlank() {\n+ return StringUtils.isBlank(url);\n }\n \n public String getUrl() {\n@@ -68,14 +69,22 @@ public abstract class ServerSiteUrlConfig {\n }\n \n public String siteUrlFor(String givenUrl, boolean honorGivenHostName) throws URISyntaxException {\n- if (url == null || isPath(givenUrl)) {\n+ if (isBlank() || isPath(givenUrl)) {\n return givenUrl; //it is a path\n }\n \n URI baseUri = new URI(url);\n URI givenUri = new URI(givenUrl);\n \n- return new URI(baseUri.getScheme(), getOrDefault(givenUri, baseUri, URI::getUserInfo), honorGivenHostName ? givenUri.getHost() : baseUri.getHost(), baseUri.getPort(), getOrDefault(givenUri, baseUri, URI::getPath), getOrDefault(givenUri, baseUri, URI::getQuery), getOrDefault(givenUri, baseUri, URI::getFragment)).toString();\n+ return new URI(\n+ baseUri.getScheme(),\n+ getOrDefault(givenUri, baseUri, URI::getUserInfo),\n+ honorGivenHostName ? givenUri.getHost() : baseUri.getHost(),\n+ baseUri.getPort(),\n+ getOrDefault(givenUri, baseUri, URI::getPath),\n+ getOrDefault(givenUri, baseUri, URI::getQuery),\n+ getOrDefault(givenUri, baseUri, URI::getFragment)\n+ ).toString();\n }\n \n private boolean isPath(String givenUrl) {\n@@ -88,7 +97,7 @@ public abstract class ServerSiteUrlConfig {\n }\n \n public boolean isAHttpsUrl() {\n- return url != null && url.matches(HTTPS_URL_REGEX);\n+ return !isBlank() && url.matches(HTTPS_URL_REGEX);\n }\n \n interface Getter {\n@@ -97,7 +106,7 @@ public abstract class ServerSiteUrlConfig {\n \n @Override\n public String toString() {\n- return hasNonNullUrl() ? url : \"\";\n+ return isBlank() ? \"\" : url;\n }\n }\n \ndiff --git a/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java b/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java\nindex ccc451b193..14968fde88 100644\n--- a/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java\n+++ b/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java\n@@ -61,11 +61,11 @@ public class ServerConfigTest {\n public void shouldReturnBlankUrlBothSiteUrlAndSecureSiteUrlIsNotDefined() {\n defaultServerConfig.setSiteUrl(null);\n defaultServerConfig.setSecureSiteUrl(null);\n- assertThat(defaultServerConfig.getSiteUrlPreferablySecured().hasNonNullUrl(), is(false));\n+ assertThat(defaultServerConfig.getSiteUrlPreferablySecured().isBlank(), is(true));\n }\n \n @Test\n- public void shouldReturnAnEmptyForSecureSiteUrlIfOnlySiteUrlIsConfigured() throws Exception {\n+ public void shouldReturnAnEmptyForSecureSiteUrlIfOnlySiteUrlIsConfigured() {\n ServerConfig serverConfig = new ServerConfig(null, null, new SiteUrl(\"http://foo.bar:813\"), new SecureSiteUrl());\n assertThat(serverConfig.getHttpsUrl(), is(new SecureSiteUrl()));\n }\ndiff --git a/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java b/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java\nindex 46826f047d..dfb2286558 100644\n--- a/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java\n+++ b/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java\n@@ -16,11 +16,14 @@\n package com.thoughtworks.go.domain;\n \n import org.junit.jupiter.api.Test;\n+import org.junit.jupiter.params.ParameterizedTest;\n+import org.junit.jupiter.params.provider.NullSource;\n+import org.junit.jupiter.params.provider.ValueSource;\n \n import java.net.URISyntaxException;\n \n-import static org.hamcrest.Matchers.is;\n import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n \n public class ServerSiteUrlConfigTest {\n @Test\n@@ -77,9 +80,14 @@ public class ServerSiteUrlConfigTest {\n assertThat(url.toString(), is(\"http://someurl.com\"));\n }\n \n- @Test\n- public void shouldReturnEmptyStringForToStringWhenTheUrlIsNotSet() throws Exception {\n- ServerSiteUrlConfig url = new SiteUrl();\n+ @ParameterizedTest\n+ @NullSource\n+ @ValueSource(strings = {\"\", \" \"})\n+ public void shouldHandleBlankUrlsConsistently(String input) throws Exception {\n+ ServerSiteUrlConfig url = new SiteUrl(input);\n assertThat(url.toString(), is(\"\"));\n+ assertThat(url.isBlank(), is(true));\n+ assertThat(url.isAHttpsUrl(), is(false));\n+ assertThat(url.siteUrlFor(\"http://test.host/foo/bar?foo=bar#quux\"), is(\"http://test.host/foo/bar?foo=bar#quux\"));\n }\n }\ndiff --git a/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java b/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java\nindex daf9d31e81..ef23185c10 100644\n--- a/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java\n+++ b/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java\n@@ -88,12 +88,12 @@ public class WebBasedPluginAuthenticationProvider extends AbstractPluginAuthenti\n return new AuthenticationToken<>(userPrinciple, credentials, pluginId, clock.currentTimeMillis(), authConfigId);\n }\n \n- private String getRootUrl(String string) {\n+ private String rootUrlFrom(String urlString) {\n try {\n- final URL url = new URL(string);\n+ final URL url = new URL(urlString);\n return new URL(url.getProtocol(), url.getHost(), url.getPort(), \"\").toString();\n } catch (MalformedURLException e) {\n- throw new RuntimeException(e);\n+ throw new RuntimeException(String.format(\"Configured siteUrl [%s] does not appear to be a valid URL\", urlString), e);\n }\n }\n \n@@ -107,11 +107,12 @@ public class WebBasedPluginAuthenticationProvider extends AbstractPluginAuthenti\n return goConfigService.security().securityAuthConfigs().findByPluginId(pluginId);\n }\n \n- public String getAuthorizationServerUrl(String pluginId, String rootURL) {\n- if (goConfigService.serverConfig().hasAnyUrlConfigured()) {\n- rootURL = getRootUrl(goConfigService.serverConfig().getSiteUrlPreferablySecured().getUrl());\n- }\n- return authorizationExtension.getAuthorizationServerUrl(pluginId, getAuthConfigs(pluginId), rootURL);\n+ public String getAuthorizationServerUrl(String pluginId, String alternateRootUrl) {\n+ String chosenRootUrl =\n+ goConfigService.serverConfig().hasAnyUrlConfigured()\n+ ? rootUrlFrom(goConfigService.serverConfig().getSiteUrlPreferablySecured().getUrl())\n+ : alternateRootUrl;\n+ return authorizationExtension.getAuthorizationServerUrl(pluginId, getAuthConfigs(pluginId), chosenRootUrl);\n }\n \n }\ndiff --git a/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java\nindex 03988934a9..3c63a1d1b5 100644\n--- a/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java\n+++ b/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java\n@@ -41,6 +41,8 @@ import org.junit.jupiter.api.extension.ExtendWith;\n import org.mockito.ArgumentCaptor;\n import org.mockito.InOrder;\n \n+import java.net.MalformedURLException;\n+\n import static com.thoughtworks.go.server.security.GoAuthority.ROLE_USER;\n import static java.util.Arrays.asList;\n import static java.util.Collections.*;\n@@ -322,6 +324,19 @@ class WebBasedPluginAuthenticationProviderTest {\n verify(authorizationExtension).getAuthorizationServerUrl(PLUGIN_ID, singletonList(githubSecurityAuthconfig), \"https://example.com\");\n }\n \n+ @Test\n+ void shouldThrowUsefulErrorIfAuthorizationServerUrlIsBad() {\n+ final ServerConfig serverConfig = mock(ServerConfig.class);\n+ when(goConfigService.serverConfig()).thenReturn(serverConfig);\n+ when(serverConfig.hasAnyUrlConfigured()).thenReturn(true);\n+ when(serverConfig.getSiteUrlPreferablySecured()).thenReturn(new SecureSiteUrl(\"https://badurl:3434:\"));\n+\n+ assertThatThrownBy(() -> authenticationProvider.getAuthorizationServerUrl(PLUGIN_ID, \"https://example.com\"))\n+ .isInstanceOf(RuntimeException.class)\n+ .hasMessageContaining(\"does not appear to be a valid URL\")\n+ .hasCauseInstanceOf(MalformedURLException.class);\n+ }\n+\n @Test\n void shouldFetchAccessTokenFromPlugin() {\n when(authorizationExtension.fetchAccessToken(PLUGIN_ID, emptyMap(), singletonMap(\"code\", \"some-code\"), singletonList(githubSecurityAuthconfig))).thenReturn(singletonMap(\"access_token\", \"some-access-token\"));"},"changed_files":{"kind":"string","value":"['config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java', 'server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java', 'config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java', 'config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.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":15770573,"string":"15,770,573"},"repo_tokens_count":{"kind":"number","value":3155800,"string":"3,155,800"},"repo_lines_count":{"kind":"number","value":372021,"string":"372,021"},"repo_files_without_tests_count":{"kind":"number","value":3332,"string":"3,332"},"changed_symbols_count":{"kind":"number","value":3869,"string":"3,869"},"changed_tokens_count":{"kind":"number","value":815,"string":"815"},"changed_lines_count":{"kind":"number","value":68,"string":"68"},"changed_files_without_tests_count":{"kind":"number","value":4,"string":"4"},"issue_symbols_count":{"kind":"number","value":1275,"string":"1,275"},"issue_words_count":{"kind":"number","value":188,"string":"188"},"issue_tokens_count":{"kind":"number","value":312,"string":"312"},"issue_lines_count":{"kind":"number","value":47,"string":"47"},"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:39","string":"1970-01-01T00:27:39"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1357,"cells":{"id":{"kind":"number","value":400,"string":"400"},"text_id":{"kind":"string","value":"gocd/gocd/11262/11260"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/11260"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/11262"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/11262"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Loading materials admin page creates syntax error on MySQL 8.0"},"issue_body":{"kind":"string","value":"### Issue Type\r\n\r\n- Bug Report\r\n\r\n### Summary\r\n\r\nthe error occurs after start go-server:\r\n```\r\n2023-01-31 11:17:15,621 ERROR [qtp338329632-38] JDBCExceptionReporter:234 - You have an error in your \r\nSQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use \r\nnear '* FROM modifications \r\n) mods JOIN materials m ON mods.materialid=m.id WHERE mo' at line 1\r\n```\r\n\r\n### Environment\r\n\r\nmy system env:\r\n```\r\nCentos 7 - kernel-3.10.0-693\r\ngo-server-22.3.0-15301\r\nMySQL 8.0.23\r\n```\r\n\r\ndb.properties:\r\n```\r\n# /etc/go/db.properties\r\ndb.driver=com.mysql.cj.jdbc.Driver\r\ndb.url=jdbc:mysql://127.0.0.1:3301/gocd?useUnicode=true&characterEncoding=utf8&useSSL=false\r\ndb.user=user_gocd\r\ndb.password=xxxxxxxx\r\ndb.maxActive=32\r\ndb.maxIdle=32\r\n```\r\n### Steps to Reproduce\r\n\r\n1. start go-server \r\n2. click the `AGENTS` OR `MATERIALS` button on the gocd web\r\n3. check the error file /var/log/go-server/go-server.log\r\n\r\n### mysql query\r\n\r\n```\r\n2023-01-31 11:17:15| cli -> ser |【Query】 SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid)\r\n as max_id, * FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id;\r\n2023-01-31 11:17:15| ser -> cli |【Err】 Err code:1064,Err msg:42000You have an error in your SQL syntax; check the\r\n manual that corresponds to your MySQL server version for the right syntax to use near '* FROM modifications ) \r\nmods JOIN materials m ON mods.materialid=m.id WHERE mo' at line 1\r\n```\r\n\r\n### Possible Fix\r\n\r\nread more from [mysql8-select](https://dev.mysql.com/doc/refman/8.0/en/select.html).\r\n\r\nUse of an unqualified * with other items in the select list may produce a parse error. For example:\r\n```\r\nSELECT id, * FROM t1\r\n```\r\nto avoid this problem, use a qualified tbl_name.* reference:\r\n```\r\nSELECT id, t1.* FROM t1\r\n```\r\n\r\nSo we should change the sql:\r\n```\r\nSELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * FROM modifications ) \r\nmods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id;\r\n\r\n==>\r\n\r\nSELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, modifications.* FROM \r\nmodifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id;\r\n```"},"base_sha":{"kind":"string","value":"b3a6bad328f3e0e7e6739e6913f13499725c605c"},"head_sha":{"kind":"string","value":"c173255552af0656a9adbbd7c725d93ba8f62ab3"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/b3a6bad328f3e0e7e6739e6913f13499725c605c...c173255552af0656a9adbbd7c725d93ba8f62ab3"},"diff":{"kind":"string","value":"diff --git a/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java b/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java\nindex 8fe5c7ba3d..162fc4e57c 100644\n--- a/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java\n+++ b/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java\n@@ -1031,7 +1031,7 @@ public class MaterialRepository extends HibernateDaoSupport {\n public List getLatestModificationForEachMaterial() {\n String queryString = \"SELECT mods.* \" +\n \"FROM (\" +\n- \" SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * \" +\n+ \" SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, modifications.* \" +\n \" FROM modifications \" +\n \") mods \" +\n \"JOIN materials m ON mods.materialid=m.id \" +"},"changed_files":{"kind":"string","value":"['server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.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":15411055,"string":"15,411,055"},"repo_tokens_count":{"kind":"number","value":3088725,"string":"3,088,725"},"repo_lines_count":{"kind":"number","value":363908,"string":"363,908"},"repo_files_without_tests_count":{"kind":"number","value":3249,"string":"3,249"},"changed_symbols_count":{"kind":"number","value":181,"string":"181"},"changed_tokens_count":{"kind":"number","value":45,"string":"45"},"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":2265,"string":"2,265"},"issue_words_count":{"kind":"number","value":300,"string":"300"},"issue_tokens_count":{"kind":"number","value":632,"string":"632"},"issue_lines_count":{"kind":"number","value":72,"string":"72"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":7,"string":"7"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:55","string":"1970-01-01T00:27:55"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1358,"cells":{"id":{"kind":"number","value":397,"string":"397"},"text_id":{"kind":"string","value":"gocd/gocd/11874/11868"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/11868"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/11874"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/11874"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"`runOnAllAgents=\"true\"` added to jobs at GoCD startup"},"issue_body":{"kind":"string","value":"##### Issue Type\r\n\r\n\r\n\r\n- Bug Report\r\n\r\n##### Summary\r\n\r\n\r\n\r\nGoCD surprisingly adds `runOnAllAgents=\"true\"` to jobs.\r\n\r\n##### Environment\r\n\r\n\r\n\r\n👋 Let me know if you need this and I can share this individually, as it might contain sensitive information.\r\n\r\n###### Basic environment details\r\n\r\n\r\n\r\n* Go Version: `23.1.0 (16080-54a6971915ff8d402c9fea8cd2ceeb6e31c8cdc8)`\r\n* JAVA Version: `17.0.6`\r\n* OS: `Linux 5.10.176+`\r\n\r\n###### Additional Environment Details\r\n\r\n\r\n\r\n##### Steps to Reproduce\r\n\r\n1. Restarting GoCD\r\n\r\n##### Expected Results\r\n\r\n1. GoCD config behaving like before.\r\n\r\n##### Actual Results\r\n\r\n1. GoCD surprisingly adds `runOnAllAgents=\"true\"` to jobs.\r\n\r\n##### Possible Fix\r\n\r\n\r\n🤷 \r\n\r\n##### Log snippets\r\n\r\n\r\n##### Code snippets/Screenshots\r\n\r\nHere is an example of a commit GoCD makes:\r\n\r\n```diff\r\ncommit a29ab7eddd8a8d864f33a656f96ad1291abe53b7\r\nAuthor: Upgrade \r\nDate: Fri Aug 11 05:11:37 2023 +0000\r\n\r\n user:Upgrade|timestamp:1691730697644|schema_version:139|go_edition:OpenSource|go_version:23.1.0 (16080-54a6971915ff8d402c9fea8cd2ceeb6e31c8cdc8)|md5:536dedf85183254cabe2192eb1f7c5e2\r\n\r\ndiff --git a/cruise-config.xml b/cruise-config.xml\r\nindex 5234ae934..65a8023b5 100644\r\n--- a/cruise-config.xml\r\n+++ b/cruise-config.xml\r\n@@ -34838,7 +34838,7 @@ fi\r\n \r\n \r\n \r\n- \r\n+ \r\n \r\n \r\n \r\n```\r\n\r\n\r\n##### Any other info\r\n\r\n"},"base_sha":{"kind":"string","value":"9a9a12047df94036b92106d4296555278eb7bce6"},"head_sha":{"kind":"string","value":"04e6ccb02476a095b12ff09f909a93bee210d2dd"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/9a9a12047df94036b92106d4296555278eb7bce6...04e6ccb02476a095b12ff09f909a93bee210d2dd"},"diff":{"kind":"string","value":"diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java b/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java\nindex 3087dc0b1f..de6c0c0a5f 100644\n--- a/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java\n+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java\n@@ -19,7 +19,6 @@ import com.thoughtworks.go.config.parser.GoConfigFieldTypeConverter;\n import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry;\n import com.thoughtworks.go.util.ConfigUtil;\n import org.jdom2.Element;\n-import org.springframework.beans.SimpleTypeConverter;\n import org.springframework.beans.TypeMismatchException;\n \n import java.lang.reflect.Field;\n@@ -33,23 +32,17 @@ public class GoConfigFieldWriter {\n private final ConfigUtil configUtil = new ConfigUtil(\"magic\");\n private final Field configField;\n private final Object value;\n- private final SimpleTypeConverter typeConverter;\n private final ConfigCache configCache;\n private final ConfigElementImplementationRegistry registry;\n \n- public GoConfigFieldWriter(Field declaredField, Object value, SimpleTypeConverter converter, ConfigCache configCache, final ConfigElementImplementationRegistry registry) {\n+ public GoConfigFieldWriter(Field declaredField, Object value, ConfigCache configCache, final ConfigElementImplementationRegistry registry) {\n this.configField = declaredField;\n this.value = value;\n this.configField.setAccessible(true);\n- this.typeConverter = converter;\n this.configCache = configCache;\n this.registry = registry;\n }\n \n- public GoConfigFieldWriter(Field declaredField, Object value, ConfigCache configCache, final ConfigElementImplementationRegistry registry) {\n- this(declaredField, value, new GoConfigFieldTypeConverter(), configCache, registry);\n- }\n-\n public Field getConfigField() {\n return configField;\n }\n@@ -78,7 +71,7 @@ public class GoConfigFieldWriter {\n try {\n setFieldIfNotNull(configField, o, val);\n } catch (TypeMismatchException e1) {\n- final String message = format(\"Could not set value [{0}] on Field [{1}] of type [{2}] \", val,\n+ final String message = format(\"Could not set value [{0}] on field [{1}] of type [{2}] \", val,\n configField.getName(), configField.getType());\n throw new RuntimeException(message, e1);\n }\n@@ -87,9 +80,7 @@ public class GoConfigFieldWriter {\n private void bombIfNullAndNotAllowed(Field field, Object instance, ConfigAttribute attribute) {\n try {\n if (!attribute.allowNull()) {\n- bombIfNull(field.get(instance),\n- () -> \"Field '\" + field.getName() + \"' is still set to null. \"\n- + \"Must give a default value.\");\n+ bombIfNull(field.get(instance), () -> \"Field '\" + field.getName() + \"' is still set to null. Must give a default value.\");\n }\n } catch (IllegalAccessException e) {\n throw bomb(\"Error getting configField: \" + field.getName(), e);\n@@ -99,7 +90,7 @@ public class GoConfigFieldWriter {\n private void setFieldIfNotNull(Field field, Object instance, Object val) {\n try {\n if (val != null) {\n- Object convertedValue = typeConverter.convertIfNecessary(val, configField.getType());\n+ Object convertedValue = GoConfigFieldTypeConverter.forThread().convertIfNecessary(val, configField.getType());\n field.set(instance, convertedValue);\n }\n } catch (IllegalAccessException e) {\n@@ -107,15 +98,15 @@ public class GoConfigFieldWriter {\n }\n }\n \n-@SuppressWarnings({\"DataFlowIssue\", \"unchecked\"})\n-private Collection parseCollection(Element e, Class collectionType) {\n+ @SuppressWarnings({\"DataFlowIssue\", \"unchecked\"})\n+ private Collection parseCollection(Element e, Class collectionType) {\n ConfigCollection collection = collectionType.getAnnotation(ConfigCollection.class);\n Class type = collection.value();\n \n \n Object o = newInstance(collectionType);\n bombUnless(o instanceof Collection,\n- () -> \"Must be some sort of list. Was: \" + collectionType.getName());\n+ () -> \"Must be some sort of list. Was: \" + collectionType.getName());\n \n Collection baseCollection = (Collection) o;\n for (Element childElement : e.getChildren()) {\n@@ -124,7 +115,7 @@ private Collection parseCollection(Element e, Class collectionType) {\n }\n }\n bombIf(baseCollection.size() < collection.minimum(),\n- () -> \"Required at least \" + collection.minimum() + \" subelements to '\" + e.getName() + \"'. \"\n+ () -> \"Required at least \" + collection.minimum() + \" subelements to '\" + e.getName() + \"'. \"\n + \"Found \" + baseCollection.size() + \".\");\n return baseCollection;\n }\n@@ -192,7 +183,7 @@ private Collection parseCollection(Element e, Class collectionType) {\n ConfigTag tag = configTag(field.getType());\n boolean optional = field.getAnnotation(ConfigSubtag.class).optional();\n boolean isMissingElement = !configUtil.hasChild(e, tag);\n- if(!optional && isMissingElement) {\n+ if (!optional && isMissingElement) {\n throw bomb(\"Non optional tag '\" + tag + \"' is not in config file. Found: \" + configUtil.elementOutput(e));\n }\n return optional && isMissingElement;\n@@ -201,7 +192,7 @@ private Collection parseCollection(Element e, Class collectionType) {\n private boolean optionalAndMissingAttribute(Element e, ConfigAttribute attribute) {\n boolean optional = attribute.optional();\n boolean isMissingAttribute = !configUtil.hasAttribute(e, attribute.value());\n- if(!optional && isMissingAttribute) {\n+ if (!optional && isMissingAttribute) {\n throw bomb(\"Non optional attribute '\" + attribute.value() + \"' is not in element: \" + configUtil.elementOutput(e));\n }\n return optional && isMissingAttribute;\ndiff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java b/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java\nindex d7c9ff96b2..40b88dd33a 100644\n--- a/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java\n+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java\n@@ -15,16 +15,25 @@\n */\n package com.thoughtworks.go.config.parser;\n \n-import java.io.File;\n-\n+import org.apache.commons.lang3.StringUtils;\n import org.springframework.beans.SimpleTypeConverter;\n+import org.springframework.beans.TypeConverter;\n import org.springframework.beans.propertyeditors.FileEditor;\n-import org.apache.commons.lang3.StringUtils;\n+\n+import java.io.File;\n \n public class GoConfigFieldTypeConverter extends SimpleTypeConverter {\n \n+ public static TypeConverter forThread() {\n+ return typeConverter.get();\n+ }\n+\n private static final CustomizedFileEditor propertyEditor = new CustomizedFileEditor();\n \n+ // Type converters are NOT thread safe. Should be OK to cache them per thread as not too large and don't think\n+ // we have too many threads that will be doing so?\n+ private static final ThreadLocal typeConverter = ThreadLocal.withInitial(GoConfigFieldTypeConverter::new);\n+\n public GoConfigFieldTypeConverter() {\n super();\n this.registerCustomEditor(File.class, propertyEditor);\ndiff --git a/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java b/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java\ndeleted file mode 100644\nindex 6a70e36071..0000000000\n--- a/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java\n+++ /dev/null\n@@ -1,40 +0,0 @@\n-/*\n- * Copyright 2023 Thoughtworks, Inc.\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- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package com.thoughtworks.go.config.parser;\n-\n-import java.beans.PropertyEditor;\n-import java.io.File;\n-import java.lang.reflect.Field;\n-import java.lang.reflect.Modifier;\n-\n-import com.thoughtworks.go.util.ReflectionUtil;\n-import org.junit.jupiter.api.Test;\n-\n-import static org.hamcrest.Matchers.is;\n-import static org.hamcrest.MatcherAssert.assertThat;\n-\n-public class GoConfigFieldTypeConverterTest {\n- @Test\n- public void shouldOnlyCreateOneInstanceOfCustomizedFileEditorAndUseIt() throws Exception {\n- GoConfigFieldTypeConverter converter = new GoConfigFieldTypeConverter();\n- Field expectedField = converter.getClass().getDeclaredField(\"propertyEditor\");\n- int modifier = expectedField.getModifiers();\n- assertThat(Modifier.isStatic(modifier), is(true));\n- assertThat(Modifier.isFinal(modifier), is(true));\n- PropertyEditor actual = converter.findCustomEditor(File.class, null);\n- assertThat(actual, is(ReflectionUtil.getStaticField(converter.getClass(), \"propertyEditor\")));\n- }\n-}\ndiff --git a/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java b/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java\nindex 8891250284..e90d5fb7ba 100644\n--- a/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java\n+++ b/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java\n@@ -20,14 +20,13 @@ import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry;\n import com.thoughtworks.go.security.GoCipher;\n import org.jdom2.Attribute;\n import org.jdom2.Element;\n-import org.springframework.beans.SimpleTypeConverter;\n import org.springframework.beans.TypeMismatchException;\n \n import java.lang.reflect.Constructor;\n import java.lang.reflect.Field;\n import java.lang.reflect.InvocationTargetException;\n-import java.util.HashMap;\n import java.util.Map;\n+import java.util.concurrent.ConcurrentHashMap;\n \n import static com.thoughtworks.go.config.ConfigCache.isAnnotationPresent;\n import static com.thoughtworks.go.config.parser.GoConfigAttributeLoader.attributeParser;\n@@ -38,8 +37,7 @@ import static com.thoughtworks.go.util.ExceptionUtils.bomb;\n import static java.text.MessageFormat.format;\n \n public class GoConfigFieldLoader {\n- private static final Map implicits = new HashMap<>();\n- private static final SimpleTypeConverter typeConverter = new GoConfigFieldTypeConverter();\n+ private static final Map implicits = new ConcurrentHashMap<>();\n \n private final Element e;\n private final T instance;\n@@ -49,7 +47,7 @@ public class GoConfigFieldLoader {\n private final ConfigElementImplementationRegistry registry;\n \n public static GoConfigFieldLoader fieldParser(Element e, T instance, Field field, ConfigCache configCache, final ConfigElementImplementationRegistry registry,\n- ConfigReferenceElements configReferenceElements) {\n+ ConfigReferenceElements configReferenceElements) {\n return new GoConfigFieldLoader<>(e, instance, field, configCache, registry, configReferenceElements);\n }\n \n@@ -93,11 +91,8 @@ public class GoConfigFieldLoader {\n }\n \n private boolean isImplicitCollection() {\n- if (!implicits.containsKey(field)) {\n- implicits.put(field, ConfigCache.isAnnotationPresent(field, ConfigSubtag.class)\n- && GoConfigClassLoader.isImplicitCollection(field.getType()));\n- }\n- return implicits.get(field);\n+ return implicits.computeIfAbsent(field,\n+ f -> ConfigCache.isAnnotationPresent(f, ConfigSubtag.class) && GoConfigClassLoader.isImplicitCollection(f.getType()));\n }\n \n private void setValue(Object val) {\n@@ -109,13 +104,12 @@ public class GoConfigFieldLoader {\n field.set(instance, constructor.newInstance(val));\n }\n } else if (val != null) {\n- Object convertedValue = typeConverter.convertIfNecessary(val, field.getType());\n- field.set(instance, convertedValue);\n+ field.set(instance, GoConfigFieldTypeConverter.forThread().convertIfNecessary(val, field.getType()));\n }\n } catch (IllegalAccessException e) {\n throw bomb(\"Error setting configField: \" + field.getName(), e);\n } catch (TypeMismatchException e) {\n- final String message = format(\"Could not set value [{0}] on Field [{1}] of type [{2}] \",\n+ final String message = format(\"Could not set value [{0}] on field [{1}] of type [{2}] \",\n val, field.getName(), field.getType());\n throw bomb(message, e);\n } catch (NoSuchMethodException e) {\ndiff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java\ndeleted file mode 100644\nindex 7d221b5f32..0000000000\n--- a/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java\n+++ /dev/null\n@@ -1,39 +0,0 @@\n-/*\n- * Copyright 2023 Thoughtworks, Inc.\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- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package com.thoughtworks.go.config.parser;\n-\n-import java.lang.reflect.Field;\n-import java.lang.reflect.Modifier;\n-\n-import org.junit.jupiter.api.Test;\n-\n-import static org.hamcrest.Matchers.is;\n-import static org.hamcrest.MatcherAssert.assertThat;\n-\n-public class GoConfigFieldLoaderTest {\n-\n- @Test\n- public void shouldOnlyCreateOneInstanceOfSimpleTypeConverterAndUseIt() throws Exception {\n- Integer dummyValue = 0;\n- Field randomField = dummyValue.getClass().getDeclaredFields()[0]; // Random field because I can't mock java.lang.reflect.Field (Sachin)\n- GoConfigFieldLoader loader = GoConfigFieldLoader.fieldParser(null, null, randomField, null, null, new ConfigReferenceElements());\n- Field expectedField = loader.getClass().getDeclaredField(\"typeConverter\");\n- int modifier = expectedField.getModifiers();\n- assertThat(Modifier.isStatic(modifier), is(true));\n- assertThat(Modifier.isFinal(modifier), is(true));\n- }\n-}\n-"},"changed_files":{"kind":"string","value":"['config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java', 'config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java', 'config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.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":15198620,"string":"15,198,620"},"repo_tokens_count":{"kind":"number","value":3045503,"string":"3,045,503"},"repo_lines_count":{"kind":"number","value":359172,"string":"359,172"},"repo_files_without_tests_count":{"kind":"number","value":3182,"string":"3,182"},"changed_symbols_count":{"kind":"number","value":4463,"string":"4,463"},"changed_tokens_count":{"kind":"number","value":843,"string":"843"},"changed_lines_count":{"kind":"number","value":64,"string":"64"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":2831,"string":"2,831"},"issue_words_count":{"kind":"number","value":347,"string":"347"},"issue_tokens_count":{"kind":"number","value":748,"string":"748"},"issue_lines_count":{"kind":"number","value":97,"string":"97"},"issue_links_count":{"kind":"number","value":1,"string":"1"},"issue_code_blocks_count":{"kind":"number","value":3,"string":"3"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:28:12","string":"1970-01-01T00:28:12"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1359,"cells":{"id":{"kind":"number","value":395,"string":"395"},"text_id":{"kind":"string","value":"gocd/gocd/631/548"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/548"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/631"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/548#issuecomment-58576865"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Polling and builds fail when a git submodule URL changes"},"issue_body":{"kind":"string","value":"This causes `git submodule update --init` to fail which means material updates fail and builds running on the agent fail if they have the stale submodule url:\n\n```\ngit submodule update --init\n--- Environment ---\n{}\n--- INPUT ----\n\n\n--OUTPUT ---\n\nERROR: fatal: reference is not a tree: 176026c856dd4cecd80fcdd5fe904fbc9f4c1385\nERROR: Unable to checkout '176026c856dd4cecd80fcdd5fe904fbc9f4c1385' in submodule path 'src/gnatsd'\n```\n\n`git submodule sync` is needed to refresh the submodule url.\n\nThis is time consuming to recover from because the fix involves running git submodule sync on the flyweights on the server and all copies on the agents which have stale urls.\n"},"base_sha":{"kind":"string","value":"c08ce3bedd2bccb769537e6d811283a57782a842"},"head_sha":{"kind":"string","value":"89442cfbb75236c00391d846bf2364ef4beef4cd"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/c08ce3bedd2bccb769537e6d811283a57782a842...89442cfbb75236c00391d846bf2364ef4beef4cd"},"diff":{"kind":"string","value":"diff --git a/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java b/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java\nindex 65d377c49a..849470b65d 100644\n--- a/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java\n+++ b/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java\n@@ -149,7 +149,7 @@ public class GitCommand extends SCMCommand {\n run(gitCmd, outputStreamConsumer);\n }\n \n- private void resetHard(ProcessOutputStreamConsumer outputStreamConsumer, Revision revision) {\n+ public void resetHard(ProcessOutputStreamConsumer outputStreamConsumer, Revision revision) {\n outputStreamConsumer.stdOutput(\"[GIT] Updating working copy to revision \" + revision.getRevision());\n String[] args = new String[]{\"reset\", \"--hard\", revision.getRevision()};\n CommandLine gitCmd = git().withArgs(args).withWorkingDir(workingDir);\n@@ -172,9 +172,17 @@ public class GitCommand extends SCMCommand {\n return;\n }\n outputStreamConsumer.stdOutput(\"[GIT] Updating git sub-modules\");\n- String[] args = new String[]{\"submodule\", \"update\", \"--init\"};\n- CommandLine gitCmd = git().withArgs(args).withWorkingDir(workingDir);\n- runOrBomb(gitCmd);\n+\n+ String[] initArgs = new String[]{\"submodule\", \"init\"};\n+ CommandLine initCmd = git().withArgs(initArgs).withWorkingDir(workingDir);\n+ runOrBomb(initCmd);\n+\n+ submoduleSync();\n+\n+ String[] updateArgs = new String[]{\"submodule\", \"update\"};\n+ CommandLine updateCmd = git().withArgs(updateArgs).withWorkingDir(workingDir);\n+ runOrBomb(updateCmd);\n+\n outputStreamConsumer.stdOutput(\"[GIT] Cleaning unversioned files and sub-modules\");\n printSubmoduleStatus(outputStreamConsumer);\n }\n@@ -259,7 +267,7 @@ public class GitCommand extends SCMCommand {\n runOrBomb(gitCmd);\n }\n \n- private void fetch(ProcessOutputStreamConsumer outputStreamConsumer) {\n+ public void fetch(ProcessOutputStreamConsumer outputStreamConsumer) {\n outputStreamConsumer.stdOutput(\"[GIT] Fetching changes\");\n CommandLine gitFetch = git().withArgs(\"fetch\", \"origin\").withWorkingDir(workingDir);\n \n@@ -357,4 +365,20 @@ public class GitCommand extends SCMCommand {\n ConsoleResult consoleResult = runOrBomb(getCurrentBranchCommand);\n return consoleResult.outputAsString();\n }\n+\n+ public void changeSubmoduleUrl(String submoduleName, String newUrl) {\n+ String[] args = new String[]{\"config\", \"--file\", \".gitmodules\", \"submodule.\" + submoduleName + \".url\", newUrl};\n+ CommandLine gitConfig = git().withArgs(args).withWorkingDir(workingDir);\n+ runOrBomb(gitConfig);\n+ }\n+\n+ public void submoduleSync() {\n+ String[] syncArgs = new String[]{\"submodule\", \"sync\"};\n+ CommandLine syncCmd = git().withArgs(syncArgs).withWorkingDir(workingDir);\n+ runOrBomb(syncCmd);\n+\n+ String[] foreachArgs = new String[]{\"submodule\", \"foreach\", \"--recursive\", \"git\", \"submodule\", \"sync\"};\n+ CommandLine foreachCmd = git().withArgs(foreachArgs).withWorkingDir(workingDir);\n+ runOrBomb(foreachCmd);\n+ }\n }\ndiff --git a/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java b/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java\nindex 7094807e96..36a7804cc2 100644\n--- a/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java\n+++ b/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java\n@@ -445,6 +445,24 @@ public class GitCommandTest {\n clonedCopy.fetchAndReset(outputStreamConsumer, new StringRevision(\"HEAD\"));\n }\n \n+ @Test\n+ public void shouldAllowSubmoduleUrlstoChange() throws Exception {\n+ InMemoryStreamConsumer outputStreamConsumer = inMemoryConsumer();\n+ GitSubmoduleRepos submoduleRepos = new GitSubmoduleRepos();\n+ String submoduleDirectoryName = \"local-submodule\";\n+ File cloneDirectory = createTempWorkingDirectory();\n+\n+ File remoteSubmoduleLocation = submoduleRepos.addSubmodule(SUBMODULE, submoduleDirectoryName);\n+\n+ GitCommand clonedCopy = new GitCommand(null, cloneDirectory, GitMaterialConfig.DEFAULT_BRANCH, false);\n+ clonedCopy.cloneFrom(outputStreamConsumer, submoduleRepos.mainRepo().getUrl());\n+ clonedCopy.fetchAndResetToHead(outputStreamConsumer);\n+\n+ submoduleRepos.changeSubmoduleUrl(submoduleDirectoryName);\n+\n+ clonedCopy.fetchAndResetToHead(outputStreamConsumer);\n+ }\n+\n private List allFilesIn(File directory, String prefixOfFiles) {\n return new ArrayList(FileUtils.listFiles(directory, andFileFilter(fileFileFilter(), prefixFileFilter(prefixOfFiles)), null));\n }\ndiff --git a/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java b/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java\nindex 6f4787a81b..423ad2fa4f 100644\n--- a/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java\n+++ b/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java\n@@ -21,6 +21,7 @@ import com.thoughtworks.go.config.materials.git.GitMaterialConfig;\n import com.thoughtworks.go.domain.materials.Modification;\n import com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;\n import com.thoughtworks.go.domain.materials.git.GitCommand;\n+import com.thoughtworks.go.domain.materials.mercurial.StringRevision;\n import com.thoughtworks.go.util.TestFileUtil;\n import org.apache.commons.io.FileUtils;\n \n@@ -137,4 +138,18 @@ public class GitSubmoduleRepos extends TestRepo {\n @Override public GitMaterial material() {\n return new GitMaterial(remoteRepoDir.getAbsolutePath());\n }\n+\n+ public void changeSubmoduleUrl(String submoduleName) throws Exception {\n+ File newSubmodule = createRepo(\"new-submodule\");\n+ addAndCommitNewFile(newSubmodule, \"new\", \"make a commit\");\n+\n+ git(remoteRepoDir).changeSubmoduleUrl(submoduleName, newSubmodule.getAbsolutePath());\n+ git(remoteRepoDir).submoduleSync();\n+\n+ git(new File(remoteRepoDir, \"local-submodule\")).fetch(inMemoryConsumer());\n+ git(new File(remoteRepoDir, \"local-submodule\")).resetHard(inMemoryConsumer(), new StringRevision(\"origin/master\"));\n+ git(remoteRepoDir).add(new File(\".gitmodules\"));\n+ git(remoteRepoDir).add(new File(\"local-submodule\"));\n+ git(remoteRepoDir).commit(\"change submodule url\");\n+ }\n }"},"changed_files":{"kind":"string","value":"['common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java', 'common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java', 'common/src/com/thoughtworks/go/domain/materials/git/GitCommand.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":7018116,"string":"7,018,116"},"repo_tokens_count":{"kind":"number","value":1409995,"string":"1,409,995"},"repo_lines_count":{"kind":"number","value":184079,"string":"184,079"},"repo_files_without_tests_count":{"kind":"number","value":1644,"string":"1,644"},"changed_symbols_count":{"kind":"number","value":1700,"string":"1,700"},"changed_tokens_count":{"kind":"number","value":362,"string":"362"},"changed_lines_count":{"kind":"number","value":34,"string":"34"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":673,"string":"673"},"issue_words_count":{"kind":"number","value":101,"string":"101"},"issue_tokens_count":{"kind":"number","value":174,"string":"174"},"issue_lines_count":{"kind":"number","value":19,"string":"19"},"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:23:32","string":"1970-01-01T00:23:32"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1360,"cells":{"id":{"kind":"number","value":407,"string":"407"},"text_id":{"kind":"string","value":"gocd/gocd/7738/7737"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/7737"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/7738"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/7738"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Issues with moving pipelines between groups"},"issue_body":{"kind":"string","value":"##### Issue Type\r\n- Bug Report\r\n\r\n##### Summary\r\n\r\nMoving pipelines between groups on the pipelines page fails if the given pipeline has a dependency material defined and uses parameters to define the upstream pipeline.\r\n\r\nIf a dependency material is defined without a name, the name defaults to the pipeline name. If the name of the upstream pipeline is a parameter then on update(in this pipeline group move) to the pipeline would fail for material name validation, as the material can only be alphanumeric. \r\n"},"base_sha":{"kind":"string","value":"fbe640c871dfe4bff5b3e3ddead658e6ca9694a0"},"head_sha":{"kind":"string","value":"504b1403e2f25ab90650f9590fd6f0562ce55c4b"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/fbe640c871dfe4bff5b3e3ddead658e6ca9694a0...504b1403e2f25ab90650f9590fd6f0562ce55c4b"},"diff":{"kind":"string","value":"diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java\nindex b1e9b4bf15..d86ea9bef4 100644\n--- a/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java\n+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java\n@@ -80,11 +80,6 @@ public class DependencyMaterialConfig extends AbstractMaterialConfig implements\n this.ignoreForScheduling = ignoreForScheduling;\n }\n \n- @Override\n- public CaseInsensitiveString getName() {\n- return super.getName() == null ? pipelineName : super.getName();\n- }\n-\n public String getUserName() {\n return \"cruise\";\n }\n@@ -207,7 +202,8 @@ public class DependencyMaterialConfig extends AbstractMaterialConfig implements\n \n @Override\n public String getDisplayName() {\n- return CaseInsensitiveString.str(getName());\n+ CaseInsensitiveString name = getName() == null ? pipelineName : getName();\n+ return name.toString();\n }\n \n @Override\ndiff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java\nindex 7d23231b7b..d8f4d38e79 100644\n--- a/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java\n+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java\n@@ -26,8 +26,9 @@ import com.thoughtworks.go.domain.materials.dependency.NewGoConfigMother;\n import com.thoughtworks.go.helper.GoConfigMother;\n import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother;\n import org.apache.commons.io.IOUtils;\n-import org.junit.Before;\n-import org.junit.Test;\n+import org.junit.jupiter.api.BeforeEach;\n+import org.junit.jupiter.api.Nested;\n+import org.junit.jupiter.api.Test;\n \n import java.io.ByteArrayInputStream;\n import java.io.ByteArrayOutputStream;\n@@ -36,18 +37,17 @@ import java.util.Map;\n \n import static com.thoughtworks.go.helper.MaterialConfigsMother.p4;\n import static java.nio.charset.StandardCharsets.UTF_8;\n-import static org.hamcrest.Matchers.*;\n-import static org.junit.Assert.assertThat;\n+import static org.assertj.core.api.Assertions.assertThat;\n \n-public class DependencyMaterialConfigTest {\n+class DependencyMaterialConfigTest {\n \n private MagicalGoConfigXmlWriter writer;\n private MagicalGoConfigXmlLoader loader;\n private CruiseConfig config;\n private PipelineConfig pipelineConfig;\n \n- @Before\n- public void setUp() throws Exception {\n+ @BeforeEach\n+ void setUp() {\n writer = new MagicalGoConfigXmlWriter(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins());\n loader = new MagicalGoConfigXmlLoader(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins());\n config = GoConfigMother.configWithPipelines(\"pipeline1\", \"pipeline2\", \"pipeline3\", \"go\");\n@@ -55,16 +55,16 @@ public class DependencyMaterialConfigTest {\n }\n \n @Test\n- public void shouldBeAbleToLoadADependencyMaterialFromConfig() throws Exception {\n+ void shouldBeAbleToLoadADependencyMaterialFromConfig() throws Exception {\n String xml = \"\";\n DependencyMaterialConfig material = loader.fromXmlPartial(xml, DependencyMaterialConfig.class);\n- assertThat(material.getPipelineName(), is(new CaseInsensitiveString(\"pipeline-name\")));\n- assertThat(material.getStageName(), is(new CaseInsensitiveString(\"stage-name\")));\n- assertThat(writer.toXmlPartial(material), is(xml));\n+ assertThat(material.getPipelineName()).isEqualTo(new CaseInsensitiveString(\"pipeline-name\"));\n+ assertThat(material.getStageName()).isEqualTo(new CaseInsensitiveString(\"stage-name\"));\n+ assertThat(writer.toXmlPartial(material)).isEqualTo(xml);\n }\n \n @Test\n- public void shouldBeAbleToSaveADependencyMaterialToConfig() throws Exception {\n+ void shouldBeAbleToSaveADependencyMaterialToConfig() throws Exception {\n DependencyMaterialConfig originalMaterial = new DependencyMaterialConfig(new CaseInsensitiveString(\"pipeline-name\"), new CaseInsensitiveString(\"stage-name\"));\n \n NewGoConfigMother mother = new NewGoConfigMother();\n@@ -79,13 +79,13 @@ public class DependencyMaterialConfigTest {\n CruiseConfig config = loader.loadConfigHolder(IOUtils.toString(inputStream, UTF_8)).config;\n \n DependencyMaterialConfig material = (DependencyMaterialConfig) config.pipelineConfigByName(new CaseInsensitiveString(\"dependent\")).materialConfigs().get(1);\n- assertThat(material, is(originalMaterial));\n- assertThat(material.getPipelineName(), is(new CaseInsensitiveString(\"pipeline-name\")));\n- assertThat(material.getStageName(), is(new CaseInsensitiveString(\"stage-name\")));\n+ assertThat(material).isEqualTo(originalMaterial);\n+ assertThat(material.getPipelineName()).isEqualTo(new CaseInsensitiveString(\"pipeline-name\"));\n+ assertThat(material.getStageName()).isEqualTo(new CaseInsensitiveString(\"stage-name\"));\n }\n \n @Test\n- public void shouldBeAbleToHaveADependencyAndOneOtherMaterial() throws Exception {\n+ void shouldBeAbleToHaveADependencyAndOneOtherMaterial() throws Exception {\n NewGoConfigMother mother = new NewGoConfigMother();\n mother.addPipeline(\"pipeline-name\", \"stage-name\", \"job-name\");\n PipelineConfig pipelineConfig = mother.addPipeline(\"dependent\", \"stage-name\", \"job-name\",\n@@ -102,62 +102,62 @@ public class DependencyMaterialConfigTest {\n CruiseConfig config = loader.loadConfigHolder(IOUtils.toString(inputStream, UTF_8)).config;\n \n MaterialConfigs materialConfigs = config.pipelineConfigByName(new CaseInsensitiveString(\"dependent\")).materialConfigs();\n- assertThat(materialConfigs.get(0), is(instanceOf(DependencyMaterialConfig.class)));\n- assertThat(materialConfigs.get(1), is(instanceOf(P4MaterialConfig.class)));\n+ assertThat(materialConfigs.get(0)).isInstanceOf(DependencyMaterialConfig.class);\n+ assertThat(materialConfigs.get(1)).isInstanceOf(P4MaterialConfig.class);\n }\n \n @Test\n- public void shouldAddErrorForInvalidMaterialName() {\n+ void shouldAddErrorForInvalidMaterialName() {\n DependencyMaterialConfig materialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"wrong name\"), new CaseInsensitiveString(\"pipeline-foo\"), new CaseInsensitiveString(\"stage-bar\"));\n materialConfig.validate(ConfigSaveValidationContext.forChain(new BasicCruiseConfig(), pipelineConfig));\n- assertThat(materialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME), is(\"Invalid material name 'wrong name'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.\"));\n+ assertThat(materialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME)).isEqualTo(\"Invalid material name 'wrong name'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.\");\n }\n \n @Test\n- public void shouldAddErrorWhenInvalidPipelineNameStage() {\n+ void shouldAddErrorWhenInvalidPipelineNameStage() {\n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig();\n Map configMap = new HashMap<>();\n configMap.put(DependencyMaterialConfig.PIPELINE_STAGE_NAME, \"invalid pipeline stage\");\n \n dependencyMaterialConfig.setConfigAttributes(configMap);\n \n- assertThat(dependencyMaterialConfig.getPipelineStageName(), is(\"invalid pipeline stage\"));\n- assertThat(dependencyMaterialConfig.errors().isEmpty(), is(false));\n- assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), is(\"'invalid pipeline stage' should conform to the pattern 'pipeline [stage]'\"));\n+ assertThat(dependencyMaterialConfig.getPipelineStageName()).isEqualTo(\"invalid pipeline stage\");\n+ assertThat(dependencyMaterialConfig.errors().isEmpty()).isFalse();\n+ assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).isEqualTo(\"'invalid pipeline stage' should conform to the pattern 'pipeline [stage]'\");\n }\n \n @Test\n- public void shouldNotBombValidationWhenMaterialNameIsNotSet() {\n+ void shouldNotBombValidationWhenMaterialNameIsNotSet() {\n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"pipeline-foo\"), new CaseInsensitiveString(\"stage-bar\"));\n dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(new BasicCruiseConfig(), pipelineConfig));\n- assertThat(dependencyMaterialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME), is(nullValue()));\n+ assertThat(dependencyMaterialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME)).isNull();\n }\n \n @Test\n- public void shouldNOTBeValidIfThePipelineExistsButTheStageDoesNot() throws Exception {\n+ void shouldNOTBeValidIfThePipelineExistsButTheStageDoesNot() throws Exception {\n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"pipeline2\"), new CaseInsensitiveString(\"stage-not-existing does not exist!\"));\n dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(config, pipelineConfig));\n ConfigErrors configErrors = dependencyMaterialConfig.errors();\n- assertThat(configErrors.isEmpty(), is(false));\n- assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), containsString(\"Stage with name 'stage-not-existing does not exist!' does not exist on pipeline 'pipeline2'\"));\n+ assertThat(configErrors.isEmpty()).isFalse();\n+ assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).contains(\"Stage with name 'stage-not-existing does not exist!' does not exist on pipeline 'pipeline2'\");\n }\n \n @Test\n- public void shouldNOTBeValidIfTheReferencedPipelineDoesNotExist() throws Exception {\n+ void shouldNOTBeValidIfTheReferencedPipelineDoesNotExist() throws Exception {\n CruiseConfig config = GoConfigMother.configWithPipelines(\"pipeline1\", \"pipeline2\", \"pipeline3\", \"go\");\n \n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"pipeline-not-exist\"), new CaseInsensitiveString(\"stage\"));\n dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(config, pipelineConfig));\n ConfigErrors configErrors = dependencyMaterialConfig.errors();\n- assertThat(configErrors.isEmpty(), is(false));\n- assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), containsString(\"Pipeline with name 'pipeline-not-exist' does not exist\"));\n+ assertThat(configErrors.isEmpty()).isFalse();\n+ assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).contains(\"Pipeline with name 'pipeline-not-exist' does not exist\");\n }\n \n @Test\n- public void setConfigAttributes_shouldPopulateFromConfigAttributes() {\n+ void setConfigAttributes_shouldPopulateFromConfigAttributes() {\n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"\"), new CaseInsensitiveString(\"\"));\n- assertThat(dependencyMaterialConfig.getPipelineStageName(), is(nullValue()));\n- assertThat(dependencyMaterialConfig.ignoreForScheduling(), is(false));\n+ assertThat(dependencyMaterialConfig.getPipelineStageName()).isNull();\n+ assertThat(dependencyMaterialConfig.ignoreForScheduling()).isFalse();\n HashMap configMap = new HashMap<>();\n configMap.put(AbstractMaterialConfig.MATERIAL_NAME, \"name1\");\n configMap.put(DependencyMaterialConfig.PIPELINE_STAGE_NAME, \"pipeline-1 [stage-1]\");\n@@ -165,30 +165,64 @@ public class DependencyMaterialConfigTest {\n \n dependencyMaterialConfig.setConfigAttributes(configMap);\n \n- assertThat(dependencyMaterialConfig.getMaterialName(), is(new CaseInsensitiveString(\"name1\")));\n- assertThat(dependencyMaterialConfig.getPipelineName(), is(new CaseInsensitiveString(\"pipeline-1\")));\n- assertThat(dependencyMaterialConfig.getStageName(), is(new CaseInsensitiveString(\"stage-1\")));\n- assertThat(dependencyMaterialConfig.getPipelineStageName(), is(\"pipeline-1 [stage-1]\"));\n- assertThat(dependencyMaterialConfig.ignoreForScheduling(), is(true));\n+ assertThat(dependencyMaterialConfig.getMaterialName()).isEqualTo(new CaseInsensitiveString(\"name1\"));\n+ assertThat(dependencyMaterialConfig.getPipelineName()).isEqualTo(new CaseInsensitiveString(\"pipeline-1\"));\n+ assertThat(dependencyMaterialConfig.getStageName()).isEqualTo(new CaseInsensitiveString(\"stage-1\"));\n+ assertThat(dependencyMaterialConfig.getPipelineStageName()).isEqualTo(\"pipeline-1 [stage-1]\");\n+ assertThat(dependencyMaterialConfig.ignoreForScheduling()).isTrue();\n }\n \n @Test\n- public void setConfigAttributes_shouldNotPopulateNameFromConfigAttributesIfNameIsEmptyOrNull() {\n+ void setConfigAttributes_shouldNotPopulateNameFromConfigAttributesIfNameIsEmptyOrNull() {\n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"name2\"), new CaseInsensitiveString(\"pipeline\"), new CaseInsensitiveString(\"stage\"));\n HashMap configMap = new HashMap<>();\n configMap.put(AbstractMaterialConfig.MATERIAL_NAME, \"\");\n \n dependencyMaterialConfig.setConfigAttributes(configMap);\n \n- assertThat(dependencyMaterialConfig.getMaterialName(), is(nullValue()));\n+ assertThat(dependencyMaterialConfig.getMaterialName()).isNull();\n }\n \n @Test\n- public void shouldValidateTree() {\n+ void shouldValidateTree() {\n DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"upstream_stage\"), new CaseInsensitiveString(\"upstream_pipeline\"), new CaseInsensitiveString(\"stage\"));\n PipelineConfig pipeline = new PipelineConfig(new CaseInsensitiveString(\"p\"), new MaterialConfigs());\n pipeline.setOrigin(new FileConfigOrigin());\n dependencyMaterialConfig.validateTree(PipelineConfigSaveValidationContext.forChain(true, \"group\", config, pipeline));\n- assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), is(\"Pipeline with name 'upstream_pipeline' does not exist, it is defined as a dependency for pipeline 'p' (cruise-config.xml)\"));\n+ assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).isEqualTo(\"Pipeline with name 'upstream_pipeline' does not exist, it is defined as a dependency for pipeline 'p' (cruise-config.xml)\");\n+ }\n+\n+ @Nested\n+ class getName {\n+ @Test\n+ void shouldBeSameAsConfiguredName() {\n+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"material name\"), new CaseInsensitiveString(\"#{upstream_pipeline}\"), new CaseInsensitiveString(\"stage\"));\n+\n+ assertThat(dependencyMaterialConfig.getName()).isEqualTo(new CaseInsensitiveString(\"material name\"));\n+ }\n+\n+ @Test\n+ void shouldBeEmptyIfNotSet() {\n+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"#{upstream_pipeline}\"), new CaseInsensitiveString(\"stage\"));\n+\n+ assertThat(dependencyMaterialConfig.getName()).isNull();\n+ }\n+ }\n+\n+ @Nested\n+ class displayName {\n+ @Test\n+ void shouldBeSameSameAsNameIfConfigured() {\n+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"material name\"), new CaseInsensitiveString(\"#{upstream_pipeline}\"), new CaseInsensitiveString(\"stage\"));\n+\n+ assertThat(dependencyMaterialConfig.getDisplayName()).isEqualTo(\"material name\");\n+ }\n+\n+ @Test\n+ void shouldBePipelineNameIfNameNotSet() {\n+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(\"#{upstream_pipeline}\"), new CaseInsensitiveString(\"stage\"));\n+\n+ assertThat(dependencyMaterialConfig.getDisplayName()).isEqualTo(\"#{upstream_pipeline}\");\n+ }\n }\n }"},"changed_files":{"kind":"string","value":"['config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.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":15603778,"string":"15,603,778"},"repo_tokens_count":{"kind":"number","value":3124659,"string":"3,124,659"},"repo_lines_count":{"kind":"number","value":370187,"string":"370,187"},"repo_files_without_tests_count":{"kind":"number","value":3319,"string":"3,319"},"changed_symbols_count":{"kind":"number","value":314,"string":"314"},"changed_tokens_count":{"kind":"number","value":58,"string":"58"},"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":513,"string":"513"},"issue_words_count":{"kind":"number","value":83,"string":"83"},"issue_tokens_count":{"kind":"number","value":94,"string":"94"},"issue_lines_count":{"kind":"number","value":9,"string":"9"},"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:21","string":"1970-01-01T00:26:21"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1361,"cells":{"id":{"kind":"number","value":396,"string":"396"},"text_id":{"kind":"string","value":"gocd/gocd/1869/1799"},"repo_owner":{"kind":"string","value":"gocd"},"repo_name":{"kind":"string","value":"gocd"},"issue_url":{"kind":"string","value":"https://github.com/gocd/gocd/issues/1799"},"pull_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/1869"},"comment_url":{"kind":"string","value":"https://github.com/gocd/gocd/pull/1869#issuecomment-194664589"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"close"},"issue_title":{"kind":"string","value":"pipeline config API: cannot create pipeline with dependency on an upstream with a template"},"issue_body":{"kind":"string","value":"Pipeline \"upstream\" uses some template that has a stage called \"run\". \n\nUsing the pipeline config API, try to create a pipeline \"downstream\" with a material that points to the upstream pipeline. \n\n```\n\"materials\": [ some_git_repo, {\"attributes\": {\"auto_update\": true, \"name\": \"upstream\", \"pipeline\": \"upstream\", \"stage\": \"run\"}, \"type\": \"dependency\"}], \n```\n\nI get the following error:\n\n```\nValidations failed for pipeline 'downstream'.... errors: pipeline: \"Stage with name 'run' does not exist on pipeline 'upstream'\"\n```\n"},"base_sha":{"kind":"string","value":"68e97393b25c016f55f58e9ba37d808c5577b429"},"head_sha":{"kind":"string","value":"e075da259f523da22a32fe0f663c9ef516abc1aa"},"diff_url":{"kind":"string","value":"https://github.com/gocd/gocd/compare/68e97393b25c016f55f58e9ba37d808c5577b429...e075da259f523da22a32fe0f663c9ef516abc1aa"},"diff":{"kind":"string","value":"diff --git a/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java b/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java\nindex a9821da177..d3e1e95df0 100644\n--- a/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java\n+++ b/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright 2015 ThoughtWorks, Inc.\n+ * Copyright 2016 ThoughtWorks, Inc.\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@@ -184,7 +184,7 @@ public class PipelineConfigService implements PipelineConfigChangedListener, Ini\n \n @Override\n public void onConfigChange(CruiseConfig newCruiseConfig) {\n- PipelineConfigurationCache.getInstance().onConfigChange(goConfigService.getConfigForEditing());\n+ PipelineConfigurationCache.getInstance().onConfigChange(goConfigService.cruiseConfig());\n if (goCache.get(GO_PIPELINE_CONFIGS_ETAGS_CACHE) != null) {\n goCache.remove(GO_PIPELINE_CONFIGS_ETAGS_CACHE);\n }\ndiff --git a/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java b/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java\nindex ad9f249ddd..6d5423aa56 100644\n--- a/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java\n+++ b/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java\n@@ -51,6 +51,7 @@ import java.util.Arrays;\n import java.util.UUID;\n \n import static com.thoughtworks.go.util.TestUtils.contains;\n+import static junit.framework.Assert.assertTrue;\n import static junit.framework.TestCase.assertFalse;\n import static org.hamcrest.core.Is.is;\n import static org.hamcrest.core.IsNot.not;\n@@ -148,6 +149,49 @@ public class PipelineConfigServiceIntegrationTest {\n assertThat(configRepository.getCurrentRevision().getUsername(), is(user.getDisplayName()));\n }\n \n+ @Test\n+ public void shouldUpdatePipelineConfigWhenDependencyMaterialHasTemplateDefined() throws Exception {\n+ CaseInsensitiveString templateName = new CaseInsensitiveString(\"template_with_param\");\n+ saveTemplateWithParamToConfig(templateName);\n+\n+ pipelineConfig.clear();\n+ pipelineConfig.setTemplateName(templateName);\n+ pipelineConfig.addParam(new ParamConfig(\"SOME_PARAM\", \"SOME_VALUE\"));\n+\n+ CruiseConfig cruiseConfig = goConfigDao.loadConfigHolder().configForEdit;\n+ cruiseConfig.update(groupName, pipelineConfig.name().toString(), pipelineConfig);\n+ saveConfig(cruiseConfig);\n+\n+ PipelineConfig downstream = GoConfigMother.createPipelineConfigWithMaterialConfig(\"downstream\", new DependencyMaterialConfig(pipelineConfig.name(), new CaseInsensitiveString(\"stage\")));\n+ pipelineConfigService.createPipelineConfig(user, downstream, result, groupName);\n+\n+ assertThat(result.toString(), result.isSuccessful(), is(true));\n+ assertTrue(downstream.materialConfigs().first().errors().isEmpty());\n+ }\n+\n+ @Test\n+ public void shouldUpdatePipelineConfigWhenFetchTaskFromUpstreamHasPipelineWithTemplateDefined() throws Exception {\n+ CaseInsensitiveString templateName = new CaseInsensitiveString(\"template_with_param\");\n+ saveTemplateWithParamToConfig(templateName);\n+\n+ pipelineConfig.clear();\n+ pipelineConfig.setTemplateName(templateName);\n+ pipelineConfig.addParam(new ParamConfig(\"SOME_PARAM\", \"SOME_VALUE\"));\n+\n+ CaseInsensitiveString stage = new CaseInsensitiveString(\"stage\");\n+ CaseInsensitiveString job = new CaseInsensitiveString(\"job\");\n+ CruiseConfig cruiseConfig = goConfigDao.loadConfigHolder().configForEdit;\n+ cruiseConfig.update(groupName, pipelineConfig.name().toString(), pipelineConfig);\n+ saveConfig(cruiseConfig);\n+\n+ PipelineConfig downstream = GoConfigMother.createPipelineConfigWithMaterialConfig(\"downstream\", new DependencyMaterialConfig(pipelineConfig.name(), stage));\n+ downstream.getStage(stage).getJobs().first().addTask(new FetchTask(pipelineConfig.name(), stage, job, \"src\", \"dest\"));\n+ pipelineConfigService.createPipelineConfig(user, downstream, result, groupName);\n+\n+ assertThat(result.toString(), result.isSuccessful(), is(true));\n+ assertTrue(downstream.materialConfigs().first().errors().isEmpty());\n+ }\n+\n @Test\n public void shouldNotCreatePipelineConfigWhenAPipelineBySameNameAlreadyExists() throws GitAPIException {\n GoConfigHolder goConfigHolderBeforeUpdate = goConfigDao.loadConfigHolder();"},"changed_files":{"kind":"string","value":"['server/src/com/thoughtworks/go/server/service/PipelineConfigService.java', 'server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.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":7502322,"string":"7,502,322"},"repo_tokens_count":{"kind":"number","value":1499524,"string":"1,499,524"},"repo_lines_count":{"kind":"number","value":198300,"string":"198,300"},"repo_files_without_tests_count":{"kind":"number","value":1822,"string":"1,822"},"changed_symbols_count":{"kind":"number","value":278,"string":"278"},"changed_tokens_count":{"kind":"number","value":52,"string":"52"},"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":524,"string":"524"},"issue_words_count":{"kind":"number","value":71,"string":"71"},"issue_tokens_count":{"kind":"number","value":132,"string":"132"},"issue_lines_count":{"kind":"number","value":14,"string":"14"},"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:24:14","string":"1970-01-01T00:24:14"},"repo_stars":{"kind":"number","value":6872,"string":"6,872"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1362,"cells":{"id":{"kind":"number","value":428,"string":"428"},"text_id":{"kind":"string","value":"real-logic/aeron/145/29"},"repo_owner":{"kind":"string","value":"real-logic"},"repo_name":{"kind":"string","value":"aeron"},"issue_url":{"kind":"string","value":"https://github.com/real-logic/aeron/issues/29"},"pull_url":{"kind":"string","value":"https://github.com/real-logic/aeron/pull/145"},"comment_url":{"kind":"string","value":"https://github.com/real-logic/aeron/pull/145"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"ReceiverTest setUp() method throws exception"},"issue_body":{"kind":"string","value":"OS (uname -a): Linux 3.5.0-51-generic #77~precise1-Ubuntu SMP Thu Jun 5 00:48:28 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux\n\nThanks for open sourcing this library. I hope to learn a lot about high performance messaging from it.\n\nI noticed that the ReceiverTest tearDown() method was throwing NPEs when closing the receiveChannelEndpoint so I wrapped the creation of the ReceiveChannelEndpoint in the ReceiverTest's setUp() method with a try/catch that printed the exception and I got this:\n\nException: java.lang.IllegalStateException: Failed to set SO_RCVBUF: attempted=131072, actual=131071\n\nLooks like UdpChannelTransport's constructor is throwing the exception.\n\n% sysctl net | grep 131071\nnet.core.rmem_max = 131071\nnet.core.wmem_max = 131071\n\nLooks like there's a hard limit we're hitting up against.\n\nThanks!\n"},"base_sha":{"kind":"string","value":"fb68c69719010f56b9698572bbeb2dac0b597f2e"},"head_sha":{"kind":"string","value":"308142d22d1afb0efdefce2867b5097ba0b2dbc4"},"diff_url":{"kind":"string","value":"https://github.com/real-logic/aeron/compare/fb68c69719010f56b9698572bbeb2dac0b597f2e...308142d22d1afb0efdefce2867b5097ba0b2dbc4"},"diff":{"kind":"string","value":"diff --git a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java\nindex e3430f374..dfd794552 100644\n--- a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java\n+++ b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java\n@@ -35,6 +35,11 @@ import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBuffer;\n import java.io.File;\n import java.nio.ByteBuffer;\n import java.nio.MappedByteBuffer;\n+\n+import java.nio.channels.DatagramChannel;\n+import java.net.StandardSocketOptions;\n+import java.io.IOException;\n+\n import java.util.Arrays;\n import java.util.Collections;\n import java.util.List;\n@@ -103,6 +108,8 @@ public final class MediaDriver implements AutoCloseable\n \n ensureDirectoriesAreRecreated();\n \n+ warnOnInsufficentSocketBuffers();\n+\n ctx.unicastSenderFlowControl(Configuration::unicastFlowControlStrategy)\n .multicastSenderFlowControl(Configuration::multicastFlowControlStrategy)\n .conductorTimerWheel(Configuration.newConductorTimerWheel())\n@@ -247,6 +254,38 @@ public final class MediaDriver implements AutoCloseable\n return this;\n }\n \n+ private void warnOnInsufficentSocketBuffers()\n+ {\n+ try (DatagramChannel probe = DatagramChannel.open())\n+ {\n+\n+ probe.setOption(StandardSocketOptions.SO_SNDBUF, Integer.MAX_VALUE);\n+ final int maxSoSndbuf = probe.getOption(StandardSocketOptions.SO_SNDBUF);\n+\n+ if (maxSoSndbuf < Configuration.SOCKET_SNDBUF_LENGTH)\n+ {\n+ System.err.println(\n+ String.format(\"WARNING: Could not get desired SO_SNDBUF: attempted=%d, actual=%d\",\n+ Configuration.SOCKET_SNDBUF_LENGTH, maxSoSndbuf));\n+ }\n+\n+ probe.setOption(StandardSocketOptions.SO_RCVBUF, Integer.MAX_VALUE);\n+ final int maxSoRcvbuf = probe.getOption(StandardSocketOptions.SO_RCVBUF);\n+\n+ if (maxSoRcvbuf < Configuration.SOCKET_RCVBUF_LENGTH)\n+ {\n+ System.err.println(\n+ String.format(\"WARNING: Could not get desired SO_RCVBUF: attempted=%d, actual=%d\",\n+ Configuration.SOCKET_RCVBUF_LENGTH, maxSoRcvbuf));\n+ }\n+ }\n+ catch (final IOException ex)\n+ {\n+ throw new RuntimeException(\n+ String.format(\"probe socket: %s\", ex.toString()), ex);\n+ }\n+ }\n+\n private void ensureDirectoriesAreRecreated()\n {\n final BiConsumer callback =\ndiff --git a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java\nindex 045ae88a8..0b8d56182 100644\n--- a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java\n+++ b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java\n@@ -78,25 +78,11 @@ public abstract class UdpChannelTransport implements AutoCloseable\n if (0 != Configuration.SOCKET_SNDBUF_LENGTH)\n {\n datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, Configuration.SOCKET_SNDBUF_LENGTH);\n- final int soSndbuf = datagramChannel.getOption(StandardSocketOptions.SO_SNDBUF);\n-\n- if (soSndbuf != Configuration.SOCKET_SNDBUF_LENGTH)\n- {\n- throw new IllegalStateException(String.format(\n- \"Failed to set SO_SNDBUF: attempted=%d, actual=%d\", Configuration.SOCKET_SNDBUF_LENGTH, soSndbuf));\n- }\n }\n \n if (0 != Configuration.SOCKET_RCVBUF_LENGTH)\n {\n datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, Configuration.SOCKET_RCVBUF_LENGTH);\n- final int soRcvbuf = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF);\n-\n- if (soRcvbuf != Configuration.SOCKET_RCVBUF_LENGTH)\n- {\n- throw new IllegalStateException(String.format(\n- \"Failed to set SO_RCVBUF: attempted=%d, actual=%d\", Configuration.SOCKET_RCVBUF_LENGTH, soRcvbuf));\n- }\n }\n \n datagramChannel.configureBlocking(false);"},"changed_files":{"kind":"string","value":"['aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java', 'aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.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":1023943,"string":"1,023,943"},"repo_tokens_count":{"kind":"number","value":209160,"string":"209,160"},"repo_lines_count":{"kind":"number","value":30104,"string":"30,104"},"repo_files_without_tests_count":{"kind":"number","value":188,"string":"188"},"changed_symbols_count":{"kind":"number","value":2273,"string":"2,273"},"changed_tokens_count":{"kind":"number","value":459,"string":"459"},"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":813,"string":"813"},"issue_words_count":{"kind":"number","value":112,"string":"112"},"issue_tokens_count":{"kind":"number","value":212,"string":"212"},"issue_lines_count":{"kind":"number","value":18,"string":"18"},"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:23:53","string":"1970-01-01T00:23:53"},"repo_stars":{"kind":"number","value":6607,"string":"6,607"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 7808647, 'C++': 2885942, 'C': 2193186, 'CMake': 83950, 'Shell': 66446, 'Batchfile': 43311, 'Dockerfile': 3239}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1363,"cells":{"id":{"kind":"number","value":258,"string":"258"},"text_id":{"kind":"string","value":"alluxio/alluxio/14635/14620"},"repo_owner":{"kind":"string","value":"alluxio"},"repo_name":{"kind":"string","value":"alluxio"},"issue_url":{"kind":"string","value":"https://github.com/Alluxio/alluxio/issues/14620"},"pull_url":{"kind":"string","value":"https://github.com/Alluxio/alluxio/pull/14635"},"comment_url":{"kind":"string","value":"https://github.com/Alluxio/alluxio/pull/14635"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"solve"},"issue_title":{"kind":"string","value":"workerFuse stressbench write Input/output error"},"issue_body":{"kind":"string","value":"**Alluxio Version:**\r\nCurrent master branch\r\n\r\n**Describe the bug**\r\nFuse stress bench with workerFuse writing data errors out. \r\nNot tuning MaxDirectMemorySize, all threads fail. Logs from `worker.out`:\r\n```\r\nio.netty.util.internal.OutOfDirectMemoryError: failed to allocate 16777216 byte(s) of direct memory (used: 4278190359, max: 4294967296)\r\n at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:754)\r\n at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:709)\r\n at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:645)\r\n at io.netty.buffer.PoolArena$DirectArena.newChunk(PoolArena.java:621)\r\n at io.netty.buffer.PoolArena.allocateNormal(PoolArena.java:204)\r\n at io.netty.buffer.PoolArena.tcacheAllocateNormal(PoolArena.java:188)\r\n at io.netty.buffer.PoolArena.allocate(PoolArena.java:138)\r\n at io.netty.buffer.PoolArena.allocate(PoolArena.java:128)\r\n at io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:378)\r\n at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:187)\r\n at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:178)\r\n at io.netty.buffer.AbstractByteBufAllocator.buffer(AbstractByteBufAllocator.java:115)\r\n at alluxio.client.block.stream.BlockOutStream.allocateBuffer(BlockOutStream.java:294)\r\n at alluxio.client.block.stream.BlockOutStream.updateCurrentChunk(BlockOutStream.java:252)\r\n at alluxio.client.block.stream.BlockOutStream.write(BlockOutStream.java:141)\r\n at alluxio.client.file.AlluxioFileOutStream.writeInternal(AlluxioFileOutStream.java:271)\r\n at alluxio.client.file.AlluxioFileOutStream.write(AlluxioFileOutStream.java:229)\r\n at alluxio.fuse.AlluxioJniFuseFileSystem.writeInternal(AlluxioJniFuseFileSystem.java:438)\r\n at alluxio.fuse.AlluxioJniFuseFileSystem.lambda$write$6(AlluxioJniFuseFileSystem.java:413)\r\n at alluxio.fuse.AlluxioFuseUtils.call(AlluxioFuseUtils.java:278)\r\n at alluxio.fuse.AlluxioJniFuseFileSystem.write(AlluxioJniFuseFileSystem.java:413)\r\n at alluxio.jnifuse.AbstractFuseFileSystem.writeCallback(AbstractFuseFileSystem.java:316)\r\n```\r\nWith following java options in `alluxio-env.sh`: `ALLUXIO_WORKER_JAVA_OPTS+=\" -Xmx24G -Xms24G -XX:MaxDirectMemorySize=18g\" `, only some threads report failure, and no logs in `worker.out`.\r\n\r\n**To Reproduce**\r\nUsing ec2 instance r5.2xlarge which has 64GB memory.\r\nUsing the following properties in `alluxio-site.properties`:\r\n```\r\nalluxio.master.hostname=localhost\r\nalluxio.master.mount.table.root.ufs=s3://xxxxx\r\naws.accessKeyId=xxxxxxxxx\r\naws.secretKey=xxxxxxxxxxxxxxx\r\n\r\nalluxio.worker.ramdisk.size=15GB\r\nalluxio.worker.fuse.enabled=true\r\nalluxio.worker.fuse.mount.alluxio.path=/fuseTest\r\nalluxio.worker.fuse.mount.point=/home/centos/fuseTest\r\n\r\n# User properties\r\nalluxio.user.file.writetype.default=MUST_CACHE\r\nalluxio.user.block.size.bytes.default=200k\r\nalluxio.client.cache.async.write.enabled=false\r\nalluxio.user.file.passive.cache.enabled=false\r\n```\r\nRun Fuse stress bench with: \r\n```\r\nbin/alluxio runClass alluxio.stress.cli.fuse.FuseIOBench --local-path /home/centos/fuseTest --operation Write --threads 32 --num-dirs 100 --num-files-per-dir 1000 --file-size 100k\r\n```\r\n\r\n**Additional information**\r\nStandalone Fuse has no such issue."},"base_sha":{"kind":"string","value":"4325774f94b2acb2019adeaf3d53713529209e5d"},"head_sha":{"kind":"string","value":"eecfcd4358dfa2cac0ae6b0275d8e7eb09f85c90"},"diff_url":{"kind":"string","value":"https://github.com/alluxio/alluxio/compare/4325774f94b2acb2019adeaf3d53713529209e5d...eecfcd4358dfa2cac0ae6b0275d8e7eb09f85c90"},"diff":{"kind":"string","value":"diff --git a/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java b/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java\nindex 0076f9b427..ffe84c9b91 100644\n--- a/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java\n+++ b/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java\n@@ -92,18 +92,23 @@ public final class BlockWorkerDataWriter implements DataWriter {\n \n @Override\n public void writeChunk(final ByteBuf buf) throws IOException {\n- if (mReservedBytes < pos() + buf.readableBytes()) {\n- try {\n- long bytesToReserve = Math.max(mBufferSize, pos() + buf.readableBytes() - mReservedBytes);\n- // Allocate enough space in the existing temporary block for the write.\n- mBlockWorker.requestSpace(mSessionId, mBlockId, bytesToReserve);\n- } catch (Exception e) {\n- throw new IOException(e);\n+ try {\n+ if (mReservedBytes < pos() + buf.readableBytes()) {\n+ try {\n+ long bytesToReserve = Math.max(mBufferSize, pos() + buf.readableBytes()\n+ - mReservedBytes);\n+ // Allocate enough space in the existing temporary block for the write.\n+ mBlockWorker.requestSpace(mSessionId, mBlockId, bytesToReserve);\n+ } catch (Exception e) {\n+ throw new IOException(e);\n+ }\n }\n+ long append = mBlockWriter.append(buf);\n+ MetricsSystem.counter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT.getName()).inc(append);\n+ MetricsSystem.meter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT_THROUGHPUT.getName()).mark(append); \n+ } finally {\n+ buf.release();\n }\n- long append = mBlockWriter.append(buf);\n- MetricsSystem.counter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT.getName()).inc(append);\n- MetricsSystem.meter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT_THROUGHPUT.getName()).mark(append);\n }\n \n @Override"},"changed_files":{"kind":"string","value":"['core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.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":9523936,"string":"9,523,936"},"repo_tokens_count":{"kind":"number","value":2143288,"string":"2,143,288"},"repo_lines_count":{"kind":"number","value":272269,"string":"272,269"},"repo_files_without_tests_count":{"kind":"number","value":1621,"string":"1,621"},"changed_symbols_count":{"kind":"number","value":1346,"string":"1,346"},"changed_tokens_count":{"kind":"number","value":309,"string":"309"},"changed_lines_count":{"kind":"number","value":25,"string":"25"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":3483,"string":"3,483"},"issue_words_count":{"kind":"number","value":169,"string":"169"},"issue_tokens_count":{"kind":"number","value":871,"string":"871"},"issue_lines_count":{"kind":"number","value":60,"string":"60"},"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:27:18","string":"1970-01-01T00:27:18"},"repo_stars":{"kind":"number","value":6326,"string":"6,326"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 15817407, 'TypeScript': 340217, 'Shell': 175186, 'Go': 79288, 'C++': 47930, 'Mustache': 15785, 'Ruby': 15044, 'SCSS': 12027, 'JavaScript': 9992, 'C': 7326, 'Roff': 5919, 'Python': 4554, 'Dockerfile': 3642, 'Handlebars': 3633, 'HTML': 3412, 'Makefile': 2362}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1364,"cells":{"id":{"kind":"number","value":1432,"string":"1,432"},"text_id":{"kind":"string","value":"micronaut-projects/micronaut-core/1273/1272"},"repo_owner":{"kind":"string","value":"micronaut-projects"},"repo_name":{"kind":"string","value":"micronaut-core"},"issue_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/issues/1272"},"pull_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/1273"},"comment_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/1273"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Regression on bean with preDestroy "},"issue_body":{"kind":"string","value":"My project has a factory that replaces the `DefaultMongoClientFactory`:\r\n\r\n```kotlin\r\n@Requirements(Requires(beans = [DefaultMongoConfiguration::class]), Requires(classes = [MongoClient::class]))\r\n@Replaces(factory = DefaultMongoClientFactory::class)\r\n@Factory\r\nclass KMongoClientFactory {\r\n\r\n companion object: KLogging()\r\n\r\n @Bean(preDestroy = \"close\")\r\n @Singleton\r\n fun kmongoClient(configuration: DefaultMongoConfiguration): MongoClient {\r\n logger.debug { \"===== KMongo creating client for ${configuration.uri}\" }\r\n val client = KMongo.createClient(MongoClientURI(configuration.uri))\r\n return client\r\n }\r\n}\r\n```\r\n\r\nThis was working last week, but I am now seeing this error:\r\n\r\n```\r\n$ ./gradlew test\r\n$ ./gradlew test\r\ne: /Users/mmindenhall/projects/micronaut-examples/hello-world-kotlin/build/tmp/kapt3/stubs/main/example/KMongoClientFactory.java:19: error: @Bean method defines a preDestroy method that does not exist or is not public: close\r\n public final com.mongodb.MongoClient kmongoClient(@org.jetbrains.annotations.NotNull()\r\n ^\r\n```\r\n\r\nIt seems likely that this was caused by the recent fix for #1267.\r\n\r\n### Task List\r\n\r\n- [x] Steps to reproduce provided\r\n- [x] Stacktrace (if present) provided\r\n- [x] Example that reproduces the problem uploaded to Github\r\n- [x] Full description of the issue provided (see below)\r\n\r\n### Steps to Reproduce\r\n\r\n1. Clone [my fork of micronaut-examples](https://github.com/mmindenhall/micronaut-examples)\r\n1. `cd micronaut-examples`\r\n1. `git checkout pre-destroy-regression`\r\n1. `cd hello-world-kotlin`\r\n1. `./gradlew test`\r\n\r\nNote that if this is executed against micronaut 1.1.0.M1 instead of 1.1.0.BUILD-SNAPSHOT, the tests all pass:\r\n\r\n1. Edit `gradle.properties`\r\n1. Change micronaut version (comment out line 2, uncomment line 3), save changes\r\n1. `./gradlew test`\r\n\r\n### Expected Behaviour\r\n\r\nEverything passes.\r\n\r\n### Actual Behaviour\r\n\r\nThe factory returns an instance of `MongoClient`, which implements the `Closeable` interface (and therefore the public `close` method). Micronaut is erroneously reporting the error above.\r\n\r\n### Environment Information\r\n\r\n- **Operating System**: macOS 10.14.3\r\n- **Micronaut Version:** 1.1.0.BUILD-SNAPSHOT\r\n- **JDK Version:** 1.8.0_191\r\n\r\n### Example Application\r\n\r\nSee steps to reproduce above.\r\n\r\n"},"base_sha":{"kind":"string","value":"bb11cd1e6e5b1d1360f9c0f941df8bcbf57363a7"},"head_sha":{"kind":"string","value":"6985a5886137dbd18d8be09a0cc12dbd386b200a"},"diff_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/compare/bb11cd1e6e5b1d1360f9c0f941df8bcbf57363a7...6985a5886137dbd18d8be09a0cc12dbd386b200a"},"diff":{"kind":"string","value":"diff --git a/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java b/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java\nindex 0929252063..4696741dd0 100644\n--- a/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java\n+++ b/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java\n@@ -202,7 +202,7 @@ public class ModelUtils {\n * @return The executable element\n */\n Optional findAccessibleNoArgumentInstanceMethod(TypeElement classElement, String methodName) {\n- return ElementFilter.methodsIn(classElement.getEnclosedElements())\n+ return ElementFilter.methodsIn(elementUtils.getAllMembers(classElement))\n .stream().filter(m -> m.getSimpleName().toString().equals(methodName) && !isPrivate(m) && !isStatic(m))\n .findFirst();\n }"},"changed_files":{"kind":"string","value":"['inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.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":6970541,"string":"6,970,541"},"repo_tokens_count":{"kind":"number","value":1407026,"string":"1,407,026"},"repo_lines_count":{"kind":"number","value":198293,"string":"198,293"},"repo_files_without_tests_count":{"kind":"number","value":1950,"string":"1,950"},"changed_symbols_count":{"kind":"number","value":157,"string":"157"},"changed_tokens_count":{"kind":"number","value":26,"string":"26"},"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":2372,"string":"2,372"},"issue_words_count":{"kind":"number","value":259,"string":"259"},"issue_tokens_count":{"kind":"number","value":569,"string":"569"},"issue_lines_count":{"kind":"number","value":72,"string":"72"},"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:50","string":"1970-01-01T00:25:50"},"repo_stars":{"kind":"number","value":5790,"string":"5,790"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1365,"cells":{"id":{"kind":"number","value":1426,"string":"1,426"},"text_id":{"kind":"string","value":"micronaut-projects/micronaut-core/2153/2152"},"repo_owner":{"kind":"string","value":"micronaut-projects"},"repo_name":{"kind":"string","value":"micronaut-core"},"issue_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/issues/2152"},"pull_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/2153"},"comment_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/2153"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"HTTP client pool caches dns lookup forever"},"issue_body":{"kind":"string","value":"When the DefaultHttpClient creates it's poolMap instance a DNS lookup is made and stored in the bootstrap instance:\r\n` Bootstrap newBootstrap = bootstrap.clone(group);\r\n newBootstrap.remoteAddress(key.getRemoteAddress());\r\n`\r\nThe remoteAddress is never updated, which means that if the ip is recycled (very common for AWS hosted services), the pool will continue to try to create connections to the original ip.\r\n\r\n### Task List\r\n- [x] Steps to reproduce provided\r\n- [x] Stacktrace (if present) provided\r\n- [x] Example that reproduces the problem uploaded to Github\r\n- [x] Full description of the issue provided (see below)\r\n\r\n### Steps to Reproduce\r\nhttps://github.com/luckyswede/micronaut-dnstest\r\n\r\n### Expected Behaviour\r\nWhen new connections are created a new DNS lookup should take place\r\n\r\n### Actual Behaviour\r\nThe original DNS lookup result is reused\r\n\r\n### Environment Information\r\n\r\n- **Operating System**: All\r\n- **Micronaut Version:** 1.2.2\r\n- **JDK Version:** 11\r\n\r\n### Example Application\r\nhttps://github.com/luckyswede/micronaut-dnstest\r\n"},"base_sha":{"kind":"string","value":"11e6988348ea8ae0c740d74e91b28c4f13937472"},"head_sha":{"kind":"string","value":"601d4e69dfd188ac8ae8ca376bee3407c858cb05"},"diff_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/compare/11e6988348ea8ae0c740d74e91b28c4f13937472...601d4e69dfd188ac8ae8ca376bee3407c858cb05"},"diff":{"kind":"string","value":"diff --git a/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java b/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java\nindex f46d23daad..760d142124 100644\n--- a/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java\n+++ b/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java\n@@ -260,7 +260,6 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr\n Bootstrap newBootstrap = bootstrap.clone(group);\n newBootstrap.remoteAddress(key.getRemoteAddress());\n \n-\n AbstractChannelPoolHandler channelPoolHandler = newPoolHandler(key);\n final Long acquireTimeoutMillis = connectionPoolConfiguration.getAcquireTimeout().map(Duration::toMillis).orElse(-1L);\n return new FixedChannelPool(\n@@ -281,6 +280,7 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr\n protected ChannelPool newPool(RequestKey key) {\n Bootstrap newBootstrap = bootstrap.clone(group);\n newBootstrap.remoteAddress(key.getRemoteAddress());\n+\n AbstractChannelPoolHandler channelPoolHandler = newPoolHandler(key);\n return new SimpleChannelPool(\n newBootstrap,\n@@ -2303,7 +2303,7 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr\n }\n \n public InetSocketAddress getRemoteAddress() {\n- return new InetSocketAddress(host, port);\n+ return InetSocketAddress.createUnresolved(host, port);\n }\n \n public boolean isSecure() {"},"changed_files":{"kind":"string","value":"['http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.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":7131028,"string":"7,131,028"},"repo_tokens_count":{"kind":"number","value":1428690,"string":"1,428,690"},"repo_lines_count":{"kind":"number","value":200862,"string":"200,862"},"repo_files_without_tests_count":{"kind":"number","value":1797,"string":"1,797"},"changed_symbols_count":{"kind":"number","value":126,"string":"126"},"changed_tokens_count":{"kind":"number","value":21,"string":"21"},"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":1100,"string":"1,100"},"issue_words_count":{"kind":"number","value":141,"string":"141"},"issue_tokens_count":{"kind":"number","value":240,"string":"240"},"issue_lines_count":{"kind":"number","value":30,"string":"30"},"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:09","string":"1970-01-01T00:26:09"},"repo_stars":{"kind":"number","value":5790,"string":"5,790"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1366,"cells":{"id":{"kind":"number","value":1421,"string":"1,421"},"text_id":{"kind":"string","value":"micronaut-projects/micronaut-core/9427/9423"},"repo_owner":{"kind":"string","value":"micronaut-projects"},"repo_name":{"kind":"string","value":"micronaut-core"},"issue_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/issues/9423"},"pull_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/9427"},"comment_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/9427"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"New allowed-origins-regex property not working..?"},"issue_body":{"kind":"string","value":"### Expected Behavior\n\nWith 3.9.0 allowed-origins no longer supports a regex value for the cors configuration. Instead you now need to use a new property called allowed-origins-regex.\r\n\r\nWhen replacing allowed-origins with allowed-origins-regex using the same regular expression and previously, it's expected that calls from an Origin matching the pattern are allowed through.\n\n### Actual Behaviour\n\nCalls with a matching Origin header are no longer accepted and a 403 forbidden is returned.\n\n### Steps To Reproduce\n\nStart a 3.8.9 micronaut server with a configuration set to \r\n\r\n```\r\nmicronaut:\r\n application:\r\n name: testApp\r\n server:\r\n cors:\r\n enabled: true\r\n configurations:\r\n web:\r\n allowed-origins: \r\n - ^http(|s):\\\\/\\\\/(\\\\w*\\\\.)*integration\\\\.mydomain\\\\.com$\r\n```\r\n\r\nMake a call to an endpoint on that server specifying an Origin value in the header of \"https://www.integration.mydomain.com\"\r\n\r\nYou should receive a 200 okay.\r\n\r\nNow change the configuration to the below and the version of Micronaut to 3.9.x\r\n```\r\nmicronaut:\r\n application:\r\n name: testApp\r\n server:\r\n cors:\r\n enabled: true\r\n configurations:\r\n web:\r\n allowed-origins-regex: ^http(|s):\\\\/\\\\/(\\\\w*\\\\.)*integration\\\\.mydomain\\\\.com$\r\n```\r\n\r\nMake the same call to an endpoint and you should receive a 403 Forbidden. (Expected that you receive a 200)\n\n### Environment Information\n\nmacOS\r\nJDK 17\r\nMicronaut 3.8.9 and 3.9.2\n\n### Example Application\n\n_No response_\n\n### Version\n\n3.9.2"},"base_sha":{"kind":"string","value":"2c1bee6be0af723c66e8ce790590f4f7d22a84d3"},"head_sha":{"kind":"string","value":"5d60708289271499c5435b7558880f01b6941656"},"diff_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/compare/2c1bee6be0af723c66e8ce790590f4f7d22a84d3...5d60708289271499c5435b7558880f01b6941656"},"diff":{"kind":"string","value":"diff --git a/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java b/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java\nindex 6dc7342aad..33278f69cc 100644\n--- a/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java\n+++ b/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright 2017-2022 original authors\n+ * Copyright 2017-2023 original 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@@ -184,22 +184,42 @@ public class CorsSimpleRequestTest {\n \"micronaut.server.cors.configurations.foo.allowed-origins\", Collections.singletonList(\"https://foo.com\")\n ),\n createRequest(\"https://foo.com\"),\n- (server, request) -> {\n+ CorsSimpleRequestTest::isSuccessfulCorsAssertion\n+ );\n+ }\n \n- RefreshCounter refreshCounter = server.getApplicationContext().getBean(RefreshCounter.class);\n- assertEquals(0, refreshCounter.getRefreshCount());\n+ /**\n+ * CORS Simple request for localhost can be allowed via configuration of a regex.\n+ * @throws IOException may throw the try for resources\n+ */\n+ @Test\n+ // \"https://github.com/micronaut-projects/micronaut-core/issues/9423\")\n+ void corsSimpleRequestForLocalhostCanBeAllowedViaRegexConfiguration() throws IOException {\n+ asserts(SPECNAME,\n+ CollectionUtils.mapOf(\n+ PROPERTY_MICRONAUT_SERVER_CORS_ENABLED, StringUtils.TRUE,\n+ \"micronaut.server.cors.configurations.foo.allowed-origins-regex\", Collections.singletonList(\"^http(|s):\\\\\\\\/\\\\\\\\/foo\\\\\\\\.com$\")\n+ ),\n+ createRequest(\"https://foo.com\"),\n+ CorsSimpleRequestTest::isSuccessfulCorsAssertion\n+ );\n+ }\n \n- AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()\n- .status(HttpStatus.OK)\n- .assertResponse(response -> CorsAssertion.builder()\n- .vary(\"Origin\")\n- .allowCredentials()\n- .allowOrigin(\"https://foo.com\")\n- .build()\n- .validate(response))\n- .build());\n- assertEquals(1, refreshCounter.getRefreshCount());\n- });\n+ /**\n+ * CORS Simple request for localhost can be forbidden via configuration of a regex.\n+ * @throws IOException may throw the try for resources\n+ */\n+ @Test\n+ // \"https://github.com/micronaut-projects/micronaut-core/issues/9423\")\n+ void corsSimpleRequestForLocalhostForbiddenViaRegexConfiguration() throws IOException {\n+ asserts(SPECNAME,\n+ CollectionUtils.mapOf(\n+ PROPERTY_MICRONAUT_SERVER_CORS_ENABLED, StringUtils.TRUE,\n+ \"micronaut.server.cors.configurations.foo.allowed-origins-regex\", Collections.singletonList(\"^http(|s):\\\\\\\\/\\\\\\\\/foo\\\\\\\\.com$\")\n+ ),\n+ createRequest(\"https://bar.com\"),\n+ CorsSimpleRequestTest::isForbidden\n+ );\n }\n \n private RequestSupplier createRequestFor(String host, String origin) {\n@@ -225,6 +245,21 @@ public class CorsSimpleRequestTest {\n assertEquals(1, refreshCounter.getRefreshCount());\n }\n \n+ static void isSuccessfulCorsAssertion(ServerUnderTest server, HttpRequest request) {\n+ RefreshCounter refreshCounter = server.getApplicationContext().getBean(RefreshCounter.class);\n+ assertEquals(0, refreshCounter.getRefreshCount());\n+ AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()\n+ .status(HttpStatus.OK)\n+ .assertResponse(response -> CorsAssertion.builder()\n+ .vary(\"Origin\")\n+ .allowCredentials()\n+ .allowOrigin(\"https://foo.com\")\n+ .build()\n+ .validate(response))\n+ .build());\n+ assertEquals(1, refreshCounter.getRefreshCount());\n+ }\n+\n static HttpRequest createRequest(String origin) {\n return createRequest(\"/refresh\", origin);\n }\ndiff --git a/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java b/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java\nindex 7bf75191a3..52601235db 100644\n--- a/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java\n+++ b/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright 2017-2020 original authors\n+ * Copyright 2017-2023 original 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@@ -62,6 +62,7 @@ import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN;\n */\n @Filter(MATCH_ALL_PATTERN)\n public class CorsFilter implements HttpServerFilter {\n+\n private static final Logger LOG = LoggerFactory.getLogger(CorsFilter.class);\n private static final ArgumentConversionContext CONVERSION_CONTEXT_HTTP_METHOD = ImmutableArgumentConversionContext.of(HttpMethod.class);\n \n@@ -140,7 +141,7 @@ public class CorsFilter implements HttpServerFilter {\n return false;\n }\n String host = httpHostResolver.resolve(request);\n- return isAny(corsOriginConfiguration.getAllowedOrigins()) && isHostLocal(host);\n+ return isAnyOrigin(corsOriginConfiguration.getAllowedOriginsRegex().isPresent(), corsOriginConfiguration.getAllowedOrigins()) && isHostLocal(host);\n }\n \n /**\n@@ -351,6 +352,11 @@ public class CorsFilter implements HttpServerFilter {\n return m.matches();\n }\n \n+ private static boolean isAnyOrigin(boolean isAllowedOriginsRegexConfigured, List values) {\n+ // True if a regular expression has not been set for origin, and the allowed hosts are still ANY\n+ return !isAllowedOriginsRegexConfigured && isAny(values);\n+ }\n+\n private static boolean isAny(List values) {\n return values == CorsOriginConfiguration.ANY;\n }"},"changed_files":{"kind":"string","value":"['http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java', 'http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.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":9143135,"string":"9,143,135"},"repo_tokens_count":{"kind":"number","value":1805359,"string":"1,805,359"},"repo_lines_count":{"kind":"number","value":250070,"string":"250,070"},"repo_files_without_tests_count":{"kind":"number","value":1907,"string":"1,907"},"changed_symbols_count":{"kind":"number","value":615,"string":"615"},"changed_tokens_count":{"kind":"number","value":132,"string":"132"},"changed_lines_count":{"kind":"number","value":10,"string":"10"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1611,"string":"1,611"},"issue_words_count":{"kind":"number","value":190,"string":"190"},"issue_tokens_count":{"kind":"number","value":369,"string":"369"},"issue_lines_count":{"kind":"number","value":59,"string":"59"},"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:28:06","string":"1970-01-01T00:28:06"},"repo_stars":{"kind":"number","value":5790,"string":"5,790"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1367,"cells":{"id":{"kind":"number","value":1434,"string":"1,434"},"text_id":{"kind":"string","value":"micronaut-projects/micronaut-core/623/618"},"repo_owner":{"kind":"string","value":"micronaut-projects"},"repo_name":{"kind":"string","value":"micronaut-core"},"issue_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/issues/618"},"pull_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/623"},"comment_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/623"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Inconsistent @Body handling in browser"},"issue_body":{"kind":"string","value":"Body is occasionally lost when uploaded from browser\r\n\r\n### Steps to Reproduce\r\n\r\nSee sample\r\n\r\n### Expected Behaviour\r\n\r\nBody handling should work\r\n\r\n### Actual Behaviour\r\n\r\nOccasional:\r\n\r\n```\r\ni.m.h.s.netty.RoutingInBoundHandler - Encoding emitted response object [ /command - Required argument [LoginCommand command] not specified] using codec: io.micronaut.jackson.codec.JsonMediaTypeCodec@3ee39da0\r\n```\r\n\r\n### Example Application\r\n\r\nhttps://github.com/liwujun0513/micronaut_demo\r\n\r\n"},"base_sha":{"kind":"string","value":"2c286aba5a06c3b684ba3475d39ca6be48ed2d2f"},"head_sha":{"kind":"string","value":"454e9d34b5d7968931b92b59600029da5fac911f"},"diff_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/compare/2c286aba5a06c3b684ba3475d39ca6be48ed2d2f...454e9d34b5d7968931b92b59600029da5fac911f"},"diff":{"kind":"string","value":"diff --git a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java\nindex cffc0be9cf..6c91f26c8e 100644\n--- a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java\n+++ b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java\n@@ -173,7 +173,7 @@ abstract class HttpStreamsHandler context.pipeline().replace(handler, \"chunked-handler\", new ChunkedWriteHandler()));\n-\n // Write the request data\n context.write(new DefaultHttpResponse(nettyResponse.protocolVersion(), nettyResponse.status(), nettyResponse.headers()), context.voidPromise());\n context.writeAndFlush(new HttpChunkedInput(new ChunkedStream(getInputStream())));\ndiff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java\nindex b120b6e0f4..7c3bd17646 100644\n--- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java\n+++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java\n@@ -19,7 +19,6 @@ package io.micronaut.http.server.netty.types.files;\n import io.micronaut.http.HttpRequest;\n import io.micronaut.http.MutableHttpResponse;\n import io.micronaut.http.netty.NettyMutableHttpResponse;\n-import io.micronaut.http.server.netty.NettyHttpServer;\n import io.micronaut.http.server.netty.SmartHttpContentCompressor;\n import io.micronaut.http.server.netty.types.NettyFileCustomizableResponseType;\n import io.micronaut.http.server.types.CustomizableResponseTypeException;\n@@ -29,12 +28,10 @@ import io.netty.channel.DefaultFileRegion;\n import io.netty.handler.codec.http.DefaultHttpResponse;\n import io.netty.handler.codec.http.FullHttpResponse;\n import io.netty.handler.codec.http.HttpChunkedInput;\n-import io.netty.handler.codec.http.HttpContentCompressor;\n import io.netty.handler.codec.http.HttpHeaders;\n import io.netty.handler.codec.http.LastHttpContent;\n import io.netty.handler.ssl.SslHandler;\n import io.netty.handler.stream.ChunkedFile;\n-import io.netty.handler.stream.ChunkedWriteHandler;\n \n import java.io.File;\n import java.io.FileNotFoundException;\n@@ -112,11 +109,6 @@ public class NettySystemFileCustomizableResponseType extends SystemFileCustomiza\n \n FullHttpResponse nettyResponse = ((NettyMutableHttpResponse) response).getNativeResponse();\n \n- //The streams codec prevents non full responses from being written\n- Optional\n- .ofNullable(context.pipeline().get(NettyHttpServer.HTTP_STREAMS_CODEC))\n- .ifPresent(handler -> context.pipeline().replace(handler, \"chunked-handler\", new ChunkedWriteHandler()));\n-\n // Write the request data\n HttpHeaders headers = nettyResponse.headers();\n context.write(new DefaultHttpResponse(nettyResponse.protocolVersion(), nettyResponse.status(), headers), context.voidPromise());\n@@ -124,12 +116,6 @@ public class NettySystemFileCustomizableResponseType extends SystemFileCustomiza\n // Write the content.\n if (context.pipeline().get(SslHandler.class) == null && SmartHttpContentCompressor.shouldSkip(headers)) {\n // SSL not enabled - can use zero-copy file transfer.\n- // Remove the content compressor to prevent incorrect behavior with zero-copy\n- HttpContentCompressor compressor = context.pipeline().get(HttpContentCompressor.class);\n- if (compressor != null) {\n- context.pipeline().remove(HttpContentCompressor.class);\n- }\n-\n context.write(new DefaultFileRegion(raf.getChannel(), 0, getLength()), context.newProgressivePromise());\n context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);\n } else {"},"changed_files":{"kind":"string","value":"['http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java', 'http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java', 'http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java', 'http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java', 'http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.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":6796725,"string":"6,796,725"},"repo_tokens_count":{"kind":"number","value":1368789,"string":"1,368,789"},"repo_lines_count":{"kind":"number","value":195312,"string":"195,312"},"repo_files_without_tests_count":{"kind":"number","value":2007,"string":"2,007"},"changed_symbols_count":{"kind":"number","value":2798,"string":"2,798"},"changed_tokens_count":{"kind":"number","value":532,"string":"532"},"changed_lines_count":{"kind":"number","value":61,"string":"61"},"changed_files_without_tests_count":{"kind":"number","value":5,"string":"5"},"issue_symbols_count":{"kind":"number","value":487,"string":"487"},"issue_words_count":{"kind":"number","value":49,"string":"49"},"issue_tokens_count":{"kind":"number","value":108,"string":"108"},"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":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:37","string":"1970-01-01T00:25:37"},"repo_stars":{"kind":"number","value":5790,"string":"5,790"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1368,"cells":{"id":{"kind":"number","value":1423,"string":"1,423"},"text_id":{"kind":"string","value":"micronaut-projects/micronaut-core/2984/2934"},"repo_owner":{"kind":"string","value":"micronaut-projects"},"repo_name":{"kind":"string","value":"micronaut-core"},"issue_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/issues/2934"},"pull_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/2984"},"comment_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/pull/2984"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"AmazonComputeInstanceMetadataResolver has an invalid path"},"issue_body":{"kind":"string","value":"While connecting the application to a consul running in a different ec2 instance (same VPC) the following error occurs in the logs\r\n\r\n`\u001b[35mi.m.d.c.a.AmazonComputeInstanceMetadataResolver\u001b[0;39m - error getting public host name from:http://169.254.169.254//latest/meta-data/publicHostname\r\njava.io.FileNotFoundException: http://169.254.169.254//latest/meta-data/public-hostname`\r\n\r\ndouble // is included in path.\r\n"},"base_sha":{"kind":"string","value":"bd51d3353b629abddfbc3ad9f909c135ab47c150"},"head_sha":{"kind":"string","value":"4876cc6f12e22b0e99acd59105550a8d546db82a"},"diff_url":{"kind":"string","value":"https://github.com/micronaut-projects/micronaut-core/compare/bd51d3353b629abddfbc3ad9f909c135ab47c150...4876cc6f12e22b0e99acd59105550a8d546db82a"},"diff":{"kind":"string","value":"diff --git a/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java b/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java\nindex 8fb8db8f8d..779a3499e3 100644\n--- a/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java\n+++ b/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java\n@@ -46,7 +46,7 @@ public class AmazonMetadataConfiguration implements Toggleable {\n * The default url value.\n */\n @SuppressWarnings(\"WeakerAccess\")\n- public static final String DEFAULT_URL = \"http://169.254.169.254/\";\n+ public static final String DEFAULT_URL = \"http://169.254.169.254\";\n \n private String url = DEFAULT_URL;\n private String metadataUrl;"},"changed_files":{"kind":"string","value":"['runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.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":7542554,"string":"7,542,554"},"repo_tokens_count":{"kind":"number","value":1507719,"string":"1,507,719"},"repo_lines_count":{"kind":"number","value":211614,"string":"211,614"},"repo_files_without_tests_count":{"kind":"number","value":1858,"string":"1,858"},"changed_symbols_count":{"kind":"number","value":144,"string":"144"},"changed_tokens_count":{"kind":"number","value":38,"string":"38"},"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":414,"string":"414"},"issue_words_count":{"kind":"number","value":38,"string":"38"},"issue_tokens_count":{"kind":"number","value":99,"string":"99"},"issue_lines_count":{"kind":"number","value":7,"string":"7"},"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:25","string":"1970-01-01T00:26:25"},"repo_stars":{"kind":"number","value":5790,"string":"5,790"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1369,"cells":{"id":{"kind":"number","value":386,"string":"386"},"text_id":{"kind":"string","value":"raphw/byte-buddy/528/527"},"repo_owner":{"kind":"string","value":"raphw"},"repo_name":{"kind":"string","value":"byte-buddy"},"issue_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/issues/527"},"pull_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/528"},"comment_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/528"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Using MethodCall onField with field locator pointing to different class fails"},"issue_body":{"kind":"string","value":"```java\r\nDynamicType.Loaded loaded = new ByteBuddy()\r\n .subclass(Object.class)\r\n .invokable(isTypeInitializer())\r\n .intercept(MethodCall.invoke(named(\"println\").and(takesArguments(Object.class)))\r\n .onField(\"out\", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with(\"\"))\r\n .make()\r\n .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);\r\nloaded.getLoaded().getDeclaredConstructor().newInstance();\r\n```\r\n\r\nThe code above fails with the error below:\r\n\r\n```\r\njava.lang.VerifyError: Local variable table overflow\r\nException Details:\r\n Location:\r\n net/bytebuddy/renamed/java/lang/Object$ByteBuddy$XtBtrrHJ.()V @0: aload_0\r\n Reason:\r\n Local index 0 is invalid\r\n Bytecode:\r\n 0x0000000: 2ab2 000f 1211 b600 17b1 \r\n```\r\n\r\nRelevant bytecode:\r\n```\r\n static ()V\r\n ALOAD 0\r\n GETSTATIC java/lang/System.out : Ljava/io/PrintStream;\r\n LDC \"\"\r\n INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V\r\n RETURN\r\n MAXSTACK = 3\r\n MAXLOCALS = 0\r\n}\r\n```\r\n"},"base_sha":{"kind":"string","value":"0f9f5d84a878b3f04cd52475c48215dbd53e5053"},"head_sha":{"kind":"string","value":"7abdaf36e9ba49e5aae30e421344d30728e68cf8"},"diff_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/compare/0f9f5d84a878b3f04cd52475c48215dbd53e5053...7abdaf36e9ba49e5aae30e421344d30728e68cf8"},"diff":{"kind":"string","value":"diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java\nindex 9b06dc57a6..6c241dc565 100644\n--- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java\n+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java\n@@ -1770,9 +1770,10 @@ public class MethodCall implements Implementation.Composable {\n if (!stackManipulation.isValid()) {\n throw new IllegalStateException(\"Cannot invoke \" + invokedMethod + \" on \" + resolution.getField());\n }\n- return new StackManipulation.Compound(invokedMethod.isStatic()\n+ return new StackManipulation.Compound(invokedMethod.isStatic() || resolution.getField().isStatic()\n ? StackManipulation.Trivial.INSTANCE\n- : MethodVariableAccess.loadThis(), FieldAccess.forField(resolution.getField()).read(), stackManipulation);\n+ : MethodVariableAccess.loadThis(),\n+ FieldAccess.forField(resolution.getField()).read(), stackManipulation);\n }\n \n @Override\ndiff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java\nindex a92ee06c90..eec5b5a728 100644\n--- a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java\n+++ b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java\n@@ -7,6 +7,7 @@ import net.bytebuddy.description.modifier.Visibility;\n import net.bytebuddy.description.type.TypeDescription;\n import net.bytebuddy.dynamic.DynamicType;\n import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;\n+import net.bytebuddy.dynamic.scaffold.FieldLocator;\n import net.bytebuddy.implementation.bytecode.StackManipulation;\n import net.bytebuddy.implementation.bytecode.assign.Assigner;\n import net.bytebuddy.implementation.bytecode.constant.TextConstant;\n@@ -276,6 +277,38 @@ public class MethodCallTest {\n .make();\n }\n \n+ @Test\n+ public void testStaticOnStaticFieldFromAnotherClass() throws Exception {\n+ DynamicType.Loaded loaded = new ByteBuddy()\n+ .subclass(Object.class)\n+ .invokable(isTypeInitializer())\n+ .intercept(MethodCall.invoke(named(\"println\").and(takesArguments(Object.class)))\n+ .onField(\"out\", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with(\"\"))\n+ .make()\n+ .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);\n+ assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));\n+ assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0));\n+ assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));\n+ Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();\n+ assertThat(instance, instanceOf(Object.class));\n+ }\n+\n+ @Test\n+ public void testOnStaticFieldFromAnotherClass() throws Exception {\n+ DynamicType.Loaded loaded = new ByteBuddy()\n+ .subclass(Object.class)\n+ .defineMethod(\"foo\", void.class)\n+ .intercept(MethodCall.invoke(named(\"println\").and(takesArguments(Object.class)))\n+ .onField(\"out\", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with(\"fooCall\"))\n+ .make()\n+ .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);\n+ assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));\n+ assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));\n+ assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));\n+ Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();\n+ assertThat(instance, instanceOf(Object.class));\n+ }\n+\n @Test\n public void testOnFieldUsingMatcher() throws Exception {\n DynamicType.Loaded loaded = new ByteBuddy()"},"changed_files":{"kind":"string","value":"['byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.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":5630943,"string":"5,630,943"},"repo_tokens_count":{"kind":"number","value":947133,"string":"947,133"},"repo_lines_count":{"kind":"number","value":125923,"string":"125,923"},"repo_files_without_tests_count":{"kind":"number","value":304,"string":"304"},"changed_symbols_count":{"kind":"number","value":484,"string":"484"},"changed_tokens_count":{"kind":"number","value":80,"string":"80"},"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":1111,"string":"1,111"},"issue_words_count":{"kind":"number","value":76,"string":"76"},"issue_tokens_count":{"kind":"number","value":287,"string":"287"},"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":3,"string":"3"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:25:35","string":"1970-01-01T00:25:35"},"repo_stars":{"kind":"number","value":5668,"string":"5,668"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1370,"cells":{"id":{"kind":"number","value":385,"string":"385"},"text_id":{"kind":"string","value":"raphw/byte-buddy/951/948"},"repo_owner":{"kind":"string","value":"raphw"},"repo_name":{"kind":"string","value":"byte-buddy"},"issue_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/issues/948"},"pull_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/951"},"comment_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/951"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"JavaConstant.MethodHandle.getDescriptor() returns wrong value for PUT_FIELD and PUT_FIELD_STATIC cases"},"issue_body":{"kind":"string","value":"As always, thanks for this project. I am nervous filing this bug because there are so few bugs in ByteBuddy that I feel like this can't actually be one! But I think it is.\r\n\r\nFor background, see https://stackoverflow.com/questions/64296731/how-do-i-install-and-use-a-constant-methodhandle-in-bytebuddy.\r\n\r\nIn the case of `PUT_FIELD` and `PUT_FIELD_STATIC` `HandleType`s, I think that the wrong value is being returned from the default implementation of `getDescriptor()`. Specifically, this will return `V` in \"field setter\" cases, because of this code:\r\n\r\nhttps://github.com/raphw/byte-buddy/blob/291a512c609b647edccfdead540764ee402abd00/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L695-L696\r\n\r\nFor a \"field setter\" method handle, this will always return `V`, and that will cause a `ClassFormatError` that resembles the following:\r\n```\r\njava.lang.ClassFormatError: Field \"fortyTwo\" in class com/foo/bar/GeneratedSubclassOf$com$foo$bar$Baz$26753A95 has illegal signature \"V\"\r\n```\r\n\r\nThis is because the return type of a \"field setter\" method handle as acquired via `JavaConstant.MethodHandle.ofSetter(FieldDescription.InDefinedShape)` will always be `void`, which is correct (see line 626 below):\r\n\r\nhttps://github.com/raphw/byte-buddy/blob/291a512c609b647edccfdead540764ee402abd00/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L623-L627\r\n\r\nBut [section 5.4.3.5 of the JVM specification](https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.5-240) indicates that if your method handle is of types 1 through 4 inclusive (which `PUT_FIELD` and `PUT_STATIC_FIELD` are), then resolution of the constant must follow the rules of field resolution. [Those rules](https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.2) indicate that the descriptor of the field reference needs to be used. ByteBuddy is instead using the method handle's return type descriptor, which, in the case of field setter method handles, anyway, is `V`.\r\n\r\nThe workaround that seems to get around this problem is to create a subclass of `JavaConstant.MethodHandle` that overrides the `getDescriptor()` method to do the right thing:\r\n```java\r\n@Override\r\npublic final String getDescriptor() {\r\n // See https://stackoverflow.com/questions/64296731/how-do-i-install-and-use-a-constant-methodhandle-in-bytebuddy.\r\n switch (this.getHandleType()) {\r\n case PUT_FIELD:\r\n case PUT_STATIC_FIELD:\r\n // In the case of \"field setter\" method handles use the sole parameter type's descriptor\r\n // to follow the rules prescribed by\r\n // https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.5-240\r\n return this.getParameterTypes().getOnly().getDescriptor();\r\n default:\r\n return super.getDescriptor();\r\n }\r\n}\r\n```\r\n\r\nWith this override, I can avoid the `ClassFormatError`. (I don't know if it is best to solve the problem here or in `asConstantPoolValue()`.)\r\n\r\nI'll attempt to put together a PR shortly.\r\n\r\nThanks again for a great project."},"base_sha":{"kind":"string","value":"291a512c609b647edccfdead540764ee402abd00"},"head_sha":{"kind":"string","value":"3795ee8733b2f8d0904fe28121a550c5e2b95997"},"diff_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/compare/291a512c609b647edccfdead540764ee402abd00...3795ee8733b2f8d0904fe28121a550c5e2b95997"},"diff":{"kind":"string","value":"diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\nindex 51ad4443c8..5e0e4e2bb6 100644\n--- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\n+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\n@@ -692,9 +692,11 @@ public interface JavaConstant {\n * @return The method descriptor of this method handle representation.\n */\n public String getDescriptor() {\n- if (handleType.isField()) {\n- return returnType.getDescriptor();\n- } else {\n+ switch (handleType) {\n+ case PUT_FIELD:\n+ case PUT_STATIC_FIELD:\n+ return parameterTypes.get(0).getDescriptor();\n+ default:\n StringBuilder stringBuilder = new StringBuilder().append('(');\n for (TypeDescription parameterType : parameterTypes) {\n stringBuilder.append(parameterType.getDescriptor());\ndiff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java\nindex b0b482f049..71b8ed1c47 100644\n--- a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java\n+++ b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java\n@@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;\n \n public class JavaConstantMethodHandleTest {\n \n- private static final String BAR = \"bar\", QUX = \"qux\";\n+ private static final String BAR = \"bar\", FROB = \"frob\", QUX = \"qux\";\n \n @Rule\n public MethodRule javaVersionRule = new JavaVersionRule();\n@@ -106,12 +106,13 @@ public class JavaConstantMethodHandleTest {\n @Test\n @SuppressWarnings(\"unchecked\")\n public void testMethodHandleOfSetter() throws Exception {\n- JavaConstant.MethodHandle methodHandle = JavaConstant.MethodHandle.ofSetter(Foo.class.getDeclaredField(BAR));\n+ JavaConstant.MethodHandle methodHandle = JavaConstant.MethodHandle.ofSetter(Foo.class.getDeclaredField(FROB));\n assertThat(methodHandle.getHandleType(), is(JavaConstant.MethodHandle.HandleType.PUT_FIELD));\n- assertThat(methodHandle.getName(), is(BAR));\n+ assertThat(methodHandle.getName(), is(FROB));\n assertThat(methodHandle.getOwnerType(), is((TypeDescription) TypeDescription.ForLoadedType.of(Foo.class)));\n assertThat(methodHandle.getReturnType(), is(TypeDescription.VOID));\n- assertThat(methodHandle.getParameterTypes(), is((List) new TypeList.ForLoadedTypes(Void.class)));\n+ assertThat(methodHandle.getParameterTypes(), is((List) new TypeList.ForLoadedTypes(Integer.class)));\n+ assertThat(methodHandle.getDescriptor(), is(methodHandle.getParameterTypes().getOnly().getDescriptor()));\n }\n \n @Test\n@@ -123,6 +124,7 @@ public class JavaConstantMethodHandleTest {\n assertThat(methodHandle.getOwnerType(), is((TypeDescription) TypeDescription.ForLoadedType.of(Foo.class)));\n assertThat(methodHandle.getReturnType(), is(TypeDescription.VOID));\n assertThat(methodHandle.getParameterTypes(), is((List) new TypeList.ForLoadedTypes(Void.class)));\n+ assertThat(methodHandle.getDescriptor(), is(methodHandle.getParameterTypes().getOnly().getDescriptor()));\n }\n \n @Test\n@@ -195,6 +197,8 @@ public class JavaConstantMethodHandleTest {\n \n public Void bar;\n \n+ public Integer frob;\n+ \n public Foo(Void value) {\n /* empty*/\n }"},"changed_files":{"kind":"string","value":"['byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.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":7028418,"string":"7,028,418"},"repo_tokens_count":{"kind":"number","value":1179473,"string":"1,179,473"},"repo_lines_count":{"kind":"number","value":163217,"string":"163,217"},"repo_files_without_tests_count":{"kind":"number","value":353,"string":"353"},"changed_symbols_count":{"kind":"number","value":299,"string":"299"},"changed_tokens_count":{"kind":"number","value":51,"string":"51"},"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":3029,"string":"3,029"},"issue_words_count":{"kind":"number","value":321,"string":"321"},"issue_tokens_count":{"kind":"number","value":786,"string":"786"},"issue_lines_count":{"kind":"number","value":42,"string":"42"},"issue_links_count":{"kind":"number","value":7,"string":"7"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:42","string":"1970-01-01T00:26:42"},"repo_stars":{"kind":"number","value":5668,"string":"5,668"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1371,"cells":{"id":{"kind":"number","value":384,"string":"384"},"text_id":{"kind":"string","value":"raphw/byte-buddy/955/954"},"repo_owner":{"kind":"string","value":"raphw"},"repo_name":{"kind":"string","value":"byte-buddy"},"issue_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/issues/954"},"pull_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/955"},"comment_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/955"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"The type assignability check in JavaConstant.Dynamic.ofInvocation() is too strict"},"issue_body":{"kind":"string","value":"Hi; it's me again; sorry!\r\n\r\nFor background: https://stackoverflow.com/questions/64360249/is-type-assignability-too-strict-in-javaconstant-dynamic-ofinvocation\r\n\r\nIn very concrete terms, I think that this assignability check:\r\n\r\nhttps://github.com/raphw/byte-buddy/blob/e4ce4af1bab578a7ac3497d07449e50628d050e7/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L1636-L1638\r\n\r\n…is too strict given that it prevents a method from being invoked that uses varargs. Specifically, `iterator.next()` will, in such a case, return something like `Glorp[]`, and (let's say) `Glorp` is not assignable to `Glorp[]`.\r\n\r\nSuppose I have:\r\n```\r\nstatic final JavaConstant toJavaConstant(final Glorp[] glorps) {\r\n final JavaConstant[] javaConstants = new JavaConstant[glorps.length];\r\n for (int i = 0; i < javaConstants.length; i++) {\r\n javaConstants[i] = toJavaConstant(glorps[i]); // another version of this method that works on scalars\r\n }\r\n return JavaConstant.Dynamic.ofInvocation(SOME_METHOD_THAT_ACCEPTS_A_VARARGS_OF_THINGS, javaConstants);\r\n}\r\n```\r\n…and `SOME_METHOD_THAT_ACCEPTS_A_VARARGS_OF_THINGS` is a `MethodDescription.InDefinedShape` that resolves to something like this:\r\n```\r\npublic static final Glorp[] toGlorps(final Glorp... glorps) {\r\n return glorps;\r\n}\r\n```\r\nCurrently, ByteBuddy will not allow this because of that type assignability check.\r\n\r\nIf I comment out lines 1636 through 1638, i.e. if I disable the type assignability check, this construction works just fine (probably thanks to all the `MethodHandle` argument conversion machinery happening at constant resolution time).\r\n\r\nI'll file a PR shortly."},"base_sha":{"kind":"string","value":"e4ce4af1bab578a7ac3497d07449e50628d050e7"},"head_sha":{"kind":"string","value":"9c7ce054a3607820241310f85a2fe44ed45e6473"},"diff_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/compare/e4ce4af1bab578a7ac3497d07449e50628d050e7...9c7ce054a3607820241310f85a2fe44ed45e6473"},"diff":{"kind":"string","value":"diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\nindex 51ad4443c8..b4b1b108ca 100644\n--- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\n+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\n@@ -1602,7 +1602,7 @@ public interface JavaConstant {\n public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List constants) {\n if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) {\n throw new IllegalArgumentException(\"Bootstrap method is no constructor or non-void static factory: \" + methodDescription);\n- } else if (methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {\n+ } else if (!methodDescription.isVarArgs() && methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {\n throw new IllegalArgumentException(\"Cannot assign \" + constants + \" to \" + methodDescription);\n }\n List arguments = new ArrayList(constants.size());\n@@ -1633,8 +1633,13 @@ public interface JavaConstant {\n throw new IllegalArgumentException(\"Not a compile-time constant: \" + constant);\n }\n }\n- if (!typeDescription.isAssignableTo(iterator.next())) {\n- throw new IllegalArgumentException(\"Cannot assign \" + constants + \" to \" + methodDescription);\n+ if (iterator.hasNext()) {\n+ TypeDescription next = iterator.next();\n+ if (!typeDescription.isAssignableTo(next)) {\n+ if (!methodDescription.isVarArgs() || iterator.hasNext() || !next.isArray() || !typeDescription.isAssignableTo(next.getComponentType())) {\n+ throw new IllegalArgumentException(\"Cannot assign \" + constants + \" to \" + methodDescription);\n+ }\n+ }\n }\n }\n return new Dynamic(new ConstantDynamic(\"invoke\",\ndiff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java\nindex f95547b3e1..faaa07f74a 100644\n--- a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java\n+++ b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java\n@@ -1,5 +1,7 @@\n package net.bytebuddy.utility;\n \n+import java.lang.reflect.Method;\n+\n import net.bytebuddy.ByteBuddy;\n import net.bytebuddy.description.type.TypeDescription;\n import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;\n@@ -478,6 +480,24 @@ public class JavaConstantDynamicTest {\n assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));\n }\n \n+ @Test\n+ @JavaVersionRule.Enforce(11)\n+ public void testInvocationOfVarargsMethod() throws Exception {\n+ final Integer[] sourceIntegers = new Integer[] { Integer.valueOf(1), Integer.valueOf(2) };\n+ Class baz = new ByteBuddy()\n+ .subclass(Foo.class)\n+ .method(isDeclaredBy(Foo.class))\n+ .intercept(FixedValue.value(toJavaConstant(sourceIntegers)))\n+ .make()\n+ .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)\n+ .getLoaded();\n+ assertThat(baz.getDeclaredFields().length, is(0));\n+ assertThat(baz.getDeclaredMethods().length, is(1));\n+ Foo foo = baz.getDeclaredConstructor().newInstance();\n+ assertThat((Integer[])baz.getDeclaredMethod(FOO).invoke(foo), equalTo(sourceIntegers));\n+ assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));\n+ }\n+\n @Test\n @JavaVersionRule.Enforce(11)\n public void testStaticFieldVarHandle() throws Exception {\n@@ -649,6 +669,7 @@ public class JavaConstantDynamicTest {\n public Object bar() {\n return null;\n }\n+\n }\n \n private static Object methodHandle() throws Exception {\n@@ -660,4 +681,24 @@ public class JavaConstantDynamicTest {\n private static Object methodType() throws Exception {\n return Class.forName(\"java.lang.invoke.MethodType\").getMethod(\"methodType\", Class.class).invoke(null, void.class);\n }\n+\n+ private static JavaConstant toJavaConstant(Integer[] integers) throws Exception {\n+ // This is convoluted and exists only to test issue #954.\n+ JavaConstant[] constants = new JavaConstant[integers.length];\n+ for (int i = 0; i < integers.length; i++) {\n+ constants[i] = toJavaConstant(integers[i]);\n+ }\n+ return JavaConstant.Dynamic.ofInvocation(JavaConstantDynamicTest.class.getDeclaredMethod(\"toIntegers\", Integer[].class), constants);\n+ }\n+\n+ private static JavaConstant toJavaConstant(Integer i) throws Exception {\n+ // This is convoluted and exists only to test issue #954.\n+ return JavaConstant.Dynamic.ofInvocation(Integer.class.getMethod(\"valueOf\", String.class), i.toString());\n+ }\n+\n+ public static Integer[] toIntegers(final Integer... varargs) {\n+ // This is convoluted and exists only to test issue #954.\n+ return varargs;\n+ }\n+\n }"},"changed_files":{"kind":"string","value":"['byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.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":7028418,"string":"7,028,418"},"repo_tokens_count":{"kind":"number","value":1179473,"string":"1,179,473"},"repo_lines_count":{"kind":"number","value":163217,"string":"163,217"},"repo_files_without_tests_count":{"kind":"number","value":353,"string":"353"},"changed_symbols_count":{"kind":"number","value":1062,"string":"1,062"},"changed_tokens_count":{"kind":"number","value":189,"string":"189"},"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":1640,"string":"1,640"},"issue_words_count":{"kind":"number","value":176,"string":"176"},"issue_tokens_count":{"kind":"number","value":421,"string":"421"},"issue_lines_count":{"kind":"number","value":31,"string":"31"},"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:26:42","string":"1970-01-01T00:26:42"},"repo_stars":{"kind":"number","value":5668,"string":"5,668"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1372,"cells":{"id":{"kind":"number","value":383,"string":"383"},"text_id":{"kind":"string","value":"raphw/byte-buddy/958/957"},"repo_owner":{"kind":"string","value":"raphw"},"repo_name":{"kind":"string","value":"byte-buddy"},"issue_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/issues/957"},"pull_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/958"},"comment_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/pull/958"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"JavaConstant.Dynamic.ofInvocation() doesn't seem to permit interface default methods as bootstrap methods"},"issue_body":{"kind":"string","value":"Using JDK 15, if I try to use `List#of(E[])` (a `static` interface method declared on `List` itself) as a bootstrap method, I get:\r\n```\r\njava.lang.IncompatibleClassChangeError: Inconsistent constant pool data in classfile for class java/util/List. Method 'java.util.List of(java.lang.Object[])' at index 19 is CONSTANT_MethodRef and should be CONSTANT_InterfaceMethodRef\r\n\tat java.base/java.lang.invoke.MethodHandleNatives.copyOutBootstrapArguments(Native Method)\r\n\tat java.base/java.lang.invoke.BootstrapMethodInvoker$VM_BSCI.copyConstants(BootstrapMethodInvoker.java:402)\r\n\tat java.base/java.lang.invoke.BootstrapMethodInvoker$VM_BSCI.fillCache(BootstrapMethodInvoker.java:377)\r\n\tat java.base/java.lang.invoke.AbstractConstantGroup$WithCache.get(AbstractConstantGroup.java:278)\r\n\tat java.base/java.lang.invoke.BootstrapMethodInvoker$PullAdapter.pullFromBootstrapMethod(BootstrapMethodInvoker.java:509)\r\n\tat java.base/java.lang.invoke.BootstrapMethodInvoker.invoke(BootstrapMethodInvoker.java:117)\r\n\tat java.base/java.lang.invoke.ConstantBootstraps.makeConstant(ConstantBootstraps.java:72)\r\n\tat java.base/java.lang.invoke.MethodHandleNatives.linkDynamicConstantImpl(MethodHandleNatives.java:327)\r\n\tat java.base/java.lang.invoke.MethodHandleNatives.linkDynamicConstant(MethodHandleNatives.java:319)\r\n```\r\nI've edited this bug description to remove what I thought was the problem. Now I just don't know what the problem is at all. 😄 "},"base_sha":{"kind":"string","value":"e4ce4af1bab578a7ac3497d07449e50628d050e7"},"head_sha":{"kind":"string","value":"265b0c623ffe1c323d524f0ffdbdf104adba1071"},"diff_url":{"kind":"string","value":"https://github.com/raphw/byte-buddy/compare/e4ce4af1bab578a7ac3497d07449e50628d050e7...265b0c623ffe1c323d524f0ffdbdf104adba1071"},"diff":{"kind":"string","value":"diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\nindex 51ad4443c8..85769d7735 100644\n--- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\n+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java\n@@ -1610,7 +1610,7 @@ public interface JavaConstant {\n methodDescription.getDeclaringType().getInternalName(),\n methodDescription.getInternalName(),\n methodDescription.getDescriptor(),\n- false));\n+ methodDescription.getDeclaringType().isInterface()));\n Iterator iterator = (methodDescription.isStatic() || methodDescription.isConstructor()\n ? methodDescription.getParameters().asTypeList().asErasures()\n : CompoundList.of(methodDescription.getDeclaringType(), methodDescription.getParameters().asTypeList().asErasures())).iterator();"},"changed_files":{"kind":"string","value":"['byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.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":7028418,"string":"7,028,418"},"repo_tokens_count":{"kind":"number","value":1179473,"string":"1,179,473"},"repo_lines_count":{"kind":"number","value":163217,"string":"163,217"},"repo_files_without_tests_count":{"kind":"number","value":353,"string":"353"},"changed_symbols_count":{"kind":"number","value":104,"string":"104"},"changed_tokens_count":{"kind":"number","value":14,"string":"14"},"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":1434,"string":"1,434"},"issue_words_count":{"kind":"number","value":91,"string":"91"},"issue_tokens_count":{"kind":"number","value":318,"string":"318"},"issue_lines_count":{"kind":"number","value":14,"string":"14"},"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:42","string":"1970-01-01T00:26:42"},"repo_stars":{"kind":"number","value":5668,"string":"5,668"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1373,"cells":{"id":{"kind":"number","value":8968,"string":"8,968"},"text_id":{"kind":"string","value":"wiremock/wiremock/2277/2085"},"repo_owner":{"kind":"string","value":"wiremock"},"repo_name":{"kind":"string","value":"wiremock"},"issue_url":{"kind":"string","value":"https://github.com/wiremock/wiremock/issues/2085"},"pull_url":{"kind":"string","value":"https://github.com/wiremock/wiremock/pull/2277"},"comment_url":{"kind":"string","value":"https://github.com/wiremock/wiremock/pull/2277"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"Result (emptyJson) returned immediately without being stored in a variable, if any"},"issue_body":{"kind":"string","value":"https://github.com/wiremock/wiremock/blob/25b82f9f97f3cc09136097b249cfd37aef924c36/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java#L60\r\n\r\nResult (emptyJson) returned immediately without being stored in a variable, if any"},"base_sha":{"kind":"string","value":"7b8a7d351255342d8d22cb5217b6847cc8ddaa29"},"head_sha":{"kind":"string","value":"831fc3090d83148420aee214bb0bb892163d87f5"},"diff_url":{"kind":"string","value":"https://github.com/wiremock/wiremock/compare/7b8a7d351255342d8d22cb5217b6847cc8ddaa29...831fc3090d83148420aee214bb0bb892163d87f5"},"diff":{"kind":"string","value":"diff --git a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java\nindex 6260fa064..e7f42f687 100644\n--- a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java\n+++ b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (C) 2021 Thomas Akehurst\n+ * Copyright (C) 2021-2023 Thomas Akehurst\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@@ -57,13 +57,13 @@ public class ParseJsonHelper extends HandlebarsHelper {\n // Edge case if JSON object is empty {}\n String jsonAsStringWithoutSpace = jsonAsString.replaceAll(\"\\\\\\\\s\", \"\");\n if (jsonAsStringWithoutSpace.equals(\"{}\") || jsonAsStringWithoutSpace.equals(\"\")) {\n- return result;\n- }\n-\n- if (jsonAsString.startsWith(\"[\") && jsonAsString.endsWith(\"]\")) {\n- result = Json.read(jsonAsString, new TypeReference>() {});\n+ result = new HashMap();\n } else {\n- result = Json.read(jsonAsString, new TypeReference>() {});\n+ if (jsonAsString.startsWith(\"[\") && jsonAsString.endsWith(\"]\")) {\n+ result = Json.read(jsonAsString, new TypeReference>() {});\n+ } else {\n+ result = Json.read(jsonAsString, new TypeReference>() {});\n+ }\n }\n }\n \ndiff --git a/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java b/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java\nindex ad973c9da..2f3195651 100644\n--- a/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java\n+++ b/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java\n@@ -33,9 +33,7 @@ import java.util.List;\n import java.util.UUID;\n import java.util.stream.Collectors;\n \n-/**\n- * @deprecated this is the legacy recorder and will be removed before 3.x is out of beta\n- */\n+/** @deprecated this is the legacy recorder and will be removed before 3.x is out of beta */\n @Deprecated\n public class StubMappingJsonRecorder implements RequestListener {\n \ndiff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java\nindex 2ac9bd44d..fadedf8c6 100644\n--- a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java\n+++ b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java\n@@ -914,6 +914,26 @@ public class ResponseTemplateTransformerTest {\n assertThat(transform(\"{{parseJson}}\"), is(\"[ERROR: Missing required JSON string parameter]\"));\n }\n \n+ @Test\n+ public void parsesEmptyJsonLiteralToAnEmptyMap() {\n+ String result = transform(\"{{#parseJson 'parsedObj'}}\\\\n\" + \"{\\\\n\" + \"}\\\\n\" + \"{{/parseJson}}\\\\n\");\n+\n+ assertThat(result, equalToCompressingWhiteSpace(\"\"));\n+ }\n+\n+ @Test\n+ public void parsesEmptyJsonVariableToAnEmptyMap() {\n+ String result =\n+ transform(\n+ \"{{#assign 'json'}}\\\\n\"\n+ + \"{\\\\n\"\n+ + \"}\\\\n\"\n+ + \"{{/assign}}\\\\n\"\n+ + \"{{parseJson json 'parsedObj'}}\\\\n\");\n+\n+ assertThat(result, equalToCompressingWhiteSpace(\"\"));\n+ }\n+\n @Test\n public void conditionalBranchingOnStringMatchesRegexInline() {\n assertThat(transform(\"{{#if (matches '123' '[0-9]+')}}YES{{/if}}\"), is(\"YES\"));\ndiff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java\nindex b5caba622..0bf38da67 100644\n--- a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java\n+++ b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (C) 2021 Thomas Akehurst\n+ * Copyright (C) 2021-2023 Thomas Akehurst\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@@ -16,8 +16,16 @@\n package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n \n import static org.hamcrest.MatcherAssert.assertThat;\n-import static org.hamcrest.Matchers.*;\n-\n+import static org.hamcrest.Matchers.aMapWithSize;\n+import static org.hamcrest.Matchers.hasEntry;\n+import static org.hamcrest.Matchers.hasKey;\n+import static org.hamcrest.Matchers.hasSize;\n+import static org.hamcrest.Matchers.instanceOf;\n+import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.isA;\n+import static org.hamcrest.Matchers.nullValue;\n+\n+import com.github.jknack.handlebars.Handlebars;\n import com.github.jknack.handlebars.Options;\n import com.github.jknack.handlebars.TagType;\n import com.github.jknack.handlebars.Template;\n@@ -116,10 +124,54 @@ public class ParseJsonHelperTest extends HandlebarsHelperTestBase {\n \n @Test\n public void parsesEmptyJsonIfSection() throws Exception {\n+ String inputJson = \"\";\n+ String variableName = \"parsedObject\";\n+ Template template = new Handlebars().compileInline(inputJson);\n+ Options options =\n+ new Options.Builder(null, null, TagType.SECTION, createContext(), template)\n+ .setParams(new Object[] {})\n+ .build();\n+ Object output = render(variableName, options);\n+\n+ // Check that it returns null\n+ assertThat(output, is(nullValue()));\n+\n+ /* Check that it stores parsed json (an empty map in this case because json is empty)\n+ * in given variable name */\n+ Object storedData = options.data(variableName);\n+ assertThat(storedData, isA(Map.class));\n+ Map castedData = (Map) storedData;\n+ assertThat(castedData, is(aMapWithSize(0)));\n+ }\n+\n+ @Test\n+ public void parsesEmptyJsonWithBracesIfSection() throws Exception {\n String inputJson = \"{}\";\n- Object output = render(inputJson, new Object[] {}, TagType.SECTION);\n+ String variableName = \"parsedObject\";\n+ Template template = new Handlebars().compileInline(inputJson);\n+ Options options =\n+ new Options.Builder(null, null, TagType.SECTION, createContext(), template)\n+ .setParams(new Object[] {})\n+ .build();\n+ Object output = render(variableName, options);\n+\n+ // Check that it returns null\n+ assertThat(output, is(nullValue()));\n+\n+ /* Check that it stores parsed json (an empty map in this case because json is empty)\n+ * in given variable name */\n+ Object storedData = options.data(variableName);\n+ assertThat(storedData, isA(Map.class));\n+ Map castedData = (Map) storedData;\n+ assertThat(castedData, is(aMapWithSize(0)));\n+ }\n \n- // Check that it returns empty object\n+ @Test\n+ public void parsesEmptyJsonIfSectionIfVariableNameNull() throws Exception {\n+ String variableName = null;\n+ Object output = render(variableName, new Object[] {}, TagType.SECTION);\n+\n+ // Check that it returns empty object because variable name is null\n assertThat(output, instanceOf(Map.class));\n Map result = (Map) output;\n assertThat(result, aMapWithSize(0));\n@@ -127,20 +179,68 @@ public class ParseJsonHelperTest extends HandlebarsHelperTestBase {\n \n @Test\n public void parsesEmptyJsonIfNotSection() throws Exception {\n+ String inputJson = \"\";\n+ String variableName = \"parsedObject\";\n+ Object[] params = {variableName};\n+ Options options =\n+ new Options.Builder(null, null, TagType.VAR, createContext(), Template.EMPTY)\n+ .setParams(params)\n+ .build();\n+ Object output = render(inputJson, options);\n+\n+ // Check that it returns empty object\n+ assertThat(output, is(nullValue()));\n+\n+ /* Check that it stores parsed json (an empty map in this case because json is empty)\n+ * in given variable name */\n+ Object storedData = options.data(variableName);\n+ assertThat(storedData, isA(Map.class));\n+ Map castedData = (Map) storedData;\n+ assertThat(castedData, is(aMapWithSize(0)));\n+ }\n+\n+ @Test\n+ public void parsesEmptyJsonWithBracesIfNotSection() throws Exception {\n String inputJson = \"{}\";\n- Object output = render(inputJson, new Object[] {}, TagType.VAR);\n+ String variableName = \"parsedObject\";\n+ Object[] params = {variableName};\n+ Options options =\n+ new Options.Builder(null, null, TagType.VAR, createContext(), Template.EMPTY)\n+ .setParams(params)\n+ .build();\n+ Object output = render(inputJson, options);\n \n // Check that it returns empty object\n+ assertThat(output, is(nullValue()));\n+\n+ /* Check that it stores parsed json (an empty map in this case because json is empty)\n+ * in given variable name */\n+ Object storedData = options.data(variableName);\n+ assertThat(storedData, isA(Map.class));\n+ Map castedData = (Map) storedData;\n+ assertThat(castedData, is(aMapWithSize(0)));\n+ }\n+\n+ @Test\n+ public void parsesEmptyJsonIfNotSectionIfVariableNameAbsent() throws Exception {\n+ String inputJson = \"{}\";\n+ Object output = render(inputJson, new Object[] {}, TagType.VAR);\n+\n+ // Check that it returns empty object because variable name is null\n assertThat(output, instanceOf(Map.class));\n Map result = (Map) output;\n assertThat(result, aMapWithSize(0));\n }\n \n private Object render(Object context, Object[] params, TagType tagType) throws IOException {\n- return helper.apply(\n+ return render(\n context,\n new Options.Builder(null, null, tagType, createContext(), Template.EMPTY)\n .setParams(params)\n .build());\n }\n+\n+ private Object render(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n }"},"changed_files":{"kind":"string","value":"['src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java', 'src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java', 'src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java', 'src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.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":1437077,"string":"1,437,077"},"repo_tokens_count":{"kind":"number","value":305440,"string":"305,440"},"repo_lines_count":{"kind":"number","value":43967,"string":"43,967"},"repo_files_without_tests_count":{"kind":"number","value":518,"string":"518"},"changed_symbols_count":{"kind":"number","value":878,"string":"878"},"changed_tokens_count":{"kind":"number","value":190,"string":"190"},"changed_lines_count":{"kind":"number","value":18,"string":"18"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":276,"string":"276"},"issue_words_count":{"kind":"number","value":13,"string":"13"},"issue_tokens_count":{"kind":"number","value":80,"string":"80"},"issue_lines_count":{"kind":"number","value":3,"string":"3"},"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:28:09","string":"1970-01-01T00:28:09"},"repo_stars":{"kind":"number","value":5664,"string":"5,664"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 3153326, 'SCSS': 65082, 'XSLT': 14502, 'HTML': 11389, 'Scala': 6556, 'JavaScript': 1343, 'Shell': 1066, 'Ruby': 117}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1374,"cells":{"id":{"kind":"number","value":9220,"string":"9,220"},"text_id":{"kind":"string","value":"shopify/react-native-skia/814/813"},"repo_owner":{"kind":"string","value":"shopify"},"repo_name":{"kind":"string","value":"react-native-skia"},"issue_url":{"kind":"string","value":"https://github.com/Shopify/react-native-skia/issues/813"},"pull_url":{"kind":"string","value":"https://github.com/Shopify/react-native-skia/pull/814"},"comment_url":{"kind":"string","value":"https://github.com/Shopify/react-native-skia/pull/814"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Android: Multitouch not working as expected"},"issue_body":{"kind":"string","value":"### Description\n\nMultitouch example (API/Touch) is not working on Android.\n\n### Version\n\n0.1.139\n\n### Steps to reproduce\n\nRun the API/Touch Handling on Android in the Example app and perform one or more touches on the screen with multiple fingers. \r\n\r\nExpected: Each finger should have a colored ring that follows your finger\r\nObserved: Only the first finger has a correct ring, all other moves and touches looks very wrong\n\n### Snack, code example, screenshot, or link to a repository\n\nhttps://github.com/Shopify/react-native-skia"},"base_sha":{"kind":"string","value":"1612227e4dcfc5662a40ef887b2d93409657e8a1"},"head_sha":{"kind":"string","value":"f81d6327163661096155788f502322ce762e9008"},"diff_url":{"kind":"string","value":"https://github.com/shopify/react-native-skia/compare/1612227e4dcfc5662a40ef887b2d93409657e8a1...f81d6327163661096155788f502322ce762e9008"},"diff":{"kind":"string","value":"diff --git a/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java b/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java\nindex 4df19305..540b77e1 100644\n--- a/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java\n+++ b/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java\n@@ -2,7 +2,6 @@ package com.shopify.reactnative.skia;\n \n import android.content.Context;\n import android.graphics.SurfaceTexture;\n-import android.util.Log;\n import android.view.Surface;\n import android.view.TextureView;\n import android.view.MotionEvent;\n@@ -56,37 +55,74 @@ public class SkiaDrawView extends TextureView implements TextureView.SurfaceText\n \n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n- int action = ev.getAction();\n- int count = ev.getPointerCount();\n+ // https://developer.android.com/training/gestures/multi\n+ int action = ev.getActionMasked();\n+\n MotionEvent.PointerCoords r = new MotionEvent.PointerCoords();\n- double[] points = new double[count*5];\n- for (int i = 0; i < count; i++) {\n- ev.getPointerCoords(i, r);\n- points[i] = r.x;\n- points[i+1] = r.y;\n- points[i+2] = ev.getPressure(i);\n- switch (action) {\n- case MotionEvent.ACTION_DOWN:\n- case MotionEvent.ACTION_POINTER_DOWN:\n- points[i+3] = 0;\n- break;\n- case MotionEvent.ACTION_MOVE:\n- points[i+3] = 1;\n- break;\n- case MotionEvent.ACTION_UP:\n- case MotionEvent.ACTION_POINTER_UP:\n- points[i+3] = 2;\n- break;\n- case MotionEvent.ACTION_CANCEL:\n- points[i+3] = 3;\n- break;\n+\n+ double[] points;\n+\n+ // If this is a pointer_up/down event we need to handle it a bit specialized\n+ switch (action) {\n+ case MotionEvent.ACTION_POINTER_DOWN:\n+ case MotionEvent.ACTION_POINTER_UP: {\n+ points = new double[5];\n+ int pointerIndex = ev.getActionIndex();\n+ ev.getPointerCoords(pointerIndex, r);\n+ points[0] = r.x;\n+ points[1] = r.y;\n+ points[2] = ev.getPressure(pointerIndex);\n+ points[3] = motionActionToType(action);\n+ points[4] = ev.getPointerId(pointerIndex);\n+\n+ updateTouchPoints(points);\n+\n+ break;\n+ }\n+ default: {\n+ // For the rest we can just handle it like expected\n+ int count = ev.getPointerCount();\n+ int pointerIndex = 0;\n+ points = new double[5 * count];\n+ for (int i = 0; i < count; i++) {\n+ ev.getPointerCoords(i, r);\n+ points[pointerIndex++] = r.x;\n+ points[pointerIndex++] = r.y;\n+ points[pointerIndex++] = ev.getPressure(i);\n+ points[pointerIndex++] = motionActionToType(action);\n+ points[pointerIndex++] = ev.getPointerId(i);\n+ }\n+\n+ updateTouchPoints(points);\n+\n+ break;\n }\n- points[i+4] = ev.getPointerId(i);\n }\n- updateTouchPoints(points);\n+\n return true;\n }\n \n+ private static int motionActionToType(int action) {\n+ int actionType = 3;\n+ switch (action) {\n+ case MotionEvent.ACTION_DOWN:\n+ case MotionEvent.ACTION_POINTER_DOWN:\n+ actionType = 0;\n+ break;\n+ case MotionEvent.ACTION_MOVE:\n+ actionType = 1;\n+ break;\n+ case MotionEvent.ACTION_UP:\n+ case MotionEvent.ACTION_POINTER_UP:\n+ actionType = 2;\n+ break;\n+ case MotionEvent.ACTION_CANCEL:\n+ actionType = 3;\n+ break;\n+ }\n+ return actionType;\n+ }\n+\n @Override\n public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {\n mSurface = new Surface(surface);"},"changed_files":{"kind":"string","value":"['package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.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":32586,"string":"32,586"},"repo_tokens_count":{"kind":"number","value":6587,"string":"6,587"},"repo_lines_count":{"kind":"number","value":992,"string":"992"},"repo_files_without_tests_count":{"kind":"number","value":12,"string":"12"},"changed_symbols_count":{"kind":"number","value":3252,"string":"3,252"},"changed_tokens_count":{"kind":"number","value":615,"string":"615"},"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":531,"string":"531"},"issue_words_count":{"kind":"number","value":79,"string":"79"},"issue_tokens_count":{"kind":"number","value":119,"string":"119"},"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":0,"string":"0"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:40","string":"1970-01-01T00:27:40"},"repo_stars":{"kind":"number","value":5300,"string":"5,300"},"repo_language":{"kind":"string","value":"TypeScript"},"repo_languages":{"kind":"string","value":"{'TypeScript': 1013030, 'C++': 584955, 'Java': 36511, 'Objective-C++': 26443, 'JavaScript': 16557, 'Objective-C': 9224, 'CMake': 6620, 'Ruby': 3879, 'Starlark': 602, 'HTML': 428, 'C': 104}"},"repo_license":{"kind":"string","value":"MIT License"}}},{"rowIdx":1375,"cells":{"id":{"kind":"number","value":10190,"string":"10,190"},"text_id":{"kind":"string","value":"StarRocks/starrocks/23320/2527"},"repo_owner":{"kind":"string","value":"StarRocks"},"repo_name":{"kind":"string","value":"starrocks"},"issue_url":{"kind":"string","value":"https://github.com/StarRocks/starrocks/issues/2527"},"pull_url":{"kind":"string","value":"https://github.com/StarRocks/starrocks/pull/23320"},"comment_url":{"kind":"string","value":"https://github.com/StarRocks/starrocks/pull/23320"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Wrong result return while date type of column is `datetime`."},"issue_body":{"kind":"string","value":"\r\ninsert and delete error.\r\n1. Precision problem of `datetime` when insert into table values.\r\n2. Delete error('ERROR 1064 (HY000): Invalid column value[null] for column k2')\r\n### Steps to reproduce the behavior (Required)\r\n```\r\nmysql> CREATE TABLE test_string2 (`k1` string not null,k2 datetime) ENGINE=OLAP duplicate key(k1) DISTRIBUTED BY HASH(`k1`) BUCKETS 3 PROPERTIES (\"replication_num\" = \"1\");\r\nQuery OK, 0 rows affected (0.01 sec)\r\n\r\nmysql> insert into test_string2 values('2021-12-29 16:58:56.032000','2021-12-29 16:58:56.032000');\r\nQuery OK, 1 row affected (0.03 sec)\r\n{'label':'insert_5e9563d2-689f-11ec-8fab-00163e10c9d6', 'status':'VISIBLE', 'txnId':'33055'}\r\n\r\nmysql> select * from test_string2;\r\n+----------------------------+----------------------------+\r\n| k1 | k2 |\r\n+----------------------------+----------------------------+\r\n| 2021-12-29 16:58:56.032000 | 2021-12-29 16:58:56.032000 |\r\n+----------------------------+----------------------------+\r\n1 row in set (0.01 sec)\r\n\r\nmysql> delete from test_string2 where k2='2021-12-29 16:58:56.032000';\r\nERROR 1064 (HY000): Invalid column value[null] for column k2\r\nmysql> delete from test_string2 where k1='2021-12-29 16:58:56.032000';\r\nQuery OK, 0 rows affected (0.02 sec)\r\n{'label':'delete_a088fb14-0748-44ce-b354-18e3b66fc20d', 'status':'VISIBLE', 'txnId':'33056'}\r\n\r\nmysql> select * from test_string2;\r\nEmpty set (0.00 sec)\r\n```\r\n\r\n-mysql\r\n```\r\nmysql> CREATE TABLE test_string2 (`k1` datetime not null,k2 datetime);\r\nQuery OK, 0 rows affected (0.02 sec)\r\n\r\nmysql> insert into test_string2 values('2021-12-29 16:58:56.032000','2021-12-29 16:58:56.032000');\r\nQuery OK, 1 row affected (0.00 sec)\r\n\r\nmysql> select * from test_string2;\r\n+---------------------+---------------------+\r\n| k1 | k2 |\r\n+---------------------+---------------------+\r\n| 2021-12-29 16:58:56 | 2021-12-29 16:58:56 |\r\n+---------------------+---------------------+\r\n1 row in set (0.00 sec)\r\n```\r\n\r\n### Expected behavior (Required)\r\n```\r\nmysql> select * from test_string2;\r\n+---------------------+---------------------+\r\n| k1 | k2 |\r\n+---------------------+---------------------+\r\n| 2021-12-29 16:58:56 | 2021-12-29 16:58:56 |\r\n+---------------------+---------------------+\r\n1 row in set (0.00 sec)\r\n```\r\n### Real behavior (Required)\r\n```\r\nmysql> select * from test_string2;\r\n+----------------------------+----------------------------+\r\n| k1 | k2 |\r\n+----------------------------+----------------------------+\r\n| 2021-12-29 16:58:56.032000 | 2021-12-29 16:58:56.032000 |\r\n+----------------------------+----------------------------+\r\n1 row in set (0.01 sec)\r\n```\r\n### StarRocks version (Required)\r\n - You can get the StarRocks version by executing SQL `select current_version()`\r\n - 2.1"},"base_sha":{"kind":"string","value":"3585258b549767bff6c4638d379c8e67a697e923"},"head_sha":{"kind":"string","value":"1836a3a138a9ea19ff8795e0315bf04e1373a2d1"},"diff_url":{"kind":"string","value":"https://github.com/StarRocks/starrocks/compare/3585258b549767bff6c4638d379c8e67a697e923...1836a3a138a9ea19ff8795e0315bf04e1373a2d1"},"diff":{"kind":"string","value":"diff --git a/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java b/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java\nindex 42f8a622dd..406ea029fc 100644\n--- a/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java\n+++ b/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java\n@@ -64,6 +64,13 @@ public class MarkedCountDownLatch extends CountDownLatch {\n return false;\n }\n \n+ public synchronized boolean markedCountDown(K key, V value, Status status) {\n+ if (st.ok()) {\n+ st = status;\n+ }\n+ return markedCountDown(key, value);\n+ }\n+\n public synchronized List> getLeftMarks() {\n return Lists.newArrayList(marks.entries());\n }\ndiff --git a/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java b/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java\nindex 146cf68054..16921c61da 100644\n--- a/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java\n+++ b/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java\n@@ -224,12 +224,26 @@ public class LeaderImpl {\n String errMsg = \"task type: \" + taskType + \", status_code: \" + taskStatus.getStatus_code().toString() +\n \", backendId: \" + backendId + \", signature: \" + signature;\n task.setErrorMsg(errMsg);\n+ LOG.warn(errMsg);\n // We start to let FE perceive the task's error msg\n if (taskType != TTaskType.MAKE_SNAPSHOT && taskType != TTaskType.UPLOAD\n && taskType != TTaskType.DOWNLOAD && taskType != TTaskType.MOVE\n && taskType != TTaskType.CLONE && taskType != TTaskType.PUBLISH_VERSION\n && taskType != TTaskType.CREATE && taskType != TTaskType.UPDATE_TABLET_META_INFO\n && taskType != TTaskType.DROP_AUTO_INCREMENT_MAP) {\n+ if (taskType == TTaskType.REALTIME_PUSH) {\n+ PushTask pushTask = (PushTask) task;\n+ if (pushTask.getPushType() == TPushType.DELETE) {\n+ LOG.info(\"remove push replica. tabletId: {}, backendId: {}\", task.getSignature(),\n+ pushTask.getBackendId());\n+\n+ String failMsg = \"Backend: \" + task.getBackendId() + \"Tablet: \" + pushTask.getTabletId() +\n+ \" error msg: \" + taskStatus.getError_msgs().toString();\n+ pushTask.countDownLatch(pushTask.getBackendId(), pushTask.getTabletId(), failMsg);\n+ AgentTaskQueue.removeTask(pushTask.getBackendId(), TTaskType.REALTIME_PUSH, \n+ task.getSignature());\n+ }\n+ }\n return result;\n }\n }\ndiff --git a/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java b/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java\nindex 4c8b8f32df..11c9cc3836 100644\n--- a/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java\n+++ b/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java\n@@ -54,6 +54,7 @@ import com.starrocks.common.DdlException;\n import com.starrocks.common.FeConstants;\n import com.starrocks.common.MarkedCountDownLatch;\n import com.starrocks.common.MetaNotFoundException;\n+import com.starrocks.common.Status;\n import com.starrocks.common.UserException;\n import com.starrocks.qe.QueryStateException;\n import com.starrocks.server.GlobalStateMgr;\n@@ -183,6 +184,7 @@ public class OlapDeleteJob extends DeleteJob {\n } finally {\n db.readUnlock();\n }\n+ LOG.info(\"countDownLatch count: {}\", countDownLatch.getCount());\n \n long timeoutMs = getTimeoutMs();\n LOG.info(\"waiting delete Job finish, signature: {}, timeout: {}\", getTransactionId(), timeoutMs);\n@@ -208,59 +210,65 @@ public class OlapDeleteJob extends DeleteJob {\n } catch (InterruptedException e) {\n LOG.warn(\"InterruptedException: \", e);\n }\n+ LOG.info(\"delete job finish, countDownLatch count: {}\", countDownLatch.getCount());\n+ \n+ String errMsg = \"\";\n+ List> unfinishedMarks = countDownLatch.getLeftMarks();\n+ Status st = countDownLatch.getStatus();\n+ // only show at most 5 results\n+ List> subList = unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5));\n+ if (!subList.isEmpty()) {\n+ errMsg = \"unfinished replicas: \" + Joiner.on(\", \").join(subList);\n+ } else if (!st.ok()) {\n+ errMsg = st.toString();\n+ }\n+ LOG.warn(errMsg);\n \n- if (!ok) {\n- String errMsg = \"\";\n- List> unfinishedMarks = countDownLatch.getLeftMarks();\n- // only show at most 5 results\n- List> subList = unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5));\n- if (!subList.isEmpty()) {\n- errMsg = \"unfinished replicas: \" + Joiner.on(\", \").join(subList);\n- }\n- LOG.warn(errMsg);\n-\n- try {\n- checkAndUpdateQuorum();\n- } catch (MetaNotFoundException e) {\n- cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());\n- throw new DdlException(e.getMessage(), e);\n- }\n- DeleteState state = getState();\n- switch (state) {\n- case DELETING:\n- LOG.warn(\"delete job timeout: transactionId {}, timeout {}, {}\", getTransactionId(), timeoutMs,\n- errMsg);\n+ try {\n+ checkAndUpdateQuorum();\n+ } catch (MetaNotFoundException e) {\n+ cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());\n+ throw new DdlException(e.getMessage(), e);\n+ }\n+ DeleteState state = getState();\n+ switch (state) {\n+ case DELETING:\n+ LOG.warn(\"delete job failed: transactionId {}, timeout {}, {}\", getTransactionId(), timeoutMs,\n+ errMsg);\n+ if (countDownLatch.getCount() > 0) {\n cancel(DeleteHandler.CancelType.TIMEOUT, \"delete job timeout\");\n- throw new DdlException(\"failed to execute delete. transaction id \" + getTransactionId() +\n- \", timeout(ms) \" + timeoutMs + \", \" + errMsg);\n- case QUORUM_FINISHED:\n- case FINISHED:\n- try {\n- long nowQuorumTimeMs = System.currentTimeMillis();\n- long endQuorumTimeoutMs = nowQuorumTimeMs + timeoutMs / 2;\n- // if job's state is quorum_finished then wait for a period of time and commit it.\n- while (getState() == DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs) {\n- checkAndUpdateQuorum();\n- Thread.sleep(1000);\n- nowQuorumTimeMs = System.currentTimeMillis();\n- LOG.debug(\"wait for quorum finished delete job: {}, txn_id: {}\", getId(),\n- getTransactionId());\n- }\n- } catch (MetaNotFoundException e) {\n- cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());\n- throw new DdlException(e.getMessage(), e);\n- } catch (InterruptedException e) {\n- cancel(DeleteHandler.CancelType.UNKNOWN, e.getMessage());\n- throw new DdlException(e.getMessage(), e);\n+ } else {\n+ cancel(DeleteHandler.CancelType.UNKNOWN, \"delete job failed\");\n+ }\n+ throw new DdlException(\"failed to execute delete. transaction id \" + getTransactionId() +\n+ \", timeout(ms) \" + timeoutMs + \", \" + errMsg);\n+ case QUORUM_FINISHED:\n+ case FINISHED:\n+ try {\n+ long nowQuorumTimeMs = System.currentTimeMillis();\n+ long endQuorumTimeoutMs = nowQuorumTimeMs + timeoutMs / 2;\n+ // if job's state is quorum_finished then wait for a period of time and commit it.\n+ while (getState() == DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs\n+ && countDownLatch.getCount() > 0) {\n+ checkAndUpdateQuorum();\n+ Thread.sleep(1000);\n+ nowQuorumTimeMs = System.currentTimeMillis();\n+ LOG.debug(\"wait for quorum finished delete job: {}, txn_id: {}\", getId(),\n+ getTransactionId());\n }\n- commit(db, timeoutMs);\n- break;\n- default:\n- throw new IllegalStateException(\"wrong delete job state: \" + state.name());\n- }\n- } else {\n- commit(db, timeoutMs);\n+ } catch (MetaNotFoundException e) {\n+ cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());\n+ throw new DdlException(e.getMessage(), e);\n+ } catch (InterruptedException e) {\n+ cancel(DeleteHandler.CancelType.UNKNOWN, e.getMessage());\n+ throw new DdlException(e.getMessage(), e);\n+ }\n+ commit(db, timeoutMs);\n+ break;\n+ default:\n+ throw new IllegalStateException(\"wrong delete job state: \" + state.name());\n }\n+\n }\n \n /**\ndiff --git a/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java b/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java\nindex bc5b8884a5..12a862afb6 100644\n--- a/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java\n+++ b/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java\n@@ -43,6 +43,7 @@ import com.starrocks.analysis.LiteralExpr;\n import com.starrocks.analysis.Predicate;\n import com.starrocks.analysis.SlotRef;\n import com.starrocks.common.MarkedCountDownLatch;\n+import com.starrocks.common.Status;\n import com.starrocks.thrift.TBrokerScanRange;\n import com.starrocks.thrift.TCondition;\n import com.starrocks.thrift.TDescriptorTable;\n@@ -50,6 +51,7 @@ import com.starrocks.thrift.TPriority;\n import com.starrocks.thrift.TPushReq;\n import com.starrocks.thrift.TPushType;\n import com.starrocks.thrift.TResourceInfo;\n+import com.starrocks.thrift.TStatusCode;\n import com.starrocks.thrift.TTabletType;\n import com.starrocks.thrift.TTaskType;\n import org.apache.logging.log4j.LogManager;\n@@ -219,6 +221,15 @@ public class PushTask extends AgentTask {\n }\n }\n \n+ public void countDownLatch(long backendId, long tabletId, String errMsg) {\n+ if (this.latch != null) {\n+ if (latch.markedCountDown(backendId, tabletId, new Status(TStatusCode.INTERNAL_ERROR, errMsg))) {\n+ LOG.info(\"pushTask current latch count: {}. backend: {}, tablet:{}\",\n+ latch.getCount(), backendId, tabletId);\n+ }\n+ }\n+ }\n+\n public long getReplicaId() {\n return replicaId;\n }"},"changed_files":{"kind":"string","value":"['fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java', 'fe/fe-core/src/main/java/com/starrocks/task/PushTask.java', 'fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java', 'fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.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":18914418,"string":"18,914,418"},"repo_tokens_count":{"kind":"number","value":3826410,"string":"3,826,410"},"repo_lines_count":{"kind":"number","value":461671,"string":"461,671"},"repo_files_without_tests_count":{"kind":"number","value":2365,"string":"2,365"},"changed_symbols_count":{"kind":"number","value":7414,"string":"7,414"},"changed_tokens_count":{"kind":"number","value":1353,"string":"1,353"},"changed_lines_count":{"kind":"number","value":138,"string":"138"},"changed_files_without_tests_count":{"kind":"number","value":4,"string":"4"},"issue_symbols_count":{"kind":"number","value":2968,"string":"2,968"},"issue_words_count":{"kind":"number","value":304,"string":"304"},"issue_tokens_count":{"kind":"number","value":846,"string":"846"},"issue_lines_count":{"kind":"number","value":71,"string":"71"},"issue_links_count":{"kind":"number","value":0,"string":"0"},"issue_code_blocks_count":{"kind":"number","value":4,"string":"4"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:28:03","string":"1970-01-01T00:28:03"},"repo_stars":{"kind":"number","value":5115,"string":"5,115"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 29776837, 'C++': 27957184, 'C': 338709, 'Python': 280032, 'Thrift': 259942, 'CMake': 170285, 'Shell': 104253, 'ANTLR': 86095, 'HTML': 26561, 'Dockerfile': 24829, 'JavaScript': 10136, 'Makefile': 7808, 'CSS': 6187, 'Yacc': 4189, 'Lex': 1752, 'Mustache': 959}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1376,"cells":{"id":{"kind":"number","value":1075,"string":"1,075"},"text_id":{"kind":"string","value":"reactor/reactor-core/206/204"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/204"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/206"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/206"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Self Suppression IllegalArgumentException when 'onErrorResume' propagates existing exception"},"issue_body":{"kind":"string","value":"Sometime conditional logic is required to determine if an error signal should be handled or propagated. The easiest and most flexible way to do this is via the use of something like this:\n\n```\nflux.onErrorResume(e -> {\n if(something){\n return just(someValue);\n else {\n throw propagate(e);\n });\n```\n\nIn this above example the else clause propagates the existing exception. This fails though due to FluxResume attempting to do `e.addSuppressed(e)` [here](https://github.com/reactor/reactor-core/blob/master/src/main/java/reactor/core/publisher/FluxResume.java#L92)\n"},"base_sha":{"kind":"string","value":"de3a2bbbdadc767ba568373feec5d5a72a568e65"},"head_sha":{"kind":"string","value":"6327441f30b599594a31db4d5e1a4604274e5219"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/de3a2bbbdadc767ba568373feec5d5a72a568e65...6327441f30b599594a31db4d5e1a4604274e5219"},"diff":{"kind":"string","value":"diff --git a/src/main/java/reactor/core/publisher/FluxResume.java b/src/main/java/reactor/core/publisher/FluxResume.java\nindex 17120d9d6..cdd99d31f 100644\n--- a/src/main/java/reactor/core/publisher/FluxResume.java\n+++ b/src/main/java/reactor/core/publisher/FluxResume.java\n@@ -89,7 +89,9 @@ final class FluxResume extends FluxSource {\n \t\t\t\t\tp = nextFactory.apply(t);\n \t\t\t\t} catch (Throwable e) {\n \t\t\t\t\tThrowable _e = Operators.onOperatorError(e);\n-\t\t\t\t\t_e.addSuppressed(t);\n+\t\t\t\t\tif(t != _e) {\n+\t\t\t\t\t _e.addSuppressed(t);\n+\t\t\t\t\t}\n \t\t\t\t\tsubscriber.onError(_e);\n \t\t\t\t\treturn;\n \t\t\t\t}\ndiff --git a/src/test/java/reactor/core/publisher/FluxResumeTest.java b/src/test/java/reactor/core/publisher/FluxResumeTest.java\nindex 58977f228..016c00fe5 100644\n--- a/src/test/java/reactor/core/publisher/FluxResumeTest.java\n+++ b/src/test/java/reactor/core/publisher/FluxResumeTest.java\n@@ -18,6 +18,7 @@ package reactor.core.publisher;\n import org.junit.Assert;\n import org.junit.Test;\n import reactor.test.subscriber.AssertSubscriber;\n+import reactor.core.Exceptions;\n \n public class FluxResumeTest {\n /*\n@@ -222,4 +223,18 @@ public class FluxResumeTest {\n \t\t .assertError(NullPointerException.class);\n \t}\n \n+\t@Test\n+\tpublic void errorPropagated() {\n+\t\tAssertSubscriber ts = AssertSubscriber.create(0);\n+\n+\t\tException exception = new NullPointerException(\"forced failure\");\n+\t\tFlux.error(exception).onErrorResumeWith(v -> {\n+\t\t throw Exceptions.propagate(v);\n+\t\t}).subscribe(ts);\n+\n+\t\tts.assertNoValues()\n+\t\t .assertNotComplete()\n+\t\t .assertErrorWith(e -> Assert.assertSame(exception, e));\n+\t}\n+\n }"},"changed_files":{"kind":"string","value":"['src/test/java/reactor/core/publisher/FluxResumeTest.java', 'src/main/java/reactor/core/publisher/FluxResume.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":1977113,"string":"1,977,113"},"repo_tokens_count":{"kind":"number","value":488605,"string":"488,605"},"repo_lines_count":{"kind":"number","value":75285,"string":"75,285"},"repo_files_without_tests_count":{"kind":"number","value":258,"string":"258"},"changed_symbols_count":{"kind":"number","value":83,"string":"83"},"changed_tokens_count":{"kind":"number","value":27,"string":"27"},"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":581,"string":"581"},"issue_words_count":{"kind":"number","value":68,"string":"68"},"issue_tokens_count":{"kind":"number","value":131,"string":"131"},"issue_lines_count":{"kind":"number","value":13,"string":"13"},"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:24:36","string":"1970-01-01T00:24:36"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1377,"cells":{"id":{"kind":"number","value":1067,"string":"1,067"},"text_id":{"kind":"string","value":"reactor/reactor-core/3492/3359"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/3359"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3492"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3492"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"EmitterProcessor queue not cleared on immediate cancellation"},"issue_body":{"kind":"string","value":"`EmitterProcessor#remove` has support to discard the buffer once the last subscriber is gone. However, it returns early if the subscribers array is already `EMPTY`. For cases where the subscription is immediately cancelled (e.g. `.take(0)`) this may leak the buffered elements. \r\n\r\nHere is a repro case:\r\n```\r\n@Test\r\nvoid shouldClearBufferOnCancellation() {\r\n BlockingQueue queue = new LinkedBlockingQueue<>();\r\n\r\n Many sink = Sinks.many().unicast().onBackpressureBuffer(queue);\r\n\r\n sink.tryEmitNext(1);\r\n sink.tryEmitNext(2);\r\n sink.tryEmitNext(3);\r\n\r\n assertThat(queue).hasSize(3);\r\n\r\n sink.asFlux().take(0).blockLast();\r\n\r\n assertThat(queue).isEmpty();\r\n}\r\n```\r\n\r\nAs a workaround `.takeWhile(x -> false)` does make the test pass for example."},"base_sha":{"kind":"string","value":"75d48b443b2e0038519e362063417a79d544e200"},"head_sha":{"kind":"string","value":"258e2852c0ffffa710b0ae745315d151b0185cab"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/75d48b443b2e0038519e362063417a79d544e200...258e2852c0ffffa710b0ae745315d151b0185cab"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java\nindex cedbf7d68..47ffd686e 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -21,6 +21,7 @@ import java.util.Queue;\n import java.util.concurrent.CancellationException;\n import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;\n import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;\n+import java.util.function.Consumer;\n import java.util.stream.Stream;\n \n import org.reactivestreams.Publisher;\n@@ -33,6 +34,8 @@ import reactor.core.Exceptions;\n import reactor.core.Fuseable;\n import reactor.core.Scannable;\n import reactor.core.publisher.Sinks.EmitResult;\n+import reactor.util.Logger;\n+import reactor.util.Loggers;\n import reactor.util.annotation.Nullable;\n import reactor.util.concurrent.Queues;\n import reactor.util.context.Context;\n@@ -70,6 +73,8 @@ import static reactor.core.publisher.FluxPublish.PublishSubscriber.TERMINATED;\n public final class EmitterProcessor extends FluxProcessor implements InternalManySink,\n \tSinks.ManyWithUpstream {\n \n+\tstatic final Logger log = Loggers.getLogger(EmitterProcessor.class);\n+\n \t@SuppressWarnings(\"rawtypes\")\n \tstatic final FluxPublish.PubSubInner[] EMPTY = new FluxPublish.PublishInner[0];\n \n@@ -133,13 +138,32 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t */\n \t@Deprecated\n \tpublic static EmitterProcessor create(int bufferSize, boolean autoCancel) {\n-\t\treturn new EmitterProcessor<>(autoCancel, bufferSize);\n+\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, null);\n+\t}\n+\n+\t/**\n+\t * Create a new {@link EmitterProcessor} using the provided backlog size and auto-cancellation.\n+\t *\n+\t * @param Type of processed signals\n+\t * @param bufferSize the internal buffer size to hold signals\n+\t * @param autoCancel automatically cancel\n+\t *\n+\t * @return a fresh processor\n+\t * @deprecated use {@link Sinks.MulticastSpec#onBackpressureBuffer(int, boolean) Sinks.many().multicast().onBackpressureBuffer(bufferSize, autoCancel)}\n+\t * (or the unsafe variant if you're sure about external synchronization). To be removed in 3.5.\n+\t */\n+\t@Deprecated\n+\tpublic static EmitterProcessor create(int bufferSize, boolean autoCancel, Consumer onDiscardHook) {\n+\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, onDiscardHook);\n \t}\n \n \tfinal int prefetch;\n \n \tfinal boolean autoCancel;\n \n+\t@Nullable\n+\tfinal Consumer onDiscard;\n+\n \tvolatile Subscription s;\n \t@SuppressWarnings(\"rawtypes\")\n \tstatic final AtomicReferenceFieldUpdater S =\n@@ -182,12 +206,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\tThrowable.class,\n \t\t\t\t\t\"error\");\n \n-\tEmitterProcessor(boolean autoCancel, int prefetch) {\n+\tEmitterProcessor(boolean autoCancel, int prefetch, @Nullable Consumer onDiscard) {\n \t\tif (prefetch < 1) {\n \t\t\tthrow new IllegalArgumentException(\"bufferSize must be strictly positive, \" + \"was: \" + prefetch);\n \t\t}\n \t\tthis.autoCancel = autoCancel;\n \t\tthis.prefetch = prefetch;\n+\t\tthis.onDiscard = onDiscard;\n \t\t//doesn't use INIT/CANCELLED distinction, contrary to FluxPublish)\n \t\t//see remove()\n \t\tSUBSCRIBERS.lazySet(this, EMPTY);\n@@ -200,7 +225,12 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t@Override\n \tpublic Context currentContext() {\n-\t\treturn Operators.multiSubscribersContext(subscribers);\n+\t\tif (onDiscard != null) {\n+\t\t\treturn Operators.enableOnDiscard(Operators.multiSubscribersContext(subscribers), onDiscard);\n+\t\t}\n+\t\telse {\n+\t\t\treturn Operators.multiSubscribersContext(subscribers);\n+\t\t}\n \t}\n \n \n@@ -213,9 +243,18 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\tdone = true;\n \t\t\tCancellationException detachException = new CancellationException(\"the ManyWithUpstream sink had a Subscription to an upstream which has been manually cancelled\");\n \t\t\tif (ERROR.compareAndSet(EmitterProcessor.this, null, detachException)) {\n+\t\t\t\tif (WIP.getAndIncrement(this) != 0) {\n+\t\t\t\t\treturn true;\n+\t\t\t\t}\n \t\t\t\tQueue q = queue;\n \t\t\t\tif (q != null) {\n-\t\t\t\t\tq.clear();\n+\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\tfor (FluxPublish.PubSubInner inner : terminate()) {\n \t\t\t\t\tinner.actual.onError(detachException);\n@@ -250,7 +289,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\tif (inner.isCancelled()) {\n \t\t\t\tremove(inner);\n \t\t\t}\n-\t\t\tdrain();\n+\t\t\tdrain(null);\n \t\t}\n \t\telse {\n \t\t\tThrowable e = error;\n@@ -275,7 +314,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\treturn EmitResult.FAIL_TERMINATED;\n \t\t}\n \t\tdone = true;\n-\t\tdrain();\n+\t\tdrain(null);\n \t\treturn EmitResult.OK;\n \t}\n \n@@ -292,7 +331,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t}\n \t\tif (Exceptions.addThrowable(ERROR, this, t)) {\n \t\t\tdone = true;\n-\t\t\tdrain();\n+\t\t\tdrain(null);\n \t\t\treturn EmitResult.OK;\n \t\t}\n \t\telse {\n@@ -303,7 +342,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t@Override\n \tpublic void onNext(T t) {\n \t\tif (sourceMode == Fuseable.ASYNC) {\n-\t\t\tdrain();\n+\t\t\tdrain(t);\n \t\t\treturn;\n \t\t}\n \t\temitNext(t, Sinks.EmitFailureHandler.FAIL_FAST);\n@@ -340,7 +379,8 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\tif (!q.offer(t)) {\n \t\t\treturn subscribers == EMPTY ? EmitResult.FAIL_ZERO_SUBSCRIBER : EmitResult.FAIL_OVERFLOW;\n \t\t}\n-\t\tdrain();\n+\n+\t\tdrain(t);\n \t\treturn EmitResult.OK;\n \t}\n \n@@ -387,7 +427,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\tif (m == Fuseable.SYNC) {\n \t\t\t\t\tsourceMode = m;\n \t\t\t\t\tqueue = f;\n-\t\t\t\t\tdrain();\n+\t\t\t\t\tdrain(null);\n \t\t\t\t\treturn;\n \t\t\t\t}\n \t\t\t\telse if (m == Fuseable.ASYNC) {\n@@ -443,8 +483,23 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\treturn super.scanUnsafe(key);\n \t}\n \n-\tfinal void drain() {\n+\tfinal void drain(@Nullable T dataSignalOfferedBeforeDrain) {\n \t\tif (WIP.getAndIncrement(this) != 0) {\n+\t\t\tConsumer discardHook = this.onDiscard;\n+\t\t\tif (dataSignalOfferedBeforeDrain != null) {\n+\t\t\t\tif (discardHook != null && isCancelled()) {\n+\t\t\t\t\ttry {\n+\t\t\t\t\t\tdiscardHook.accept(dataSignalOfferedBeforeDrain);\n+\t\t\t\t\t}\n+\t\t\t\t\tcatch (Throwable t) {\n+\t\t\t\t\t\tlog.warn(\"Error in discard hook\", t);\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\telse if (done) {\n+\t\t\t\t\tOperators.onNextDropped(dataSignalOfferedBeforeDrain,\n+\t\t\t\t\t\t\tcurrentContext());\n+\t\t\t\t}\n+\t\t\t}\n \t\t\treturn;\n \t\t}\n \n@@ -458,11 +513,12 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t\t\tboolean empty = q == null || q.isEmpty();\n \n-\t\t\tif (checkTerminated(d, empty)) {\n+\t\t\tif (checkTerminated(d, empty, null)) {\n \t\t\t\treturn;\n \t\t\t}\n \n \t\t\tFluxPublish.PubSubInner[] a = subscribers;\n+\t\t\tConsumer onDiscardHook = onDiscard;\n \n \t\t\tif (a != EMPTY && !empty) {\n \t\t\t\tlong maxRequested = Long.MAX_VALUE;\n@@ -492,9 +548,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\t\td = true;\n \t\t\t\t\t\tv = null;\n \t\t\t\t\t}\n-\t\t\t\t\tif (checkTerminated(d, v == null)) {\n+\t\t\t\t\tempty = v == null;\n+\t\t\t\t\tif (checkTerminated(d, empty, v)) {\n \t\t\t\t\t\treturn;\n \t\t\t\t\t}\n+\t\t\t\t\tif (!empty && onDiscardHook != null) {\n+\t\t\t\t\t\tdiscard(v, onDiscardHook);\n+\t\t\t\t\t}\n \t\t\t\t\tif (sourceMode != Fuseable.SYNC) {\n \t\t\t\t\t\ts.request(1);\n \t\t\t\t\t}\n@@ -519,7 +579,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t\t\t\t\tempty = v == null;\n \n-\t\t\t\t\tif (checkTerminated(d, empty)) {\n+\t\t\t\t\tif (checkTerminated(d, empty, v)) {\n \t\t\t\t\t\treturn;\n \t\t\t\t\t}\n \n@@ -528,7 +588,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\t\tif (sourceMode == Fuseable.SYNC) {\n \t\t\t\t\t\t\t//the q is empty\n \t\t\t\t\t\t\tdone = true;\n-\t\t\t\t\t\t\tcheckTerminated(true, true);\n+\t\t\t\t\t\t\tcheckTerminated(true, true, null);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t}\n@@ -555,7 +615,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t}\n \t\t\telse if ( sourceMode == Fuseable.SYNC ) {\n \t\t\t\tdone = true;\n-\t\t\t\tif (checkTerminated(true, empty)) { //empty can be true if no subscriber\n+\t\t\t\tif (checkTerminated(true, empty, null)) { //empty can be true if no subscriber\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n@@ -572,13 +632,23 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\treturn SUBSCRIBERS.getAndSet(this, TERMINATED);\n \t}\n \n-\tboolean checkTerminated(boolean d, boolean empty) {\n+\tboolean checkTerminated(boolean d, boolean empty, @Nullable T value) {\n \t\tif (s == Operators.cancelledSubscription()) {\n \t\t\tif (autoCancel) {\n \t\t\t\tterminate();\n+\n \t\t\t\tQueue q = queue;\n \t\t\t\tif (q != null) {\n-\t\t\t\t\tq.clear();\n+\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\tif (value != null) {\n+\t\t\t\t\t\t\tdiscard(value, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\treturn true;\n@@ -588,7 +658,16 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\tif (e != null && e != Exceptions.TERMINATED) {\n \t\t\t\tQueue q = queue;\n \t\t\t\tif (q != null) {\n-\t\t\t\t\tq.clear();\n+\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\tif (value != null) {\n+\t\t\t\t\t\t\tdiscard(value, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\tfor (FluxPublish.PubSubInner inner : terminate()) {\n \t\t\t\t\tinner.actual.onError(e);\n@@ -605,6 +684,31 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\treturn false;\n \t}\n \n+\tstatic void discardQueue(Queue q, Consumer hook) {\n+\t\tfor (; ; ) {\n+\t\t\tT toDiscard = q.poll();\n+\t\t\tif (toDiscard == null) {\n+\t\t\t\tbreak;\n+\t\t\t}\n+\n+\t\t\ttry {\n+\t\t\t\thook.accept(toDiscard);\n+\t\t\t}\n+\t\t\tcatch (Throwable t) {\n+\t\t\t\tlog.warn(\"Error while discarding a queue element, continuing with next queue element\", t);\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tstatic void discard(T value, Consumer hook) {\n+\t\ttry {\n+\t\t\thook.accept(value);\n+\t\t}\n+\t\tcatch (Throwable t) {\n+\t\t\tlog.warn(\"Error while discarding a queue element, continuing with next queue element\", t);\n+\t\t}\n+\t}\n+\n \tfinal boolean add(EmitterInner inner) {\n \t\tfor (; ; ) {\n \t\t\tFluxPublish.PubSubInner[] a = subscribers;\n@@ -624,7 +728,27 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \tfinal void remove(FluxPublish.PubSubInner inner) {\n \t\tfor (; ; ) {\n \t\t\tFluxPublish.PubSubInner[] a = subscribers;\n-\t\t\tif (a == TERMINATED || a == EMPTY) {\n+\t\t\tif (a == EMPTY) {\n+\t\t\t\t// means cancelled without adding\n+\t\t\t\tif (autoCancel && Operators.terminate(S, this)) {\n+\t\t\t\t\tif (WIP.getAndIncrement(this) != 0) {\n+\t\t\t\t\t\treturn;\n+\t\t\t\t\t}\n+\t\t\t\t\tterminate();\n+\t\t\t\t\tQueue q = queue;\n+\t\t\t\t\tif (q != null) {\n+\t\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse {\n+\t\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t\t}\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\telse if (a == TERMINATED) {\n \t\t\t\treturn;\n \t\t\t}\n \t\t\tint n = a.length;\n@@ -659,7 +783,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\tterminate();\n \t\t\t\t\tQueue q = queue;\n \t\t\t\t\tif (q != null) {\n-\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse {\n+\t\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\treturn;\n@@ -683,13 +813,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t\t@Override\n \t\tvoid drainParent() {\n-\t\t\tparent.drain();\n+\t\t\tparent.drain(null);\n \t\t}\n \n \t\t@Override\n \t\tvoid removeAndDrainParent() {\n \t\t\tparent.remove(this);\n-\t\t\tparent.drain();\n+\t\t\tparent.drain(null);\n \t\t}\n \t}\n \ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java\nindex e9183e4ba..16ceea978 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -18,6 +18,7 @@ package reactor.core.publisher;\n \n import java.time.Duration;\n import java.util.Queue;\n+import java.util.function.Consumer;\n \n import org.reactivestreams.Publisher;\n import org.reactivestreams.Subscriber;\n@@ -420,6 +421,31 @@ public final class Sinks {\n \t\t * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels\n \t\t */\n \t\t ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel);\n+\n+\t\t/**\n+\t\t * A {@link Sinks.ManyWithUpstream} with the following characteristics:\n+\t\t *
    \n+\t\t *
  • Multicast
  • \n+\t\t *
  • Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}\n+\t\t * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.
  • \n+\t\t *
  • Backpressure : this sink honors downstream demand by conforming to the lowest demand in case\n+\t\t * of multiple subscribers.
    If the difference between multiple subscribers is too high compared to {@code bufferSize}:\n+\t\t *
    • {@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}
    • \n+\t\t *
    • {@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}\n+\t\t * an {@link Exceptions#failWithOverflow() overflow error}.
    \n+\t\t *
  • \n+\t\t *
  • Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}\n+\t\t * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements\n+\t\t * that have been buffered due to backpressure/warm up.
  • \n+\t\t *
\n+\t\t *

\n+\t\t * \"\"\n+\t\t *\n+\t\t * @param bufferSize the maximum queue size\n+\t\t * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels\n+\t\t * @param onDiscardHook should be called when values from queue are cleared\n+\t\t */\n+\t\t ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer onDiscardHook);\n \t}\n \n \t/**\n@@ -557,6 +583,31 @@ public final class Sinks {\n \t\t */\n \t\t Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel);\n \n+\t\t/**\n+\t\t * A {@link Sinks.Many} with the following characteristics:\n+\t\t *

    \n+\t\t *
  • Multicast
  • \n+\t\t *
  • Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}\n+\t\t * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.
  • \n+\t\t *
  • Backpressure : this sink honors downstream demand by conforming to the lowest demand in case\n+\t\t * of multiple subscribers.
    If the difference between multiple subscribers is too high compared to {@code bufferSize}:\n+\t\t *
    • {@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}
    • \n+\t\t *
    • {@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}\n+\t\t * an {@link Exceptions#failWithOverflow() overflow error}.
    \n+\t\t *
  • \n+\t\t *
  • Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}\n+\t\t * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements\n+\t\t * that have been buffered due to backpressure/warm up.
  • \n+\t\t *
\n+\t\t *

\n+\t\t * \"\"\n+\t\t *\n+\t\t * @param bufferSize the maximum queue size\n+\t\t * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels\n+\t\t * @param onDiscardHook should be called when values from queue are cleared\n+\t\t */\n+\t\t Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer onDiscardHook);\n+\n \t\t/**\n \t\t A {@link Sinks.Many} with the following characteristics:\n \t\t *

    \ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java\nindex 33d6f45ce..cb4d48f70 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -20,6 +20,7 @@ import java.time.Duration;\n import java.util.Queue;\n import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;\n import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;\n+import java.util.function.Consumer;\n \n import reactor.core.Disposable;\n import reactor.core.publisher.Sinks.Empty;\n@@ -109,17 +110,22 @@ final class SinksSpecs {\n \n \t\t@Override\n \t\tpublic Sinks.Many onBackpressureBuffer() {\n-\t\t\treturn new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);\n+\t\t\treturn new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);\n \t\t}\n \n \t\t@Override\n \t\tpublic Sinks.Many onBackpressureBuffer(int bufferSize) {\n-\t\t\treturn new SinkManyEmitterProcessor<>(true, bufferSize);\n+\t\t\treturn new SinkManyEmitterProcessor<>(true, bufferSize, null);\n \t\t}\n \n \t\t@Override\n \t\tpublic Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel) {\n-\t\t\treturn new SinkManyEmitterProcessor<>(autoCancel, bufferSize);\n+\t\t\treturn new SinkManyEmitterProcessor<>(autoCancel, bufferSize, null);\n+\t\t}\n+\n+\t\t@Override\n+\t\tpublic Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer hook) {\n+\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, hook);\n \t\t}\n \n \t\t@Override\n@@ -179,12 +185,17 @@ final class SinksSpecs {\n \n \t\t@Override\n \t\tpublic Sinks.ManyWithUpstream multicastOnBackpressureBuffer() {\n-\t\t\treturn new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);\n+\t\t\treturn new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);\n \t\t}\n \n \t\t@Override\n \t\tpublic Sinks.ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel) {\n-\t\t\treturn new SinkManyEmitterProcessor<>(autoCancel, bufferSize);\n+\t\t\treturn new SinkManyEmitterProcessor<>(autoCancel, bufferSize, null);\n+\t\t}\n+\n+\t\t@Override\n+\t\tpublic Sinks.ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer hook) {\n+\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, hook);\n \t\t}\n \t}\n \n@@ -252,6 +263,13 @@ final class SinksSpecs {\n \t\t\treturn wrapMany(new SinkManyEmitterProcessor<>(autoCancel, bufferSize));\n \t\t}\n \n+\t\t@Override\n+\t\tpublic Many onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer onDiscardHook) {\n+\t\t\t@SuppressWarnings(\"deprecation\") // EmitterProcessor will be removed in 3.5.\n+\t\t\tfinal EmitterProcessor original = EmitterProcessor.create(bufferSize, autoCancel, onDiscardHook);\n+\t\t\treturn wrapMany(original);\n+\t\t}\n+\n \t\t@Override\n \t\tpublic Many directAllOrNothing() {\n \t\t\tfinal SinkManyBestEffort original = SinkManyBestEffort.createAllOrNothing();\n@@ -351,6 +369,7 @@ final class SinksSpecs {\n \t\t}\n \n \t\t@Override\n+\n \t\tpublic Many onBackpressureBuffer(Queue queue) {\n \t\t\tfinal SinkManyUnicast original = SinkManyUnicast.create(queue);\n \t\t\treturn wrapMany(original);\ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java\nindex d32f9e7f1..fc8556136 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -530,9 +530,9 @@ public final class UnicastProcessor extends FluxProcessor\n \t\t\tthis.actual = actual;\n \t\t\tif (cancelled) {\n \t\t\t\tthis.hasDownstream = false;\n-\t\t\t} else {\n-\t\t\t\tdrain(null);\n \t\t\t}\n+\n+\t\t\tdrain(null);\n \t\t} else {\n \t\t\tOperators.error(actual, new IllegalStateException(\"UnicastProcessor \" +\n \t\t\t\t\t\"allows only a single Subscriber\"));\n@@ -556,7 +556,7 @@ public final class UnicastProcessor extends FluxProcessor\n \n \t\tdoTerminate();\n \n-\t\tif (WIP.getAndIncrement(this) == 0) {\n+\t\tif (actual != null && WIP.getAndIncrement(this) == 0) {\n \t\t\tif (!outputFused) {\n \t\t\t\t// discard MUST be happening only and only if there is no racing on elements consumption\n \t\t\t\t// which is guaranteed by the WIP guard here in case non-fused output\ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java\nindex f1cc13d99..acffdc76b 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java\n@@ -172,6 +172,12 @@ public class OnDiscardShouldNotLeakTest {\n \t\t\tDiscardScenario.sinkSource(\"unicastSink\", Sinks.unsafe().many().unicast()::onBackpressureBuffer, null),\n \t\t\tDiscardScenario.sinkSource(\"unicastSinkAndPublishOn\", Sinks.unsafe().many().unicast()::onBackpressureBuffer,\n \t\t\t\t\tf -> f.publishOn(Schedulers.immediate())),\n+\t\t\tDiscardScenario.sinkSource(\"multicastBufferSink\",\n+\t\t\t\t\t() -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),\n+\t\t\t\t\tnull),\n+\t\t\tDiscardScenario.sinkSource(\"multicastBufferSinkAndPublishOn\",\n+\t\t\t\t\t() -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),\n+\t\t\t\t\tf -> f.publishOn(Schedulers.immediate())),\n \t\t\tDiscardScenario.fluxSource(\"singleOrEmpty\", f -> f.singleOrEmpty().onErrorReturn(Tracked.RELEASED)),\n \t\t\tDiscardScenario.fluxSource(\"collect\", f -> f.collect(ArrayList::new, ArrayList::add)\n \t\t\t .doOnSuccess(l -> l.forEach(Tracked::safeRelease))\n@@ -656,7 +662,11 @@ public class OnDiscardShouldNotLeakTest {\n \t\t\t\tSinks.Many sink = sinksManySupplier.get();\n \t\t\t\t//noinspection CallingSubscribeInNonBlockingScope\n \t\t\t\tmain.flux().subscribe(\n-\t\t\t\t\t\tv -> sink.emitNext(v, FAIL_FAST),\n+\t\t\t\t\t\tv -> {\n+\t\t\t\t\t\t\tif (sink.tryEmitNext(v) != Sinks.EmitResult.OK) {\n+\t\t\t\t\t\t\t\tv.release();\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t},\n \t\t\t\t\t\te -> sink.emitError(e, FAIL_FAST),\n \t\t\t\t\t\t() -> sink.emitComplete(FAIL_FAST));\n \t\t\t\tFlux finalFlux = sink.asFlux();\ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java b/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java\nindex 449d47892..9b72087e5 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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 java.util.concurrent.TimeUnit;\n import java.util.concurrent.atomic.AtomicReference;\n import java.util.stream.Stream;\n \n+import org.assertj.core.api.Assertions;\n import org.awaitility.Awaitility;\n import org.junit.jupiter.api.Disabled;\n import org.junit.jupiter.api.Test;\n@@ -40,6 +41,7 @@ import reactor.core.Scannable;\n import reactor.core.scheduler.Scheduler;\n import reactor.core.scheduler.Schedulers;\n import reactor.test.AutoDisposingExtension;\n+import reactor.test.MemoryUtils;\n import reactor.test.StepVerifier;\n import reactor.test.publisher.TestPublisher;\n import reactor.test.subscriber.AssertSubscriber;\n@@ -62,6 +64,21 @@ class SinkManyEmitterProcessorTest {\n \n \t@RegisterExtension\n \tAutoDisposingExtension afterTest = new AutoDisposingExtension();\n+\t//https://github.com/reactor/reactor-core/issues/3359\n+\t@Test\n+\tvoid shouldClearBufferOnCancellation() {\n+\t\tMemoryUtils.OffHeapDetector tracker = new MemoryUtils.OffHeapDetector();\n+\t\tEmitterProcessor source = EmitterProcessor.create(32, true, MemoryUtils.Tracked::release);\n+\n+\t\tAssertions.assertThat(source.tryEmitNext(tracker.track(1))).isEqualTo(Sinks.EmitResult.OK);\n+\t\tAssertions.assertThat(source.tryEmitNext(tracker.track(2))).isEqualTo(Sinks.EmitResult.OK);\n+\t\tAssertions.assertThat(source.tryEmitNext(tracker.track(3))).isEqualTo(Sinks.EmitResult.OK);\n+\n+\t\tsource.take(0).blockLast();\n+\n+\t\ttracker.assertNoLeaks();\n+\t}\n+\n \n \t@Test\n \tvoid smokeTestManyWithUpstream() {\n@@ -862,7 +879,7 @@ class SinkManyEmitterProcessorTest {\n \t\tAssertSubscriber testSubscriber1 = new AssertSubscriber<>(Context.of(\"key\", \"value1\"));\n \t\tAssertSubscriber testSubscriber2 = new AssertSubscriber<>(Context.of(\"key\", \"value2\"));\n \n-\t\tSinkManyEmitterProcessor sinkManyEmitterProcessor = new SinkManyEmitterProcessor<>(false, 1);\n+\t\tSinkManyEmitterProcessor sinkManyEmitterProcessor = new SinkManyEmitterProcessor<>(false, 1, null);\n \t\tsinkManyEmitterProcessor.subscribe(testSubscriber1);\n \t\tsinkManyEmitterProcessor.subscribe(testSubscriber2);\n \ndiff --git a/reactor-core/src/test/java/reactor/test/MemoryUtils.java b/reactor-core/src/test/java/reactor/test/MemoryUtils.java\nindex 55223eeb3..e32ba8420 100644\n--- a/reactor-core/src/test/java/reactor/test/MemoryUtils.java\n+++ b/reactor-core/src/test/java/reactor/test/MemoryUtils.java\n@@ -18,6 +18,7 @@ package reactor.test;\n \n import java.lang.ref.PhantomReference;\n import java.lang.ref.ReferenceQueue;\n+import java.util.ArrayList;\n import java.util.Collection;\n import java.util.LinkedList;\n import java.util.List;\n@@ -170,6 +171,8 @@ public class MemoryUtils {\n \t\t */\n \t\tpublic static final Tracked RELEASED = new Tracked(\"RELEASED\", true);\n \n+\t\tfinal List touches = new ArrayList<>();\n+\n \t\t/**\n \t\t * Check if an arbitrary object is a {@link Tracked}, and if so release it.\n \t\t *\n@@ -210,6 +213,10 @@ public class MemoryUtils {\n \t set(true);\n \t }\n \n+\t\tpublic void touch(String msg) {\n+\t\t\ttouches.add(msg);\n+\t\t}\n+\n \t\t/**\n \t\t * Check if this {@link Tracked} object has been released.\n \t\t *\n@@ -221,6 +228,10 @@ public class MemoryUtils {\n \n \t @Override\n \t public boolean equals(Object o) {\n+\t\t if (o instanceof String) {\n+\t\t\t touch(o.toString());\n+\t\t\t\treturn false;\n+\t\t }\n \t if (this == o) return true;\n \t if (o == null || getClass() != o.getClass()) return false;\n \n@@ -237,10 +248,16 @@ public class MemoryUtils {\n \t //NOTE: AssertJ has a special representation of AtomicBooleans, so we override it in AssertionsUtils\n \t @Override\n \t public String toString() {\n-\t return \"Tracked{\" +\n-\t \" id=\" + identifier +\n-\t \" released=\" + get() +\n-\t \" }\";\n+\t return get()\n+\t\t\t ? \"Tracked{\" +\n+\t\t \" id=\" + identifier +\n+\t\t \" released=\" + get() +\n+\t\t \" }\"\n+\t\t\t : \"Tracked{\" +\n+\t\t\t\t \" id=\" + identifier +\n+\t\t\t\t \" released=\" + get() +\n+\t\t\t\t \" touches=\" + touches +\n+\t\t\t\t \" }\";\n \t }\n \t}\n }"},"changed_files":{"kind":"string","value":"['reactor-core/src/main/java/reactor/core/publisher/Sinks.java', 'reactor-core/src/test/java/reactor/test/MemoryUtils.java', 'reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java', 'reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java', 'reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.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":4080238,"string":"4,080,238"},"repo_tokens_count":{"kind":"number","value":1014099,"string":"1,014,099"},"repo_lines_count":{"kind":"number","value":138124,"string":"138,124"},"repo_files_without_tests_count":{"kind":"number","value":496,"string":"496"},"changed_symbols_count":{"kind":"number","value":10881,"string":"10,881"},"changed_tokens_count":{"kind":"number","value":2762,"string":"2,762"},"changed_lines_count":{"kind":"number","value":270,"string":"270"},"changed_files_without_tests_count":{"kind":"number","value":4,"string":"4"},"issue_symbols_count":{"kind":"number","value":770,"string":"770"},"issue_words_count":{"kind":"number","value":80,"string":"80"},"issue_tokens_count":{"kind":"number","value":186,"string":"186"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"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:28:06","string":"1970-01-01T00:28:06"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1378,"cells":{"id":{"kind":"number","value":1068,"string":"1,068"},"text_id":{"kind":"string","value":"reactor/reactor-core/3486/3359"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/3359"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3486"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3486"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"EmitterProcessor queue not cleared on immediate cancellation"},"issue_body":{"kind":"string","value":"`EmitterProcessor#remove` has support to discard the buffer once the last subscriber is gone. However, it returns early if the subscribers array is already `EMPTY`. For cases where the subscription is immediately cancelled (e.g. `.take(0)`) this may leak the buffered elements. \r\n\r\nHere is a repro case:\r\n```\r\n@Test\r\nvoid shouldClearBufferOnCancellation() {\r\n BlockingQueue queue = new LinkedBlockingQueue<>();\r\n\r\n Many sink = Sinks.many().unicast().onBackpressureBuffer(queue);\r\n\r\n sink.tryEmitNext(1);\r\n sink.tryEmitNext(2);\r\n sink.tryEmitNext(3);\r\n\r\n assertThat(queue).hasSize(3);\r\n\r\n sink.asFlux().take(0).blockLast();\r\n\r\n assertThat(queue).isEmpty();\r\n}\r\n```\r\n\r\nAs a workaround `.takeWhile(x -> false)` does make the test pass for example."},"base_sha":{"kind":"string","value":"8549191d09486a6baf94712f1ec6ca6bf1e76ccf"},"head_sha":{"kind":"string","value":"236c84f7e96c7e5426cf1c25bbece4584d8ad088"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/8549191d09486a6baf94712f1ec6ca6bf1e76ccf...236c84f7e96c7e5426cf1c25bbece4584d8ad088"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java\nindex fbd251e96..82319a6d3 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -21,6 +21,7 @@ import java.util.Queue;\n import java.util.concurrent.CancellationException;\n import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;\n import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;\n+import java.util.function.Consumer;\n import java.util.stream.Stream;\n \n import org.reactivestreams.Publisher;\n@@ -33,6 +34,8 @@ import reactor.core.Exceptions;\n import reactor.core.Fuseable;\n import reactor.core.Scannable;\n import reactor.core.publisher.Sinks.EmitResult;\n+import reactor.util.Logger;\n+import reactor.util.Loggers;\n import reactor.util.annotation.Nullable;\n import reactor.util.concurrent.Queues;\n import reactor.util.context.Context;\n@@ -70,6 +73,8 @@ import static reactor.core.publisher.FluxPublish.PublishSubscriber.TERMINATED;\n public final class EmitterProcessor extends FluxProcessor implements InternalManySink,\n \tSinks.ManyWithUpstream {\n \n+\tstatic final Logger log = Loggers.getLogger(EmitterProcessor.class);\n+\n \t@SuppressWarnings(\"rawtypes\")\n \tstatic final FluxPublish.PubSubInner[] EMPTY = new FluxPublish.PublishInner[0];\n \n@@ -133,13 +138,32 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t */\n \t@Deprecated\n \tpublic static EmitterProcessor create(int bufferSize, boolean autoCancel) {\n-\t\treturn new EmitterProcessor<>(autoCancel, bufferSize);\n+\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, null);\n+\t}\n+\n+\t/**\n+\t * Create a new {@link EmitterProcessor} using the provided backlog size and auto-cancellation.\n+\t *\n+\t * @param Type of processed signals\n+\t * @param bufferSize the internal buffer size to hold signals\n+\t * @param autoCancel automatically cancel\n+\t *\n+\t * @return a fresh processor\n+\t * @deprecated use {@link Sinks.MulticastSpec#onBackpressureBuffer(int, boolean) Sinks.many().multicast().onBackpressureBuffer(bufferSize, autoCancel)}\n+\t * (or the unsafe variant if you're sure about external synchronization). To be removed in 3.5.\n+\t */\n+\t@Deprecated\n+\tpublic static EmitterProcessor create(int bufferSize, boolean autoCancel, Consumer onDiscardHook) {\n+\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, onDiscardHook);\n \t}\n \n \tfinal int prefetch;\n \n \tfinal boolean autoCancel;\n \n+\t@Nullable\n+\tfinal Consumer onDiscard;\n+\n \tvolatile Subscription s;\n \t@SuppressWarnings(\"rawtypes\")\n \tstatic final AtomicReferenceFieldUpdater S =\n@@ -182,12 +206,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\tThrowable.class,\n \t\t\t\t\t\"error\");\n \n-\tEmitterProcessor(boolean autoCancel, int prefetch) {\n+\tEmitterProcessor(boolean autoCancel, int prefetch, @Nullable Consumer onDiscard) {\n \t\tif (prefetch < 1) {\n \t\t\tthrow new IllegalArgumentException(\"bufferSize must be strictly positive, \" + \"was: \" + prefetch);\n \t\t}\n \t\tthis.autoCancel = autoCancel;\n \t\tthis.prefetch = prefetch;\n+\t\tthis.onDiscard = onDiscard;\n \t\t//doesn't use INIT/CANCELLED distinction, contrary to FluxPublish)\n \t\t//see remove()\n \t\tSUBSCRIBERS.lazySet(this, EMPTY);\n@@ -200,7 +225,12 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t@Override\n \tpublic Context currentContext() {\n-\t\treturn Operators.multiSubscribersContext(subscribers);\n+\t\tif (onDiscard != null) {\n+\t\t\treturn Operators.enableOnDiscard(Operators.multiSubscribersContext(subscribers), onDiscard);\n+\t\t}\n+\t\telse {\n+\t\t\treturn Operators.multiSubscribersContext(subscribers);\n+\t\t}\n \t}\n \n \n@@ -213,9 +243,18 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\tdone = true;\n \t\t\tCancellationException detachException = new CancellationException(\"the ManyWithUpstream sink had a Subscription to an upstream which has been manually cancelled\");\n \t\t\tif (ERROR.compareAndSet(EmitterProcessor.this, null, detachException)) {\n+\t\t\t\tif (WIP.getAndIncrement(this) != 0) {\n+\t\t\t\t\treturn true;\n+\t\t\t\t}\n \t\t\t\tQueue q = queue;\n \t\t\t\tif (q != null) {\n-\t\t\t\t\tq.clear();\n+\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\tfor (FluxPublish.PubSubInner inner : terminate()) {\n \t\t\t\t\tinner.actual.onError(detachException);\n@@ -250,7 +289,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\tif (inner.isCancelled()) {\n \t\t\t\tremove(inner);\n \t\t\t}\n-\t\t\tdrain();\n+\t\t\tdrain(null);\n \t\t}\n \t\telse {\n \t\t\tThrowable e = error;\n@@ -275,7 +314,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\treturn EmitResult.FAIL_TERMINATED;\n \t\t}\n \t\tdone = true;\n-\t\tdrain();\n+\t\tdrain(null);\n \t\treturn EmitResult.OK;\n \t}\n \n@@ -292,7 +331,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t}\n \t\tif (Exceptions.addThrowable(ERROR, this, t)) {\n \t\t\tdone = true;\n-\t\t\tdrain();\n+\t\t\tdrain(null);\n \t\t\treturn EmitResult.OK;\n \t\t}\n \t\telse {\n@@ -303,7 +342,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t@Override\n \tpublic void onNext(T t) {\n \t\tif (sourceMode == Fuseable.ASYNC) {\n-\t\t\tdrain();\n+\t\t\tdrain(t);\n \t\t\treturn;\n \t\t}\n \t\temitNext(t, Sinks.EmitFailureHandler.FAIL_FAST);\n@@ -340,7 +379,8 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\tif (!q.offer(t)) {\n \t\t\treturn subscribers == EMPTY ? EmitResult.FAIL_ZERO_SUBSCRIBER : EmitResult.FAIL_OVERFLOW;\n \t\t}\n-\t\tdrain();\n+\n+\t\tdrain(t);\n \t\treturn EmitResult.OK;\n \t}\n \n@@ -387,7 +427,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\tif (m == Fuseable.SYNC) {\n \t\t\t\t\tsourceMode = m;\n \t\t\t\t\tqueue = f;\n-\t\t\t\t\tdrain();\n+\t\t\t\t\tdrain(null);\n \t\t\t\t\treturn;\n \t\t\t\t}\n \t\t\t\telse if (m == Fuseable.ASYNC) {\n@@ -443,8 +483,23 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\treturn super.scanUnsafe(key);\n \t}\n \n-\tfinal void drain() {\n+\tfinal void drain(@Nullable T dataSignalOfferedBeforeDrain) {\n \t\tif (WIP.getAndIncrement(this) != 0) {\n+\t\t\tConsumer discardHook = this.onDiscard;\n+\t\t\tif (dataSignalOfferedBeforeDrain != null) {\n+\t\t\t\tif (discardHook != null && isCancelled()) {\n+\t\t\t\t\ttry {\n+\t\t\t\t\t\tdiscardHook.accept(dataSignalOfferedBeforeDrain);\n+\t\t\t\t\t}\n+\t\t\t\t\tcatch (Throwable t) {\n+\t\t\t\t\t\tlog.warn(\"Error in discard hook\", t);\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\telse if (done) {\n+\t\t\t\t\tOperators.onNextDropped(dataSignalOfferedBeforeDrain,\n+\t\t\t\t\t\t\tcurrentContext());\n+\t\t\t\t}\n+\t\t\t}\n \t\t\treturn;\n \t\t}\n \n@@ -458,11 +513,12 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t\t\tboolean empty = q == null || q.isEmpty();\n \n-\t\t\tif (checkTerminated(d, empty)) {\n+\t\t\tif (checkTerminated(d, empty, null)) {\n \t\t\t\treturn;\n \t\t\t}\n \n \t\t\tFluxPublish.PubSubInner[] a = subscribers;\n+\t\t\tConsumer onDiscardHook = onDiscard;\n \n \t\t\tif (a != EMPTY && !empty) {\n \t\t\t\tlong maxRequested = Long.MAX_VALUE;\n@@ -492,9 +548,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\t\td = true;\n \t\t\t\t\t\tv = null;\n \t\t\t\t\t}\n-\t\t\t\t\tif (checkTerminated(d, v == null)) {\n+\t\t\t\t\tempty = v == null;\n+\t\t\t\t\tif (checkTerminated(d, empty, v)) {\n \t\t\t\t\t\treturn;\n \t\t\t\t\t}\n+\t\t\t\t\tif (!empty && onDiscardHook != null) {\n+\t\t\t\t\t\tdiscard(v, onDiscardHook);\n+\t\t\t\t\t}\n \t\t\t\t\tif (sourceMode != Fuseable.SYNC) {\n \t\t\t\t\t\ts.request(1);\n \t\t\t\t\t}\n@@ -519,7 +579,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t\t\t\t\tempty = v == null;\n \n-\t\t\t\t\tif (checkTerminated(d, empty)) {\n+\t\t\t\t\tif (checkTerminated(d, empty, v)) {\n \t\t\t\t\t\treturn;\n \t\t\t\t\t}\n \n@@ -528,7 +588,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\t\tif (sourceMode == Fuseable.SYNC) {\n \t\t\t\t\t\t\t//the q is empty\n \t\t\t\t\t\t\tdone = true;\n-\t\t\t\t\t\t\tcheckTerminated(true, true);\n+\t\t\t\t\t\t\tcheckTerminated(true, true, null);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t}\n@@ -555,7 +615,7 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t}\n \t\t\telse if ( sourceMode == Fuseable.SYNC ) {\n \t\t\t\tdone = true;\n-\t\t\t\tif (checkTerminated(true, empty)) { //empty can be true if no subscriber\n+\t\t\t\tif (checkTerminated(true, empty, null)) { //empty can be true if no subscriber\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n@@ -572,13 +632,23 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\treturn SUBSCRIBERS.getAndSet(this, TERMINATED);\n \t}\n \n-\tboolean checkTerminated(boolean d, boolean empty) {\n+\tboolean checkTerminated(boolean d, boolean empty, @Nullable T value) {\n \t\tif (s == Operators.cancelledSubscription()) {\n \t\t\tif (autoCancel) {\n \t\t\t\tterminate();\n+\n \t\t\t\tQueue q = queue;\n \t\t\t\tif (q != null) {\n-\t\t\t\t\tq.clear();\n+\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\tif (value != null) {\n+\t\t\t\t\t\t\tdiscard(value, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\treturn true;\n@@ -588,7 +658,16 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\tif (e != null && e != Exceptions.TERMINATED) {\n \t\t\t\tQueue q = queue;\n \t\t\t\tif (q != null) {\n-\t\t\t\t\tq.clear();\n+\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\tif (value != null) {\n+\t\t\t\t\t\t\tdiscard(value, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\tfor (FluxPublish.PubSubInner inner : terminate()) {\n \t\t\t\t\tinner.actual.onError(e);\n@@ -605,6 +684,31 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\treturn false;\n \t}\n \n+\tstatic void discardQueue(Queue q, Consumer hook) {\n+\t\tfor (; ; ) {\n+\t\t\tT toDiscard = q.poll();\n+\t\t\tif (toDiscard == null) {\n+\t\t\t\tbreak;\n+\t\t\t}\n+\n+\t\t\ttry {\n+\t\t\t\thook.accept(toDiscard);\n+\t\t\t}\n+\t\t\tcatch (Throwable t) {\n+\t\t\t\tlog.warn(\"Error while discarding a queue element, continuing with next queue element\", t);\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tstatic void discard(T value, Consumer hook) {\n+\t\ttry {\n+\t\t\thook.accept(value);\n+\t\t}\n+\t\tcatch (Throwable t) {\n+\t\t\tlog.warn(\"Error while discarding a queue element, continuing with next queue element\", t);\n+\t\t}\n+\t}\n+\n \tfinal boolean add(EmitterInner inner) {\n \t\tfor (; ; ) {\n \t\t\tFluxPublish.PubSubInner[] a = subscribers;\n@@ -624,7 +728,27 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \tfinal void remove(FluxPublish.PubSubInner inner) {\n \t\tfor (; ; ) {\n \t\t\tFluxPublish.PubSubInner[] a = subscribers;\n-\t\t\tif (a == TERMINATED || a == EMPTY) {\n+\t\t\tif (a == EMPTY) {\n+\t\t\t\t// means cancelled without adding\n+\t\t\t\tif (autoCancel && Operators.terminate(S, this)) {\n+\t\t\t\t\tif (WIP.getAndIncrement(this) != 0) {\n+\t\t\t\t\t\treturn;\n+\t\t\t\t\t}\n+\t\t\t\t\tterminate();\n+\t\t\t\t\tQueue q = queue;\n+\t\t\t\t\tif (q != null) {\n+\t\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse {\n+\t\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t\t}\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\telse if (a == TERMINATED) {\n \t\t\t\treturn;\n \t\t\t}\n \t\t\tint n = a.length;\n@@ -659,7 +783,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \t\t\t\t\tterminate();\n \t\t\t\t\tQueue q = queue;\n \t\t\t\t\tif (q != null) {\n-\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t\tConsumer hook = this.onDiscard;\n+\t\t\t\t\t\tif (hook != null) {\n+\t\t\t\t\t\t\tdiscardQueue(q, hook);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse {\n+\t\t\t\t\t\t\tq.clear();\n+\t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\treturn;\n@@ -683,13 +813,13 @@ public final class EmitterProcessor extends FluxProcessor implements In\n \n \t\t@Override\n \t\tvoid drainParent() {\n-\t\t\tparent.drain();\n+\t\t\tparent.drain(null);\n \t\t}\n \n \t\t@Override\n \t\tvoid removeAndDrainParent() {\n \t\t\tparent.remove(this);\n-\t\t\tparent.drain();\n+\t\t\tparent.drain(null);\n \t\t}\n \t}\n \ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java\nindex e9183e4ba..16ceea978 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -18,6 +18,7 @@ package reactor.core.publisher;\n \n import java.time.Duration;\n import java.util.Queue;\n+import java.util.function.Consumer;\n \n import org.reactivestreams.Publisher;\n import org.reactivestreams.Subscriber;\n@@ -420,6 +421,31 @@ public final class Sinks {\n \t\t * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels\n \t\t */\n \t\t ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel);\n+\n+\t\t/**\n+\t\t * A {@link Sinks.ManyWithUpstream} with the following characteristics:\n+\t\t *
      \n+\t\t *
    • Multicast
    • \n+\t\t *
    • Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}\n+\t\t * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.
    • \n+\t\t *
    • Backpressure : this sink honors downstream demand by conforming to the lowest demand in case\n+\t\t * of multiple subscribers.
      If the difference between multiple subscribers is too high compared to {@code bufferSize}:\n+\t\t *
      • {@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}
      • \n+\t\t *
      • {@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}\n+\t\t * an {@link Exceptions#failWithOverflow() overflow error}.
      \n+\t\t *
    • \n+\t\t *
    • Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}\n+\t\t * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements\n+\t\t * that have been buffered due to backpressure/warm up.
    • \n+\t\t *
    \n+\t\t *

    \n+\t\t * \"\"\n+\t\t *\n+\t\t * @param bufferSize the maximum queue size\n+\t\t * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels\n+\t\t * @param onDiscardHook should be called when values from queue are cleared\n+\t\t */\n+\t\t ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer onDiscardHook);\n \t}\n \n \t/**\n@@ -557,6 +583,31 @@ public final class Sinks {\n \t\t */\n \t\t Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel);\n \n+\t\t/**\n+\t\t * A {@link Sinks.Many} with the following characteristics:\n+\t\t *

      \n+\t\t *
    • Multicast
    • \n+\t\t *
    • Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}\n+\t\t * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.
    • \n+\t\t *
    • Backpressure : this sink honors downstream demand by conforming to the lowest demand in case\n+\t\t * of multiple subscribers.
      If the difference between multiple subscribers is too high compared to {@code bufferSize}:\n+\t\t *
      • {@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}
      • \n+\t\t *
      • {@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}\n+\t\t * an {@link Exceptions#failWithOverflow() overflow error}.
      \n+\t\t *
    • \n+\t\t *
    • Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}\n+\t\t * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements\n+\t\t * that have been buffered due to backpressure/warm up.
    • \n+\t\t *
    \n+\t\t *

    \n+\t\t * \"\"\n+\t\t *\n+\t\t * @param bufferSize the maximum queue size\n+\t\t * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels\n+\t\t * @param onDiscardHook should be called when values from queue are cleared\n+\t\t */\n+\t\t Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer onDiscardHook);\n+\n \t\t/**\n \t\t A {@link Sinks.Many} with the following characteristics:\n \t\t *

      \ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java\nindex e72e7fec0..f5242dcb2 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -20,6 +20,7 @@ import java.time.Duration;\n import java.util.Queue;\n import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;\n import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;\n+import java.util.function.Consumer;\n \n import reactor.core.Disposable;\n import reactor.core.publisher.Sinks.Empty;\n@@ -109,17 +110,22 @@ final class SinksSpecs {\n \n \t\t@Override\n \t\tpublic Sinks.Many onBackpressureBuffer() {\n-\t\t\treturn new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);\n+\t\t\treturn new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);\n \t\t}\n \n \t\t@Override\n \t\tpublic Sinks.Many onBackpressureBuffer(int bufferSize) {\n-\t\t\treturn new EmitterProcessor<>(true, bufferSize);\n+\t\t\treturn new EmitterProcessor<>(true, bufferSize, null);\n \t\t}\n \n \t\t@Override\n \t\tpublic Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel) {\n-\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize);\n+\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, null);\n+\t\t}\n+\n+\t\t@Override\n+\t\tpublic Sinks.Many onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer hook) {\n+\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, hook);\n \t\t}\n \n \t\t@Override\n@@ -179,12 +185,17 @@ final class SinksSpecs {\n \n \t\t@Override\n \t\tpublic Sinks.ManyWithUpstream multicastOnBackpressureBuffer() {\n-\t\t\treturn new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);\n+\t\t\treturn new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);\n \t\t}\n \n \t\t@Override\n \t\tpublic Sinks.ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel) {\n-\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize);\n+\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, null);\n+\t\t}\n+\n+\t\t@Override\n+\t\tpublic Sinks.ManyWithUpstream multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer hook) {\n+\t\t\treturn new EmitterProcessor<>(autoCancel, bufferSize, hook);\n \t\t}\n \t}\n \n@@ -258,6 +269,13 @@ final class SinksSpecs {\n \t\t\treturn wrapMany(original);\n \t\t}\n \n+\t\t@Override\n+\t\tpublic Many onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer onDiscardHook) {\n+\t\t\t@SuppressWarnings(\"deprecation\") // EmitterProcessor will be removed in 3.5.\n+\t\t\tfinal EmitterProcessor original = EmitterProcessor.create(bufferSize, autoCancel, onDiscardHook);\n+\t\t\treturn wrapMany(original);\n+\t\t}\n+\n \t\t@Override\n \t\tpublic Many directAllOrNothing() {\n \t\t\tfinal SinkManyBestEffort original = SinkManyBestEffort.createAllOrNothing();\n@@ -367,6 +385,7 @@ final class SinksSpecs {\n \t\t}\n \n \t\t@Override\n+\n \t\tpublic Many onBackpressureBuffer(Queue queue) {\n \t\t\t@SuppressWarnings(\"deprecation\") // UnicastProcessor will be removed in 3.5.\n \t\t\tfinal UnicastProcessor original = UnicastProcessor.create(queue);\ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java\nindex d21f4280b..5f11a4140 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -530,9 +530,9 @@ public final class UnicastProcessor extends FluxProcessor\n \t\t\tthis.actual = actual;\n \t\t\tif (cancelled) {\n \t\t\t\tthis.hasDownstream = false;\n-\t\t\t} else {\n-\t\t\t\tdrain(null);\n \t\t\t}\n+\n+\t\t\tdrain(null);\n \t\t} else {\n \t\t\tOperators.error(actual, new IllegalStateException(\"UnicastProcessor \" +\n \t\t\t\t\t\"allows only a single Subscriber\"));\n@@ -556,7 +556,7 @@ public final class UnicastProcessor extends FluxProcessor\n \n \t\tdoTerminate();\n \n-\t\tif (WIP.getAndIncrement(this) == 0) {\n+\t\tif (actual != null && WIP.getAndIncrement(this) == 0) {\n \t\t\tif (!outputFused) {\n \t\t\t\t// discard MUST be happening only and only if there is no racing on elements consumption\n \t\t\t\t// which is guaranteed by the WIP guard here in case non-fused output\ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java b/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java\nindex bd04e9936..3f7c69a8b 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicLong;\n import java.util.concurrent.atomic.AtomicReference;\n import java.util.stream.Stream;\n \n+import org.assertj.core.api.Assertions;\n import org.awaitility.Awaitility;\n import org.junit.jupiter.api.Disabled;\n import org.junit.jupiter.api.Test;\n@@ -42,6 +43,7 @@ import reactor.core.Scannable;\n import reactor.core.scheduler.Scheduler;\n import reactor.core.scheduler.Schedulers;\n import reactor.test.AutoDisposingExtension;\n+import reactor.test.MemoryUtils;\n import reactor.test.StepVerifier;\n import reactor.test.publisher.TestPublisher;\n import reactor.test.subscriber.AssertSubscriber;\n@@ -65,6 +67,21 @@ public class EmitterProcessorTest {\n \n \t@RegisterExtension\n \tAutoDisposingExtension afterTest = new AutoDisposingExtension();\n+\t//https://github.com/reactor/reactor-core/issues/3359\n+\t@Test\n+\tvoid shouldClearBufferOnCancellation() {\n+\t\tMemoryUtils.OffHeapDetector tracker = new MemoryUtils.OffHeapDetector();\n+\t\tEmitterProcessor source = EmitterProcessor.create(32, true, MemoryUtils.Tracked::release);\n+\n+\t\tAssertions.assertThat(source.tryEmitNext(tracker.track(1))).isEqualTo(Sinks.EmitResult.OK);\n+\t\tAssertions.assertThat(source.tryEmitNext(tracker.track(2))).isEqualTo(Sinks.EmitResult.OK);\n+\t\tAssertions.assertThat(source.tryEmitNext(tracker.track(3))).isEqualTo(Sinks.EmitResult.OK);\n+\n+\t\tsource.take(0).blockLast();\n+\n+\t\ttracker.assertNoLeaks();\n+\t}\n+\n \n \t@Test\n \tvoid smokeTestManyWithUpstream() {\n@@ -1012,7 +1029,7 @@ public class EmitterProcessorTest {\n \t\tAssertSubscriber testSubscriber1 = new AssertSubscriber<>(Context.of(\"key\", \"value1\"));\n \t\tAssertSubscriber testSubscriber2 = new AssertSubscriber<>(Context.of(\"key\", \"value2\"));\n \n-\t\tEmitterProcessor emitterProcessor = new EmitterProcessor<>(false, 1);\n+\t\tEmitterProcessor emitterProcessor = new EmitterProcessor<>(false, 1, null);\n \t\temitterProcessor.subscribe(testSubscriber1);\n \t\temitterProcessor.subscribe(testSubscriber2);\n \ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java\nindex f0cbb8abb..0d6b4f822 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -152,6 +152,12 @@ public class OnDiscardShouldNotLeakTest {\n \t\t\tDiscardScenario.sinkSource(\"unicastSink\", Sinks.unsafe().many().unicast()::onBackpressureBuffer, null),\n \t\t\tDiscardScenario.sinkSource(\"unicastSinkAndPublishOn\", Sinks.unsafe().many().unicast()::onBackpressureBuffer,\n \t\t\t\t\tf -> f.publishOn(Schedulers.immediate())),\n+\t\t\tDiscardScenario.sinkSource(\"multicastBufferSink\",\n+\t\t\t\t\t() -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),\n+\t\t\t\t\tnull),\n+\t\t\tDiscardScenario.sinkSource(\"multicastBufferSinkAndPublishOn\",\n+\t\t\t\t\t() -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),\n+\t\t\t\t\tf -> f.publishOn(Schedulers.immediate())),\n \t\t\tDiscardScenario.fluxSource(\"singleOrEmpty\", f -> f.singleOrEmpty().onErrorReturn(Tracked.RELEASED)),\n \t\t\tDiscardScenario.fluxSource(\"collect\", f -> f.collect(ArrayList::new, ArrayList::add)\n \t\t\t .doOnSuccess(l -> l.forEach(Tracked::safeRelease))\n@@ -617,7 +623,11 @@ public class OnDiscardShouldNotLeakTest {\n \t\t\t\tSinks.Many sink = sinksManySupplier.get();\n \t\t\t\t//noinspection CallingSubscribeInNonBlockingScope\n \t\t\t\tmain.flux().subscribe(\n-\t\t\t\t\t\tv -> sink.emitNext(v, FAIL_FAST),\n+\t\t\t\t\t\tv -> {\n+\t\t\t\t\t\t\tif (sink.tryEmitNext(v) != Sinks.EmitResult.OK) {\n+\t\t\t\t\t\t\t\tv.release();\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t},\n \t\t\t\t\t\te -> sink.emitError(e, FAIL_FAST),\n \t\t\t\t\t\t() -> sink.emitComplete(FAIL_FAST));\n \t\t\t\tFlux finalFlux = sink.asFlux();\ndiff --git a/reactor-core/src/test/java/reactor/test/MemoryUtils.java b/reactor-core/src/test/java/reactor/test/MemoryUtils.java\nindex 54084c403..289cd9e23 100644\n--- a/reactor-core/src/test/java/reactor/test/MemoryUtils.java\n+++ b/reactor-core/src/test/java/reactor/test/MemoryUtils.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2018-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2018-2023 VMware Inc. or its affiliates, All Rights Reserved.\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."},"changed_files":{"kind":"string","value":"['reactor-core/src/main/java/reactor/core/publisher/Sinks.java', 'reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java', 'reactor-core/src/test/java/reactor/test/MemoryUtils.java', 'reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java', 'reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.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":3793901,"string":"3,793,901"},"repo_tokens_count":{"kind":"number","value":946852,"string":"946,852"},"repo_lines_count":{"kind":"number","value":129078,"string":"129,078"},"repo_files_without_tests_count":{"kind":"number","value":463,"string":"463"},"changed_symbols_count":{"kind":"number","value":10801,"string":"10,801"},"changed_tokens_count":{"kind":"number","value":2752,"string":"2,752"},"changed_lines_count":{"kind":"number","value":270,"string":"270"},"changed_files_without_tests_count":{"kind":"number","value":4,"string":"4"},"issue_symbols_count":{"kind":"number","value":770,"string":"770"},"issue_words_count":{"kind":"number","value":80,"string":"80"},"issue_tokens_count":{"kind":"number","value":186,"string":"186"},"issue_lines_count":{"kind":"number","value":23,"string":"23"},"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:28:05","string":"1970-01-01T00:28:05"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1379,"cells":{"id":{"kind":"number","value":1071,"string":"1,071"},"text_id":{"kind":"string","value":"reactor/reactor-core/3156/3137"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/3137"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3156"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3156"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"ClassCastException when using Hooks"},"issue_body":{"kind":"string","value":"\r\n\r\nWe have a registered Hook for metrics purposes, which transforms Monos and Fluxes.\r\n\r\nWhen using in in conjunction with `collectList` and `flatMap`, we get a `ClassCastException` (see example below):\r\n\r\n```\r\njava.lang.ClassCastException: class reactor.core.publisher.FluxDoFinally$DoFinallySubscriber cannot be cast to class reactor.core.Fuseable$QueueSubscription (reactor.core.publisher.FluxDoFinally$DoFinallySubscriber and reactor.core.Fuseable$QueueSubscription are in unnamed module of loader 'app')\r\n\r\n\tat reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:177)\r\n\tat reactor.core.publisher.FluxDoFinally$DoFinallySubscriber.onSubscribe(FluxDoFinally.java:107)\r\n\tat reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:178)\r\n\tat reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onSubscribe(MonoCollectList.java:78)\r\n\tat reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53)\r\n\tat reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59)\r\n\tat reactor.core.publisher.Mono.subscribe(Mono.java:4397)\r\n\tat reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:200)\r\n\tat reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53)\r\n\tat reactor.core.publisher.Mono.subscribe(Mono.java:4382)\r\n\tat reactor.core.publisher.Mono.block(Mono.java:1706)\r\n\tat com.aviloo.testing.actor.HookProblemTest.reproduceClassCastExceptionWithHooks(HookProblemTest.java:27)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)\r\n\tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\r\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)\r\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)\r\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)\r\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)\r\n\tat org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)\r\n\tat org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)\r\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)\r\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)\r\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)\r\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)\r\n\tat org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)\r\n\tat org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)\r\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)\r\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)\r\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)\r\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)\r\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1511)\r\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)\r\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)\r\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1511)\r\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)\r\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)\r\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)\r\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)\r\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)\r\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\r\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)\r\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)\r\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)\r\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)\r\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)\r\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)\r\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)\r\n\tat org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)\r\n\tat org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)\r\n\tat com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)\r\n\tat com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)\r\n\tat com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)\r\n\tat com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)\r\n\tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)\r\n\tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)\r\n\tSuppressed: java.lang.Exception: #block terminated with an error\r\n\t\tat reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)\r\n\t\tat reactor.core.publisher.Mono.block(Mono.java:1707)\r\n\t\t... 71 more\r\n```\r\n\r\nIt seems that the hook transforms the subscription such that it does not implement `QueueSubscription` anymore.\r\n\r\n## Expected Behavior\r\n\r\nNo exception.\r\n\r\n## Actual Behavior\r\n\r\nSee description.\r\n\r\n## Steps to Reproduce\r\n\r\nThis is the most minimal example I could come up with.\r\n\r\n```java\r\n\t@Test\r\n\tpublic void reproduceClassCastExceptionWithHooks() throws Exception {\r\n\t\tHooks.onLastOperator(objectPublisher -> {\r\n\t\t\tif (objectPublisher instanceof Mono) {\r\n\t\t\t\treturn Hooks.convertToMonoBypassingHooks(objectPublisher, false)\r\n\t\t\t\t\t\t.doOnSubscribe(subscription -> {\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.doFinally(signalType -> {\r\n\t\t\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\treturn objectPublisher;\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tMono.just(1)\r\n\t\t\t\t.flatMap(fsm -> Flux.just(1, 2, 3).collectList())\r\n\t\t\t\t// .flatMap(Mono::just) // this will solve the ClassCastException --> workaround\r\n\t\t\t\t.block();\r\n\t}\r\n```\r\n\r\n## Possible Solution\r\n\r\nWorkaround: Add a \"kind of no-op\" transformation. See comment in unit test. Still, this is very uggly, since you would have to add this to every such occurence... \r\n\r\nIs there anything else we could do? Or did we miss something? How do you think about it?\r\n\r\n## Your Environment\r\nUbuntu 22.04\r\nJava temurin-17.0.4\r\nreactor 3.4.21\r\n"},"base_sha":{"kind":"string","value":"4768c43f0e6cd3ff2806e6cfc8e659f88b39b513"},"head_sha":{"kind":"string","value":"ff5769678f6d7c498aa5bb547e7116f131bdf965"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/4768c43f0e6cd3ff2806e6cfc8e659f88b39b513...ff5769678f6d7c498aa5bb547e7116f131bdf965"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/core/publisher/Flux.java b/reactor-core/src/main/java/reactor/core/publisher/Flux.java\nindex 6ac402e20..222ad4336 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/Flux.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/Flux.java\n@@ -8445,6 +8445,10 @@ public abstract class Flux implements CorePublisher {\n \t\tCorePublisher publisher = Operators.onLastAssembly(this);\n \t\tCoreSubscriber subscriber = Operators.toCoreSubscriber(actual);\n \n+\t\tif (subscriber instanceof Fuseable.QueueSubscription && this != publisher && this instanceof Fuseable && !(publisher instanceof Fuseable)) {\n+\t\t\tsubscriber = new FluxHide.SuppressFuseableSubscriber<>(subscriber);\n+\t\t}\n+\n \t\ttry {\n \t\t\tif (publisher instanceof OptimizableOperator) {\n \t\t\t\tOptimizableOperator operator = (OptimizableOperator) publisher;\ndiff --git a/reactor-core/src/main/java/reactor/core/publisher/Mono.java b/reactor-core/src/main/java/reactor/core/publisher/Mono.java\nindex c665a457a..f79e56640 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/Mono.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/Mono.java\n@@ -4375,6 +4375,10 @@ public abstract class Mono implements CorePublisher {\n \t\tCorePublisher publisher = Operators.onLastAssembly(this);\n \t\tCoreSubscriber subscriber = Operators.toCoreSubscriber(actual);\n \n+\t\tif (subscriber instanceof Fuseable.QueueSubscription && this != publisher && this instanceof Fuseable && !(publisher instanceof Fuseable)) {\n+\t\t\tsubscriber = new FluxHide.SuppressFuseableSubscriber<>(subscriber);\n+\t\t}\n+\n \t\ttry {\n \t\t\tif (publisher instanceof OptimizableOperator) {\n \t\t\t\tOptimizableOperator operator = (OptimizableOperator) publisher;\ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java b/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java\nindex 63a1a612b..b1920212f 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -70,7 +70,6 @@ public class HooksTest {\n \t\t}\n \t}\n \n-\n \t@Test\n \tpublic void staticActivationOfOperatorDebug() {\n \t\tString oldProp = System.setProperty(\"reactor.trace.operatorStacktrace\", \"true\");\n@@ -142,6 +141,7 @@ public class HooksTest {\n \t\tFunction, ? extends Publisher> hook = p -> p;\n \t\tHooks.onEachOperator(hook);\n \n+\n \t\tassertThat(Hooks.onEachOperatorHook).isSameAs(hook);\n \t}\n \n@@ -1254,4 +1254,30 @@ public class HooksTest {\n \t\t\t}\n \t\t};\n \t}\n+\n+\t// https://github.com/reactor/reactor-core/issues/3137\n+\t@Test\n+\tpublic void reproduceClassCastExceptionWithHooks() {\n+\t\tHooks.onLastOperator(objectPublisher -> {\n+\t\t\tif (objectPublisher instanceof Mono) {\n+\t\t\t\treturn Hooks.convertToMonoBypassingHooks(objectPublisher, false)\n+\t\t\t\t .doFinally(signalType -> {\n+\t\t\t\t });\n+\t\t\t} else {\n+\t\t\t\treturn objectPublisher;\n+\t\t\t}\n+\t\t});\n+\n+\t\ttry {\n+\t\t\tMono.just(1)\n+\t\t\t .flatMap(fsm -> Mono.just(1)\n+\t\t\t .doOnSubscribe(subscription -> {\n+\t\t\t }))\n+\t\t\t .doOnSubscribe(subscription -> {\n+\t\t\t })\n+\t\t\t .block();\n+\t\t} finally {\n+\t\t\tHooks.resetOnLastOperator();\n+\t\t}\n+\t}\n }"},"changed_files":{"kind":"string","value":"['reactor-core/src/test/java/reactor/core/publisher/HooksTest.java', 'reactor-core/src/main/java/reactor/core/publisher/Mono.java', 'reactor-core/src/main/java/reactor/core/publisher/Flux.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":3738196,"string":"3,738,196"},"repo_tokens_count":{"kind":"number","value":932081,"string":"932,081"},"repo_lines_count":{"kind":"number","value":127518,"string":"127,518"},"repo_files_without_tests_count":{"kind":"number","value":458,"string":"458"},"changed_symbols_count":{"kind":"number","value":444,"string":"444"},"changed_tokens_count":{"kind":"number","value":86,"string":"86"},"changed_lines_count":{"kind":"number","value":8,"string":"8"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":10536,"string":"10,536"},"issue_words_count":{"kind":"number","value":394,"string":"394"},"issue_tokens_count":{"kind":"number","value":2208,"string":"2,208"},"issue_lines_count":{"kind":"number","value":144,"string":"144"},"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:27:40","string":"1970-01-01T00:27:40"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1380,"cells":{"id":{"kind":"number","value":1069,"string":"1,069"},"text_id":{"kind":"string","value":"reactor/reactor-core/3351/3336"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/3336"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3351"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3351"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"FlatMapDelayError hangs on callable source error"},"issue_body":{"kind":"string","value":"\r\nFlatMapDelayError does not propagate an onError signal when a callable source produces an error. \r\nIt also does not cancel the upstream subscription. This results in a hanging flux that can never complete because it \r\ndoes not process any more values from the upstream publisher nor does it signal a termination to downstream subscribers.\r\n\r\nNotably this only occurs when the error is from a callable source. When the mapping function throws the error directly \r\nthen the behavior is as expected where the backlog is consumed and the flux terminates with an error. However when the \r\noperator is modified with onErrorConsume the error is properly swallowed and processing continues.\r\n\r\nThis does not affect concatMapDelayError as far as I have been able to test\r\n\r\n\r\n\r\n## Expected Behavior\r\n\r\nFlatMapDelayError should cancel the upstream subscription, process the backlog, then emit an onError response\r\n\r\n## Actual Behavior\r\n\r\nFlatMapDelayError never completes when callable source throws an error\r\n\r\n## Possible Solution\r\n\r\nThis behavior seems to have been introduced here \r\nhttps://github.com/reactor/reactor-core/commit/af0cb628ece3c0a543512ea9913c4ff72ba18566#diff-3ad99cc26a2bc1707dda2203da9a667ccf3abdd52aac45ee6b2c4cea438a842fR361-R363. \r\nHowever I do not know the side effects well enough to give a full solution.\r\n\r\nAdditionally it appears that this is caused by some optimization around the flatMap operator as there is a current test which utilizes .hide() on the error flux and completes successfully\r\nlinked here https://github.com/reactor/reactor-core/blob/912441f7d36adfb84f06595cecd8895b7518d8c9/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java#L604\r\n\r\nA difference when using hide though is that the upstream subscription is still never cancelled so there is still a deviation of behavior from the thrown case as this would cause hot infinite publishers to never propagate the error and continue requesting events.\r\n\r\n\r\n## Steps to Reproduce\r\n\r\n\r\nBelow are examples for the direct throw vs callable source\r\n\r\n```java\r\n@Test\r\nvoid workingFlatMapDelayError() {\r\n\tFlux.just(0, 1, 2, 3).log()\r\n .flatMapDelayError(integer -> {\r\n throw new RuntimeException(); // Cancels upstream subscription after consuming one event\r\n }, 1, 1)\r\n .as(StepVerifier::create)\r\n .expectError()\r\n .verify(Duration.ofSeconds(1)); // Completes as expected\r\n}\r\n\r\n@Test\r\nvoid hangingFlatMapDelayError() {\r\n\tFlux.just(0, 1, 2, 3).log()\r\n .flatMapDelayError(integer -> {\r\n return Flux.error(new RuntimeException()); // Does not cancel upstream subscription\r\n }, 1, 1)\r\n .as(StepVerifier::create)\r\n .expectError()\r\n .verify(Duration.ofSeconds(1)); // Triggers timeout\r\n}\r\n\r\n@Test\r\nvoid deoptimizedFlatMapDelayError() {\r\n\tFlux.just(0, 1, 2, 3).log()\r\n .flatMapDelayError(integer -> {\r\n return Flux.error(new RuntimeException()).hide(); // Does not cancel upstream subscription\r\n }, 1, 1)\r\n .as(StepVerifier::create)\r\n .expectError()\r\n .verify(Duration.ofSeconds(1)); // Completes after consuming all events\r\n}\r\n```\r\n\r\n## Your Environment\r\n\r\n\r\n\r\n* Reactor version(s) used: reactor-core 3.5.2, reactor-test 3.5.2\r\n* Other relevant libraries versions (eg. `netty`, ...): N/A\r\n* JVM version (`java -version`): 17\r\n* OS and version (eg `uname -a`): Windows 11"},"base_sha":{"kind":"string","value":"3dbc0701a061f7e20e304e0475a5ddac1745bddd"},"head_sha":{"kind":"string","value":"075639613aeec1890f7d10ba4e747a261da6adde"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/3dbc0701a061f7e20e304e0475a5ddac1745bddd...075639613aeec1890f7d10ba4e747a261da6adde"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java b/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java\nindex f3959edd3..e14d6eb1f 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -416,6 +416,7 @@ final class FluxFlatMap extends InternalFluxOperator {\n \t\t\t\t\t\tonError(Operators.onOperatorError(s, e_, t, ctx));\n \t\t\t\t\t}\n \t\t\t\t\tOperators.onDiscard(t, ctx);\n+\t\t\t\t\ttryEmitScalar(null);\n \t\t\t\t\treturn;\n \t\t\t\t}\n \t\t\t\ttryEmitScalar(v);\ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java\nindex 7176da584..599772402 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -42,7 +42,6 @@ import reactor.core.Scannable;\n import reactor.core.TestLoggerExtension;\n import reactor.core.publisher.FluxPeekFuseableTest.AssertQueueSubscription;\n import reactor.core.scheduler.Schedulers;\n-import reactor.test.util.LoggerUtils;\n import reactor.test.StepVerifier;\n import reactor.test.publisher.TestPublisher;\n import reactor.test.subscriber.AssertSubscriber;\n@@ -1869,4 +1868,41 @@ public class FluxFlatMapTest {\n \t\t .expectError(NoSuchMethodException.class)\n \t\t .verify();\n \t}\n+\n+\tstatic class FluxFlatMapDelayError3336Test {\n+\n+\t\t@Test\n+\t\tvoid workingFlatMapDelayError() {\n+\t\t\tFlux.just(0, 1, 2, 3)\n+\t\t\t .flatMapDelayError(integer -> {\n+\t\t\t\t throw new RuntimeException(); // Cancels upstream subscription after consuming one event\n+\t\t\t }, 1, 1)\n+\t\t\t .as(StepVerifier::create)\n+\t\t\t .expectError()\n+\t\t\t .verify(Duration.ofSeconds(1)); // Completes as expected\n+\t\t}\n+\n+\t\t@Test\n+\t\tvoid hangingFlatMapDelayError() {\n+\t\t\tFlux.just(0, 1, 2, 3)\n+\t\t\t .flatMapDelayError(integer -> {\n+\t\t\t\t return Flux.error(new RuntimeException()); // Does not cancel upstream subscription\n+\t\t\t }, 1, 1)\n+\t\t\t .as(StepVerifier::create)\n+\t\t\t .expectError()\n+\t\t\t .verify(Duration.ofSeconds(1)); // Triggers timeout\n+\t\t}\n+\n+\t\t@Test\n+\t\tvoid deoptimizedFlatMapDelayError() {\n+\t\t\tFlux.just(0, 1, 2, 3)\n+\t\t\t .flatMapDelayError(integer -> {\n+\t\t\t\t return Flux.error(new RuntimeException())\n+\t\t\t\t .hide(); // Does not cancel upstream subscription\n+\t\t\t }, 1, 1)\n+\t\t\t .as(StepVerifier::create)\n+\t\t\t .expectError()\n+\t\t\t .verify(Duration.ofSeconds(1)); // Completes after consuming all events\n+\t\t}\n+\t}\n }"},"changed_files":{"kind":"string","value":"['reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.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":3998388,"string":"3,998,388"},"repo_tokens_count":{"kind":"number","value":995207,"string":"995,207"},"repo_lines_count":{"kind":"number","value":135651,"string":"135,651"},"repo_files_without_tests_count":{"kind":"number","value":489,"string":"489"},"changed_symbols_count":{"kind":"number","value":186,"string":"186"},"changed_tokens_count":{"kind":"number","value":51,"string":"51"},"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":4430,"string":"4,430"},"issue_words_count":{"kind":"number","value":532,"string":"532"},"issue_tokens_count":{"kind":"number","value":1016,"string":"1,016"},"issue_lines_count":{"kind":"number","value":88,"string":"88"},"issue_links_count":{"kind":"number","value":5,"string":"5"},"issue_code_blocks_count":{"kind":"number","value":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:56","string":"1970-01-01T00:27:56"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1381,"cells":{"id":{"kind":"number","value":1070,"string":"1,070"},"text_id":{"kind":"string","value":"reactor/reactor-core/3262/3253"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/3253"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3262"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3262"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"Mono and Flux with onErrorContinue hangs on network errors (thrown by Netty)"},"issue_body":{"kind":"string","value":"When I use an `onErrorContinue` on a `Mono` or a `Flux` that gets its input from a `WebClient`, the whole chain hangs in case a network error is thrown. I've seen this behaviour with errors caused by a connection timeout, read timeout, unknown host and a refused connection.\r\n\r\nPlease note that I created this bug in reactor-core, because this is the place where `onErrorContinue` is defined. I suspect that this bug is not specific to the netty http client, but I haven't tested that. \r\n\r\n## Expected Behavior\r\nI expect the program to continue and not to cause any thread to hang.\r\n\r\n## Actual Behavior\r\nThe thread that executes the Mono (or Flux) blocks forever.\r\n\r\n## Steps to Reproduce\r\n\r\nYou can use the following junit 5 tests (one for Mono and one for Flux) to reproduce this issue. This test instantiates a WebClient with a 200ms response timeout. This client is then used to do a call to \"https://httpstat.us/200?sleep=500\" that will return a 200 response only after 500ms. This way we force a response timeout to be thrown.\r\n\r\nA failing test means that the `block()` did not return any result within 5 seconds.\r\n\r\n```java\r\npublic class NettyReactorTest {\r\n private final WebClient webClient;\r\n\r\n public NettyReactorTest() {\r\n final ReactorClientHttpConnector httpConnector = new ReactorClientHttpConnector(\r\n HttpClient.create().responseTimeout(Duration.ofMillis(200)));\r\n\r\n this.webClient = WebClient.builder()\r\n .baseUrl(\"https://httpstat.us\")\r\n .clientConnector(httpConnector)\r\n .build();\r\n }\r\n\r\n @Test\r\n public void testMonoOnErrorContinueDoesNotHangOnTimeouts() {\r\n Mono> call = webClient.get()\r\n .uri(\"/200?sleep=500\")\r\n .retrieve()\r\n .toBodilessEntity()\r\n .onErrorContinue((e, o) -> {\r\n });\r\n\r\n Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> call.block());\r\n }\r\n\r\n @Test\r\n public void testFluxOnErrorContinueDoesNotHangOnTimeouts() {\r\n Mono> call = webClient.get()\r\n .uri(\"/200?sleep=500\")\r\n .retrieve()\r\n .toBodilessEntity();\r\n\r\n Mono>> calls = Flux.fromIterable(List.of(1, 2, 3))\r\n .flatMap(i -> call)\r\n .onErrorContinue((e, o) -> {})\r\n .collectList();\r\n\r\n Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> calls.block());\r\n }\r\n}\r\n```\r\n\r\n## Extra information\r\n\r\nWhen we take a thread dump a little while after we run the test (that blocks) we see that the thread that calls `block()` is stuck on the `Mono.block()` operator:\r\n```\r\njunit-timeout-thread-1\r\n jdk.internal.misc.Unsafe.park(boolean, long) Unsafe.java (native)\r\n java.util.concurrent.locks.LockSupport.park(Object) LockSupport.java:194\r\n java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt() AbstractQueuedSynchronizer.java:885\r\n java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(int) AbstractQueuedSynchronizer.java:1039\r\n java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(int) AbstractQueuedSynchronizer.java:1345\r\n java.util.concurrent.CountDownLatch.await() CountDownLatch.java:232\r\n reactor.core.publisher.BlockingSingleSubscriber.blockingGet() BlockingSingleSubscriber.java:87\r\n reactor.core.publisher.Mono.block() Mono.java:1707\r\n NettyReactorTest.lambda$testMonoOnErrorContinueDoesNotHangOnTimeouts$1(Mono) NettyReactorTest.java:52\r\n NettyReactorTest$$Lambda$529.get()\r\n org.junit.jupiter.api.AssertTimeout.lambda$assertTimeoutPreemptively$4(AtomicReference, ThrowingSupplier) AssertTimeout.java:138\r\n org.junit.jupiter.api.AssertTimeout$$Lambda$530.call()\r\n java.util.concurrent.FutureTask.run() FutureTask.java:264\r\n java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) ThreadPoolExecutor.java:1128\r\n java.util.concurrent.ThreadPoolExecutor$Worker.run() ThreadPoolExecutor.java:628\r\n java.lang.Thread.run() Thread.java:829\r\n```\r\n\r\n## Possible Solution\r\n\r\nNot a solution, but more of a way to mitigate the impact.\r\n\r\nI am aware that `onErrorContinue` is a specialised operator and that for my specific case I could (and should) have used `onErrorResume`. Indeed, replacing `onErrorContinue` with `onErrorResume` in the above tests makes the problem go away. So, perhaps I am just another case of someone using it wrongly and \"tripping up on it\" (https://github.com/reactor/reactor-core/issues/2184).\r\n\r\nYet, this seemingly innocent code causes a rather nasty issue that should either be:\r\n* fixed if this is indeed a bug or \r\n* prevented if this is an unjust use of the `onErrorContinue` operator. \r\n\r\nFor the latter, I like @simonbasle's suggestion to move this operator to an `unsafe()` subgroup. This would have prevented me from using it and use `onErrorResume` instead as suggested in the documentation.\r\n\r\n## Your Environment\r\n* Reactor version(s) used: 3.4.22\r\n* Other relevant libraries versions (eg. `netty`, ...):\r\n** netty: 1.0.22\r\n** spring / spring-web: 5.3.22\r\n* JVM version (`java -version`): OpenJDK Runtime Environment Zulu11.58+15-CA (build 11.0.16+8-LTS)\r\n* OS and version (eg `uname -a`): Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64 x86_64 (macOS Monterey)\r\n"},"base_sha":{"kind":"string","value":"b31b331e1c37bf468320185474d39bc504afea99"},"head_sha":{"kind":"string","value":"0cc9e9831f1609f268c9f45de7d0782615cc0309"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/b31b331e1c37bf468320185474d39bc504afea99...0cc9e9831f1609f268c9f45de7d0782615cc0309"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java b/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java\nindex 3283bd781..540501b5c 100644\n--- a/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java\n+++ b/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -31,6 +31,7 @@ import reactor.core.publisher.Mono;\n import reactor.core.scheduler.Scheduler;\n import reactor.core.scheduler.Schedulers;\n import reactor.util.annotation.Nullable;\n+import reactor.util.context.Context;\n import reactor.util.context.ContextView;\n \n /**\n@@ -539,69 +540,73 @@ public final class RetryBackoffSpec extends Retry {\n \t@Override\n \tpublic Flux generateCompanion(Flux t) {\n \t\tvalidateArguments();\n-\t\treturn t.concatMap(retryWhenState -> {\n-\t\t\t//capture the state immediately\n-\t\t\tRetrySignal copy = retryWhenState.copy();\n-\t\t\tThrowable currentFailure = copy.failure();\n-\t\t\tlong iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();\n-\n-\t\t\tif (currentFailure == null) {\n-\t\t\t\treturn Mono.error(new IllegalStateException(\"Retry.RetrySignal#failure() not expected to be null\"));\n-\t\t\t}\n-\n-\t\t\tif (!errorFilter.test(currentFailure)) {\n-\t\t\t\treturn Mono.error(currentFailure);\n-\t\t\t}\n-\n-\t\t\tif (iteration >= maxAttempts) {\n-\t\t\t\treturn Mono.error(retryExhaustedGenerator.apply(this, copy));\n-\t\t\t}\n-\n-\t\t\tDuration nextBackoff;\n-\t\t\ttry {\n-\t\t\t\tnextBackoff = minBackoff.multipliedBy((long) Math.pow(2, iteration));\n-\t\t\t\tif (nextBackoff.compareTo(maxBackoff) > 0) {\n+\t\treturn Flux.deferContextual(cv ->\n+\t\t t.contextWrite(cv)\n+\t\t\t.concatMap(retryWhenState -> {\n+\t\t\t\t//capture the state immediately\n+\t\t\t\tRetrySignal copy = retryWhenState.copy();\n+\t\t\t\tThrowable currentFailure = copy.failure();\n+\t\t\t\tlong iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();\n+\n+\t\t\t\tif (currentFailure == null) {\n+\t\t\t\t\treturn Mono.error(new IllegalStateException(\"Retry.RetrySignal#failure() not expected to be null\"));\n+\t\t\t\t}\n+\n+\t\t\t\tif (!errorFilter.test(currentFailure)) {\n+\t\t\t\t\treturn Mono.error(currentFailure);\n+\t\t\t\t}\n+\n+\t\t\t\tif (iteration >= maxAttempts) {\n+\t\t\t\t\treturn Mono.error(retryExhaustedGenerator.apply(this, copy));\n+\t\t\t\t}\n+\n+\t\t\t\tDuration nextBackoff;\n+\t\t\t\ttry {\n+\t\t\t\t\tnextBackoff = minBackoff.multipliedBy((long) Math.pow(2, iteration));\n+\t\t\t\t\tif (nextBackoff.compareTo(maxBackoff) > 0) {\n+\t\t\t\t\t\tnextBackoff = maxBackoff;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\tcatch (ArithmeticException overflow) {\n \t\t\t\t\tnextBackoff = maxBackoff;\n \t\t\t\t}\n-\t\t\t}\n-\t\t\tcatch (ArithmeticException overflow) {\n-\t\t\t\tnextBackoff = maxBackoff;\n-\t\t\t}\n-\n-\t\t\t//short-circuit delay == 0 case\n-\t\t\tif (nextBackoff.isZero()) {\n-\t\t\t\treturn RetrySpec.applyHooks(copy, Mono.just(iteration),\n+\n+\t\t\t\t//short-circuit delay == 0 case\n+\t\t\t\tif (nextBackoff.isZero()) {\n+\t\t\t\t\treturn RetrySpec.applyHooks(copy, Mono.just(iteration),\n+\t\t\t\t\t\t\tsyncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry);\n+\t\t\t\t}\n+\n+\t\t\t\tThreadLocalRandom random = ThreadLocalRandom.current();\n+\n+\t\t\t\tlong jitterOffset;\n+\t\t\t\ttry {\n+\t\t\t\t\tjitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor))\n+\t\t\t\t\t\t\t.dividedBy(100)\n+\t\t\t\t\t\t\t.toMillis();\n+\t\t\t\t}\n+\t\t\t\tcatch (ArithmeticException ae) {\n+\t\t\t\t\tjitterOffset = Math.round(Long.MAX_VALUE * jitterFactor);\n+\t\t\t\t}\n+\t\t\t\tlong lowBound = Math.max(minBackoff.minus(nextBackoff)\n+\t\t\t\t\t\t.toMillis(), -jitterOffset);\n+\t\t\t\tlong highBound = Math.min(maxBackoff.minus(nextBackoff)\n+\t\t\t\t\t\t.toMillis(), jitterOffset);\n+\n+\t\t\t\tlong jitter;\n+\t\t\t\tif (highBound == lowBound) {\n+\t\t\t\t\tif (highBound == 0) jitter = 0;\n+\t\t\t\t\telse jitter = random.nextLong(highBound);\n+\t\t\t\t}\n+\t\t\t\telse {\n+\t\t\t\t\tjitter = random.nextLong(lowBound, highBound);\n+\t\t\t\t}\n+\t\t\t\tDuration effectiveBackoff = nextBackoff.plusMillis(jitter);\n+\t\t\t\treturn RetrySpec.applyHooks(copy, Mono.delay(effectiveBackoff,\n+\t\t\t\t\t\t\t\tbackoffSchedulerSupplier.get()),\n \t\t\t\t\t\tsyncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry);\n-\t\t\t}\n-\n-\t\t\tThreadLocalRandom random = ThreadLocalRandom.current();\n-\n-\t\t\tlong jitterOffset;\n-\t\t\ttry {\n-\t\t\t\tjitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor))\n-\t\t\t\t .dividedBy(100)\n-\t\t\t\t .toMillis();\n-\t\t\t}\n-\t\t\tcatch (ArithmeticException ae) {\n-\t\t\t\tjitterOffset = Math.round(Long.MAX_VALUE * jitterFactor);\n-\t\t\t}\n-\t\t\tlong lowBound = Math.max(minBackoff.minus(nextBackoff)\n-\t\t\t .toMillis(), -jitterOffset);\n-\t\t\tlong highBound = Math.min(maxBackoff.minus(nextBackoff)\n-\t\t\t .toMillis(), jitterOffset);\n-\n-\t\t\tlong jitter;\n-\t\t\tif (highBound == lowBound) {\n-\t\t\t\tif (highBound == 0) jitter = 0;\n-\t\t\t\telse jitter = random.nextLong(highBound);\n-\t\t\t}\n-\t\t\telse {\n-\t\t\t\tjitter = random.nextLong(lowBound, highBound);\n-\t\t\t}\n-\t\t\tDuration effectiveBackoff = nextBackoff.plusMillis(jitter);\n-\t\t\treturn RetrySpec.applyHooks(copy, Mono.delay(effectiveBackoff,\n-\t\t\t\t\tbackoffSchedulerSupplier.get()),\n-\t\t\t\t\tsyncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry);\n-\t\t});\n+\t\t\t})\n+\t\t .contextWrite(c -> Context.empty())\n+\t\t);\n \t}\n }\ndiff --git a/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java b/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java\nindex 55c3ae989..710ff4de8 100644\n--- a/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java\n+++ b/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2020-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.\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 java.util.function.Predicate;\n import reactor.core.Exceptions;\n import reactor.core.publisher.Flux;\n import reactor.core.publisher.Mono;\n+import reactor.util.context.Context;\n import reactor.util.context.ContextView;\n \n /**\n@@ -353,25 +354,30 @@ public final class RetrySpec extends Retry {\n \n \t@Override\n \tpublic Flux generateCompanion(Flux flux) {\n-\t\treturn flux.concatMap(retryWhenState -> {\n-\t\t\t//capture the state immediately\n-\t\t\tRetrySignal copy = retryWhenState.copy();\n-\t\t\tThrowable currentFailure = copy.failure();\n-\t\t\tlong iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();\n+\t\treturn Flux.deferContextual(cv ->\n+\t\t\tflux\n+\t\t\t\t\t.contextWrite(cv)\n+\t\t\t\t\t.concatMap(retryWhenState -> {\n+\t\t\t\t\t\t//capture the state immediately\n+\t\t\t\t\t\tRetrySignal copy = retryWhenState.copy();\n+\t\t\t\t\t\tThrowable currentFailure = copy.failure();\n+\t\t\t\t\t\tlong iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();\n \n-\t\t\tif (currentFailure == null) {\n-\t\t\t\treturn Mono.error(new IllegalStateException(\"RetryWhenState#failure() not expected to be null\"));\n-\t\t\t}\n-\t\t\telse if (!errorFilter.test(currentFailure)) {\n-\t\t\t\treturn Mono.error(currentFailure);\n-\t\t\t}\n-\t\t\telse if (iteration >= maxAttempts) {\n-\t\t\t\treturn Mono.error(retryExhaustedGenerator.apply(this, copy));\n-\t\t\t}\n-\t\t\telse {\n-\t\t\t\treturn applyHooks(copy, Mono.just(iteration), doPreRetry, doPostRetry, asyncPreRetry, asyncPostRetry);\n-\t\t\t}\n-\t\t});\n+\t\t\t\t\t\tif (currentFailure == null) {\n+\t\t\t\t\t\t\treturn Mono.error(new IllegalStateException(\"RetryWhenState#failure() not expected to be null\"));\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse if (!errorFilter.test(currentFailure)) {\n+\t\t\t\t\t\t\treturn Mono.error(currentFailure);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse if (iteration >= maxAttempts) {\n+\t\t\t\t\t\t\treturn Mono.error(retryExhaustedGenerator.apply(this, copy));\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\telse {\n+\t\t\t\t\t\t\treturn applyHooks(copy, Mono.just(iteration), doPreRetry, doPostRetry, asyncPreRetry, asyncPostRetry);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t})\n+\t\t\t\t\t.contextWrite(c -> Context.empty())\n+\t\t);\n \t}\n \n \t//===================\ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java\nindex ceab36edb..1eb0dbad5 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java\n@@ -58,6 +58,33 @@ public class FluxRetryWhenTest {\n \tFlux rangeError = Flux.concat(Flux.range(1, 2),\n \t\t\tFlux.error(new RuntimeException(\"forced failure 0\")));\n \n+\t@Test\n+\t//https://github.com/reactor/reactor-core/issues/3253\n+\tpublic void shouldFailWhenOnErrorContinueEnabled() {\n+\t\tMono.create(sink -> {\n+\t\t\t\t\tthrow new RuntimeException(\"blah\");\n+\t\t\t\t})\n+\t\t\t\t.retryWhen(Retry.indefinitely().filter(t -> false))\n+\t\t\t\t.onErrorContinue((e, o) -> {})\n+\t\t\t\t.as(StepVerifier::create)\n+\t\t\t\t.expectError()\n+\t\t\t\t.verify(Duration.ofSeconds(10));\n+\t}\n+\n+\t@Test\n+\t//https://github.com/reactor/reactor-core/issues/3253\n+\tpublic void shouldWorkAsExpected() {\n+\t\tMono.just(1)\n+\t\t\t.map(v -> { // ensure original context is propagated\n+\t\t\t\tthrow new RuntimeException(\"boom\");\n+\t\t\t})\n+\t\t\t.retryWhen(Retry.indefinitely().filter(t -> false))\n+\t\t\t.onErrorContinue((e, o) -> {})\n+\t\t\t.as(StepVerifier::create)\n+\t\t\t.expectComplete()\n+\t\t\t.verify(Duration.ofSeconds(10));\n+\t}\n+\n \t@Test\n \tpublic void dontRepeat() {\n \t\tAssertSubscriber ts = AssertSubscriber.create();"},"changed_files":{"kind":"string","value":"['reactor-core/src/main/java/reactor/util/retry/RetrySpec.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java', 'reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.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":3974838,"string":"3,974,838"},"repo_tokens_count":{"kind":"number","value":989269,"string":"989,269"},"repo_lines_count":{"kind":"number","value":134931,"string":"134,931"},"repo_files_without_tests_count":{"kind":"number","value":486,"string":"486"},"changed_symbols_count":{"kind":"number","value":6265,"string":"6,265"},"changed_tokens_count":{"kind":"number","value":1511,"string":"1,511"},"changed_lines_count":{"kind":"number","value":173,"string":"173"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":5454,"string":"5,454"},"issue_words_count":{"kind":"number","value":534,"string":"534"},"issue_tokens_count":{"kind":"number","value":1293,"string":"1,293"},"issue_lines_count":{"kind":"number","value":102,"string":"102"},"issue_links_count":{"kind":"number","value":3,"string":"3"},"issue_code_blocks_count":{"kind":"number","value":2,"string":"2"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:27:47","string":"1970-01-01T00:27:47"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1382,"cells":{"id":{"kind":"number","value":1066,"string":"1,066"},"text_id":{"kind":"string","value":"reactor/reactor-core/3555/3554"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/3554"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3555"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/3555"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"`FluxGroupBy`'s `GroupedFlux` does not propagate the `Subscription` to the second (rejected) `Subscriber`"},"issue_body":{"kind":"string","value":"When calling flatMap on a Publisher which throws an exception upon subscription, there are certain cases where checkTerminated throws a NPE and masks the actual exception. Furthermore flatMap never terminates.\r\n\r\n## Expected Behavior\r\nflatMap terminates with the actual Error\r\n\r\n## Actual Behavior\r\nNPE and no Termination. Stacktrace from the example below\r\n\r\n```\r\n2023-08-02 13:04:02 ERROR Operators - Operator called default onErrorDropped\r\njava.lang.NullPointerException: null\r\n\tat reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:840) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:609) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:589) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxFlatMap$FlatMapMain.onError(FluxFlatMap.java:452) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxGroupBy$UnicastGroupedFlux.subscribe(FluxGroupBy.java:721) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxRetry$RetrySubscriber.resubscribe(FluxRetry.java:117) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxRetry.subscribeOrReturn(FluxRetry.java:52) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.Flux.subscribe(Flux.java:8759) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:427) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxGroupBy$GroupByMain.drainLoop(FluxGroupBy.java:393) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxGroupBy$GroupByMain.drain(FluxGroupBy.java:329) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxGroupBy$GroupByMain.onNext(FluxGroupBy.java:207) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxArray$ArraySubscription.slowPath(FluxArray.java:127) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxArray$ArraySubscription.request(FluxArray.java:100) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxGroupBy$GroupByMain.onSubscribe(FluxGroupBy.java:171) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.core.publisher.Flux.subscribe(Flux.java:8773) ~[reactor-core-3.5.8.jar:3.5.8]\r\n\tat reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.toVerifierAndSubscribe(DefaultStepVerifierBuilder.java:891) ~[reactor-test-3.5.8.jar:3.5.8]\r\n\tat reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:831) ~[reactor-test-3.5.8.jar:3.5.8]\r\n\tat reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:823) ~[reactor-test-3.5.8.jar:3.5.8]\r\n\tat reactor.test.DefaultStepVerifierBuilder.verifyErrorSatisfies(DefaultStepVerifierBuilder.java:685) ~[reactor-test-3.5.8.jar:3.5.8]\r\n```\r\n## Steps to Reproduce\r\n```kotlin\r\n @Test\r\n fun flatMapExceptionTest() {\r\n StepVerifier.create(Flux.just(1, 2, 3, 4, 5, 6)\r\n .groupBy {\r\n it > 3\r\n }\r\n .flatMap {\r\n it.flatMap { Mono.error(Error(\"whoopsies\")) }.retry(2)\r\n }\r\n ).verifyErrorSatisfies {\r\n assertThat(it).hasMessage(\"whoopsies\")\r\n }\r\n }\r\n```\r\nThe actual error here (GroupedFlux allows only one Subscriber) is hidden by the NPE\r\n\r\n## Possible Solution\r\nNull check? Not sure if there is more behind it.\r\n\r\n## Your Environment\r\n* Reactor version(s) used: 3.5.8\r\n* JVM version (`java -version`): openjdk version \"11.0.17\" 2022-10-18 LTS\r\n* OS and version (eg `uname -a`): Linux S0155454 6.2.0-26-generic\r\n"},"base_sha":{"kind":"string","value":"b38936e387c31c36044f55448dce5033c580bc9c"},"head_sha":{"kind":"string","value":"91a201de9651a2242d4ec66cda310d9b18f125fc"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/b38936e387c31c36044f55448dce5033c580bc9c...91a201de9651a2242d4ec66cda310d9b18f125fc"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java b/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java\nindex 30cad47c3..08092c8e0 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java\n@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.\n+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.\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@@ -718,7 +718,7 @@ final class FluxGroupBy extends InternalFluxOperator> {\n \n+\t@Test\n+\t// see https://github.com/reactor/reactor-core/issues/3554\n+\tvoid flatMapExceptionTest() {\n+\t\tFlux.just(1, 2, 3, 4, 5, 6)\n+\t\t .groupBy(it -> it > 3)\n+\t\t .flatMap(it -> it.flatMap(__ -> Mono.error(new RuntimeException(\"whoopsies\"))).retry(2))\n+\t\t .as(StepVerifier::create)\n+\t\t .verifyErrorSatisfies(it -> assertThat(it).hasMessage(\"GroupedFlux allows only one Subscriber\"));\n+\t}\n+\n \t@Test\n \t@Tag(\"slow\")\n \t//see https://github.com/reactor/reactor-core/issues/2730"},"changed_files":{"kind":"string","value":"['reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.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":3812390,"string":"3,812,390"},"repo_tokens_count":{"kind":"number","value":951638,"string":"951,638"},"repo_lines_count":{"kind":"number","value":129701,"string":"129,701"},"repo_files_without_tests_count":{"kind":"number","value":464,"string":"464"},"changed_symbols_count":{"kind":"number","value":262,"string":"262"},"changed_tokens_count":{"kind":"number","value":59,"string":"59"},"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":3961,"string":"3,961"},"issue_words_count":{"kind":"number","value":222,"string":"222"},"issue_tokens_count":{"kind":"number","value":1214,"string":"1,214"},"issue_lines_count":{"kind":"number","value":61,"string":"61"},"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:28:11","string":"1970-01-01T00:28:11"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1383,"cells":{"id":{"kind":"number","value":1072,"string":"1,072"},"text_id":{"kind":"string","value":"reactor/reactor-core/2216/2196"},"repo_owner":{"kind":"string","value":"reactor"},"repo_name":{"kind":"string","value":"reactor-core"},"issue_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/issues/2196"},"pull_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/2216"},"comment_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/pull/2216"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fix"},"issue_title":{"kind":"string","value":"repeatWhenEmpty hangs on cancel when discard hook is present"},"issue_body":{"kind":"string","value":"## Expected Behavior\r\nIt should be safe to cancel the sequence.\r\n\r\n## Actual Behavior\r\nCancelling a sequence which is in a `repeatWhenEmpty()` loop will cause issues when a discard hook has been registered. In that case `Operators.onDiscardMultiple()` is invoked with the iterator used to keep track of the current iteration and the hook would be called for every remaining number up to `Long.MAX_VALUE`. \r\n\r\n## Steps to Reproduce\r\nThis test case will succeed when removing the `doOnDiscard()` operator.\r\n\r\n```java\r\n@Test\r\npublic void shouldCompleteEventually()\r\n{\r\n StepVerifier.create(Mono.empty()\r\n .repeatWhenEmpty(Repeat.once())\r\n .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release))\r\n .thenAwait()\r\n .thenCancel()\r\n .verify(Duration.ofSeconds(5));\r\n}\r\n```\r\n\r\n## Possible Solution\r\nProbably we should treat the remaining iterations in a way that they can be safely discarded without bothering any application level hooks. Also, I guess `FluxStream` should not be considered \"knownToBeFinite\" if its size is `Long.MAX_VALUE`.\r\n\r\n## Your Environment\r\n* Reactor version(s) used: 3.3.6.RELEASE\r\n"},"base_sha":{"kind":"string","value":"19d1c1c9808641b2d50922a3c9cc800fbc33d4c6"},"head_sha":{"kind":"string","value":"f6a5f5b920aec6a55b7887e252feb5aa112e4392"},"diff_url":{"kind":"string","value":"https://github.com/reactor/reactor-core/compare/19d1c1c9808641b2d50922a3c9cc800fbc33d4c6...f6a5f5b920aec6a55b7887e252feb5aa112e4392"},"diff":{"kind":"string","value":"diff --git a/reactor-core/src/main/java/reactor/core/publisher/Mono.java b/reactor-core/src/main/java/reactor/core/publisher/Mono.java\nindex 6cd3bd838..14e668db1 100644\n--- a/reactor-core/src/main/java/reactor/core/publisher/Mono.java\n+++ b/reactor-core/src/main/java/reactor/core/publisher/Mono.java\n@@ -27,6 +27,7 @@ import java.util.concurrent.CompletableFuture;\n import java.util.concurrent.CompletionStage;\n import java.util.concurrent.TimeUnit;\n import java.util.concurrent.TimeoutException;\n+import java.util.concurrent.atomic.AtomicLong;\n import java.util.function.BiConsumer;\n import java.util.function.BiFunction;\n import java.util.function.BiPredicate;\n@@ -133,9 +134,9 @@ public abstract class Mono implements Publisher {\n \t * }\n \t * }\n \t * };\n-\t * \n+\t *\n \t * client.addListener(listener);\n-\t * \n+\t *\n \t * sink.onDispose(() -&gt; client.removeListener(listener));\n \t * });\n \t * \n@@ -2675,7 +2676,7 @@ public abstract class Mono implements Publisher {\n \n \t/**\n \t * Hides the identity of this {@link Mono} instance.\n-\t * \n+\t *\n \t *

      The main purpose of this operator is to prevent certain identity-based\n \t * optimizations from happening, mostly for diagnostic purposes.\n \t *\n@@ -2684,7 +2685,7 @@ public abstract class Mono implements Publisher {\n \tpublic final Mono hide() {\n \t return onAssembly(new MonoHide<>(this));\n \t}\n-\t\n+\n \t/**\n \t * Ignores onNext signal (dropping it) and only propagates termination events.\n \t *\n@@ -3416,23 +3417,16 @@ public abstract class Mono implements Publisher {\n \t * as long as the companion {@link Publisher} produces an onNext signal and the maximum number of repeats isn't exceeded.\n \t */\n \tpublic final Mono repeatWhenEmpty(int maxRepeat, Function, ? extends Publisher> repeatFactory) {\n-\t\treturn Mono.defer(() -> {\n-\t\t\tFlux iterations;\n-\n-\t\t\tif(maxRepeat == Integer.MAX_VALUE) {\n-\t\t\t\titerations = Flux.fromStream(LongStream.range(0, Long.MAX_VALUE).boxed());\n+\t\treturn Mono.defer(() -> this.repeatWhen(o -> {\n+\t\t\tif (maxRepeat == Integer.MAX_VALUE) {\n+\t\t\t\treturn repeatFactory.apply(o.index().map(Tuple2::getT1));\n \t\t\t}\n \t\t\telse {\n-\t\t\t\titerations = Flux\n-\t\t\t\t\t.range(0, maxRepeat)\n-\t\t\t\t\t.map(Integer::longValue)\n-\t\t\t\t\t.concatWith(Flux.error(new IllegalStateException(\"Exceeded maximum number of repeats\"), true));\n+\t\t\t\treturn repeatFactory.apply(o.index().map(Tuple2::getT1)\n+\t\t\t\t\t\t.take(maxRepeat)\n+\t\t\t\t\t\t.concatWith(Flux.error(new IllegalStateException(\"Exceeded maximum number of repeats\"), true)));\n \t\t\t}\n-\n-\t\t\treturn this.repeatWhen(o -> repeatFactory.apply(o\n-\t\t\t\t\t\t.zipWith(iterations, 1, (c, i) -> i)))\n-\t\t\t .next();\n-\t\t});\n+\t\t}).next());\n \t}\n \n \ndiff --git a/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java b/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java\nindex 3bff20b94..e000821f5 100644\n--- a/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java\n+++ b/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java\n@@ -18,8 +18,10 @@ package reactor.core.publisher;\n \n import org.junit.Assert;\n import org.junit.Test;\n+import reactor.test.StepVerifier;\n import reactor.test.subscriber.AssertSubscriber;\n \n+import java.time.Duration;\n import java.util.ArrayList;\n import java.util.Arrays;\n import java.util.List;\n@@ -91,4 +93,13 @@ public class MonoRepeatWhenEmptyTest {\n Assert.assertEquals(Arrays.asList(0L, 1L), iterations);\n }\n \n+ @Test(timeout = 1000L)\n+ public void gh2196_discardHandlerHang() {\n+ StepVerifier.create(Mono.empty()\n+ .repeatWhenEmpty(f -> f.next())\n+ .doOnDiscard(Object.class, System.out::println))\n+ .thenAwait()\n+ .thenCancel()\n+ .verify();\n+ }\n }"},"changed_files":{"kind":"string","value":"['reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java', 'reactor-core/src/main/java/reactor/core/publisher/Mono.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":2953786,"string":"2,953,786"},"repo_tokens_count":{"kind":"number","value":734107,"string":"734,107"},"repo_lines_count":{"kind":"number","value":104103,"string":"104,103"},"repo_files_without_tests_count":{"kind":"number","value":385,"string":"385"},"changed_symbols_count":{"kind":"number","value":947,"string":"947"},"changed_tokens_count":{"kind":"number","value":237,"string":"237"},"changed_lines_count":{"kind":"number","value":30,"string":"30"},"changed_files_without_tests_count":{"kind":"number","value":1,"string":"1"},"issue_symbols_count":{"kind":"number","value":1209,"string":"1,209"},"issue_words_count":{"kind":"number","value":139,"string":"139"},"issue_tokens_count":{"kind":"number","value":252,"string":"252"},"issue_lines_count":{"kind":"number","value":28,"string":"28"},"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:32","string":"1970-01-01T00:26:32"},"repo_stars":{"kind":"number","value":4602,"string":"4,602"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 8928316, 'Kotlin': 48023}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1384,"cells":{"id":{"kind":"number","value":3322,"string":"3,322"},"text_id":{"kind":"string","value":"vespa-engine/vespa/14164/14153"},"repo_owner":{"kind":"string","value":"vespa-engine"},"repo_name":{"kind":"string","value":"vespa"},"issue_url":{"kind":"string","value":"https://github.com/vespa-engine/vespa/issues/14153"},"pull_url":{"kind":"string","value":"https://github.com/vespa-engine/vespa/pull/14164"},"comment_url":{"kind":"string","value":"https://github.com/vespa-engine/vespa/pull/14164"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"resolves"},"issue_title":{"kind":"string","value":"bm25 does not give any relevance score for fields defined outside the document"},"issue_body":{"kind":"string","value":"/search/?yql=select%20*%20from%20sources%20*%20where%20titlebest%20contains%20\"best\"%3B&ranking=titlebest \r\n=>\r\n`\"relevance\": 0,`\r\n\r\n/search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20\"best\"%3B&ranking=title\r\n=>\r\n`\"relevance\": 0.31872690041420326,`\r\n\r\n\r\nSchema:\r\n```\r\nschema music {\r\n document music {\r\n field title type string {\r\n indexing: summary | index\r\n index: enable-bm25\r\n }\r\n } \r\n field titlebest type string {\r\n stemming: best\r\n indexing: input title | summary | index\r\n index: enable-bm25\r\n }\r\n rank-profile title {\r\n first-phase {\r\n expression: bm25(title)\r\n }\r\n }\r\n rank-profile titlebest {`\r\n first-phase {\r\n expression: bm25(titlebest)\r\n }\r\n }\r\n}\r\n```"},"base_sha":{"kind":"string","value":"f454184d22c6c46d23710f7cfda988ee40efa641"},"head_sha":{"kind":"string","value":"5fa9bce02e30aa93cf986a3d946363df35a50cc0"},"diff_url":{"kind":"string","value":"https://github.com/vespa-engine/vespa/compare/f454184d22c6c46d23710f7cfda988ee40efa641...5fa9bce02e30aa93cf986a3d946363df35a50cc0"},"diff":{"kind":"string","value":"diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java\nindex 0ab8a2308a4..3a60a75f75f 100644\n--- a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java\n+++ b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java\n@@ -394,6 +394,9 @@ public class Search implements ImmutableSearch {\n if (current.isPrefix()) {\n consolidated.setPrefix(true);\n }\n+ if (current.useInterleavedFeatures()) {\n+ consolidated.setInterleavedFeatures(true);\n+ }\n \n if (consolidated.getRankType() == null) {\n consolidated.setRankType(current.getRankType());\ndiff --git a/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java b/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java\nindex f992d5ee0ba..1734c58ddc9 100644\n--- a/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java\n+++ b/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java\n@@ -8,7 +8,9 @@ import org.junit.Test;\n \n import java.io.IOException;\n \n+import static com.yahoo.config.model.test.TestUtil.joinLines;\n import static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertTrue;\n \n /**\n * Rank settings\n@@ -34,4 +36,27 @@ public class IndexSettingsTestCase extends SchemaTestCase {\n assertEquals(Stemming.MULTIPLE, multiStemmed.getStemming(search));\n }\n \n+ @Test\n+ public void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException {\n+ SearchBuilder builder = SearchBuilder.createFromString(joinLines(\n+ \"search test {\",\n+ \" document test {\",\n+ \" field content type string {\",\n+ \" indexing: index | summary\",\n+ \" index: enable-bm25\",\n+ \" }\",\n+ \" }\",\n+ \" field extra type string {\",\n+ \" indexing: input content | index | summary\",\n+ \" index: enable-bm25\",\n+ \" }\",\n+ \"}\"\n+ ));\n+ Search search = builder.getSearch();\n+ Index contentIndex = search.getIndex(\"content\");\n+ assertTrue(contentIndex.useInterleavedFeatures());\n+ Index extraIndex = search.getIndex(\"extra\");\n+ assertTrue(extraIndex.useInterleavedFeatures());\n+ }\n+\n }"},"changed_files":{"kind":"string","value":"['config-model/src/main/java/com/yahoo/searchdefinition/Search.java', 'config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.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":20798737,"string":"20,798,737"},"repo_tokens_count":{"kind":"number","value":4247905,"string":"4,247,905"},"repo_lines_count":{"kind":"number","value":549412,"string":"549,412"},"repo_files_without_tests_count":{"kind":"number","value":5592,"string":"5,592"},"changed_symbols_count":{"kind":"number","value":127,"string":"127"},"changed_tokens_count":{"kind":"number","value":22,"string":"22"},"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":748,"string":"748"},"issue_words_count":{"kind":"number","value":66,"string":"66"},"issue_tokens_count":{"kind":"number","value":222,"string":"222"},"issue_lines_count":{"kind":"number","value":35,"string":"35"},"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":4562,"string":"4,562"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 42949616, 'C++': 30143509, 'Go': 685517, 'CMake': 604483, 'Shell': 271272, 'JavaScript': 73336, 'Python': 56537, 'C': 54788, 'HTML': 54520, 'CSS': 40916, 'TLA': 36167, 'Perl': 23134, 'Roff': 17506, 'Yacc': 14735, 'Objective-C': 12547, 'Lex': 11499, 'Ruby': 10690, 'ANTLR': 7984, 'LLVM': 6152, 'Makefile': 5906, 'PigLatin': 5724, 'Raku': 3729, 'GAP': 3312, 'Kotlin': 1870, 'Emacs Lisp': 91}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1385,"cells":{"id":{"kind":"number","value":3812,"string":"3,812"},"text_id":{"kind":"string","value":"muzei/muzei/46/45"},"repo_owner":{"kind":"string","value":"muzei"},"repo_name":{"kind":"string","value":"muzei"},"issue_url":{"kind":"string","value":"https://github.com/muzei/muzei/issues/45"},"pull_url":{"kind":"string","value":"https://github.com/muzei/muzei/pull/46"},"comment_url":{"kind":"string","value":"https://github.com/muzei/muzei/pull/46"},"links_count":{"kind":"number","value":2,"string":"2"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Bad image URL crashes Muzei"},"issue_body":{"kind":"string","value":"I'm writing an extension, which pulls the image URLs from a web site. When the URL is formatted incorrectly, Muzei crashes. It should be made more error tolerant. Most of the time this shouldn't be a problem, but if the web site designer changes the site, the code retrieving the image URLs could be bad/incorrect until the extension can be updated. \n\nTo duplicate, publish artwork using a URI like \"www.example.com\".\n\nHere is the stack trace:\n03-06 22:48:08.053 20350-5944/? E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[TaskQueueService]\n Process: net.nurik.roman.muzei, PID: 20350\n java.lang.NullPointerException\n at com.google.android.apps.muzei.util.IOUtil.readFullyWriteToOutputStream(IOUtil.java:210)\n at com.google.android.apps.muzei.util.IOUtil.readFullyWriteToFile(IOUtil.java:202)\n at com.google.android.apps.muzei.ArtworkCache.maybeDownloadCurrentArtworkSync(ArtworkCache.java:122)\n at com.google.android.apps.muzei.TaskQueueService.onHandleIntent(TaskQueueService.java:56)\n at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)\n at android.os.Handler.dispatchMessage(Handler.java:102)\n at android.os.Looper.loop(Looper.java:136)\n at android.os.HandlerThread.run(HandlerThread.java:61)\n"},"base_sha":{"kind":"string","value":"a9d2ccfaeccabad26f9c6eba26355882654cc4c1"},"head_sha":{"kind":"string","value":"bb64b9572c3c66d656bd6301fc231cec083d1111"},"diff_url":{"kind":"string","value":"https://github.com/muzei/muzei/compare/a9d2ccfaeccabad26f9c6eba26355882654cc4c1...bb64b9572c3c66d656bd6301fc231cec083d1111"},"diff":{"kind":"string","value":"diff --git a/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java b/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java\nindex efffc15e..225ae342 100644\n--- a/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java\n+++ b/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java\n@@ -58,6 +58,10 @@ public class IOUtil {\n }\n \n String scheme = uri.getScheme();\n+ if (scheme == null) {\n+ throw new OpenUriException(false, new IOException(\"Uri had no scheme\"));\n+ }\n+\n InputStream in = null;\n if (\"content\".equals(scheme)) {\n try {\n@@ -118,7 +122,6 @@ public class IOUtil {\n \n } catch (MalformedURLException e) {\n throw new OpenUriException(false, e);\n-\n } catch (IOException e) {\n if (conn != null && responseCode > 0) {\n throw new OpenUriException("},"changed_files":{"kind":"string","value":"['main/src/main/java/com/google/android/apps/muzei/util/IOUtil.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":552584,"string":"552,584"},"repo_tokens_count":{"kind":"number","value":113670,"string":"113,670"},"repo_lines_count":{"kind":"number","value":14734,"string":"14,734"},"repo_files_without_tests_count":{"kind":"number","value":78,"string":"78"},"changed_symbols_count":{"kind":"number","value":131,"string":"131"},"changed_tokens_count":{"kind":"number","value":26,"string":"26"},"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":1328,"string":"1,328"},"issue_words_count":{"kind":"number","value":103,"string":"103"},"issue_tokens_count":{"kind":"number","value":311,"string":"311"},"issue_lines_count":{"kind":"number","value":17,"string":"17"},"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:23:14","string":"1970-01-01T00:23:14"},"repo_stars":{"kind":"number","value":4519,"string":"4,519"},"repo_language":{"kind":"string","value":"Kotlin"},"repo_languages":{"kind":"string","value":"{'Kotlin': 1044847, 'Python': 283216, 'Java': 116450, 'HTML': 36975, 'JavaScript': 32588, 'SCSS': 30501, 'CSS': 23867}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1386,"cells":{"id":{"kind":"number","value":1441,"string":"1,441"},"text_id":{"kind":"string","value":"geysermc/geyser/316/307"},"repo_owner":{"kind":"string","value":"geysermc"},"repo_name":{"kind":"string","value":"geyser"},"issue_url":{"kind":"string","value":"https://github.com/GeyserMC/Geyser/issues/307"},"pull_url":{"kind":"string","value":"https://github.com/GeyserMC/Geyser/pull/316"},"comment_url":{"kind":"string","value":"https://github.com/GeyserMC/Geyser/pull/316"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"closes"},"issue_title":{"kind":"string","value":"Xbox, Switch crashes when loading in a dimension that is not the overworld"},"issue_body":{"kind":"string","value":"\r\n\r\n\r\n\r\n**Describe the bug**\r\nXbox crashes when the player is joining into The Nether or The End.\r\n\r\n**To Reproduce**\r\nJoin Geyser on Xbox with your player loading into The End or The Nether.\r\n\r\n**Expected behavior**\r\nMinecraft does not crash.\r\n\r\n**Server Version**\r\nPaper 161\r\n\r\n**Geyser Version**\r\nMaster 25, Inventory 11\r\n\r\n**Minecraft: Bedrock Edition Version**\r\n1.14.30 Xbox\r\n"},"base_sha":{"kind":"string","value":"e5f08403357add9dc1d1800b9c117d3864ab7f83"},"head_sha":{"kind":"string","value":"f04a267d98c1edc03ab5af0e2d392992f4c78deb"},"diff_url":{"kind":"string","value":"https://github.com/geysermc/geyser/compare/e5f08403357add9dc1d1800b9c117d3864ab7f83...f04a267d98c1edc03ab5af0e2d392992f4c78deb"},"diff":{"kind":"string","value":"diff --git a/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java b/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java\nindex 6fffcda8..cf6c2ee2 100644\n--- a/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java\n+++ b/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java\n@@ -27,6 +27,7 @@ package org.geysermc.connector.network;\n \n import com.nukkitx.protocol.bedrock.BedrockPacket;\n import com.nukkitx.protocol.bedrock.packet.*;\n+import org.geysermc.common.AuthType;\n import org.geysermc.common.IGeyserConfiguration;\n import org.geysermc.connector.GeyserConnector;\n import org.geysermc.connector.network.session.GeyserSession;\n@@ -107,7 +108,7 @@ public class UpstreamPacketHandler extends LoggingPacketHandler {\n \n @Override\n public boolean handle(MovePlayerPacket packet) {\n- if (!session.isLoggedIn() && !session.isLoggingIn()) {\n+ if (!session.isLoggedIn() && !session.isLoggingIn() && session.getConnector().getAuthType() == AuthType.ONLINE) {\n // TODO it is safer to key authentication on something that won't change (UUID, not username)\n if (!couldLoginUserByName(session.getAuthData().getName())) {\n LoginEncryptionUtils.showLoginWindow(session);\ndiff --git a/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java b/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java\nindex 749dacb2..d5b2e75d 100644\n--- a/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java\n+++ b/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java\n@@ -149,15 +149,6 @@ public class GeyserSession implements CommandSender {\n public void connect(RemoteServer remoteServer) {\n startGame();\n this.remoteServer = remoteServer;\n- if (connector.getAuthType() != AuthType.ONLINE) {\n- connector.getLogger().info(\n- \"Attempting to login using \" + connector.getAuthType().name().toLowerCase() + \" mode... \" +\n- (connector.getAuthType() == AuthType.OFFLINE ?\n- \"authentication is disabled.\" : \"authentication will be encrypted\"\n- )\n- );\n- authenticate(authData.getName());\n- }\n \n ChunkUtils.sendEmptyChunks(this, playerEntity.getPosition().toInt(), 0, false);\n \n@@ -174,6 +165,18 @@ public class GeyserSession implements CommandSender {\n upstream.sendPacket(playStatusPacket);\n }\n \n+ public void login() {\n+ if (connector.getAuthType() != AuthType.ONLINE) {\n+ connector.getLogger().info(\n+ \"Attempting to login using \" + connector.getAuthType().name().toLowerCase() + \" mode... \" +\n+ (connector.getAuthType() == AuthType.OFFLINE ?\n+ \"authentication is disabled.\" : \"authentication will be encrypted\"\n+ )\n+ );\n+ authenticate(authData.getName());\n+ }\n+ }\n+\n public void authenticate(String username) {\n authenticate(username, \"\");\n }\n@@ -184,7 +187,7 @@ public class GeyserSession implements CommandSender {\n return;\n }\n \n- loggedIn = true;\n+ loggingIn = true;\n // new thread so clients don't timeout\n new Thread(() -> {\n try {\ndiff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java\nindex 54a5112d..87da2d00 100644\n--- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java\n+++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java\n@@ -40,6 +40,7 @@ public class BedrockSetLocalPlayerAsInitializedTranslator extends PacketTranslat\n if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) {\n if (!session.getUpstream().isInitialized()) {\n session.getUpstream().setInitialized(true);\n+ session.login();\n \n for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) {\n if (!entity.isValid()) {\ndiff --git a/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java\nindex 0d6caaed..34fe2271 100644\n--- a/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java\n+++ b/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java\n@@ -29,7 +29,6 @@ import org.geysermc.connector.entity.PlayerEntity;\n import org.geysermc.connector.network.session.GeyserSession;\n import org.geysermc.connector.network.translators.PacketTranslator;\n import org.geysermc.connector.network.translators.Translator;\n-import org.geysermc.connector.utils.ChunkUtils;\n import org.geysermc.connector.utils.DimensionUtils;\n \n import com.github.steveice10.mc.protocol.packet.ingame.server.ServerJoinGamePacket;\n@@ -69,7 +68,6 @@ public class JavaJoinGameTranslator extends PacketTranslator {\n@@ -50,14 +50,26 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator= 1) {\n+ bootstrap.getGeyserLogger().info(\"Kicking \" + players.size() + \" player(s)\");\n+\n+ for (GeyserSession playerSession : players.values()) {\n+ playerSession.disconnect(\"Geyser Proxy shutting down.\");\n+ }\n+\n+ CompletableFuture future = CompletableFuture.runAsync(new Runnable() {\n+ @Override\n+ public void run() {\n+ // Simulate a long-running Job\n+ try {\n+ while (true) {\n+ if (players.size() == 0) {\n+ return;\n+ }\n+\n+ TimeUnit.MILLISECONDS.sleep(100);\n+ }\n+ } catch (InterruptedException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ }\n+ });\n+\n+ // Block and wait for the future to complete\n+ try {\n+ future.get();\n+ bootstrap.getGeyserLogger().info(\"Kicked all players\");\n+ } catch (Exception e) {\n+ // Quietly fail\n+ }\n+ }\n+\n generalThreadPool.shutdown();\n bedrockServer.close();\n players.clear();\n@@ -149,6 +184,8 @@ public class GeyserConnector {\n authType = null;\n commandMap.getCommands().clear();\n commandMap = null;\n+\n+ bootstrap.getGeyserLogger().info(\"Geyser shutdown successfully.\");\n }\n \n public void addPlayer(GeyserSession player) {\ndiff --git a/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java b/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java\nindex 4694d0fd..2222cdef 100644\n--- a/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java\n+++ b/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java\n@@ -48,6 +48,11 @@ public class StopCommand extends GeyserCommand {\n if (!sender.isConsole() && connector.getPlatformType() == PlatformType.STANDALONE) {\n return;\n }\n+\n connector.shutdown();\n+\n+ if (connector.getPlatformType() == PlatformType.STANDALONE) {\n+ System.exit(0);\n+ }\n }\n }"},"changed_files":{"kind":"string","value":"['bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java', 'connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java', 'connector/src/main/java/org/geysermc/connector/GeyserConnector.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":738490,"string":"738,490"},"repo_tokens_count":{"kind":"number","value":160116,"string":"160,116"},"repo_lines_count":{"kind":"number","value":18755,"string":"18,755"},"repo_files_without_tests_count":{"kind":"number","value":230,"string":"230"},"changed_symbols_count":{"kind":"number","value":1594,"string":"1,594"},"changed_tokens_count":{"kind":"number","value":271,"string":"271"},"changed_lines_count":{"kind":"number","value":44,"string":"44"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":393,"string":"393"},"issue_words_count":{"kind":"number","value":57,"string":"57"},"issue_tokens_count":{"kind":"number","value":98,"string":"98"},"issue_lines_count":{"kind":"number","value":15,"string":"15"},"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:26","string":"1970-01-01T00:26:26"},"repo_stars":{"kind":"number","value":4071,"string":"4,071"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 3890490, 'Kotlin': 27417}"},"repo_license":{"kind":"string","value":"MIT License"}}},{"rowIdx":1392,"cells":{"id":{"kind":"number","value":248,"string":"248"},"text_id":{"kind":"string","value":"killbill/killbill/1289/1288"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/1288"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1289"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1289"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"NPE in /1.0/kb/invoices/:invoiceId/payments"},"issue_body":{"kind":"string","value":"Aborted `payment_attempts` can have a corresponding row in `invoice_payments` with a `NULL` `payment_id` (note that the `payment_cookie_id` i.e. the `payment_attempts. transaction_external_key` won't be `NULL` though):\r\n\r\n```\r\nMySQL [killbill]> select * from invoice_payments order by record_id desc limit 1\\\\G\r\n*************************** 1. row ***************************\r\n record_id: 3\r\n id: e7f6b1d0-3823-4c5b-9226-12327af64492\r\n type: ATTEMPT\r\n invoice_id: 742a1a60-58f8-4ed2-b9db-b1816a741f44\r\n payment_id: NULL\r\n payment_date: 2012-05-02 00:37:59\r\n amount: 0.000000000\r\n currency: USD\r\n processed_currency: USD\r\n payment_cookie_id: bac67833-ac7c-458d-8e2a-659c0cdfb0b6\r\nlinked_invoice_payment_id: NULL\r\n success: 0\r\n created_by: PaymentRequestProcessor\r\n created_date: 2012-05-02 00:37:59\r\n account_record_id: 1\r\n tenant_record_id: 0\r\n1 row in set (0.00 sec)\r\n```\r\n\r\nThis can trigger a NPE here: https://github.com/killbill/killbill/blob/1be24a4a144e80abcf45a5982deb7c1f2e22aa3b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java#L623\r\n\r\n```\r\njava.lang.NullPointerException: null\r\n at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:877)\r\n at com.google.common.collect.ImmutableSet$Builder.add(ImmutableSet.java:483)\r\n at com.google.common.collect.ImmutableSet.copyOf(ImmutableSet.java:248)\r\n at com.google.common.collect.ImmutableSet.copyOf(ImmutableSet.java:230)\r\n at org.killbill.billing.jaxrs.resources.InvoiceResource.getPaymentsForInvoice(InvoiceResource.java:620)\r\n```"},"base_sha":{"kind":"string","value":"1be24a4a144e80abcf45a5982deb7c1f2e22aa3b"},"head_sha":{"kind":"string","value":"35e7720d186913255dab22053598ebfed436a7c7"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/1be24a4a144e80abcf45a5982deb7c1f2e22aa3b...35e7720d186913255dab22053598ebfed436a7c7"},"diff":{"kind":"string","value":"diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java\nindex 6d1def04a1..b917d4a740 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java\n@@ -25,6 +25,7 @@ import java.net.URI;\n import java.util.ArrayList;\n import java.util.Comparator;\n import java.util.HashMap;\n+import java.util.HashSet;\n import java.util.List;\n import java.util.Locale;\n import java.util.Map;\n@@ -83,6 +84,7 @@ import org.killbill.billing.payment.api.InvoicePaymentApi;\n import org.killbill.billing.payment.api.Payment;\n import org.killbill.billing.payment.api.PaymentApi;\n import org.killbill.billing.payment.api.PaymentApiException;\n+import org.killbill.billing.payment.api.PaymentOptions;\n import org.killbill.billing.payment.api.PluginProperty;\n import org.killbill.billing.tenant.api.TenantApiException;\n import org.killbill.billing.tenant.api.TenantKV.TenantKey;\n@@ -110,7 +112,6 @@ import com.google.common.base.Function;\n import com.google.common.base.Preconditions;\n import com.google.common.collect.ImmutableList;\n import com.google.common.collect.ImmutableMap;\n-import com.google.common.collect.ImmutableSet;\n import com.google.common.collect.Iterables;\n import com.google.common.collect.Lists;\n import com.google.common.collect.Ordering;\n@@ -617,12 +618,12 @@ public class InvoiceResource extends JaxRsResourceBase {\n final Invoice invoice = invoiceApi.getInvoice(invoiceId, tenantContext);\n \n // Extract unique set of paymentId for this invoice\n- final Set invoicePaymentIds = ImmutableSet.copyOf(Iterables.transform(invoice.getPayments(), new Function() {\n- @Override\n- public UUID apply(final InvoicePayment input) {\n- return input.getPaymentId();\n+ final Set invoicePaymentIds = new HashSet();\n+ for (final InvoicePayment invoicePayment : invoice.getPayments()) {\n+ if (invoicePayment.getPaymentId() != null) {\n+ invoicePaymentIds.add(invoicePayment.getPaymentId());\n }\n- }));\n+ }\n if (invoicePaymentIds.isEmpty()) {\n return Response.status(Status.OK).entity(ImmutableList.of()).build();\n }\n@@ -655,6 +656,7 @@ public class InvoiceResource extends JaxRsResourceBase {\n public Response createInstantPayment(@PathParam(\"invoiceId\") final UUID invoiceId,\n final InvoicePaymentJson payment,\n @QueryParam(QUERY_PAYMENT_EXTERNAL) @DefaultValue(\"false\") final Boolean externalPayment,\n+ @QueryParam(QUERY_PAYMENT_CONTROL_PLUGIN_NAME) final List paymentControlPluginNames,\n @QueryParam(QUERY_PLUGIN_PROPERTY) final List pluginPropertiesString,\n @HeaderParam(HDR_CREATED_BY) final String createdBy,\n @HeaderParam(HDR_REASON) final String reason,\n@@ -672,8 +674,9 @@ public class InvoiceResource extends JaxRsResourceBase {\n final UUID paymentMethodId = externalPayment ? null :\n (payment.getPaymentMethodId() != null ? payment.getPaymentMethodId() : account.getPaymentMethodId());\n \n- final InvoicePayment result = createPurchaseForInvoice(account, invoiceId, payment.getPurchasedAmount(), paymentMethodId, externalPayment,\n- payment.getPaymentExternalKey(), null, pluginProperties, callContext);\n+ final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(externalPayment, paymentControlPluginNames);\n+ final InvoicePayment result = createPurchaseForInvoice(account, invoiceId, payment.getPurchasedAmount(), paymentMethodId,\n+ payment.getPaymentExternalKey(), null, pluginProperties, paymentOptions, callContext);\n return result != null ?\n uriBuilder.buildResponse(uriInfo, InvoicePaymentResource.class, \"getInvoicePayment\", result.getPaymentId(), request) :\n Response.status(Status.NO_CONTENT).build();\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java\nindex 2f61bd1b57..4726ddc8ad 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java\n@@ -22,7 +22,6 @@ import java.io.IOException;\n import java.io.OutputStream;\n import java.math.BigDecimal;\n import java.net.URI;\n-import java.util.ArrayList;\n import java.util.Arrays;\n import java.util.Collection;\n import java.util.Collections;\n@@ -553,7 +552,35 @@ public abstract class JaxRsResourceBase implements JaxrsResource {\n return properties;\n }\n \n- protected InvoicePayment createPurchaseForInvoice(final Account account, final UUID invoiceId, final BigDecimal amountToPay, final UUID paymentMethodId, final Boolean externalPayment, final String paymentExternalKey, final String transactionExternalKey, final Iterable pluginProperties, final CallContext callContext) throws PaymentApiException {\n+ protected InvoicePayment createPurchaseForInvoice(final Account account,\n+ final UUID invoiceId,\n+ final BigDecimal amountToPay,\n+ final UUID paymentMethodId,\n+ final Boolean externalPayment,\n+ final String paymentExternalKey,\n+ final String transactionExternalKey,\n+ final Iterable pluginProperties,\n+ final CallContext callContext) throws PaymentApiException {\n+ return createPurchaseForInvoice(account,\n+ invoiceId,\n+ amountToPay,\n+ paymentMethodId,\n+ paymentExternalKey,\n+ transactionExternalKey,\n+ pluginProperties,\n+ createInvoicePaymentControlPluginApiPaymentOptions(externalPayment),\n+ callContext);\n+ }\n+\n+ protected InvoicePayment createPurchaseForInvoice(final Account account,\n+ final UUID invoiceId,\n+ final BigDecimal amountToPay,\n+ final UUID paymentMethodId,\n+ final String paymentExternalKey,\n+ final String transactionExternalKey,\n+ final Iterable pluginProperties,\n+ final PaymentOptions paymentOptions,\n+ final CallContext callContext) throws PaymentApiException {\n try {\n return invoicePaymentApi.createPurchaseForInvoicePayment(account,\n invoiceId,\n@@ -564,7 +591,7 @@ public abstract class JaxRsResourceBase implements JaxrsResource {\n paymentExternalKey,\n transactionExternalKey,\n pluginProperties,\n- createInvoicePaymentControlPluginApiPaymentOptions(externalPayment),\n+ paymentOptions,\n callContext);\n } catch (final PaymentApiException e) {\n if (e.getCode() == ErrorCode.PAYMENT_PLUGIN_EXCEPTION.getCode() /* &&\ndiff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java\nindex 4e8856125a..a0facd3ff9 100644\n--- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java\n+++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java\n@@ -1,6 +1,6 @@\n /*\n- * Copyright 2014-2015 Groupon, Inc\n- * Copyright 2014-2015 The Billing Project, LLC\n+ * Copyright 2014-2020 Groupon, Inc\n+ * Copyright 2014-2020 The Billing Project, LLC\n *\n * The Billing Project licenses this file to you under the Apache License, version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n@@ -19,14 +19,12 @@ package org.killbill.billing.jaxrs;\n \n import java.math.BigDecimal;\n import java.util.Arrays;\n-import java.util.HashMap;\n import java.util.LinkedHashMap;\n import java.util.List;\n import java.util.Map;\n import java.util.UUID;\n \n import javax.annotation.Nullable;\n-import javax.ws.rs.HEAD;\n \n import org.joda.time.DateTime;\n import org.killbill.billing.ObjectType;\n@@ -38,6 +36,8 @@ import org.killbill.billing.client.model.Tags;\n import org.killbill.billing.client.model.gen.Account;\n import org.killbill.billing.client.model.gen.AuditLog;\n import org.killbill.billing.client.model.gen.ComboPaymentTransaction;\n+import org.killbill.billing.client.model.gen.Invoice;\n+import org.killbill.billing.client.model.gen.InvoicePayment;\n import org.killbill.billing.client.model.gen.Payment;\n import org.killbill.billing.client.model.gen.PaymentMethod;\n import org.killbill.billing.client.model.gen.PaymentMethodPluginDetail;\n@@ -219,6 +219,50 @@ public class TestPayment extends TestJaxrsBase {\n }\n }\n \n+ @Test(groups = \"slow\", description = \"https://github.com/killbill/killbill/issues/1288\")\n+ public void testWithAbortedInvoicePayment() throws Exception {\n+ mockPaymentProviderPlugin.makeNextPaymentFailWithError();\n+ final Account account = createAccountWithPMBundleAndSubscriptionAndWaitForFirstInvoice(false);\n+ // Getting Invoice #2 (first after Trial period)\n+ final Invoice failedInvoice = accountApi.getInvoicesForAccount(account.getAccountId(), null, null, RequestOptions.empty()).get(1);\n+\n+ // Verify initial state\n+ final Payments initialPayments = accountApi.getPaymentsForAccount(account.getAccountId(), true, false, ImmutableMap.of(), AuditLevel.NONE, requestOptions);\n+ Assert.assertEquals(initialPayments.size(), 1);\n+ Assert.assertEquals(initialPayments.get(0).getTransactions().size(), 1);\n+ Assert.assertEquals(initialPayments.get(0).getTransactions().get(0).getStatus(), TransactionStatus.PAYMENT_FAILURE);\n+ Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().size(), 2);\n+ Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().get(0).getStateName(), \"RETRIED\");\n+ Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().get(1).getStateName(), \"SCHEDULED\");\n+ final InvoicePayments initialInvoicePayments = invoiceApi.getPaymentsForInvoice(failedInvoice.getInvoiceId(), requestOptions);\n+ Assert.assertEquals(initialInvoicePayments.size(), 1);\n+ Assert.assertEquals(initialInvoicePayments.get(0).getPaymentId(), initialPayments.get(0).getPaymentId());\n+\n+ // Trigger manually an invoice payment but make the control plugin abort it\n+ mockPaymentControlProviderPlugin.setAborted(true);\n+ final HashMultimap queryParams = HashMultimap.create();\n+ queryParams.putAll(\"controlPluginName\", Arrays.asList(MockPaymentControlProviderPlugin.PLUGIN_NAME));\n+ final RequestOptions inputOptions = RequestOptions.builder()\n+ .withCreatedBy(createdBy)\n+ .withReason(reason)\n+ .withComment(comment)\n+ .withQueryParams(queryParams).build();\n+ final InvoicePayment invoicePayment = new InvoicePayment();\n+ invoicePayment.setPurchasedAmount(failedInvoice.getBalance());\n+ invoicePayment.setAccountId(failedInvoice.getAccountId());\n+ invoicePayment.setTargetInvoiceId(failedInvoice.getInvoiceId());\n+ final InvoicePayment invoicePaymentNull = invoiceApi.createInstantPayment(failedInvoice.getInvoiceId(), invoicePayment, true, null, inputOptions);\n+ Assert.assertNull(invoicePaymentNull);\n+\n+ // Verify new state\n+ final Payments updatedPayments = accountApi.getPaymentsForAccount(account.getAccountId(), true, false, ImmutableMap.of(), AuditLevel.NONE, requestOptions);\n+ Assert.assertEquals(updatedPayments.size(), 1);\n+ Assert.assertEquals(updatedPayments.get(0).getPaymentId(), initialPayments.get(0).getPaymentId());\n+ final InvoicePayments updatedInvoicePayments = invoiceApi.getPaymentsForInvoice(failedInvoice.getInvoiceId(), requestOptions);\n+ Assert.assertEquals(updatedInvoicePayments.size(), 1);\n+ Assert.assertEquals(updatedInvoicePayments.get(0).getPaymentId(), updatedPayments.get(0).getPaymentId());\n+ }\n+\n @Test(groups = \"slow\")\n public void testWithFailedPaymentAndScheduledAttemptsGetInvoicePayment() throws Exception {\n mockPaymentProviderPlugin.makeNextPaymentFailWithError();"},"changed_files":{"kind":"string","value":"['profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.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":6411254,"string":"6,411,254"},"repo_tokens_count":{"kind":"number","value":1198901,"string":"1,198,901"},"repo_lines_count":{"kind":"number","value":138507,"string":"138,507"},"repo_files_without_tests_count":{"kind":"number","value":1026,"string":"1,026"},"changed_symbols_count":{"kind":"number","value":4350,"string":"4,350"},"changed_tokens_count":{"kind":"number","value":551,"string":"551"},"changed_lines_count":{"kind":"number","value":52,"string":"52"},"changed_files_without_tests_count":{"kind":"number","value":2,"string":"2"},"issue_symbols_count":{"kind":"number","value":1747,"string":"1,747"},"issue_words_count":{"kind":"number","value":104,"string":"104"},"issue_tokens_count":{"kind":"number","value":470,"string":"470"},"issue_lines_count":{"kind":"number","value":34,"string":"34"},"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:26:25","string":"1970-01-01T00:26:25"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1393,"cells":{"id":{"kind":"number","value":247,"string":"247"},"text_id":{"kind":"string","value":"killbill/killbill/1371/1370"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/1370"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1371"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1371"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Sub-millisecond precision in catalog date can lead to duplicate invoice items"},"issue_body":{"kind":"string","value":"If the catalog effective date is set to `2020-09-16T10:34:25.348646Z` for instance, the DDL must support sub-millisecond precision (by default, it doesn't)."},"base_sha":{"kind":"string","value":"0b850e9bcf5b632c2422691d6f2c731d179f4f84"},"head_sha":{"kind":"string","value":"2796799bb8a7e73acfde0dfd1d318852ade8ca8d"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/0b850e9bcf5b632c2422691d6f2c731d179f4f84...2796799bb8a7e73acfde0dfd1d318852ade8ca8d"},"diff":{"kind":"string","value":"diff --git a/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java b/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java\nindex 398f49bb61..65c0cd69cb 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java\n@@ -25,6 +25,7 @@ import javax.annotation.Nullable;\n \n import org.joda.time.DateTime;\n import org.joda.time.LocalDate;\n+import org.joda.time.Seconds;\n import org.killbill.billing.catalog.api.Currency;\n import org.killbill.billing.invoice.api.InvoiceItem;\n import org.killbill.billing.invoice.api.InvoiceItemType;\n@@ -127,7 +128,11 @@ public class InvoiceItemCatalogBase extends InvoiceItemBase implements InvoiceIt\n return false;\n }\n final InvoiceItemCatalogBase that = (InvoiceItemCatalogBase) o;\n- if (catalogEffectiveDate != null && that.catalogEffectiveDate != null && catalogEffectiveDate.compareTo(that.catalogEffectiveDate) != 0) {\n+ if (catalogEffectiveDate != null &&\n+ that.catalogEffectiveDate != null &&\n+ catalogEffectiveDate.compareTo(that.catalogEffectiveDate) != 0 &&\n+ // https://github.com/killbill/killbill/issues/1370\n+ Math.abs(Seconds.secondsBetween(catalogEffectiveDate, that.catalogEffectiveDate).getSeconds()) != 0) {\n return false;\n } else if (catalogEffectiveDate == null || that.catalogEffectiveDate == null) {\n /* At least one such item has a 'null' catalogEffectiveDate, reflecting a prior 0.22 release item\ndiff --git a/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java b/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java\nindex 43e974cdd4..8c1bbd0698 100644\n--- a/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java\n+++ b/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java\n@@ -22,6 +22,7 @@ import java.math.BigDecimal;\n import java.util.List;\n import java.util.UUID;\n \n+import org.joda.time.DateTime;\n import org.joda.time.LocalDate;\n import org.killbill.billing.invoice.model.TaxInvoiceItem;\n import org.testng.Assert;\n@@ -243,6 +244,29 @@ public class TestInvoiceItemDao extends InvoiceTestSuiteWithEmbeddedDB {\n createAndVerifyExternalCharge(new BigDecimal(\"10.2\"), Currency.MGA);\n }\n \n+ @Test(groups = \"slow\", description = \"https://github.com/killbill/killbill/issues/1370\")\n+ public void testFixedPriceWithSubMillisecondCatalogEffectiveDateInvoiceSqlDao() throws EntityPersistenceException {\n+ final UUID invoiceId = UUID.randomUUID();\n+ final UUID accountId = account.getId();\n+ final LocalDate startDate = new LocalDate(2012, 4, 1);\n+\n+ final InvoiceItem fixedPriceInvoiceItem = new FixedPriceInvoiceItem(invoiceId,\n+ accountId,\n+ UUID.randomUUID(),\n+ UUID.randomUUID(),\n+ \"test product\",\n+ \"test plan\",\n+ \"test phase\",\n+ new DateTime(\"2020-09-16T10:34:25.348646Z\"),\n+ startDate,\n+ TEN,\n+ Currency.USD);\n+ invoiceUtil.createInvoiceItem(fixedPriceInvoiceItem, context);\n+\n+ final InvoiceItemModelDao savedItem = invoiceUtil.getInvoiceItemById(fixedPriceInvoiceItem.getId(), context);\n+ assertSameInvoiceItem(fixedPriceInvoiceItem, savedItem);\n+ }\n+\n private void createAndVerifyExternalCharge(final BigDecimal amount, final Currency currency) throws EntityPersistenceException {\n final InvoiceItem externalChargeInvoiceItem = new ExternalChargeInvoiceItem(UUID.randomUUID(), account.getId(), UUID.randomUUID(),\n UUID.randomUUID().toString(), new LocalDate(2012, 4, 1), new LocalDate(2012, 5, 1), amount, currency, null);"},"changed_files":{"kind":"string","value":"['invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.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":6434529,"string":"6,434,529"},"repo_tokens_count":{"kind":"number","value":1203210,"string":"1,203,210"},"repo_lines_count":{"kind":"number","value":139094,"string":"139,094"},"repo_files_without_tests_count":{"kind":"number","value":1027,"string":"1,027"},"changed_symbols_count":{"kind":"number","value":533,"string":"533"},"changed_tokens_count":{"kind":"number","value":113,"string":"113"},"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":156,"string":"156"},"issue_words_count":{"kind":"number","value":21,"string":"21"},"issue_tokens_count":{"kind":"number","value":46,"string":"46"},"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:26:42","string":"1970-01-01T00:26:42"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1394,"cells":{"id":{"kind":"number","value":246,"string":"246"},"text_id":{"kind":"string","value":"killbill/killbill/1427/1422"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/1422"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1427"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1427"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Search endpoint issue"},"issue_body":{"kind":"string","value":"```\r\nGET http://127.0.0.1:8080/1.0/kb/accounts/search/john?offset=0&limit=1&accountWithBalance=true&accountWithBalanceAndCBA=false\r\n```\r\n\r\nResults in:\r\n\r\n```\r\norg.glassfish.jersey.server.internal.process.MappableException: java.lang.IllegalArgumentException: The template variable 'searchKey' has no value\r\n```\r\n\r\nIt looks like we need to update `JaxrsUriBuilder` and pass the search key as such (instead of params):\r\n\r\n```\r\nuriBuilder.resolveTemplate(\"searchKey\", \"john\")\r\n```\r\n\r\nThis is likely a regression from https://github.com/killbill/killbill/issues/1384."},"base_sha":{"kind":"string","value":"535e3f5278786dae29bef6da40bd0ca1cff46426"},"head_sha":{"kind":"string","value":"d7661c8d75f73248928f0e2b1e5c542f428e4b1f"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/535e3f5278786dae29bef6da40bd0ca1cff46426...d7661c8d75f73248928f0e2b1e5c542f428e4b1f"},"diff":{"kind":"string","value":"diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java\nindex 0d414e234a..f86d400bf5 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java\n@@ -230,9 +230,14 @@ public class AccountResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination accounts = accountUserApi.getAccounts(offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, \"getAccounts\", accounts.getNextOffset(), limit, ImmutableMap.of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),\n- QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(AccountResource.class,\n+ \"getAccounts\",\n+ accounts.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),\n+ QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of());\n return buildStreamingPaginationResponse(accounts,\n new Function() {\n @Override\n@@ -260,10 +265,14 @@ public class AccountResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination accounts = accountUserApi.searchAccounts(searchKey, offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, \"searchAccounts\", accounts.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),\n- QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(AccountResource.class,\n+ \"searchAccounts\",\n+ accounts.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),\n+ QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of(\"searchKey\", searchKey));\n return buildStreamingPaginationResponse(accounts,\n new Function() {\n @Override\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java\nindex 3f7afc8d8c..ed30c1b7bf 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java\n@@ -313,6 +313,7 @@ public class AdminResource extends JaxRsResourceBase {\n \"triggerInvoiceGenerationForParkedAccounts\",\n tags.getNextOffset(),\n limit,\n+ ImmutableMap.of(),\n ImmutableMap.of());\n return Response.status(Status.OK)\n .entity(json)\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java\nindex ea2d0a1180..5a15ec0952 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java\n@@ -193,7 +193,7 @@ public class BundleResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination bundles = subscriptionApi.getSubscriptionBundles(offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, \"getBundles\", bundles.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, \"getBundles\", bundles.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of());\n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n return buildStreamingPaginationResponse(bundles,\n new Function() {\n@@ -228,8 +228,7 @@ public class BundleResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination bundles = subscriptionApi.searchSubscriptionBundles(searchKey, offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, \"searchBundles\", bundles.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(BundleResource.class,\"searchBundles\", bundles.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of(\"searchKey\", searchKey));\n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n return buildStreamingPaginationResponse(bundles,\n new Function() {\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java\nindex 271042051a..b273aa6091 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java\n@@ -98,7 +98,7 @@ public class CustomFieldResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination customFields = customFieldUserApi.getCustomFields(offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, \"getCustomFields\", customFields.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, \"getCustomFields\", customFields.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of());\n \n return buildStreamingPaginationResponse(customFields,\n new Function() {\n@@ -135,10 +135,15 @@ public class CustomFieldResource extends JaxRsResourceBase {\n customFieldUserApi.searchCustomFields(fieldName, fieldValue, ObjectType.valueOf(objectType), offset, limit, tenantContext) :\n customFieldUserApi.searchCustomFields(fieldName, ObjectType.valueOf(objectType), offset, limit, tenantContext);\n \n- final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, \"searchCustomFields\", customFields.getNextOffset(), limit, ImmutableMap.of(\"objectType\", objectType,\n- \"fieldName\", fieldName,\n- \"fieldValue\", MoreObjects.firstNonNull(fieldValue, \"\"),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class,\n+ \"searchCustomFields\",\n+ customFields.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(\"objectType\", objectType,\n+ \"fieldName\", fieldName,\n+ \"fieldValue\", MoreObjects.firstNonNull(fieldValue, \"\"),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of());\n return buildStreamingPaginationResponse(customFields,\n new Function() {\n @Override\n@@ -166,8 +171,7 @@ public class CustomFieldResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination customFields = customFieldUserApi.searchCustomFields(searchKey, offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, \"searchCustomFields\", customFields.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, \"searchCustomFields\", customFields.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of(\"searchKey\", searchKey));\n return buildStreamingPaginationResponse(customFields,\n new Function() {\n @Override\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java\nindex 451811c6f3..7053e9425b 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java\n@@ -270,7 +270,7 @@ public class InvoiceResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws InvoiceApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination invoices = invoiceApi.getInvoices(offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, \"getInvoices\", invoices.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, \"getInvoices\", invoices.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of());\n \n \n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n@@ -302,8 +302,7 @@ public class InvoiceResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination invoices = invoiceApi.searchInvoices(searchKey, offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, \"searchInvoices\", invoices.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, \"searchInvoices\", invoices.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of(\"searchKey\", searchKey));\n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n return buildStreamingPaginationResponse(invoices,\n new Function() {\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java\nindex 5402912ebe..605bc77310 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java\n@@ -168,8 +168,13 @@ public class PaymentMethodResource extends JaxRsResourceBase {\n paymentMethods = paymentApi.getPaymentMethods(offset, limit, pluginName, withPluginInfo, pluginProperties, tenantContext);\n }\n \n- final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, \"getPaymentMethods\", paymentMethods.getNextOffset(), limit, ImmutableMap.of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class,\n+ \"getPaymentMethods\",\n+ paymentMethods.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of());\n \n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n final Map accounts = new HashMap();\n@@ -226,9 +231,13 @@ public class PaymentMethodResource extends JaxRsResourceBase {\n paymentMethods = paymentApi.searchPaymentMethods(searchKey, offset, limit, pluginName, withPluginInfo, pluginProperties, tenantContext);\n }\n \n- final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, \"searchPaymentMethods\", paymentMethods.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class,\n+ \"searchPaymentMethods\",\n+ paymentMethods.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of(\"searchKey\", searchKey));\n \n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n final Map accounts = new HashMap();\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java\nindex bbe6e4aa62..99934df39e 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java\n@@ -178,8 +178,13 @@ public class PaymentResource extends ComboPaymentResource {\n payments = paymentApi.getPayments(offset, limit, pluginName, withPluginInfo, withAttempts, pluginProperties, tenantContext);\n }\n \n- final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, \"getPayments\", payments.getNextOffset(), limit, ImmutableMap.of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class,\n+ \"getPayments\",\n+ payments.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of());\n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n \n return buildStreamingPaginationResponse(payments,\n@@ -224,9 +229,13 @@ public class PaymentResource extends ComboPaymentResource {\n payments = paymentApi.searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, withAttempts, pluginProperties, tenantContext);\n }\n \n- final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, \"searchPayments\", payments.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class,\n+ \"searchPayments\",\n+ payments.getNextOffset(),\n+ limit,\n+ ImmutableMap.of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),\n+ QUERY_AUDIT, auditMode.getLevel().toString()),\n+ ImmutableMap.of(\"searchKey\", searchKey));\n final AtomicReference> accountsAuditLogs = new AtomicReference>(new HashMap());\n \n return buildStreamingPaginationResponse(payments,\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java\nindex 9762fb8c05..bb76391d56 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java\n@@ -98,7 +98,7 @@ public class TagResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination tags = tagUserApi.getTags(offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(TagResource.class, \"getTags\", tags.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(TagResource.class, \"getTags\", tags.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of());\n \n final Map tagDefinitionsCache = new HashMap();\n for (final TagDefinition tagDefinition : tagUserApi.getTagDefinitions(tenantContext)) {\n@@ -132,8 +132,7 @@ public class TagResource extends JaxRsResourceBase {\n @javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException {\n final TenantContext tenantContext = context.createTenantContextNoAccountId(request);\n final Pagination tags = tagUserApi.searchTags(searchKey, offset, limit, tenantContext);\n- final URI nextPageUri = uriBuilder.nextPage(TagResource.class, \"searchTags\", tags.getNextOffset(), limit, ImmutableMap.of(\"searchKey\", searchKey,\n- QUERY_AUDIT, auditMode.getLevel().toString()));\n+ final URI nextPageUri = uriBuilder.nextPage(TagResource.class, \"searchTags\", tags.getNextOffset(), limit, ImmutableMap.of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.of(\"searchKey\", searchKey));\n final Map tagDefinitionsCache = new HashMap();\n for (final TagDefinition tagDefinition : tagUserApi.getTagDefinitions(tenantContext)) {\n tagDefinitionsCache.put(tagDefinition.getId(), tagDefinition);\ndiff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java\nindex 6d9f9b666c..d57cb06701 100644\n--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java\n+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java\n@@ -117,7 +117,12 @@ public class JaxrsUriBuilder {\n return objectId != null ? uriBuilder.build(objectId) : uriBuilder.build();\n }\n \n- public URI nextPage(final Class theClass, final String getMethodName, final Long nextOffset, final Long limit, final Map params) {\n+ public URI nextPage(final Class theClass,\n+ final String getMethodName,\n+ final Long nextOffset,\n+ final Long limit,\n+ final Map queryParams,\n+ final Map pathParams) {\n if (nextOffset == null || limit == null) {\n // End of pagination?\n return null;\n@@ -125,8 +130,11 @@ public class JaxrsUriBuilder {\n \n final UriBuilder uriBuilder = getUriBuilder(theClass, getMethodName).queryParam(JaxRsResourceBase.QUERY_SEARCH_OFFSET, nextOffset)\n .queryParam(JaxRsResourceBase.QUERY_SEARCH_LIMIT, limit);\n- for (final String key : params.keySet()) {\n- uriBuilder.queryParam(key, params.get(key));\n+ for (final String key : queryParams.keySet()) {\n+ uriBuilder.queryParam(key, queryParams.get(key));\n+ }\n+ for (final String key : pathParams.keySet()) {\n+ uriBuilder.resolveTemplate(key, pathParams.get(key));\n }\n return uriBuilder.build();\n }\ndiff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java\nindex d6bbd1b5d6..46dc3cc8bb 100644\n--- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java\n+++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java\n@@ -118,13 +118,27 @@ public class TestAccount extends TestJaxrsBase {\n public void testAccountOk() throws Exception {\n final Account input = createAccount();\n \n+ // Create a second account (https://github.com/killbill/killbill/issues/1422 regression testing)\n+ final Account secondAccount = createAccount();\n+ final Account retrievedSecondAccount = accountApi.getAccountByKey(secondAccount.getExternalKey(), requestOptions);\n+ Assert.assertEquals(secondAccount, retrievedSecondAccount);\n+\n // Retrieves by external key\n final Account retrievedAccount = accountApi.getAccountByKey(input.getExternalKey(), requestOptions);\n- Assert.assertTrue(retrievedAccount.equals(input));\n+ Assert.assertEquals(input, retrievedAccount);\n \n // Try search endpoint\n searchAccount(input, retrievedAccount);\n \n+ // Force limit=1 (https://github.com/killbill/killbill/issues/1422 regression testing)\n+ final Accounts allAccounts = accountApi.searchAccounts(input.getCompany(), 0L, 1L, false, false, AuditLevel.NONE, requestOptions);\n+ // Company name is the same for both accounts\n+ Assert.assertEquals(allAccounts.size(), 1);\n+ Assert.assertEquals(allAccounts.get(0).getExternalKey(), retrievedAccount.getExternalKey());\n+ final Accounts secondPage = allAccounts.getNext();\n+ Assert.assertEquals(secondPage.size(), 1);\n+ Assert.assertEquals(secondPage.get(0).getExternalKey(), retrievedSecondAccount.getExternalKey());\n+\n // Update Account\n final Account newInput = new Account(input.getAccountId(),\n \"zozo\", 4, input.getExternalKey(), \"rr@google.com\", 18,\n@@ -445,9 +459,6 @@ public class TestAccount extends TestJaxrsBase {\n // Search by email\n doSearchAccount(input.getEmail(), output);\n \n- // Search by company name\n- doSearchAccount(input.getCompany(), output);\n-\n // Search by external key.\n // Note: we will always find a match since we don't update it\n final List accountsByExternalKey = accountApi.searchAccounts(input.getExternalKey(), requestOptions);"},"changed_files":{"kind":"string","value":"['jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java', 'profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.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":6492754,"string":"6,492,754"},"repo_tokens_count":{"kind":"number","value":1215206,"string":"1,215,206"},"repo_lines_count":{"kind":"number","value":140489,"string":"140,489"},"repo_files_without_tests_count":{"kind":"number","value":1042,"string":"1,042"},"changed_symbols_count":{"kind":"number","value":15066,"string":"15,066"},"changed_tokens_count":{"kind":"number","value":2117,"string":"2,117"},"changed_lines_count":{"kind":"number","value":109,"string":"109"},"changed_files_without_tests_count":{"kind":"number","value":9,"string":"9"},"issue_symbols_count":{"kind":"number","value":563,"string":"563"},"issue_words_count":{"kind":"number","value":46,"string":"46"},"issue_tokens_count":{"kind":"number","value":148,"string":"148"},"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":3,"string":"3"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:26:58","string":"1970-01-01T00:26:58"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1395,"cells":{"id":{"kind":"number","value":245,"string":"245"},"text_id":{"kind":"string","value":"killbill/killbill/1530/1528"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/1528"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1530"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1530#discussion_r751898548"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"close"},"issue_title":{"kind":"string","value":"Pending subscription shows a `PENDING` state after being canceled"},"issue_body":{"kind":"string","value":"Scenario:\r\n1. Create a subscription with an future start (billing) date -> `PENDING` state\r\n2. Cancel the subscription immediately -> This will default to the future start date\r\n3. Fetch the subscription and check the state -> `CANCELLED` state\r\n\r\nIt seems that in step 3. `state` is incorrectly showing `PENDING`"},"base_sha":{"kind":"string","value":"2b80b0445c7baf1f613425bb236a8cb36f1f377a"},"head_sha":{"kind":"string","value":"9890c11b6b4cdcdb5c3196f890fa672cb250da44"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/2b80b0445c7baf1f613425bb236a8cb36f1f377a...9890c11b6b4cdcdb5c3196f890fa672cb250da44"},"diff":{"kind":"string","value":"diff --git a/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java b/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java\nindex 1a9e0cfa83..157269856b 100644\n--- a/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java\n+++ b/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java\n@@ -184,6 +184,7 @@ public class DefaultSubscriptionBase extends EntityBase implements SubscriptionB\n throw new IllegalStateException(\"Should return a valid EntitlementState\");\n }\n \n+\n @Override\n public EntitlementSourceType getSourceType() {\n if (transitions == null) {\ndiff --git a/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java b/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java\nindex aa74d92dc7..3d7680b140 100644\n--- a/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java\n+++ b/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java\n@@ -509,17 +509,22 @@ public class TestUserApiCancel extends SubscriptionTestSuiteWithEmbeddedDB {\n assertEquals(subscription.getStartDate().compareTo(startDate.toDateTime(accountData.getReferenceTime())), 0);\n \n subscription.cancelWithPolicy(BillingActionPolicy.IMMEDIATE, callContext);\n+ \n+ final DefaultSubscriptionBase subscription2 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);\n+ assertEquals(subscription2.getStartDate().compareTo(subscription.getStartDate()), 0);\n+ assertEquals(subscription2.getState(), Entitlement.EntitlementState.PENDING);\n \n testListener.pushExpectedEvents(NextEvent.CREATE, NextEvent.CANCEL);\n clock.addDays(5);\n assertListenerStatus();\n \n- final DefaultSubscriptionBase subscription2 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);\n- assertEquals(subscription2.getStartDate().compareTo(subscription.getStartDate()), 0);\n- assertEquals(subscription2.getState(), Entitlement.EntitlementState.CANCELLED);\n- assertNull(subscription2.getCurrentPlan());\n+ final DefaultSubscriptionBase subscription3 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);\n+ assertEquals(subscription3.getStartDate().compareTo(subscription.getStartDate()), 0);\n+ assertEquals(subscription3.getState(), Entitlement.EntitlementState.CANCELLED);\n+ assertNull(subscription3.getCurrentPlan());\n }\n-\n+ \n+ \n \n @Test(groups = \"slow\", description=\"See https://github.com/killbill/killbill/issues/1207\")\n public void testDoubleFutureLaterCancellation() throws SubscriptionBaseApiException {"},"changed_files":{"kind":"string","value":"['subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java', 'subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.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":6580195,"string":"6,580,195"},"repo_tokens_count":{"kind":"number","value":1232435,"string":"1,232,435"},"repo_lines_count":{"kind":"number","value":142320,"string":"142,320"},"repo_files_without_tests_count":{"kind":"number","value":1051,"string":"1,051"},"changed_symbols_count":{"kind":"number","value":1,"string":"1"},"changed_tokens_count":{"kind":"number","value":1,"string":"1"},"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":313,"string":"313"},"issue_words_count":{"kind":"number","value":50,"string":"50"},"issue_tokens_count":{"kind":"number","value":72,"string":"72"},"issue_lines_count":{"kind":"number","value":6,"string":"6"},"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:17","string":"1970-01-01T00:27:17"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1396,"cells":{"id":{"kind":"number","value":251,"string":"251"},"text_id":{"kind":"string","value":"killbill/killbill/1075/1074"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/1074"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1075"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1075"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Wrong computed invoice target date for non-UTC TZ"},"issue_body":{"kind":"string","value":"See [mailing-list thread](https://groups.google.com/forum/#!msg/killbilling-users/ChJ7DeOQCzk/BQzCL5E0BAAJ)."},"base_sha":{"kind":"string","value":"938aa3e7d3c8c980cfa3b9416927ca7ae69e2dd9"},"head_sha":{"kind":"string","value":"b6860e565acc632e859e67ab72721f9a06d7aef1"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/938aa3e7d3c8c980cfa3b9416927ca7ae69e2dd9...b6860e565acc632e859e67ab72721f9a06d7aef1"},"diff":{"kind":"string","value":"diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java\nindex a7140c378f..0e8cd1a603 100644\n--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java\n+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java\n@@ -426,15 +426,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen\n return (DefaultSubscriptionBase) sub;\n }\n \n- protected Account createAccountWithOsgiPaymentMethod(final AccountData accountData) throws Exception {\n- return createAccountWithPaymentMethod(accountData, BeatrixIntegrationModule.OSGI_PLUGIN_NAME);\n- }\n-\n protected Account createAccountWithNonOsgiPaymentMethod(final AccountData accountData) throws Exception {\n- return createAccountWithPaymentMethod(accountData, BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME);\n- }\n-\n- private Account createAccountWithPaymentMethod(final AccountData accountData, final String paymentPluginName) throws Exception {\n final Account account = accountUserApi.createAccount(accountData, callContext);\n assertNotNull(account);\n \n@@ -442,7 +434,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen\n \n final PaymentMethodPlugin info = createPaymentMethodPlugin();\n \n- paymentApi.addPaymentMethod(account, UUID.randomUUID().toString(), paymentPluginName, true, info, PLUGIN_PROPERTIES, callContext);\n+ paymentApi.addPaymentMethod(account, UUID.randomUUID().toString(), BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME, true, info, PLUGIN_PROPERTIES, callContext);\n return accountUserApi.getAccountById(account.getId(), callContext);\n }\n \n@@ -451,6 +443,10 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen\n }\n \n protected AccountData getAccountData(@Nullable final Integer billingDay) {\n+ return getAccountData(billingDay, DateTimeZone.UTC);\n+ }\n+\n+ protected AccountData getAccountData(@Nullable final Integer billingDay, final DateTimeZone tz) {\n final MockAccountBuilder builder = new MockAccountBuilder()\n .name(UUID.randomUUID().toString().substring(1, 8))\n .firstNameLength(6)\n@@ -460,7 +456,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen\n .externalKey(UUID.randomUUID().toString().substring(1, 8))\n .currency(Currency.USD)\n .referenceTime(clock.getUTCNow())\n- .timeZone(DateTimeZone.UTC);\n+ .timeZone(tz);\n if (billingDay != null) {\n builder.billingCycleDayLocal(billingDay);\n }\ndiff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java\nindex 3d5c66a248..455173d6ee 100644\n--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java\n+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java\n@@ -1,7 +1,7 @@\n /*\n * Copyright 2010-2013 Ning, Inc.\n- * Copyright 2014-2016 Groupon, Inc\n- * Copyright 2014-2016 The Billing Project, LLC\n+ * Copyright 2014-2018 Groupon, Inc\n+ * Copyright 2014-2018 The Billing Project, LLC\n *\n * The Billing Project licenses this file to you under the Apache License, version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n@@ -20,9 +20,10 @@ package org.killbill.billing.beatrix.integration;\n \n import java.util.Collection;\n import java.util.List;\n-import java.util.UUID;\n \n import org.joda.time.DateTime;\n+import org.joda.time.DateTimeZone;\n+import org.joda.time.LocalDate;\n import org.killbill.billing.ObjectType;\n import org.killbill.billing.account.api.Account;\n import org.killbill.billing.api.TestApiListener.NextEvent;\n@@ -30,13 +31,8 @@ import org.killbill.billing.catalog.api.BillingPeriod;\n import org.killbill.billing.catalog.api.ProductCategory;\n import org.killbill.billing.entitlement.api.DefaultEntitlement;\n import org.killbill.billing.invoice.api.Invoice;\n-import org.killbill.billing.invoice.api.InvoiceStatus;\n import org.killbill.billing.invoice.api.InvoiceUserApi;\n-import org.killbill.billing.util.api.TagApiException;\n-import org.killbill.billing.util.api.TagDefinitionApiException;\n import org.killbill.billing.util.api.TagUserApi;\n-import org.killbill.billing.util.tag.ControlTagType;\n-import org.killbill.billing.util.tag.Tag;\n import org.testng.annotations.BeforeMethod;\n import org.testng.annotations.Test;\n \n@@ -102,4 +98,47 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {\n assertEquals(invoices.size(), 1);\n }\n \n+ @Test(groups = \"slow\", description = \"https://github.com/killbill/killbill/issues/1074\")\n+ public void testAutoInvoiceOffWithTZ() throws Exception {\n+ clock.setTime(new DateTime(2018, 12, 1, 0, 25, 0, 0));\n+\n+ account = createAccountWithNonOsgiPaymentMethod(getAccountData(null, DateTimeZone.forID(\"America/Los_Angeles\")));\n+ assertEquals(account.getBillCycleDayLocal(), (Integer) 0);\n+\n+ final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), \"externalKey\", productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);\n+ assertNotNull(bpEntitlement);\n+ assertEquals(accountUserApi.getAccountById(account.getId(), callContext).getBillCycleDayLocal(), (Integer) 30);\n+\n+ List invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);\n+ assertEquals(invoices.size(), 1);\n+ assertEquals(invoices.get(0).getInvoiceItems().size(), 1);\n+ assertEquals(invoices.get(0).getTargetDate(), new LocalDate(2018, 11, 30));\n+ assertEquals(invoices.get(0).getInvoiceItems().get(0).getStartDate(), new LocalDate(2018, 11, 30));\n+\n+ clock.setTime(new DateTime(2018, 12, 30, 0, 20, 0, 0));\n+ assertEquals(clock.getUTCToday(), new LocalDate(2018, 12, 30));\n+ assertEquals(clock.getUTCNow().toDateTime(account.getTimeZone()).toLocalDate(), new LocalDate(2018, 12, 29));\n+ // Still in trial\n+ assertListenerStatus();\n+ assertEquals(entitlementApi.getEntitlementForId(bpEntitlement.getId(), callContext).getLastActivePhase().getName(), \"shotgun-monthly-trial\");\n+ assertEquals(invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext).size(), 1);\n+\n+ // Adding / Removing AUTO_INVOICING_OFF shouldn't have any impact\n+ add_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT);\n+ remove_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.NULL_INVOICE);\n+\n+ assertListenerStatus();\n+ assertEquals(entitlementApi.getEntitlementForId(bpEntitlement.getId(), callContext).getLastActivePhase().getName(), \"shotgun-monthly-trial\");\n+ assertEquals(invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext).size(), 1);\n+\n+ busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);\n+ clock.setTime(new DateTime(2018, 12, 31, 0, 25, 0, 0));\n+ assertListenerStatus();\n+\n+ invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);\n+ assertEquals(invoices.size(), 2);\n+ assertEquals(invoices.get(1).getTargetDate(), new LocalDate(2018, 12, 30));\n+ assertEquals(invoices.get(1).getInvoiceItems().get(0).getStartDate(), new LocalDate(2018, 12, 30));\n+ assertEquals(invoices.get(1).getInvoiceItems().get(0).getEndDate(), new LocalDate(2019, 1, 30));\n+ }\n }\ndiff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java\nindex f901875e05..4715f25131 100644\n--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java\n+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java\n@@ -1,7 +1,7 @@\n /*\n * Copyright 2010-2013 Ning, Inc.\n- * Copyright 2014-2017 Groupon, Inc\n- * Copyright 2014-2017 The Billing Project, LLC\n+ * Copyright 2014-2018 Groupon, Inc\n+ * Copyright 2014-2018 The Billing Project, LLC\n *\n * The Billing Project licenses this file to you under the Apache License, version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n@@ -22,21 +22,15 @@ import java.math.BigDecimal;\n import java.util.Collection;\n \n import org.joda.time.DateTime;\n-import org.testng.annotations.BeforeMethod;\n-import org.testng.annotations.Test;\n-\n import org.killbill.billing.ObjectType;\n import org.killbill.billing.account.api.Account;\n import org.killbill.billing.api.TestApiListener.NextEvent;\n import org.killbill.billing.catalog.api.BillingPeriod;\n-import org.killbill.billing.catalog.api.PriceListSet;\n import org.killbill.billing.catalog.api.ProductCategory;\n import org.killbill.billing.entitlement.api.DefaultEntitlement;\n import org.killbill.billing.invoice.api.Invoice;\n-import org.killbill.billing.subscription.api.user.SubscriptionBaseBundle;\n-import org.killbill.billing.util.config.definition.PaymentConfig;\n-\n-import com.google.inject.Inject;\n+import org.testng.annotations.BeforeMethod;\n+import org.testng.annotations.Test;\n \n import static org.testng.Assert.assertEquals;\n import static org.testng.Assert.assertNotNull;\n@@ -45,10 +39,8 @@ import static org.testng.Assert.assertTrue;\n public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {\n \n private Account account;\n- private SubscriptionBaseBundle bundle;\n private String productName;\n private BillingPeriod term;\n- private String planSetName;\n \n @Override\n @BeforeMethod(groups = \"slow\")\n@@ -62,7 +54,6 @@ public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {\n assertNotNull(account);\n productName = \"Shotgun\";\n term = BillingPeriod.MONTHLY;\n- planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;\n }\n \n @Test(groups = \"slow\")\n@@ -242,7 +233,6 @@ public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {\n \n }\n \n-\n private void addDelayBceauseOfLackOfCorrectSynchro() {\n // TODO When removing the tag, the payment system will schedule retries for payments that are in non terminal state\n // The issue is that at this point we know the event went on the bus but we don't know if the listener in payment completed\ndiff --git a/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java b/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java\nindex 767cd30d00..2bc350b107 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java\n@@ -326,7 +326,7 @@ public class InvoiceDispatcher {\n LocalDate inputTargetDate = inputTargetDateMaybeNull;\n // A null inputTargetDate is only allowed in UPCOMING_INVOICE dryRun mode to have the system compute it\n if (inputTargetDate == null && !upcomingInvoiceDryRun) {\n- inputTargetDate = clock.getUTCToday();\n+ inputTargetDate = context.toLocalDate(clock.getUTCNow());\n }\n Preconditions.checkArgument(inputTargetDate != null || upcomingInvoiceDryRun, \"inputTargetDate is required in non dryRun mode\");\n "},"changed_files":{"kind":"string","value":"['beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java', 'invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java', 'beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java', 'beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.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":6223188,"string":"6,223,188"},"repo_tokens_count":{"kind":"number","value":1167835,"string":"1,167,835"},"repo_lines_count":{"kind":"number","value":135115,"string":"135,115"},"repo_files_without_tests_count":{"kind":"number","value":1018,"string":"1,018"},"changed_symbols_count":{"kind":"number","value":122,"string":"122"},"changed_tokens_count":{"kind":"number","value":25,"string":"25"},"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":108,"string":"108"},"issue_words_count":{"kind":"number","value":3,"string":"3"},"issue_tokens_count":{"kind":"number","value":39,"string":"39"},"issue_lines_count":{"kind":"number","value":1,"string":"1"},"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:44","string":"1970-01-01T00:25:44"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1397,"cells":{"id":{"kind":"number","value":257,"string":"257"},"text_id":{"kind":"string","value":"killbill/killbill/405/118"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/118"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/405"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/405"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixed"},"issue_title":{"kind":"string","value":"Invoice formatter display wrong currency symbol"},"issue_body":{"kind":"string","value":"First of all, the code is using the locale to set the currency formatter. For instance in \nDefaultInvoiceFormatter:\n\n```\n public String getFormattedPaidAmount() {\n final NumberFormat number = NumberFormat.getCurrencyInstance(locale);\n return number.format(getPaidAmount().doubleValue());\n }\n```\n\nThe number format returned is based on the locale which is 'good' so it knows how to display the dots, comma, ... but wrong it comes to display the currency symbol.\n"},"base_sha":{"kind":"string","value":"2eda0f052c5c04c53b18bf249c02ba489881349b"},"head_sha":{"kind":"string","value":"43afb0759795e3ffdf748925e592b65738e00f25"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/2eda0f052c5c04c53b18bf249c02ba489881349b...43afb0759795e3ffdf748925e592b65738e00f25"},"diff":{"kind":"string","value":"diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java\nindex 8ae278acfc..a3fed268b4 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java\n@@ -17,24 +17,22 @@\n package org.killbill.billing.invoice.template.formatters;\n \n import java.math.BigDecimal;\n-import java.text.NumberFormat;\n+import java.text.DecimalFormat;\n+import java.text.DecimalFormatSymbols;\n import java.util.ArrayList;\n import java.util.Collection;\n import java.util.Iterator;\n import java.util.List;\n import java.util.Locale;\n+import java.util.Map;\n import java.util.UUID;\n \n+import org.joda.money.CurrencyUnit;\n import org.joda.time.DateTime;\n import org.joda.time.LocalDate;\n import org.joda.time.format.DateTimeFormat;\n import org.joda.time.format.DateTimeFormatter;\n import org.killbill.billing.callcontext.InternalTenantContext;\n-import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory;\n-import org.killbill.billing.tenant.api.TenantInternalApi;\n-import org.slf4j.Logger;\n-import org.slf4j.LoggerFactory;\n-\n import org.killbill.billing.catalog.api.Currency;\n import org.killbill.billing.currency.api.CurrencyConversion;\n import org.killbill.billing.currency.api.CurrencyConversionApi;\n@@ -45,17 +43,18 @@ import org.killbill.billing.invoice.api.InvoiceItem;\n import org.killbill.billing.invoice.api.InvoiceItemType;\n import org.killbill.billing.invoice.api.InvoicePayment;\n import org.killbill.billing.invoice.api.formatters.InvoiceFormatter;\n+import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory;\n import org.killbill.billing.invoice.model.CreditAdjInvoiceItem;\n import org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem;\n import org.killbill.billing.invoice.model.DefaultInvoice;\n import org.killbill.billing.util.template.translation.TranslatorConfig;\n+import org.slf4j.Logger;\n+import org.slf4j.LoggerFactory;\n \n import com.google.common.base.Objects;\n import com.google.common.base.Strings;\n import com.google.common.collect.ImmutableList;\n \n-import static org.killbill.billing.util.DefaultAmountFormatter.round;\n-\n /**\n * Format invoice fields\n */\n@@ -70,8 +69,11 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {\n private final CurrencyConversionApi currencyConversionApi;\n private final InternalTenantContext context;\n private final ResourceBundleFactory bundleFactory;\n+ private Map currencyLocaleMap;\n \n- public DefaultInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, final CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory, final InternalTenantContext context) {\n+ public DefaultInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale,\n+ final CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory,\n+ final InternalTenantContext context, Map currencyLocaleMap) {\n this.config = config;\n this.invoice = invoice;\n this.dateFormatter = DateTimeFormat.mediumDate().withLocale(locale);\n@@ -79,6 +81,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {\n this.currencyConversionApi = currencyConversionApi;\n this.bundleFactory = bundleFactory;\n this.context = context;\n+ this.currencyLocaleMap = currencyLocaleMap;\n }\n \n @Override\n@@ -198,35 +201,56 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {\n \n @Override\n public BigDecimal getChargedAmount() {\n- return round(Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO);\n }\n \n @Override\n public BigDecimal getOriginalChargedAmount() {\n- return round(Objects.firstNonNull(invoice.getOriginalChargedAmount(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(invoice.getOriginalChargedAmount(), BigDecimal.ZERO);\n }\n \n @Override\n public BigDecimal getBalance() {\n- return round(Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO);\n }\n \n @Override\n public String getFormattedChargedAmount() {\n- final NumberFormat number = NumberFormat.getCurrencyInstance(locale);\n- return number.format(getChargedAmount().doubleValue());\n+ return getFormattedAmountByLocaleAndInvoiceCurrency(getChargedAmount());\n }\n \n @Override\n public String getFormattedPaidAmount() {\n- final NumberFormat number = NumberFormat.getCurrencyInstance(locale);\n- return number.format(getPaidAmount().doubleValue());\n+ return getFormattedAmountByLocaleAndInvoiceCurrency(getPaidAmount());\n }\n \n @Override\n public String getFormattedBalance() {\n- final NumberFormat number = NumberFormat.getCurrencyInstance(locale);\n- return number.format(getBalance().doubleValue());\n+ return getFormattedAmountByLocaleAndInvoiceCurrency(getBalance());\n+ }\n+\n+ // Returns the formatted amount with the correct currency symbol that is get from the invoice currency.\n+ private String getFormattedAmountByLocaleAndInvoiceCurrency(BigDecimal amount) {\n+\n+ String invoiceCurrencyCode = invoice.getCurrency().toString();\n+ CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode);\n+\n+ final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);\n+ DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols();\n+ dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode());\n+\n+ try {\n+ final java.util.Currency currency = java.util.Currency.getInstance(invoiceCurrencyCode);\n+ dfs.setCurrencySymbol(currency.getSymbol(currencyLocaleMap.get(currency)));\n+ } catch (Exception e) {\n+ dfs.setCurrencySymbol(currencyUnit.getSymbol(locale));\n+ }\n+\n+ numberFormatter.setDecimalFormatSymbols(dfs);\n+ numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits());\n+ numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits());\n+\n+ return numberFormatter.format(amount.doubleValue());\n }\n \n @Override\n@@ -288,7 +312,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {\n \n @Override\n public BigDecimal getPaidAmount() {\n- return round(Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO);\n }\n \n @Override\n@@ -337,13 +361,18 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {\n return invoice;\n }\n \n+ @SuppressWarnings(\"UnusedDeclaration\")\n+ protected Map getCurrencyLocaleMap() {\n+ return currencyLocaleMap;\n+ }\n+\n @Override\n public BigDecimal getCreditedAmount() {\n- return round(Objects.firstNonNull(invoice.getCreditedAmount(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(invoice.getCreditedAmount(), BigDecimal.ZERO);\n }\n \n @Override\n public BigDecimal getRefundedAmount() {\n- return round(Objects.firstNonNull(invoice.getRefundedAmount(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(invoice.getRefundedAmount(), BigDecimal.ZERO);\n }\n }\ndiff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java\nindex 890fb30338..6496df73f5 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java\n@@ -16,7 +16,10 @@\n \n package org.killbill.billing.invoice.template.formatters;\n \n+import java.util.Currency;\n+import java.util.HashMap;\n import java.util.Locale;\n+import java.util.Map;\n \n import org.killbill.billing.callcontext.InternalTenantContext;\n import org.killbill.billing.currency.api.CurrencyConversionApi;\n@@ -24,7 +27,6 @@ import org.killbill.billing.invoice.api.Invoice;\n import org.killbill.billing.invoice.api.formatters.InvoiceFormatter;\n import org.killbill.billing.invoice.api.formatters.InvoiceFormatterFactory;\n import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory;\n-import org.killbill.billing.tenant.api.TenantInternalApi;\n import org.killbill.billing.util.template.translation.TranslatorConfig;\n \n public class DefaultInvoiceFormatterFactory implements InvoiceFormatterFactory {\n@@ -32,6 +34,17 @@ public class DefaultInvoiceFormatterFactory implements InvoiceFormatterFactory {\n @Override\n public InvoiceFormatter createInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, CurrencyConversionApi currencyConversionApi,\n final ResourceBundleFactory bundleFactory, final InternalTenantContext context) {\n- return new DefaultInvoiceFormatter(config, invoice, locale, currencyConversionApi, bundleFactory, context);\n+\n+ // this initialization relies on System.currentTimeMillis() instead of the Kill Bill clock (it won't be accurate when moving the clock)\n+ Map currencyLocaleMap = new HashMap();\n+ for (Locale localeItem : Locale.getAvailableLocales()) {\n+ try {\n+ java.util.Currency currency = java.util.Currency.getInstance(localeItem);\n+ currencyLocaleMap.put(currency, localeItem);\n+ }catch (Exception e){\n+ }\n+ }\n+\n+ return new DefaultInvoiceFormatter(config, invoice, locale, currencyConversionApi, bundleFactory, context, currencyLocaleMap);\n }\n }\ndiff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java\nindex 51ddcc637a..5516c8ca90 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java\n@@ -36,14 +36,10 @@ import org.killbill.billing.util.LocaleUtils;\n import org.killbill.billing.util.template.translation.DefaultCatalogTranslator;\n import org.killbill.billing.util.template.translation.Translator;\n import org.killbill.billing.util.template.translation.TranslatorConfig;\n-import org.slf4j.Logger;\n-import org.slf4j.LoggerFactory;\n \n import com.google.common.base.Objects;\n import com.google.common.base.Strings;\n \n-import static org.killbill.billing.util.DefaultAmountFormatter.round;\n-\n /**\n * Format invoice item fields\n */\n@@ -71,7 +67,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {\n \n @Override\n public BigDecimal getAmount() {\n- return round(Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO));\n+ return Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO);\n }\n \n @Override\n@@ -168,7 +164,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {\n \n @Override\n public BigDecimal getRate() {\n- return round(BigDecimal.ZERO);\n+ return BigDecimal.ZERO;\n }\n \n @Override\ndiff --git a/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java b/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java\nindex df0a9d7a08..6d5cc0afb0 100644\n--- a/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java\n+++ b/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java\n@@ -34,7 +34,6 @@ import org.killbill.billing.invoice.api.InvoiceItem;\n import org.killbill.billing.invoice.api.InvoiceItemType;\n import org.killbill.billing.invoice.api.InvoicePaymentType;\n import org.killbill.billing.invoice.api.formatters.InvoiceFormatter;\n-import org.killbill.billing.invoice.api.formatters.InvoiceFormatterFactory;\n import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory.ResourceBundleType;\n import org.killbill.billing.invoice.model.CreditAdjInvoiceItem;\n import org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem;\n@@ -89,7 +88,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {\n Assert.assertEquals(invoice.getCreditedAmount().doubleValue(), 0.00);\n \n // Verify the merge\n- final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext);\n+ final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext, getAvailableLocales());\n final List invoiceItems = formatter.getInvoiceItems();\n Assert.assertEquals(invoiceItems.size(), 1);\n Assert.assertEquals(invoiceItems.get(0).getInvoiceItemType(), InvoiceItemType.FIXED);\n@@ -143,7 +142,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {\n Assert.assertEquals(invoice.getRefundedAmount().doubleValue(), -1.00);\n \n // Verify the merge\n- final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext);\n+ final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext, getAvailableLocales());\n final List invoiceItems = formatter.getInvoiceItems();\n Assert.assertEquals(invoiceItems.size(), 4);\n Assert.assertEquals(invoiceItems.get(0).getInvoiceItemType(), InvoiceItemType.FIXED);\n@@ -160,7 +159,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {\n public void testFormattedAmount() throws Exception {\n final FixedPriceInvoiceItem fixedItemEUR = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,\n UUID.randomUUID().toString(), UUID.randomUUID().toString(),\n- new LocalDate(), new BigDecimal(\"1499.95\"), Currency.EUR);\n+ new LocalDate(), new BigDecimal(\"1499.952\"), Currency.EUR);\n final Invoice invoiceEUR = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.EUR);\n invoiceEUR.addInvoiceItem(fixedItemEUR);\n \n@@ -186,6 +185,158 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {\n Locale.FRANCE);\n }\n \n+ @Test(groups = \"fast\")\n+ public void testFormattedAmountFranceAndJPY() throws Exception {\n+\n+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,\n+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),\n+ new LocalDate(), new BigDecimal(\"1500.00\"), Currency.JPY);\n+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.JPY);\n+ invoice.addInvoiceItem(fixedItem);\n+\n+ checkOutput(invoice,\n+ \"\\\\n\" +\n+ \" {{invoice.formattedChargedAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedPaidAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedBalance}}\\\\n\" +\n+ \"\",\n+ \"\\\\n\" +\n+ \" 1 500 ¥\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" 0 ¥\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" 1 500 ¥\\\\n\" +\n+ \"\",\n+ Locale.FRANCE);\n+ }\n+\n+ @Test(groups = \"fast\")\n+ public void testFormattedAmountUSAndBTC() throws Exception {\n+\n+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,\n+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),\n+ new LocalDate(), new BigDecimal(\"1105.28843439\"), Currency.BTC);\n+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.BTC);\n+ invoice.addInvoiceItem(fixedItem);\n+\n+ checkOutput(invoice,\n+ \"\\\\n\" +\n+ \" {{invoice.formattedChargedAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedPaidAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedBalance}}\\\\n\" +\n+ \"\",\n+ \"\\\\n\" +\n+ \" BTC1,105.28843439\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" BTC0.00000000\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" BTC1,105.28843439\\\\n\" +\n+ \"\",\n+ Locale.US);\n+ }\n+\n+ @Test(groups = \"fast\")\n+ public void testFormattedAmountUSAndEUR() throws Exception {\n+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,\n+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),\n+ new LocalDate(), new BigDecimal(\"2635.14\"), Currency.EUR);\n+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.EUR);\n+ invoice.addInvoiceItem(fixedItem);\n+\n+ checkOutput(invoice,\n+ \"\\\\n\" +\n+ \" {{invoice.formattedChargedAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedPaidAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedBalance}}\\\\n\" +\n+ \"\",\n+ \"\\\\n\" +\n+ \" €2,635.14\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" €0.00\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" €2,635.14\\\\n\" +\n+ \"\",\n+ Locale.US);\n+ }\n+\n+ @Test(groups = \"fast\")\n+ public void testFormattedAmountUSAndBRL() throws Exception {\n+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,\n+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),\n+ new LocalDate(), new BigDecimal(\"2635.14\"), Currency.BRL);\n+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.BRL);\n+ invoice.addInvoiceItem(fixedItem);\n+\n+ checkOutput(invoice,\n+ \"\\\\n\" +\n+ \" {{invoice.formattedChargedAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedPaidAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedBalance}}\\\\n\" +\n+ \"\",\n+ \"\\\\n\" +\n+ \" R$2,635.14\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" R$0.00\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" R$2,635.14\\\\n\" +\n+ \"\",\n+ Locale.US);\n+ }\n+\n+ @Test(groups = \"fast\")\n+ public void testFormattedAmountUSAndGBP() throws Exception {\n+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,\n+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),\n+ new LocalDate(), new BigDecimal(\"1499.95\"), Currency.GBP);\n+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.GBP);\n+ invoice.addInvoiceItem(fixedItem);\n+\n+ checkOutput(invoice,\n+ \"\\\\n\" +\n+ \" {{invoice.formattedChargedAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedPaidAmount}}\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" {{invoice.formattedBalance}}\\\\n\" +\n+ \"\",\n+ \"\\\\n\" +\n+ \" £1,499.95\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" £0.00\\\\n\" +\n+ \"\\\\n\" +\n+ \"\\\\n\" +\n+ \" £1,499.95\\\\n\" +\n+ \"\",\n+ Locale.US);\n+ }\n+\n @Test(groups = \"fast\")\n public void testProcessedCurrencyExists() throws Exception {\n final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), clock.getUTCNow(), UUID.randomUUID(), new Integer(234), new LocalDate(), new LocalDate(), Currency.BRL, Currency.USD, false);\n@@ -329,7 +480,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {\n \n data.put(\"text\", translator);\n \n- data.put(\"invoice\", new DefaultInvoiceFormatter(config, invoice, Locale.US, currencyConversionApi, resourceBundleFactory, internalCallContext));\n+ data.put(\"invoice\", new DefaultInvoiceFormatter(config, invoice, Locale.US, currencyConversionApi, resourceBundleFactory, internalCallContext, getAvailableLocales()));\n \n final String formattedText = templateEngine.executeTemplateText(template, data);\n \n@@ -338,9 +489,23 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {\n \n private void checkOutput(final Invoice invoice, final String template, final String expected, final Locale locale) {\n final Map data = new HashMap();\n- data.put(\"invoice\", new DefaultInvoiceFormatter(config, invoice, locale, null, resourceBundleFactory, internalCallContext));\n+ data.put(\"invoice\", new DefaultInvoiceFormatter(config, invoice, locale, null, resourceBundleFactory, internalCallContext, getAvailableLocales()));\n \n final String formattedText = templateEngine.executeTemplateText(template, data);\n Assert.assertEquals(formattedText, expected);\n }\n+\n+ private Map getAvailableLocales() {\n+ Map currencyLocaleMap = new HashMap();\n+\n+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.US), Locale.US);\n+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.FRANCE), Locale.FRANCE);\n+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.JAPAN), Locale.JAPAN);\n+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.UK), Locale.UK);\n+ Locale brLocale = new Locale(\"pt\", \"BR\");\n+ currencyLocaleMap.put(java.util.Currency.getInstance(brLocale), brLocale);\n+\n+ return currencyLocaleMap;\n+ }\n+\n }"},"changed_files":{"kind":"string","value":"['invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java', 'invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java', 'invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java', 'invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.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":4510922,"string":"4,510,922"},"repo_tokens_count":{"kind":"number","value":859544,"string":"859,544"},"repo_lines_count":{"kind":"number","value":101923,"string":"101,923"},"repo_files_without_tests_count":{"kind":"number","value":872,"string":"872"},"changed_symbols_count":{"kind":"number","value":5674,"string":"5,674"},"changed_tokens_count":{"kind":"number","value":993,"string":"993"},"changed_lines_count":{"kind":"number","value":96,"string":"96"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":475,"string":"475"},"issue_words_count":{"kind":"number","value":63,"string":"63"},"issue_tokens_count":{"kind":"number","value":96,"string":"96"},"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":1,"string":"1"},"pull_create_at":{"kind":"timestamp","value":"1970-01-01T00:24:04","string":"1970-01-01T00:24:04"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1398,"cells":{"id":{"kind":"number","value":253,"string":"253"},"text_id":{"kind":"string","value":"killbill/killbill/1016/1015"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/1015"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1016"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/1016"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"Possible double payments with invoice payments in UNKNOWN state"},"issue_body":{"kind":"string","value":"Scenario:\r\n\r\n1. Invoice payment in `UNKNOWN` state\r\n2. Trigger a new successful payment by calling `invoicePaymentApi.createPurchaseForInvoicePayment`\r\n3. Fix the original payment (`UNKNOWN -> SUCCESS`)\r\n\r\nResult: the invoice ends up double payed and the invoice balance is negative (absolute value is the amount of the payment).\r\n"},"base_sha":{"kind":"string","value":"08ffcbbd2cf366a9f26603248384fab50722da14"},"head_sha":{"kind":"string","value":"29a6f930250b640dd511002a6a60597509e24a10"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/08ffcbbd2cf366a9f26603248384fab50722da14...29a6f930250b640dd511002a6a60597509e24a10"},"diff":{"kind":"string","value":"diff --git a/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java b/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java\nindex ffe6ad5e9a..e6534c81d5 100644\n--- a/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java\n+++ b/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java\n@@ -84,5 +84,7 @@ public interface InvoiceInternalApi {\n \n public List getInvoicePaymentsByAccount(UUID accountId, TenantContext context);\n \n+ public List getInvoicePaymentsByInvoice(UUID invoiceId, InternalTenantContext context);\n+\n public InvoicePayment getInvoicePaymentByCookieId(String cookieId, TenantContext context);\n }\ndiff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java\nindex b00c5e308a..4eca162eba 100644\n--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java\n+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java\n@@ -1095,4 +1095,139 @@ public class TestInvoicePayment extends TestIntegrationBase {\n Assert.assertEquals(payments.get(0).getTransactions().size(), 1);\n \n }\n+\n+ @Test(groups = \"slow\")\n+ public void testWithUNKNOWNPaymentFixedToSuccess() throws Exception {\n+ // Verify integration with Overdue in that particular test\n+ final String configXml = \"\" +\n+ \" \" +\n+ \" \" +\n+ \" DAYS1\" +\n+ \" \" +\n+ \" \" +\n+ \" \" +\n+ \" \" +\n+ \" DAYS1\" +\n+ \" \" +\n+ \" \" +\n+ \" Reached OD1\" +\n+ \" true\" +\n+ \" false\" +\n+ \" \" +\n+ \" \" +\n+ \"\";\n+ final InputStream is = new ByteArrayInputStream(configXml.getBytes());\n+ final DefaultOverdueConfig config = XMLLoader.getObjectFromStreamNoValidation(is, DefaultOverdueConfig.class);\n+ overdueConfigCache.loadDefaultOverdueConfig(config);\n+\n+ clock.setDay(new LocalDate(2012, 4, 1));\n+\n+ final AccountData accountData = getAccountData(1);\n+ final Account account = createAccountWithNonOsgiPaymentMethod(accountData);\n+ accountChecker.checkAccount(account.getId(), accountData, callContext);\n+\n+ checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId());\n+\n+ paymentPlugin.makeNextPaymentUnknown();\n+\n+ final DefaultEntitlement baseEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), \"bundleKey\", \"Shotgun\", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);\n+\n+ addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_PLUGIN_ERROR, NextEvent.INVOICE_PAYMENT_ERROR);\n+\n+ invoiceChecker.checkChargedThroughDate(baseEntitlement.getId(), new LocalDate(2012, 6, 1), callContext);\n+\n+ final List invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);\n+ assertEquals(invoices.size(), 2);\n+\n+ final Invoice invoice1 = invoices.get(0).getInvoiceItems().get(0).getInvoiceItemType() == InvoiceItemType.RECURRING ?\n+ invoices.get(0) : invoices.get(1);\n+ assertTrue(invoice1.getBalance().compareTo(new BigDecimal(\"249.95\")) == 0);\n+ assertTrue(invoice1.getPaidAmount().compareTo(BigDecimal.ZERO) == 0);\n+ assertTrue(invoice1.getChargedAmount().compareTo(new BigDecimal(\"249.95\")) == 0);\n+ assertEquals(invoice1.getPayments().size(), 1);\n+ assertEquals(invoice1.getPayments().get(0).getAmount().compareTo(BigDecimal.ZERO), 0);\n+ assertEquals(invoice1.getPayments().get(0).getCurrency(), Currency.USD);\n+ assertFalse(invoice1.getPayments().get(0).isSuccess());\n+ assertNotNull(invoice1.getPayments().get(0).getPaymentId());\n+\n+ final BigDecimal accountBalance1 = invoiceUserApi.getAccountBalance(account.getId(), callContext);\n+ assertTrue(accountBalance1.compareTo(new BigDecimal(\"249.95\")) == 0);\n+\n+ final List payments = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.of(), callContext);\n+ assertEquals(payments.size(), 1);\n+ assertEquals(payments.get(0).getPurchasedAmount().compareTo(BigDecimal.ZERO), 0);\n+ assertEquals(payments.get(0).getTransactions().size(), 1);\n+ assertEquals(payments.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal(\"249.95\")), 0);\n+ assertEquals(payments.get(0).getTransactions().get(0).getCurrency(), Currency.USD);\n+ assertEquals(payments.get(0).getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0);\n+ assertEquals(payments.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD);\n+ assertEquals(payments.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.UNKNOWN);\n+ assertEquals(payments.get(0).getPaymentAttempts().size(), 1);\n+ assertEquals(payments.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);\n+ assertEquals(payments.get(0).getPaymentAttempts().get(0).getStateName(), \"ABORTED\");\n+\n+ // Verify account transitions to OD1\n+ addDaysAndCheckForCompletion(2, NextEvent.BLOCK);\n+ checkODState(\"OD1\", account.getId());\n+\n+ // Verify we cannot trigger double payments\n+ try {\n+ invoicePaymentApi.createPurchaseForInvoicePayment(account,\n+ invoice1.getId(),\n+ payments.get(0).getPaymentMethodId(),\n+ null,\n+ invoice1.getBalance(),\n+ invoice1.getCurrency(),\n+ clock.getUTCNow(),\n+ null,\n+ null,\n+ ImmutableList.of(),\n+ PAYMENT_OPTIONS,\n+ callContext);\n+ Assert.fail();\n+ } catch (final PaymentApiException e) {\n+ Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode());\n+ assertListenerStatus();\n+ }\n+\n+ // Transition the payment to success\n+ final PaymentTransaction existingPaymentTransaction = payments.get(0).getTransactions().get(0);\n+ final PaymentTransaction updatedPaymentTransaction = Mockito.mock(PaymentTransaction.class);\n+ Mockito.when(updatedPaymentTransaction.getId()).thenReturn(existingPaymentTransaction.getId());\n+ Mockito.when(updatedPaymentTransaction.getExternalKey()).thenReturn(existingPaymentTransaction.getExternalKey());\n+ Mockito.when(updatedPaymentTransaction.getTransactionType()).thenReturn(existingPaymentTransaction.getTransactionType());\n+ Mockito.when(updatedPaymentTransaction.getProcessedAmount()).thenReturn(new BigDecimal(\"249.95\"));\n+ Mockito.when(updatedPaymentTransaction.getProcessedCurrency()).thenReturn(existingPaymentTransaction.getCurrency());\n+ busHandler.pushExpectedEvents(NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT, NextEvent.BLOCK);\n+ adminPaymentApi.fixPaymentTransactionState(payments.get(0), updatedPaymentTransaction, TransactionStatus.SUCCESS, null, null, ImmutableList.of(), callContext);\n+ assertListenerStatus();\n+\n+ checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId());\n+\n+ final Invoice invoice2 = invoiceUserApi.getInvoice(invoice1.getId(), callContext);\n+ assertTrue(invoice2.getBalance().compareTo(BigDecimal.ZERO) == 0);\n+ assertTrue(invoice2.getPaidAmount().compareTo(new BigDecimal(\"249.95\")) == 0);\n+ assertTrue(invoice2.getChargedAmount().compareTo(new BigDecimal(\"249.95\")) == 0);\n+ assertEquals(invoice2.getPayments().size(), 1);\n+ assertEquals(invoice2.getPayments().get(0).getAmount().compareTo(new BigDecimal(\"249.95\")), 0);\n+ assertEquals(invoice2.getPayments().get(0).getCurrency(), Currency.USD);\n+ assertTrue(invoice2.getPayments().get(0).isSuccess());\n+ assertNotNull(invoice2.getPayments().get(0).getPaymentId());\n+\n+ final BigDecimal accountBalance2 = invoiceUserApi.getAccountBalance(account.getId(), callContext);\n+ assertTrue(accountBalance2.compareTo(BigDecimal.ZERO) == 0);\n+\n+ final List payments2 = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.of(), callContext);\n+ assertEquals(payments2.size(), 1);\n+ assertEquals(payments2.get(0).getPurchasedAmount().compareTo(new BigDecimal(\"249.95\")), 0);\n+ assertEquals(payments2.get(0).getTransactions().size(), 1);\n+ assertEquals(payments2.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal(\"249.95\")), 0);\n+ assertEquals(payments2.get(0).getTransactions().get(0).getCurrency(), Currency.USD);\n+ assertEquals(payments2.get(0).getTransactions().get(0).getProcessedAmount().compareTo(new BigDecimal(\"249.95\")), 0);\n+ assertEquals(payments2.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD);\n+ assertEquals(payments2.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS);\n+ assertEquals(payments2.get(0).getPaymentAttempts().size(), 1);\n+ assertEquals(payments2.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);\n+ assertEquals(payments2.get(0).getPaymentAttempts().get(0).getStateName(), \"SUCCESS\");\n+ }\n }\ndiff --git a/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java b/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java\nindex 0f2cba226c..1b9e082849 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java\n@@ -217,6 +217,18 @@ public class DefaultInvoiceInternalApi implements InvoiceInternalApi {\n ));\n }\n \n+ @Override\n+ public List getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) {\n+ return ImmutableList.copyOf(Collections2.transform(dao.getInvoicePaymentsByInvoice(invoiceId, context),\n+ new Function() {\n+ @Override\n+ public InvoicePayment apply(final InvoicePaymentModelDao input) {\n+ return new DefaultInvoicePayment(input);\n+ }\n+ }\n+ ));\n+ }\n+\n @Override\n public InvoicePayment getInvoicePaymentByCookieId(final String cookieId, final TenantContext context) {\n final InvoicePaymentModelDao invoicePaymentModelDao = dao.getInvoicePaymentByCookieId(cookieId, internalCallContextFactory.createInternalTenantContext(context.getAccountId(), ObjectType.ACCOUNT, context));\ndiff --git a/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java b/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java\nindex 963e6c9cf4..cc48631f72 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java\n@@ -559,6 +559,16 @@ public class DefaultInvoiceDao extends EntityDaoBase getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) {\n+ return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper>() {\n+ @Override\n+ public List inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {\n+ return entitySqlDaoWrapperFactory.become(InvoicePaymentSqlDao.class).getAllPaymentsForInvoiceIncludedInit(invoiceId.toString(), context);\n+ }\n+ });\n+ }\n+\n @Override\n public InvoicePaymentModelDao getInvoicePaymentByCookieId(final String cookieId, final InternalTenantContext context) {\n return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper() {\ndiff --git a/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java b/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java\nindex 8d4f871c8b..e7c77901b5 100644\n--- a/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java\n+++ b/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java\n@@ -66,6 +66,8 @@ public interface InvoiceDao extends EntityDao getInvoicePaymentsByAccount(InternalTenantContext context);\n \n+ List getInvoicePaymentsByInvoice(final UUID invoiceId, InternalTenantContext context);\n+\n InvoicePaymentModelDao getInvoicePaymentByCookieId(String cookieId, InternalTenantContext internalTenantContext);\n \n BigDecimal getAccountBalance(UUID accountId, InternalTenantContext context);\ndiff --git a/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java b/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java\nindex b51ee616f0..32499dff55 100644\n--- a/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java\n+++ b/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java\n@@ -233,6 +233,19 @@ public class MockInvoiceDao extends MockEntityDaoBase getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) {\n+ final List result = new LinkedList();\n+ synchronized (monitor) {\n+ for (final InvoicePaymentModelDao payment : payments.values()) {\n+ if (invoiceId.equals(payment.getInvoiceId())) {\n+ result.add(payment);\n+ }\n+ }\n+ }\n+ return result;\n+ }\n+\n @Override\n public List getInvoicePaymentsByAccount(final InternalTenantContext context) {\n \ndiff --git a/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java b/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java\nindex ecb7dd218c..01277a9b92 100644\n--- a/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java\n+++ b/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java\n@@ -55,6 +55,7 @@ import org.killbill.billing.payment.api.PaymentApiException;\n import org.killbill.billing.payment.api.PluginProperty;\n import org.killbill.billing.payment.api.TransactionStatus;\n import org.killbill.billing.payment.api.TransactionType;\n+import org.killbill.billing.payment.core.janitor.IncompletePaymentTransactionTask;\n import org.killbill.billing.payment.dao.PaymentDao;\n import org.killbill.billing.payment.dao.PaymentModelDao;\n import org.killbill.billing.payment.dao.PaymentTransactionModelDao;\n@@ -321,7 +322,6 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi\n return new DefaultPriorPaymentControlResult(true);\n }\n \n-\n // Get account and check if it is child and payment is delegated to parent => abort\n \n final AccountData accountData = accountApi.getAccountById(invoice.getAccountId(), internalContext);\n@@ -340,7 +340,7 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi\n \n // Do we have a paymentMethod ?\n if (paymentControlPluginContext.getPaymentMethodId() == null) {\n- log.warn(\"Payment for invoiceId='{}' was not triggered, accountId='{}' doesn't have a default payment method\", getInvoiceId(pluginProperties), paymentControlPluginContext.getAccountId());\n+ log.warn(\"Payment for invoiceId='{}' was not triggered, accountId='{}' doesn't have a default payment method\", invoiceId, paymentControlPluginContext.getAccountId());\n invoiceApi.recordPaymentAttemptCompletion(invoiceId,\n paymentControlPluginContext.getAmount(),\n paymentControlPluginContext.getCurrency(),\n@@ -359,6 +359,16 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi\n return new DefaultPriorPaymentControlResult(true);\n }\n \n+ final List existingInvoicePayments = invoiceApi.getInvoicePaymentsByInvoice(invoiceId, internalContext);\n+ for (final InvoicePayment existingInvoicePayment : existingInvoicePayments) {\n+ final List existingTransactions = paymentDao.getPaymentTransactionsByExternalKey(existingInvoicePayment.getPaymentCookieId(), internalContext);\n+ for (final PaymentTransactionModelDao existingTransaction : existingTransactions) {\n+ if (existingTransaction.getTransactionStatus() == TransactionStatus.UNKNOWN) {\n+ log.warn(\"Existing paymentTransactionId='{}' for invoiceId='{}' in UNKNOWN state\", existingTransaction.getId(), invoiceId);\n+ return new DefaultPriorPaymentControlResult(true);\n+ }\n+ }\n+ }\n \n //\n // Insert attempt row with a success = false status to implement a two-phase commit strategy and guard against scenario where payment would go through\ndiff --git a/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java b/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java\nindex 32bba1c8da..78004a59c5 100644\n--- a/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java\n+++ b/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java\n@@ -1,7 +1,7 @@\n /*\n * Copyright 2010-2013 Ning, Inc.\n- * Copyright 2014-2016 Groupon, Inc\n- * Copyright 2014-2016 The Billing Project, LLC\n+ * Copyright 2014-2018 Groupon, Inc\n+ * Copyright 2014-2018 The Billing Project, LLC\n *\n * The Billing Project licenses this file to you under the Apache License, version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n@@ -76,6 +76,7 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {\n private final AtomicBoolean makeNextPaymentFailWithException = new AtomicBoolean(false);\n private final AtomicBoolean makeAllPaymentsFailWithError = new AtomicBoolean(false);\n private final AtomicBoolean makeNextPaymentPending = new AtomicBoolean(false);\n+ private final AtomicBoolean makeNextPaymentUnknown = new AtomicBoolean(false);\n private final AtomicInteger makePluginWaitSomeMilliseconds = new AtomicInteger(0);\n private final AtomicReference overrideNextProcessedAmount = new AtomicReference();\n private final AtomicReference overrideNextProcessedCurrency = new AtomicReference();\n@@ -206,6 +207,7 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {\n makeNextPaymentFailWithError.set(false);\n makeNextPaymentFailWithCancellation.set(false);\n makeNextPaymentPending.set(false);\n+ makeNextPaymentUnknown.set(false);\n makePluginWaitSomeMilliseconds.set(0);\n overrideNextProcessedAmount.set(null);\n paymentMethods.clear();\n@@ -222,6 +224,10 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {\n makeNextPaymentPending.set(true);\n }\n \n+ public void makeNextPaymentUnknown() {\n+ makeNextPaymentUnknown.set(true);\n+ }\n+\n public void makeNextPaymentFailWithCancellation() {\n makeNextPaymentFailWithCancellation.set(true);\n }\n@@ -465,6 +471,8 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {\n status = PaymentPluginStatus.CANCELED;\n } else if (makeNextPaymentPending.getAndSet(false)) {\n status = PaymentPluginStatus.PENDING;\n+ } else if (makeNextPaymentUnknown.getAndSet(false)) {\n+ status = PaymentPluginStatus.UNDEFINED;\n } else {\n status = PaymentPluginStatus.PROCESSED;\n }"},"changed_files":{"kind":"string","value":"['beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java', 'invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java', 'api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java', 'invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java', 'payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java', 'payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java']"},"changed_files_exts":{"kind":"string","value":"{'.java': 8}"},"changed_files_count":{"kind":"number","value":8,"string":"8"},"java_changed_files_count":{"kind":"number","value":8,"string":"8"},"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":8,"string":"8"},"repo_symbols_count":{"kind":"number","value":6119816,"string":"6,119,816"},"repo_tokens_count":{"kind":"number","value":1147700,"string":"1,147,700"},"repo_lines_count":{"kind":"number","value":132717,"string":"132,717"},"repo_files_without_tests_count":{"kind":"number","value":1008,"string":"1,008"},"changed_symbols_count":{"kind":"number","value":3226,"string":"3,226"},"changed_tokens_count":{"kind":"number","value":500,"string":"500"},"changed_lines_count":{"kind":"number","value":40,"string":"40"},"changed_files_without_tests_count":{"kind":"number","value":5,"string":"5"},"issue_symbols_count":{"kind":"number","value":331,"string":"331"},"issue_words_count":{"kind":"number","value":45,"string":"45"},"issue_tokens_count":{"kind":"number","value":68,"string":"68"},"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:25:30","string":"1970-01-01T00:25:30"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}},{"rowIdx":1399,"cells":{"id":{"kind":"number","value":256,"string":"256"},"text_id":{"kind":"string","value":"killbill/killbill/550/548"},"repo_owner":{"kind":"string","value":"killbill"},"repo_name":{"kind":"string","value":"killbill"},"issue_url":{"kind":"string","value":"https://github.com/killbill/killbill/issues/548"},"pull_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/550"},"comment_url":{"kind":"string","value":"https://github.com/killbill/killbill/pull/550"},"links_count":{"kind":"number","value":1,"string":"1"},"link_keyword":{"kind":"string","value":"fixes"},"issue_title":{"kind":"string","value":"DefaultPaymentGatewayApi doesn't respect isAborted flag"},"issue_body":{"kind":"string","value":"We should make sure 422 is returned if the HPP payment is aborted by a control plugin.\n"},"base_sha":{"kind":"string","value":"071796f5dcb8dd7c52fd8a0cd28aa0cf1a6a0120"},"head_sha":{"kind":"string","value":"13fd4001d59e59868186e2a306146d572be750dc"},"diff_url":{"kind":"string","value":"https://github.com/killbill/killbill/compare/071796f5dcb8dd7c52fd8a0cd28aa0cf1a6a0120...13fd4001d59e59868186e2a306146d572be750dc"},"diff":{"kind":"string","value":"diff --git a/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java b/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java\nindex ec17b19c60..09685fa60b 100644\n--- a/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java\n+++ b/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java\n@@ -34,6 +34,7 @@ import org.killbill.billing.control.plugin.api.PriorPaymentControlResult;\n import org.killbill.billing.payment.core.PaymentExecutors;\n import org.killbill.billing.payment.core.PaymentGatewayProcessor;\n import org.killbill.billing.payment.core.sm.control.ControlPluginRunner;\n+import org.killbill.billing.payment.core.sm.control.PaymentControlApiAbortException;\n import org.killbill.billing.payment.dispatcher.PluginDispatcher;\n import org.killbill.billing.payment.dispatcher.PluginDispatcher.PluginDispatcherReturnType;\n import org.killbill.billing.payment.plugin.api.GatewayNotification;\n@@ -147,6 +148,8 @@ public class DefaultPaymentGatewayApi extends DefaultApiBase implements PaymentG\n PaymentApiType.HPP, null, HPPType.BUILD_FORM_DESCRIPTOR,\n null, null, true, paymentControlPluginNames, properties, callContext);\n \n+ } catch (final PaymentControlApiAbortException e) {\n+ throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_API_ABORTED, e.getPluginName());\n } catch (final PaymentControlApiException e) {\n throw new PaymentApiException(e, ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e);\n }\ndiff --git a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java\nindex f2b1472cc3..1ee36fc04a 100644\n--- a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java\n+++ b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java\n@@ -25,7 +25,6 @@ import javax.annotation.Nullable;\n import javax.inject.Inject;\n \n import org.joda.time.DateTime;\n-import org.killbill.billing.ErrorCode;\n import org.killbill.billing.account.api.Account;\n import org.killbill.billing.callcontext.DefaultCallContext;\n import org.killbill.billing.catalog.api.Currency;\n@@ -38,7 +37,6 @@ import org.killbill.billing.control.plugin.api.PaymentControlContext;\n import org.killbill.billing.control.plugin.api.PaymentControlPluginApi;\n import org.killbill.billing.control.plugin.api.PriorPaymentControlResult;\n import org.killbill.billing.osgi.api.OSGIServiceRegistration;\n-import org.killbill.billing.payment.api.PaymentApiException;\n import org.killbill.billing.payment.api.PluginProperty;\n import org.killbill.billing.payment.api.TransactionType;\n import org.killbill.billing.payment.retry.DefaultFailureCallResult;\ndiff --git a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java\nindex c3524e5bd6..33b4df4b54 100644\n--- a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java\n+++ b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java\n@@ -22,7 +22,7 @@ import org.killbill.billing.control.plugin.api.PaymentControlApiException;\n /**\n * Created by arodrigues on 5/6/16.\n */\n-class PaymentControlApiAbortException extends PaymentControlApiException {\n+public class PaymentControlApiAbortException extends PaymentControlApiException {\n private final String pluginName;\n \n public PaymentControlApiAbortException(final String pluginName) {\ndiff --git a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java\nindex 680221b084..3aa3554519 100644\n--- a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java\n+++ b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java\n@@ -21,6 +21,7 @@ import java.util.ArrayList;\n import java.util.List;\n import java.util.UUID;\n \n+import org.killbill.billing.ErrorCode;\n import org.killbill.billing.account.api.Account;\n import org.killbill.billing.control.plugin.api.OnFailurePaymentControlResult;\n import org.killbill.billing.control.plugin.api.OnSuccessPaymentControlResult;\n@@ -152,6 +153,20 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD\n \n }\n \n+ @Test(groups = \"fast\")\n+ public void testBuildFormDescriptorWithPaymentControlAbortedPayment() throws PaymentApiException {\n+ plugin.setAborted(true);\n+\n+ // Set a random UUID to verify the plugin will successfully override it\n+ try {\n+ paymentGatewayApi.buildFormDescriptorWithPaymentControl(account, UUID.randomUUID(), ImmutableList.of(), ImmutableList.of(), paymentOptions, callContext);\n+ Assert.fail();\n+ } catch (PaymentApiException e) {\n+ Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode());\n+ }\n+\n+ }\n+\n public static class TestPaymentGatewayApiValidationPlugin implements PaymentControlPluginApi {\n \n public static final String VALIDATION_PLUGIN_NAME = \"TestPaymentGatewayApiValidationPlugin\";\n@@ -216,13 +231,20 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD\n private Iterable newOnResultProperties;\n private Iterable removedOnResultProperties;\n \n+ private boolean aborted;\n+\n public TestPaymentGatewayApiControlPlugin() {\n+ this.aborted = false;\n this.newPriorCallProperties = ImmutableList.of();\n this.removedPriorCallProperties = ImmutableList.of();\n this.newOnResultProperties = ImmutableList.of();\n this.removedOnResultProperties = ImmutableList.of();\n }\n \n+ public void setAborted(final boolean aborted) {\n+ this.aborted = aborted;\n+ }\n+\n public void setPriorCallProperties(final Iterable newPriorCallProperties, final Iterable removedPriorCallProperties) {\n this.newPriorCallProperties = newPriorCallProperties;\n this.removedPriorCallProperties = removedPriorCallProperties;\n@@ -235,7 +257,7 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD\n \n @Override\n public PriorPaymentControlResult priorCall(final PaymentControlContext paymentControlContext, final Iterable properties) throws PaymentControlApiException {\n- return new DefaultPriorPaymentControlResult(false, account.getPaymentMethodId(), null, null, getAdjustedProperties(properties, newPriorCallProperties, removedPriorCallProperties));\n+ return new DefaultPriorPaymentControlResult(aborted, account.getPaymentMethodId(), null, null, getAdjustedProperties(properties, newPriorCallProperties, removedPriorCallProperties));\n }\n \n @Override"},"changed_files":{"kind":"string","value":"['payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java', 'payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java', 'payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java', 'payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.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":4876641,"string":"4,876,641"},"repo_tokens_count":{"kind":"number","value":926318,"string":"926,318"},"repo_lines_count":{"kind":"number","value":109381,"string":"109,381"},"repo_files_without_tests_count":{"kind":"number","value":927,"string":"927"},"changed_symbols_count":{"kind":"number","value":596,"string":"596"},"changed_tokens_count":{"kind":"number","value":95,"string":"95"},"changed_lines_count":{"kind":"number","value":7,"string":"7"},"changed_files_without_tests_count":{"kind":"number","value":3,"string":"3"},"issue_symbols_count":{"kind":"number","value":87,"string":"87"},"issue_words_count":{"kind":"number","value":17,"string":"17"},"issue_tokens_count":{"kind":"number","value":20,"string":"20"},"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:24:23","string":"1970-01-01T00:24:23"},"repo_stars":{"kind":"number","value":4053,"string":"4,053"},"repo_language":{"kind":"string","value":"Java"},"repo_languages":{"kind":"string","value":"{'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}"},"repo_license":{"kind":"string","value":"Apache License 2.0"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":13,"numItemsPerPage":100,"numTotalItems":2522,"offset":1300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzgyMDg4OSwic3ViIjoiL2RhdGFzZXRzL0pldEJyYWlucy1SZXNlYXJjaC9sY2EtYnVnLWxvY2FsaXphdGlvbiIsImV4cCI6MTc1NzgyNDQ4OSwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.ZOjaLlDkkZyIJ0vkOI0FL9Gi-672pa2pvtqs0dDXnSzJeJRNS6GBzCDPi_bO8G7aiZ1aexEBji6mb9h7kE1LBQ","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,587
      thundernest/k-9/5110/5106
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/5106
      https://github.com/thundernest/k-9/pull/5110
      https://github.com/thundernest/k-9/pull/5110
      1
      fixes
      Import functionality is almost broken
      **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: ### 1 1. Export k9s_settings on older App version. 2. Remove older App version. 3. Install build v5.727. 4. Have firewall block App from internet. 5. Import all previously exported settings. 6. (Optional) Enable Internet access for App. 7. All Mail accounts have only an empty "Outbox" folder. ### 2 1. Export k9s_settings on older App version. 2. Remove older App version. 3. Install build v5.727. 4. Let App have internet access. 5. Import all previously exported settings. 6. Provide wrong password for any amount of mail accounts. 7. All Mail accounts, that were provided with a wrong password, have only an empty "Outbox" folder. 8. Remove faulty Mail account. 9. Re-import this faulty mail account, only. 10. The empty "Outbox" folder is now the default folder on top of all folders. 11. Every time you change to this mail account, the "Outbox" folder will _always_ be the first one opened on top. 12. There is no way to set the "Inbox" folder back to top. This is only a summary of all the issues. There are more very similar issues, that I do not want to repeat here. In short, the Import functionality is almost broken; if you just make 1 mistake, you have to uninstall and re-install the whole application. This is no way to treat imports. **Expected behavior** Importing works smoothly. **Environment (please complete the following information):** - K-9 Mail version: v5.727 - Android version: 11 - Device: POCO X3 - Account type: Generic IMAP **Additional context** The "stable" version always crashes, when I try to import settings. That's why I am using the newest "Pre-Release" version. **Logs** Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here: No, I will not uninstall and re-install the App for the 7th time.
      2b769f8db3d1c68c286792fb9f7fee6cace901aa
      71e2d24fbbe8301bcaea363ff0b930d8ff3327d5
      https://github.com/thundernest/k-9/compare/2b769f8db3d1c68c286792fb9f7fee6cace901aa...71e2d24fbbe8301bcaea363ff0b930d8ff3327d5
      diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java index 67c365a44..38fb82ca2 100644 --- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -2356,6 +2356,8 @@ public class MessagingController { sendPendingMessages(account, listener); + refreshFolderListIfStale(account); + try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode();
      ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,574,874
      509,020
      71,922
      412
      45
      9
      2
      1
      1,972
      315
      473
      48
      1
      0
      1970-01-01T00:26:51
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,586
      thundernest/k-9/5131/5004
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/5004
      https://github.com/thundernest/k-9/pull/5131
      https://github.com/thundernest/k-9/pull/5131
      1
      fixes
      Email address too long for line
      **Describe the bug** A mail address that is too long to fit on the display won't be accepted as one address but two (or more) addresses. **To Reproduce** Try to send an email to an address that is too long for your display width, for example `[email protected]`. The app will now display the address in two lines, in my case like this: `abcdefghijklmnopqrstuvwxyz@outlook. com` The app will now see every line as single address and think you want to send mails to `abcdefghijklmnopqrstuvwxyz@outlook.` and `com`. **Expected behavior** The app should see the address as a single one, even after a new line. **Environment** - K-9 Mail version: 5.721 - Android version: 10 - Device: Samsung Galaxy A9
      5655bf3c03147f2d145e750057e12cd1530eacfd
      09ab26f763ca53f0dd146636cd72add74647ce3a
      https://github.com/thundernest/k-9/compare/5655bf3c03147f2d145e750057e12cd1530eacfd...09ab26f763ca53f0dd146636cd72add74647ce3a
      diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java b/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java index 8e5452e08..72e46e091 100644 --- a/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java +++ b/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java @@ -204,6 +204,10 @@ public class RecipientSelectView extends TokenCompleteTextView<Recipient> implem @Override public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { + if (!hasFocus) { + performCompletion(); + } + super.onFocusChanged(hasFocus, direction, previous); if (hasFocus) { displayKeyboard();
      ['app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,559,059
      505,701
      71,434
      406
      72
      13
      4
      1
      739
      117
      167
      16
      0
      0
      1970-01-01T00:26:52
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,582
      thundernest/k-9/5146/4125
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4125
      https://github.com/thundernest/k-9/pull/5146
      https://github.com/thundernest/k-9/pull/5146
      1
      fixes
      Not handling reject response correctly when multiple recipients
      ### Similar issues found #3616 ### Root Cause My mail server is enforcing a 'reject' rule on unknown recipient domain. So any email containing unknown domain will **not** be accepted. It works with other MUA I tested, and indeed the 450 error is raised and no mail is sent until the list of recipients is sanitized. In the case of K9-Mail, I end up with a **mangled header missing multiple fields** (From / Date) and with an 'unexpected end of header'. For Googlemail, the server respond waving RFC 5322 and refuse to accept the email. Others will discard and send a report to the recipient regarding the bad formatted email, and Outlook/Microsoft will accept it but it will be blank for the recipient. On K9-Mail side, the email will be stuck forever in the Outbox, trying to resend the botched email every now and then, never succeeding (as expected). ### Expected behavior Whenever a recipient is rejected, the MUA should handle it gracefully. Testing with Thunderbird and SOGo, they both raise the error and do not try further attempts to deliver the email until the 'bad' recipients have been removed from the list. K9-Mail should do the same and stop all attempt on receiving the reject from the mail server until the list of recipients has been sanitized. ### Actual behavior Mail server rejects the email, with and from=<> as per bouncing standards, however K9-Mail basically integrate that bad-formatted header and use it to try sending the email to the rest of the recipients. ### Steps to reproduce 0. Enforce reject rule on unknown recipient domains on your mail server (**before** any permit rule) 1. Prepare an email to multiple recipients with at least one 'bad' recipient (ex: unknown domain. Ex: [email protected]) 2. Send it from K9-Mail 3. Check your Outbox in K9-Mail and your logs on the mail server ### Environment K-9 Mail version: 5.500 Android version: 8.1.0 Account type (IMAP, POP3, WebDAV/Exchange): IMAP Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here: Logs from the mail server: ``` Jul 23 09:44:35 myhost postfix/smtpd[26369]: connect from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137] Jul 23 09:44:35 myhost postfix/smtpd[26369]: Anonymous TLS connection established from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137]: TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits) Jul 23 09:44:35 myhost postfix/smtpd[26369]: CEC231003: client=XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137], sasl_method=PLAIN, [email protected] Jul 23 09:44:35 myhost postfix/smtpd[26369]: CEC231003: reject: RCPT from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137]: 450 4.1.2 <[email protected]>: <b>Recipient address rejected: Domain not found</b>; from=<[email protected]> to=<[email protected]> proto=ESMTP helo=<[XXX.XXX.XXX.119]> Jul 23 09:44:36 myhost postfix/cleanup[26374]: CEC231003: message-id=<> Jul 23 09:44:36 myhost opendkim[32642]: <b>CEC231003: can't determine message sender; accepting</b> Jul 23 09:44:36 myhost opendmarc[619]: CEC231003: RFC5322 requirement error: missing From field; accepting Jul 23 09:44:36 myhost postfix/qmgr[26269]: CEC231003: from=<[email protected]>, size=213, nrcpt=2 (queue active) Jul 23 09:44:36 myhost postfix/smtp[26375]: Untrusted TLS connection established to gmail-smtp-in.l.google.com[2a00:1450:400c:c0a::1b]:25: TLSv1.2 with cipher ECDHE-RSA-CHACHA20-POLY1305 (256/256 bits) Jul 23 09:44:36 myhost postfix/smtpd[26369]: disconnect from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137] ehlo=2 starttls=1 auth=1 mail=1 rcpt=2/3 data=1 quit=1 commands=9/10 Jul 23 09:44:36 myhost postfix/smtp[26375]: CEC231003: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[2a00:1450:400c:c0a::1b]:25, delay=0.99, delays=0.4/0.01/0.16/0.43, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[2a00:1450:400c:c0a::1b] said: 550-5.7.1 [2a01:4f8:10a:2493:b827:a8ff:fe4b:b71c 11] Our system has 550-5.7.1 detected that this message is not RFC 5322 compliant: 550-5.7.1 'From' header is missing. 550-5.7.1 To reduce the amount of spam sent to Gmail, this message has been 550-5.7.1 blocked. Please visit 550-5.7.1 https://support.google.com/mail/?p=RfcMessageNonCompliant 550 5.7.1 and review RFC 5322 specifications for more information. y4si40902182wrr.356 - gsmtp (in reply to end of DATA command)) ```
      3457f69c562f47ca1fe5daebfbdb5a02b7c856c4
      987325d226dc225c8f9158e4534a3120c938b0e5
      https://github.com/thundernest/k-9/compare/3457f69c562f47ca1fe5daebfbdb5a02b7c856c4...987325d226dc225c8f9158e4534a3120c938b0e5
      diff --git a/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java b/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java index aeaff52f6..001919834 100644 --- a/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java +++ b/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java @@ -413,7 +413,6 @@ public class SmtpTransport extends Transport { pipelinedCommands.add(String.format("RCPT TO:<%s>", address)); } - pipelinedCommands.add("DATA"); executePipelinedCommands(pipelinedCommands); readPipelinedResponse(pipelinedCommands); } else { @@ -422,10 +421,10 @@ public class SmtpTransport extends Transport { for (String address : addresses) { executeCommand("RCPT TO:<%s>", address); } - - executeCommand("DATA"); } + executeCommand("DATA"); + EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream( new LineWrapOutputStream(new SmtpDataStuffing(outputStream), 1000)); @@ -618,35 +617,23 @@ public class SmtpTransport extends Transport { private void readPipelinedResponse(Queue<String> pipelinedCommands) throws IOException, MessagingException { String responseLine; List<String> results = new ArrayList<>(); - NegativeSmtpReplyException firstNegativeResponse = null; - boolean dataCommandOk = true; - for (String command : pipelinedCommands) { + MessagingException firstException = null; + for (int i = 0, size = pipelinedCommands.size(); i < size; i++) { results.clear(); responseLine = readCommandResponseLine(results); try { responseLineToCommandResponse(responseLine, results); } catch (MessagingException exception) { - if (command.equals("DATA")) { - dataCommandOk = false; - } - if (firstNegativeResponse == null) { - firstNegativeResponse = (NegativeSmtpReplyException) exception; + if (firstException == null) { + firstException = exception; } } } - if (firstNegativeResponse != null) { - try { - if (dataCommandOk) { - executeCommand("."); - } - throw firstNegativeResponse; - } catch (NegativeSmtpReplyException e) { - throw firstNegativeResponse; - } + if (firstException != null) { + throw firstException; } - } private CommandResponse responseLineToCommandResponse(String line, List<String> results) throws MessagingException { diff --git a/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java b/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java index 06aa6f9e7..33a4025c4 100644 --- a/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java +++ b/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java @@ -692,9 +692,9 @@ public class SmtpTransportTest { MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); - server.expect("DATA"); server.output("250 OK"); server.output("250 OK"); + server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); @@ -740,12 +740,8 @@ public class SmtpTransportTest { MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); - server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); - server.output("354 End data with <CR><LF>.<CR><LF>"); - server.expect("."); - server.output("554 no valid recipients"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); @@ -770,10 +766,8 @@ public class SmtpTransportTest { MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); - server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); - server.output("554 no valid recipients given"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); @@ -798,13 +792,9 @@ public class SmtpTransportTest { server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("RCPT TO:<user3@localhost>"); - server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); server.output("550 remote mail to <user3@localhost> not allowed"); - server.output("354 End data with <CR><LF>.<CR><LF>"); - server.expect("."); - server.output("554 no valid recipients given"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); @@ -829,13 +819,9 @@ public class SmtpTransportTest { server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("RCPT TO:<user3@localhost>"); - server.expect("DATA"); server.output("250 OK"); server.output("250 OK"); server.output("550 remote mail to <user3@localhost> not allowed"); - server.output("354 End data with <CR><LF>.<CR><LF>"); - server.expect("."); - server.output("250 OK"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection();
      ['mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java', 'mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      2,558,990
      505,695
      71,435
      406
      1,158
      212
      29
      1
      4,451
      551
      1,382
      49
      2
      1
      1970-01-01T00:26:53
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,580
      thundernest/k-9/5216/5204
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/5204
      https://github.com/thundernest/k-9/pull/5216
      https://github.com/thundernest/k-9/pull/5216
      1
      fixes
      Crash when sending to address with an umlaut
      I haven't done any variation testing, as I just finally found out. What I had was: A contact which I accidentially typed an `ü` instead of `ue`, used the contact suggestion feature for recepient. As soon as I hit send, Android's "Application has stopped working" window popped up, after a restart it's as if nothing had happened. Replacing the character in my contacts helped, but It took me probably a month to figure out what the issue was.
      cc2413a180af45b76fa12d4440111d34a1e92c94
      12213b53165ff051552483ff32caa4eddef91b14
      https://github.com/thundernest/k-9/compare/cc2413a180af45b76fa12d4440111d34a1e92c94...12213b53165ff051552483ff32caa4eddef91b14
      diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java index e2cf5893e..d9ca0307c 100644 --- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java +++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java @@ -28,6 +28,7 @@ import com.fsck.k9.ui.R; import com.fsck.k9.mail.Address; import com.fsck.k9.view.RecipientSelectView.Recipient; import com.fsck.k9.view.RecipientSelectView.RecipientCryptoStatus; +import org.apache.james.mime4j.util.CharsetUtil; import timber.log.Timber; import static java.lang.String.CASE_INSENSITIVE_ORDER; @@ -240,13 +241,14 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> { Address[] addresses = Address.parseUnencoded(uid); for (Address address : addresses) { - if (recipientMap.containsKey(address.getAddress())) { + String emailAddress = address.getAddress(); + if (!isSupportedEmailAddress(emailAddress) || recipientMap.containsKey(emailAddress)) { continue; } Recipient recipient = new Recipient(address); recipients.add(recipient); - recipientMap.put(address.getAddress(), recipient); + recipientMap.put(emailAddress, recipient); } } @@ -256,10 +258,12 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> { private void fillContactDataFromAddresses(Address[] addresses, List<Recipient> recipients, Map<String, Recipient> recipientMap) { for (Address address : addresses) { - // TODO actually query contacts - not sure if this is possible in a single query tho :( - Recipient recipient = new Recipient(address); - recipients.add(recipient); - recipientMap.put(address.getAddress(), recipient); + if (isSupportedEmailAddress(address.getAddress())) { + // TODO actually query contacts - not sure if this is possible in a single query tho :( + Recipient recipient = new Recipient(address); + recipients.add(recipient); + recipientMap.put(address.getAddress(), recipient); + } } } @@ -438,7 +442,7 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> { String email = cursor.getString(INDEX_EMAIL); // already exists? just skip then - if (email == null || recipientMap.containsKey(email)) { + if (email == null || !isSupportedEmailAddress(email) || recipientMap.containsKey(email)) { // TODO We should probably merging contacts with the same email address continue; } @@ -583,4 +587,7 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> { } } + private boolean isSupportedEmailAddress(String address) { + return CharsetUtil.isASCII(address); + } }
      ['app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,528,405
      500,145
      70,553
      402
      1,328
      220
      21
      1
      448
      78
      100
      5
      0
      0
      1970-01-01T00:26:56
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,651
      thundernest/k-9/2003/1965
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/1965
      https://github.com/thundernest/k-9/pull/2003
      https://github.com/thundernest/k-9/pull/2003
      1
      fixes
      CC/BCC Disappear if you tap subject first
      ### Expected behavior While composing a new email, if I type the subject first, and compose the email, THEN go back and fill out the addresses of BCC and CC. ### Actual behavior While composing a new email, if I type the subject first, the BCC and CC address fields disappear (have them configured to show by default). No way to get them back because the BCC/CC icon is missing (see previous issue) ### Steps to reproduce 1. Tap to compose a new email 2. Tap and type a subject 3. BCC/CC address fields disappear ### Environment K-9 Mail version: 5.201 Android version: 6.0 Account type (IMAP, POP3, WebDAV/Exchange):IMAP
      6beb9902dade44b5f6dce8e8e8a2638e7be9e6ef
      963645cad626c3ea2f732ebf66390b072aa444f5
      https://github.com/thundernest/k-9/compare/6beb9902dade44b5f6dce8e8e8a2638e7be9e6ef...963645cad626c3ea2f732ebf66390b072aa444f5
      diff --git a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java index cf805041d..be62c922a 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java @@ -541,7 +541,9 @@ public class RecipientPresenter implements PermissionPingCallback { } public void onNonRecipientFieldFocused() { - hideEmptyExtendedRecipientFields(); + if (!account.isAlwaysShowCcBcc()) { + hideEmptyExtendedRecipientFields(); + } } public void onClickCryptoStatus() {
      ['k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,455,426
      685,807
      94,549
      422
      149
      28
      4
      1
      655
      109
      168
      18
      0
      0
      1970-01-01T00:24:43
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,578
      thundernest/k-9/5262/5261
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/5261
      https://github.com/thundernest/k-9/pull/5262
      https://github.com/thundernest/k-9/pull/5262
      1
      fixes
      Crash when clicking compose button in message list widget
      **Describe the bug** Clicking the envelope icon in the message list widget crashes the app. **To Reproduce** Steps to reproduce the behavior: 1. Set up an account 2. Drag the message list widget to a home screen 3. Click the envelope icon (compose message) in the upper right of the home screen widget 4. Observe app crash **Environment (please complete the following information):** - K-9 Mail version: 5.734-SNAPSHOT **Logs** ``` Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter accountUuid at com.fsck.k9.Preferences.getAccount(Unknown Source:2) at com.fsck.k9.activity.MessageCompose.onCreate(MessageCompose.java:284) ```
      f58860f8bbe3a59e180cc87dc410e16b295592f7
      034e1fbd790dc4af6f60bd980f59489e375a31fe
      https://github.com/thundernest/k-9/compare/f58860f8bbe3a59e180cc87dc410e16b295592f7...034e1fbd790dc4af6f60bd980f59489e375a31fe
      diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java index 0601958fd..c2cb3fd28 100644 --- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java +++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java @@ -281,7 +281,9 @@ public class MessageCompose extends K9Activity implements OnClickListener, relatedMessageReference.getAccountUuid() : intent.getStringExtra(EXTRA_ACCOUNT); - account = preferences.getAccount(accountUuid); + if (accountUuid != null) { + account = preferences.getAccount(accountUuid); + } if (account == null) { account = preferences.getDefaultAccount();
      ['app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,515,829
      497,753
      70,226
      402
      162
      27
      4
      1
      759
      89
      171
      19
      0
      1
      1970-01-01T00:26:58
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,655
      thundernest/k-9/1890/1879
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/1879
      https://github.com/thundernest/k-9/pull/1890
      https://github.com/thundernest/k-9/pull/1890
      1
      fixes
      Crash: OOM during migration
      Via Play Developer Console App version: 5.200 ``` java.lang.OutOfMemoryError: Failed to allocate a 2060 byte allocation with 1974 free bytes and 1974B until OOM at org.apache.james.mime4j.stream.MimeEntity.advanceToBoundary(MimeEntity.java:387) at org.apache.james.mime4j.stream.MimeEntity.advance(MimeEntity.java:331) at org.apache.james.mime4j.stream.MimeTokenStream.next(MimeTokenStream.java:360) at org.apache.james.mime4j.parser.MimeStreamParser.parse(MimeStreamParser.java:176) at com.fsck.k9.mail.message.MessageHeaderParser.parse(MessageHeaderParser.java:24) at com.fsck.k9.mailstore.LocalMessage.populateFromGetMessageCursor(LocalMessage.java:127) at com.fsck.k9.mailstore.LocalStore$13.doDbWork(LocalStore.java:638) at com.fsck.k9.mailstore.LocalStore$13.doDbWork(LocalStore.java:615) at com.fsck.k9.mailstore.LockableDatabase.execute(LockableDatabase.java:275) at com.fsck.k9.mailstore.LocalStore.getMessages(LocalStore.java:615) at com.fsck.k9.mailstore.LocalFolder$10.doDbWork(LocalFolder.java:880) at com.fsck.k9.mailstore.LocalFolder$10.doDbWork(LocalFolder.java:875) at com.fsck.k9.mailstore.LockableDatabase.execute(LockableDatabase.java:275) at com.fsck.k9.mailstore.LocalFolder.getMessages(LocalFolder.java:875) at com.fsck.k9.mailstore.migrations.MigrationTo55.createFtsSearchTable(MigrationTo55.java:36) at com.fsck.k9.mailstore.migrations.Migrations.upgradeDatabase(Migrations.java:66) at com.fsck.k9.mailstore.StoreSchemaDefinition.upgradeDatabase(StoreSchemaDefinition.java:60) at com.fsck.k9.mailstore.StoreSchemaDefinition.doDbUpgrade(StoreSchemaDefinition.java:36) at com.fsck.k9.mailstore.LockableDatabase.openOrCreateDataspace(LockableDatabase.java:381) at com.fsck.k9.mailstore.LockableDatabase.open(LockableDatabase.java:354) at com.fsck.k9.mailstore.LocalStore.<init>(LocalStore.java:210) at com.fsck.k9.mailstore.LocalStore.getInstance(LocalStore.java:235) at com.fsck.k9.Account.getLocalStore(Account.java:1278) at com.fsck.k9.controller.MessagingController.setupPushing(MessagingController.java:4322) at com.fsck.k9.service.MailService.setupPushers(MailService.java:349) at com.fsck.k9.service.MailService.reschedulePushers(MailService.java:338) at com.fsck.k9.service.MailService.access$100(MailService.java:24) at com.fsck.k9.service.MailService$1.run(MailService.java:194) at com.fsck.k9.service.CoreService$1.run(CoreService.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) ```
      50d81f7034e60e50cbd67007144bf7e23137aa87
      b0574804813c978d9826380667cf01b8e50429de
      https://github.com/thundernest/k-9/compare/50d81f7034e60e50cbd67007144bf7e23137aa87...b0574804813c978d9826380667cf01b8e50429de
      diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java index e9458479a..9cd8f2319 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java @@ -896,6 +896,42 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable { } } + public List<String> getAllMessageUids() throws MessagingException { + try { + return localStore.database.execute(false, new DbCallback<List<String>>() { + @Override + public List<String> doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { + Cursor cursor = null; + ArrayList<String> result = new ArrayList<>(); + + try { + open(OPEN_MODE_RO); + + cursor = db.rawQuery( + "SELECT uid " + + "FROM messages " + + "WHERE empty = 0 AND deleted = 0 AND " + + "folder_id = ? ORDER BY date DESC", + new String[] { Long.toString(mFolderId) }); + + while (cursor.moveToNext()) { + String uid = cursor.getString(0); + result.add(uid); + } + } catch (MessagingException e) { + throw new WrappedException(e); + } finally { + Utility.closeQuietly(cursor); + } + + return result; + } + }); + } catch (WrappedException e) { + throw(MessagingException) e.getCause(); + } + } + public List<LocalMessage> getMessagesByUids(@NonNull List<String> uids) throws MessagingException { open(OPEN_MODE_RW); List<LocalMessage> messages = new ArrayList<>(); diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java index 4f8f7e5dc..e9fb197ab 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java @@ -1,9 +1,7 @@ package com.fsck.k9.mailstore.migrations; -import java.util.ArrayList; import java.util.Collections; -import java.util.Iterator; import java.util.List; import android.content.ContentValues; @@ -20,8 +18,8 @@ import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.message.extractors.MessageFulltextCreator; -public class MigrationTo55 { - public static void createFtsSearchTable(SQLiteDatabase db, MigrationsHelper migrationsHelper) { +class MigrationTo55 { + static void createFtsSearchTable(SQLiteDatabase db, MigrationsHelper migrationsHelper) { db.execSQL("CREATE VIRTUAL TABLE messages_fulltext USING fts4 (fulltext)"); LocalStore localStore = migrationsHelper.getLocalStore(); @@ -33,13 +31,11 @@ public class MigrationTo55 { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); for (LocalFolder folder : folders) { - Iterator<LocalMessage> localMessages = new ArrayList<>(folder.getMessages(null, false)).iterator(); - while (localMessages.hasNext()) { - LocalMessage localMessage = localMessages.next(); - // The LocalMessage objects are heavy once they have been loaded, so we free them asap - localMessages.remove(); - + List<String> messageUids = folder.getAllMessageUids(); + for (String messageUid : messageUids) { + LocalMessage localMessage = folder.getMessage(messageUid); folder.fetch(Collections.singletonList(localMessage), fp, null); + String fulltext = fulltextCreator.createFulltext(localMessage); if (!TextUtils.isEmpty(fulltext)) { Log.d(K9.LOG_TAG, "fulltext for msg id " + localMessage.getId() + " is " + fulltext.length() + " chars long");
      ['k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,440,397
      682,554
      94,169
      420
      2,413
      385
      52
      2
      2,654
      89
      677
      38
      0
      1
      1970-01-01T00:24:43
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,654
      thundernest/k-9/1891/1878
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/1878
      https://github.com/thundernest/k-9/pull/1891
      https://github.com/thundernest/k-9/pull/1891
      1
      fixes
      Crash: NPE in MessageCryptoHelper.addCryptoResultAnnotationToMessage()
      Via Play Developer Console App version: 5.200 ``` java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65916, result=0, data=null} to activity {com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.NullPointerException: Attempt to read from field 'com.fsck.k9.mail.Part com.fsck.k9.ui.crypto.MessageCryptoHelper$CryptoPart.part' on a null object reference at android.app.ActivityThread.deliverResults(ActivityThread.java:3733) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776) at android.app.ActivityThread.-wrap16(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5461) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to read from field 'com.fsck.k9.mail.Part com.fsck.k9.ui.crypto.MessageCryptoHelper$CryptoPart.part' on a null object reference at com.fsck.k9.ui.crypto.MessageCryptoHelper.addCryptoResultAnnotationToMessage(MessageCryptoHelper.java:575) at com.fsck.k9.ui.crypto.MessageCryptoHelper.onCryptoOperationCanceled(MessageCryptoHelper.java:558) at com.fsck.k9.ui.crypto.MessageCryptoHelper.onActivityResult(MessageCryptoHelper.java:536) at com.fsck.k9.activity.MessageLoaderHelper.onActivityResult(MessageLoaderHelper.java:168) at com.fsck.k9.ui.messageview.MessageViewFragment.onPendingIntentResult(MessageViewFragment.java:393) at com.fsck.k9.activity.MessageList.onActivityResult(MessageList.java:1600) at android.app.Activity.dispatchActivityResult(Activity.java:6456) at android.app.ActivityThread.deliverResults(ActivityThread.java:3729) ... 9 more ```
      50d81f7034e60e50cbd67007144bf7e23137aa87
      97e9e3267f35a67eeb1ff6542224825dad6f9aba
      https://github.com/thundernest/k-9/compare/50d81f7034e60e50cbd67007144bf7e23137aa87...97e9e3267f35a67eeb1ff6542224825dad6f9aba
      diff --git a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java index 28387c9f7..2600ddcf0 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java @@ -58,13 +58,14 @@ import org.openintents.openpgp.util.OpenPgpUtils; public class MessageCryptoHelper { private static final int INVALID_OPENPGP_RESULT_CODE = -1; private static final MimeBodyPart NO_REPLACEMENT_PART = null; - public static final int REQUEST_CODE_USER_INTERACTION = 124; - public static final int PROGRESS_SIZE_THRESHOLD = 4096; + private static final int REQUEST_CODE_USER_INTERACTION = 124; + private static final int PROGRESS_SIZE_THRESHOLD = 4096; private final Context context; private final String openPgpProviderPackage; private final Object callbackLock = new Object(); + private final Deque<CryptoPart> partsToDecryptOrVerify = new ArrayDeque<>(); @Nullable private MessageCryptoCallback callback; @@ -76,7 +77,6 @@ public class MessageCryptoHelper { private MessageCryptoAnnotations messageAnnotations; - private Deque<CryptoPart> partsToDecryptOrVerify = new ArrayDeque<>(); private CryptoPart currentCryptoPart; private Intent currentCryptoResult; private Intent userInteractionResultIntent; @@ -554,8 +554,12 @@ public class MessageCryptoHelper { } private void onCryptoOperationCanceled() { - CryptoResultAnnotation errorPart = CryptoResultAnnotation.createOpenPgpCanceledAnnotation(); - addCryptoResultAnnotationToMessage(errorPart); + // there are weird states that get us here when we're not actually processing any part. just skip in that case + // see https://github.com/k9mail/k-9/issues/1878 + if (currentCryptoPart != null) { + CryptoResultAnnotation errorPart = CryptoResultAnnotation.createOpenPgpCanceledAnnotation(); + addCryptoResultAnnotationToMessage(errorPart); + } onCryptoFinished(); } @@ -579,8 +583,17 @@ public class MessageCryptoHelper { } private void onCryptoFinished() { - currentCryptoPart = null; - partsToDecryptOrVerify.removeFirst(); + boolean currentPartIsFirstInQueue = partsToDecryptOrVerify.peekFirst() == currentCryptoPart; + if (!currentPartIsFirstInQueue) { + throw new IllegalStateException( + "Trying to remove part from queue that is not the currently processed one!"); + } + if (currentCryptoPart != null) { + partsToDecryptOrVerify.removeFirst(); + currentCryptoPart = null; + } else { + Log.e(K9.LOG_TAG, "Got to onCryptoFinished() with no part in processing!", new Throwable()); + } decryptOrVerifyNextPart(); } @@ -594,7 +607,7 @@ public class MessageCryptoHelper { } private void cleanupAfterProcessingFinished() { - partsToDecryptOrVerify = null; + partsToDecryptOrVerify.clear(); openPgpApi = null; if (openPgpServiceConnection != null) { openPgpServiceConnection.unbindFromService(); @@ -613,11 +626,13 @@ public class MessageCryptoHelper { throw new AssertionError("Callback may only be reattached for the same message!"); } synchronized (callbackLock) { - if (queuedResult != null) { - Log.d(K9.LOG_TAG, "Returning cached result to reattached callback"); - } this.callback = callback; - deliverResult(); + + boolean hasCachedResult = queuedResult != null || queuedPendingIntent != null; + if (hasCachedResult) { + Log.d(K9.LOG_TAG, "Returning cached result or pending intent to reattached callback"); + deliverResult(); + } } } @@ -663,6 +678,8 @@ public class MessageCryptoHelper { callback.startPendingIntentForCryptoHelper( queuedPendingIntent.getIntentSender(), REQUEST_CODE_USER_INTERACTION, null, 0, 0, 0); queuedPendingIntent = null; + } else { + throw new IllegalStateException("deliverResult() called with no result!"); } }
      ['k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,440,397
      682,554
      94,169
      420
      2,260
      447
      41
      1
      1,969
      88
      443
      26
      0
      1
      1970-01-01T00:24:43
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,570
      thundernest/k-9/5546/5545
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/5545
      https://github.com/thundernest/k-9/pull/5546
      https://github.com/thundernest/k-9/pull/5546
      1
      fixes
      v5.802 doesn't retract android notification on delete of unread message
      **Describe the bug** Separate IMAP client deletes unread message, v5.802 does not retract New Message notification previously posted when IMAP PUSH saw new msg arrive **To Reproduce** 1. send message to an account watched via IMAP PUSH by K-9 v5.802 2. K-9 posts a notification immediately (cool) 3. via another IMAP client (desktop, even K-9 v5.600 on another android), delete the message before marking it read 4. Android notification previously posted by K-9 v5.802 is not retracted and stays visible (note that v5.600 properly retracts in such a case) **Expected behavior** A message never marked read but deleted by another client should retract K-9's previously posted new-message notification. **Environment:** - K-9 Mail version: v5.802 - Android version: 8.0 // old, I know - Device: LG V20 // old, I know - Account type: IMAP (gmail) **Additional context** Note as mentioned above, v5.600 (K-9) does retract notifications in such cases A work-around that the end-user may practice is as follows: Whichever separate non-K9(v5.802) IMAP client is being used (desktop client of some form on another machine, K-9 v5.600 itself on another Android device), if you FIRST mark the newest message read, THEN delete that newest message, K-9 v5.802 DOES properly retract the previously posted new-msg android-notification. So I'm wondering if K-9 v5.802 could be changed to treat a message deletion (for a message just received and for which the android system notification was posted, and which is still an unread message) as experiencing both an "is read" and "is deleted" state change? I realize, having briefly scanned the issues list here that there are many challenges surrounding android notifications, and that this may not be an easy thing to track down and solve. I hope I've provided enough info. In summary: message arrives, remains new/unread, is deleted from another IMAP client, K-9 v5.802 leaves the android notif up (while 5.600 removes the notif under the same conditions). conversely: message arrives, remains new/unrerad, is first marked read from another IMAP client, then deleted from another IMAP client, K-9 v5.802 tears down the android notif previously posted for the new message.
      11c85745d0369db1b2d7e3a7bffbbf2ee6fbdc61
      04d68624ada65bc96ee8b5102f02d9022c7fdbe7
      https://github.com/thundernest/k-9/compare/11c85745d0369db1b2d7e3a7bffbbf2ee6fbdc61...04d68624ada65bc96ee8b5102f02d9022c7fdbe7
      diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java index d84f5ec96..716322605 100644 --- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -2775,6 +2775,11 @@ public class MessagingController { for (MessagingListener messagingListener : getListeners(listener)) { messagingListener.synchronizeMailboxRemovedMessage(account, folderServerId, messageServerId); } + + String accountUuid = account.getUuid(); + long folderId = getFolderIdOrThrow(account, folderServerId); + MessageReference messageReference = new MessageReference(accountUuid, folderId, messageServerId, null); + notificationController.removeNewMailNotification(account, messageReference); } @Override
      ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,505,728
      495,533
      69,968
      400
      335
      59
      5
      1
      2,263
      348
      532
      38
      0
      0
      1970-01-01T00:27:08
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,633
      thundernest/k-9/3315/3138
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/3138
      https://github.com/thundernest/k-9/pull/3315
      https://github.com/thundernest/k-9/pull/3315
      1
      fixes
      twitter background image - td element
      the background images (for previewing videos in the twitter e-mails) aren't displayed for some reason. [twitter.zip](https://github.com/k9mail/k-9/files/1667936/twitter.zip) Could you pls take a look? :) Regards, Djfe
      fd07e1a2264988f5c67f21cd92a88874dd11800c
      9cad669af8bc0a4c64e4b896beed6b21b15053b7
      https://github.com/thundernest/k-9/compare/fd07e1a2264988f5c67f21cd92a88874dd11800c...9cad669af8bc0a4c64e4b896beed6b21b15053b7
      diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java index 1707f7c9e..ad11115fc 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java +++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java @@ -17,13 +17,13 @@ public class HtmlSanitizer { .addAttributes("font", "color", "face", "size") .addAttributes("table", "align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "width") - .addAttributes("tr", "align", "bgcolor", "valign") + .addAttributes("tr", "align", "background", "bgcolor", "valign") .addAttributes("th", - "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted", - "valign", "width") + "align", "background", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", + "sorted", "valign", "width") .addAttributes("td", - "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", - "width") + "align", "background", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", + "valign", "width") .addAttributes("map", "name") .addAttributes("area", "shape", "coords", "href", "alt") .addProtocols("area", "href", "http", "https")
      ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,651,204
      716,146
      100,113
      503
      801
      189
      10
      1
      229
      25
      58
      9
      1
      0
      1970-01-01T00:25:23
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,650
      thundernest/k-9/2025/1908
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/1908
      https://github.com/thundernest/k-9/pull/2025
      https://github.com/thundernest/k-9/pull/2025
      1
      fixes
      Cannot zoom HTML messages properly if at all
      ### Expected behavior HTML mail should pinch zoom as it always has ### Actual behavior In 5.201 I tried zooming a few HTML emails. Nether would pinch zoom (though double tapping made them a tiny bit bigger). At least once this led to a crash of the app. I reverted to 5.010 and zoom works just fine with the same mail - in fact, it never had any such issue so I'm not upgrading until this is fixed. ### Steps to reproduce Open html email e.g. from Xbox.com Pinch zoom Either nothing happens, it moves a tiny bit, or it ends up crashing. ### Environment K-9 Mail version: 5.201 is broken for this. Works fine in 5.010 Android version: 7.0 on Nexus 6 IMAP
      217c61430d55949316a645d23f24717f7bc098bb
      c7c0ad0b7b77db1960dcf8956e54e549d9599644
      https://github.com/thundernest/k-9/compare/217c61430d55949316a645d23f24717f7bc098bb...c7c0ad0b7b77db1960dcf8956e54e549d9599644
      diff --git a/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java b/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java index 5897c3b22..d97ec9ced 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java +++ b/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java @@ -100,25 +100,14 @@ public class NonLockingScrollView extends ScrollView { @Override protected void onFinishInflate() { super.onFinishInflate(); - excludeChildrenFromInterceptions(this); + setupDelegationOfTouchAndHierarchyChangeEvents(); } - - /** - * Traverses the view tree for {@link WebView}s so they can be excluded from touch - * interceptions and receive all events. - */ - private void excludeChildrenFromInterceptions(View node) { - // If additional types of children should be excluded (e.g. horizontal scrolling banners), - // this needs to be modified accordingly. - if (node instanceof WebView) { - mChildrenNeedingAllTouches.add(node); - } else if (node instanceof ViewGroup) { - ViewGroup viewGroup = (ViewGroup) node; - final int childCount = viewGroup.getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = viewGroup.getChildAt(i); - excludeChildrenFromInterceptions(child); - } + + private void setupDelegationOfTouchAndHierarchyChangeEvents() { + OnHierarchyChangeListener listener = new HierarchyTreeChangeListener(); + setOnHierarchyChangeListener(listener); + for (int i = 0, childCount = getChildCount(); i < childCount; i++) { + listener.onChildViewAdded(this, getChildAt(i)); } } @@ -167,4 +156,32 @@ public class NonLockingScrollView extends ScrollView { super.requestChildFocus(child, focused); } } + + class HierarchyTreeChangeListener implements OnHierarchyChangeListener { + @Override + public void onChildViewAdded(View parent, View child) { + if (child instanceof WebView) { + mChildrenNeedingAllTouches.add(child); + } else if (child instanceof ViewGroup) { + ViewGroup childGroup = (ViewGroup) child; + childGroup.setOnHierarchyChangeListener(this); + for (int i = 0, childCount = childGroup.getChildCount(); i < childCount; i++) { + onChildViewAdded(childGroup, childGroup.getChildAt(i)); + } + } + } + + @Override + public void onChildViewRemoved(View parent, View child) { + if (child instanceof WebView) { + mChildrenNeedingAllTouches.remove(child); + } else if (child instanceof ViewGroup) { + ViewGroup childGroup = (ViewGroup) child; + for (int i = 0, childCount = childGroup.getChildCount(); i < childCount; i++) { + onChildViewRemoved(childGroup, childGroup.getChildAt(i)); + } + childGroup.setOnHierarchyChangeListener(null); + } + } + } }
      ['k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,455,680
      685,885
      94,555
      423
      2,536
      481
      53
      1
      681
      124
      170
      22
      0
      0
      1970-01-01T00:24:44
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,649
      thundernest/k-9/2037/1950
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/1950
      https://github.com/thundernest/k-9/pull/2037
      https://github.com/thundernest/k-9/pull/2037
      1
      fixes
      Contact auto selecting first item
      If there are "[email protected]" and "[email protected]" in my Contacts and i type "[email protected]" then app selects first entry from contacts and i cannot send email to "[email protected]". Previous versions allowed me type address and select one from suggestions if i want. Work around is to end the address with a comma & a space so new address object is created. K-9 Mail version: 5.201
      92196c012823b626d92e13349d160e8516e4abc2
      bb514f7140052ea9a0b85cb4ba34c275419c7013
      https://github.com/thundernest/k-9/compare/92196c012823b626d92e13349d160e8516e4abc2...bb514f7140052ea9a0b85cb4ba34c275419c7013
      diff --git a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java index 28ca83b25..bae224116 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java +++ b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java @@ -229,14 +229,9 @@ public class RecipientSelectView extends TokenCompleteTextView<Recipient> implem @Override public void performCompletion() { if (getListSelection() == ListView.INVALID_POSITION && enoughToFilter()) { - Object bestGuess; - if (getAdapter().getCount() > 0) { - bestGuess = getAdapter().getItem(0); - } else { - bestGuess = defaultObject(currentCompletionText()); - } - if (bestGuess != null) { - replaceText(convertSelectionToString(bestGuess)); + Object recipientText = defaultObject(currentCompletionText()); + if (recipientText != null) { + replaceText(convertSelectionToString(recipientText)); } } else { super.performCompletion();
      ['k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,456,480
      686,030
      94,572
      423
      532
      94
      11
      1
      409
      64
      91
      6
      0
      0
      1970-01-01T00:24:44
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,600
      thundernest/k-9/4931/4914
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4914
      https://github.com/thundernest/k-9/pull/4931
      https://github.com/thundernest/k-9/pull/4931
      1
      fixes
      Wrong OpenPGP key used when sending signed-only email
      I have recently noticed that if I set the sending of an email with the openpgp signature only option, I don't have the possibility to choose which identity to use. k9 v5.718 uses the first signature key available in openkeychain although it is not even that of the email from which I send. then an email is sent with the address xxx @ xxx signed by a yyyu @ yyy identity how to choose which signature key to use? I have no choices
      22cdb8c41fc58c865c853c6d7efc6db61724fbf0
      d718b33ef62c5b728a85ea563561f210aa1acfb3
      https://github.com/thundernest/k-9/compare/22cdb8c41fc58c865c853c6d7efc6db61724fbf0...d718b33ef62c5b728a85ea563561f210aa1acfb3
      diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java index a9e1ace70..66b261bed 100644 --- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java +++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java @@ -364,6 +364,7 @@ public class RecipientPresenter { public void onSwitchIdentity(Identity identity) { // TODO decide what actually to do on identity switch? + asyncUpdateCryptoStatus(); /* if (mIdentityChanged) { mBccWrapper.setVisibility(View.VISIBLE);
      ['app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,740,265
      540,532
      76,542
      417
      35
      6
      1
      1
      433
      83
      102
      1
      0
      0
      1970-01-01T00:26:38
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,601
      thundernest/k-9/4921/4918
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4918
      https://github.com/thundernest/k-9/pull/4921
      https://github.com/thundernest/k-9/pull/4921
      1
      fixes
      Umlauts in encrypted headings
      When I sent a mail with the heading "Test verschlüsselt", it after receiving it read "?ISO-8859-1?Q?Test_verschl=FCsselt_?=".
      753e03aa22a1f1d97e426f719de0844874ce7521
      bdbd8d98b2592d5dbf1e236ddeb81fd0dccb2444
      https://github.com/thundernest/k-9/compare/753e03aa22a1f1d97e426f719de0844874ce7521...bdbd8d98b2592d5dbf1e236ddeb81fd0dccb2444
      diff --git a/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java b/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java index 3d902654e..4499e955b 100644 --- a/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java +++ b/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java @@ -107,7 +107,7 @@ public class MessageViewInfoExtractor { boolean hasProtectedSubject = "v1".equalsIgnoreCase(protectedHeadersParam) && protectedSubjectHeader.length > 0; if (hasProtectedSubject) { - return protectedSubjectHeader[0]; + return MimeUtility.unfoldAndDecode(protectedSubjectHeader[0]); } return null;
      ['app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,785,395
      549,471
      77,730
      424
      122
      23
      2
      1
      126
      16
      42
      1
      0
      0
      1970-01-01T00:26:38
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,603
      thundernest/k-9/4795/4790
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4790
      https://github.com/thundernest/k-9/pull/4795
      https://github.com/thundernest/k-9/pull/4795
      2
      fixes
      Crash when attachment file is changed while TC document picker dialog is open
      ### Expected behavior error message "File not found" or Folder rescan when switching back to file picker (TC issue) ### Actual behavior short glimpse of mail editor with attached file, then app crash ### Steps to reproduce 1. Compose mail 2. open file attachment dialog 3. select "Total Commander" 5. navigate to folder X 6. Switch to some file browser and rename file Y in folder X 7. Switch back to K-9, select file Y (under old filename), attach - with "TotalCmd (file://url)" - nothing is attached - same with Picasa - stock album or "Simple Gallery" manage to attach the image anyway, but under a generic number ### Environment K-9 Mail version: 5.6 Android version: 7.1.1 Account type (IMAP, POP3, WebDAV/Exchange): IMAP Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here: [k9-log.txt](https://github.com/k9mail/k-9/files/4688569/k9-log.txt)
      b9eba6971fa86b95a4855caddbfa7144e5c23884
      a2287ce31cee3b6d229c782cc6cb00f6be0470d8
      https://github.com/thundernest/k-9/compare/b9eba6971fa86b95a4855caddbfa7144e5c23884...a2287ce31cee3b6d229c782cc6cb00f6be0470d8
      diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java index 1da4ce6e5..5c699dcf8 100644 --- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java +++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java @@ -60,6 +60,13 @@ public class AttachmentContentLoader extends AsyncTaskLoader<Attachment> { SafeContentResolver safeContentResolver = SafeContentResolver.newInstance(context); InputStream in = safeContentResolver.openInputStream(sourceAttachment.uri); + if (in == null) { + Timber.w("Error opening attachment for reading: %s", sourceAttachment.uri); + + cachedResultAttachment = sourceAttachment.deriveWithLoadCancelled(); + return cachedResultAttachment; + } + try { FileOutputStream out = new FileOutputStream(file); try {
      ['app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,831,249
      558,404
      78,943
      423
      276
      46
      7
      1
      947
      135
      246
      32
      2
      0
      1970-01-01T00:26:30
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,604
      thundernest/k-9/4743/4742
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4742
      https://github.com/thundernest/k-9/pull/4743
      https://github.com/thundernest/k-9/pull/4743
      1
      fixes
      when replying to a message, original message is not quoted
      ### Expected behavior upon selecting "reply" or "reply all", i expect the original email to be quoted in the compose message interface. (this was also the previous behavior before i updated to 5.711) ### Actual behavior the compose message interface is empty and looks like crafting a new message. ### Steps to reproduce 1. receive an email 2. reply to that email ### Environment K-9 Mail version: 5.711 Android version: 10 Account type: imap
      5a4a269926116a4f373699510bf868a848cdb8d8
      e830656d80c62f9d667a83aafde11cd1dc2d157c
      https://github.com/thundernest/k-9/compare/5a4a269926116a4f373699510bf868a848cdb8d8...e830656d80c62f9d667a83aafde11cd1dc2d157c
      diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java index bae37949f..ef0f6eb1a 100644 --- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -671,12 +671,6 @@ public class MessagingController { notificationController.showAuthenticationErrorNotification(account, incoming); } - private static void closeFolder(LocalFolder f) { - if (f != null) { - f.close(); - } - } - private void queuePendingCommand(Account account, PendingCommand command) { try { LocalStore localStore = localStoreProvider.getInstance(account); @@ -756,74 +750,70 @@ public class MessagingController { LocalStore localStore = localStoreProvider.getInstance(account); long folderId = command.folderId; LocalFolder localFolder = localStore.getFolder(folderId); - try { - localFolder.open(); - - String folderServerId = localFolder.getServerId(); - String uid = command.uid; + localFolder.open(); - LocalMessage localMessage = localFolder.getMessage(uid); - if (localMessage == null) { - return; - } + String folderServerId = localFolder.getServerId(); + String uid = command.uid; - if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { - //FIXME: This should never happen. Throw in debug builds. - return; - } + LocalMessage localMessage = localFolder.getMessage(uid); + if (localMessage == null) { + return; + } - Backend backend = getBackend(account); + if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { + //FIXME: This should never happen. Throw in debug builds. + return; + } - if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { - Timber.w("Local message with uid %s has flag %s already set, checking for remote message with " + - "same message id", localMessage.getUid(), X_REMOTE_COPY_STARTED); + Backend backend = getBackend(account); - String messageServerId = backend.findByMessageId(folderServerId, localMessage.getMessageId()); - if (messageServerId != null) { - Timber.w("Local message has flag %s already set, and there is a remote message with uid %s, " + - "assuming message was already copied and aborting this copy", - X_REMOTE_COPY_STARTED, messageServerId); + if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { + Timber.w("Local message with uid %s has flag %s already set, checking for remote message with " + + "same message id", localMessage.getUid(), X_REMOTE_COPY_STARTED); - String oldUid = localMessage.getUid(); - localMessage.setUid(messageServerId); - localFolder.changeUid(localMessage); + String messageServerId = backend.findByMessageId(folderServerId, localMessage.getMessageId()); + if (messageServerId != null) { + Timber.w("Local message has flag %s already set, and there is a remote message with uid %s, " + + "assuming message was already copied and aborting this copy", + X_REMOTE_COPY_STARTED, messageServerId); - for (MessagingListener l : getListeners()) { - l.messageUidChanged(account, folderId, oldUid, localMessage.getUid()); - } + String oldUid = localMessage.getUid(); + localMessage.setUid(messageServerId); + localFolder.changeUid(localMessage); - return; - } else { - Timber.w("No remote message with message-id found, proceeding with append"); + for (MessagingListener l : getListeners()) { + l.messageUidChanged(account, folderId, oldUid, localMessage.getUid()); } + + return; + } else { + Timber.w("No remote message with message-id found, proceeding with append"); } + } - /* - * If the message does not exist remotely we just upload it and then - * update our local copy with the new uid. - */ - FetchProfile fp = new FetchProfile(); - fp.add(FetchProfile.Item.BODY); - localFolder.fetch(Collections.singletonList(localMessage), fp, null); - String oldUid = localMessage.getUid(); - localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); + /* + * If the message does not exist remotely we just upload it and then + * update our local copy with the new uid. + */ + FetchProfile fp = new FetchProfile(); + fp.add(FetchProfile.Item.BODY); + localFolder.fetch(Collections.singletonList(localMessage), fp, null); + String oldUid = localMessage.getUid(); + localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); - String messageServerId = backend.uploadMessage(folderServerId, localMessage); + String messageServerId = backend.uploadMessage(folderServerId, localMessage); - if (messageServerId == null) { - // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded - // version will be downloaded during the next sync. - localFolder.destroyMessages(Collections.singletonList(localMessage)); - } else { - localMessage.setUid(messageServerId); - localFolder.changeUid(localMessage); + if (messageServerId == null) { + // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded + // version will be downloaded during the next sync. + localFolder.destroyMessages(Collections.singletonList(localMessage)); + } else { + localMessage.setUid(messageServerId); + localFolder.changeUid(localMessage); - for (MessagingListener l : getListeners()) { - l.messageUidChanged(account, folderId, oldUid, localMessage.getUid()); - } + for (MessagingListener l : getListeners()) { + l.messageUidChanged(account, folderId, oldUid, localMessage.getUid()); } - } finally { - localFolder.close(); } } @@ -1012,26 +1002,21 @@ public class MessagingController { LocalStore localStore = localStoreProvider.getInstance(account); LocalFolder localFolder = localStore.getFolder(command.folderId); - String folderServerId; - try { - localFolder.open(); - folderServerId = localFolder.getServerId(); + localFolder.open(); + String folderServerId = localFolder.getServerId(); - Timber.i("Marking all messages in %s:%s as read", account, folderServerId); + Timber.i("Marking all messages in %s:%s as read", account, folderServerId); - // TODO: Make this one database UPDATE operation - List<LocalMessage> messages = localFolder.getMessages(null, false); - for (Message message : messages) { - if (!message.isSet(Flag.SEEN)) { - message.setFlag(Flag.SEEN, true); - } + // TODO: Make this one database UPDATE operation + List<LocalMessage> messages = localFolder.getMessages(null, false); + for (Message message : messages) { + if (!message.isSet(Flag.SEEN)) { + message.setFlag(Flag.SEEN, true); } + } - for (MessagingListener l : getListeners()) { - l.folderStatusChanged(account, folderServerId); - } - } finally { - localFolder.close(); + for (MessagingListener l : getListeners()) { + l.folderStatusChanged(account, folderServerId); } Backend backend = getBackend(account); @@ -1137,10 +1122,9 @@ public class MessagingController { public void setFlag(Account account, long folderId, List<LocalMessage> messages, Flag flag, boolean newState) { // TODO: Put this into the background, but right now some callers depend on the message // objects being modified right after this method returns. - LocalFolder localFolder = null; try { LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(folderId); + LocalFolder localFolder = localStore.getFolder(folderId); localFolder.open(); // Update the messages in the local store @@ -1163,8 +1147,6 @@ public class MessagingController { processPendingCommands(account); } catch (MessagingException me) { throw new RuntimeException(me); - } finally { - closeFolder(localFolder); } } @@ -1172,10 +1154,9 @@ public class MessagingController { * Set or remove a flag for a message referenced by message UID. */ public void setFlag(Account account, long folderId, String uid, Flag flag, boolean newState) { - LocalFolder localFolder = null; try { LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(folderId); + LocalFolder localFolder = localStore.getFolder(folderId); localFolder.open(); LocalMessage message = localFolder.getMessage(uid); @@ -1184,8 +1165,6 @@ public class MessagingController { } } catch (MessagingException me) { throw new RuntimeException(me); - } finally { - closeFolder(localFolder); } } @@ -1214,10 +1193,9 @@ public class MessagingController { private void loadMessageRemoteSynchronous(Account account, long folderId, String uid, MessagingListener listener, boolean loadPartialFromSearch) { - LocalFolder localFolder = null; try { LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(folderId); + LocalFolder localFolder = localStore.getFolder(folderId); localFolder.open(); String folderServerId = localFolder.getServerId(); @@ -1265,8 +1243,6 @@ public class MessagingController { } notifyUserIfCertificateProblem(account, e, true); Timber.e(e, "Error while loading remote message"); - } finally { - closeFolder(localFolder); } } @@ -1284,7 +1260,6 @@ public class MessagingController { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(Collections.singletonList(message), fp, null); - localFolder.close(); notificationController.removeNewMailNotification(account, message.makeMessageReference()); markMessageAsReadOnView(account, message); @@ -1306,7 +1281,6 @@ public class MessagingController { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); localFolder.fetch(Collections.singletonList(message), fp, null); - localFolder.close(); return message; } @@ -1328,12 +1302,11 @@ public class MessagingController { put("loadAttachment", listener, new Runnable() { @Override public void run() { - LocalFolder localFolder = null; try { String folderServerId = message.getFolder().getServerId(); LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(folderServerId); + LocalFolder localFolder = localStore.getFolder(folderServerId); ProgressBodyFactory bodyFactory = new ProgressBodyFactory(new ProgressListener() { @Override @@ -1359,8 +1332,6 @@ public class MessagingController { l.loadAttachmentFailed(account, message, part, me.getMessage()); } notifyUserIfCertificateProblem(account, me, true); - } finally { - closeFolder(localFolder); } } }); @@ -1385,7 +1356,6 @@ public class MessagingController { if (plaintextSubject != null) { localMessage.setCachedDecryptedSubject(plaintextSubject); } - localFolder.close(); OutboxStateRepository outboxStateRepository = localStore.getOutboxStateRepository(); outboxStateRepository.initializeOutboxState(messageId); @@ -1454,9 +1424,8 @@ public class MessagingController { } private boolean messagesPendingSend(final Account account) { - LocalFolder localFolder = null; try { - localFolder = localStoreProvider.getInstance(account).getFolder(account.getOutboxFolderId()); + LocalFolder localFolder = localStoreProvider.getInstance(account).getFolder(account.getOutboxFolderId()); if (!localFolder.exists()) { return false; } @@ -1468,8 +1437,6 @@ public class MessagingController { } } catch (Exception e) { Timber.e(e, "Exception while checking for unsent messages"); - } finally { - closeFolder(localFolder); } return false; } @@ -1479,13 +1446,12 @@ public class MessagingController { */ @VisibleForTesting protected void sendPendingMessagesSynchronous(final Account account) { - LocalFolder localFolder = null; Exception lastFailure = null; boolean wasPermanentFailure = false; try { LocalStore localStore = localStoreProvider.getInstance(account); OutboxStateRepository outboxStateRepository = localStore.getOutboxStateRepository(); - localFolder = localStore.getFolder(account.getOutboxFolderId()); + LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderId()); if (!localFolder.exists()) { Timber.v("Outbox does not exist"); return; @@ -1614,7 +1580,6 @@ public class MessagingController { if (lastFailure == null) { notificationController.clearSendFailedNotification(account); } - closeFolder(localFolder); } } @@ -1885,7 +1850,6 @@ public class MessagingController { } public void deleteDraft(final Account account, long id) { - LocalFolder localFolder = null; try { Long folderId = account.getDraftsFolderId(); if (folderId == null) { @@ -1894,7 +1858,7 @@ public class MessagingController { } LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(folderId); + LocalFolder localFolder = localStore.getFolder(folderId); localFolder.open(); String uid = localFolder.getMessageUidById(id); if (uid != null) { @@ -1903,8 +1867,6 @@ public class MessagingController { } } catch (MessagingException me) { Timber.e(me, "Error deleting draft"); - } finally { - closeFolder(localFolder); } } @@ -2007,8 +1969,6 @@ public class MessagingController { private void deleteMessagesSynchronous(final Account account, final String folder, final List<LocalMessage> messages, MessagingListener listener) { - LocalFolder localFolder = null; - LocalFolder localTrashFolder = null; try { List<LocalMessage> localOnlyMessages = new ArrayList<>(); List<LocalMessage> syncedMessages = new ArrayList<>(); @@ -2026,12 +1986,13 @@ public class MessagingController { Backend backend = getBackend(account); LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(folder); + LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(); long folderId = localFolder.getDatabaseId(); Map<String, String> uidMap = null; Long trashFolderId = account.getTrashFolderId(); + LocalFolder localTrashFolder = null; if (!account.hasTrashFolder() || folderId == trashFolderId || (backend.getSupportsTrashFolder() && !backend.isDeleteMoveToTrash())) { Timber.d("Not moving deleted messages to local Trash folder. Removing local copies."); @@ -2097,9 +2058,6 @@ public class MessagingController { throw new UnavailableAccountException(e); } catch (MessagingException me) { throw new RuntimeException("Error deleting message from local store.", me); - } finally { - closeFolder(localFolder); - closeFolder(localTrashFolder); } } @@ -2139,7 +2097,6 @@ public class MessagingController { putBackground("emptyTrash", listener, new Runnable() { @Override public void run() { - LocalFolder localFolder = null; try { Long trashFolderId = account.getTrashFolderId(); if (trashFolderId == null) { @@ -2148,7 +2105,7 @@ public class MessagingController { } LocalStore localStore = localStoreProvider.getInstance(account); - localFolder = localStore.getFolder(trashFolderId); + LocalFolder localFolder = localStore.getFolder(trashFolderId); localFolder.open(); String trashFolderServerId = localFolder.getServerId(); @@ -2174,8 +2131,6 @@ public class MessagingController { throw new UnavailableAccountException(e); } catch (Exception e) { Timber.e(e, "emptyTrash failed"); - } finally { - closeFolder(localFolder); } } }); @@ -2189,9 +2144,8 @@ public class MessagingController { @VisibleForTesting protected void clearFolderSynchronous(Account account, long folderId) { - LocalFolder localFolder = null; try { - localFolder = localStoreProvider.getInstance(account).getFolder(folderId); + LocalFolder localFolder = localStoreProvider.getInstance(account).getFolder(folderId); localFolder.open(); localFolder.clearAllMessages(); } catch (UnavailableStorageException e) { @@ -2199,8 +2153,6 @@ public class MessagingController { throw new UnavailableAccountException(e); } catch (Exception e) { Timber.e(e, "clearFolder failed"); - } finally { - closeFolder(localFolder); } } diff --git a/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java b/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java index f3c797d1e..413f2f80b 100644 --- a/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java +++ b/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java @@ -60,7 +60,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -324,10 +323,6 @@ public class LocalFolder { boolean integrate = isIntegrate; } - public void close() { - databaseId = -1; - } - public int getMessageCount() throws MessagingException { try { return this.localStore.getDatabase().execute(false, new DbCallback<Integer>() { diff --git a/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java b/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java index f7d1df7d1..9aede2d19 100644 --- a/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java +++ b/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java @@ -196,7 +196,6 @@ public class RawMessageProvider extends ContentProvider { FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.BODY); localFolder.fetch(Collections.singletonList(message), fetchProfile, null); - localFolder.close(); return message; } catch (MessagingException e) { diff --git a/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java b/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java index d281594b4..895ca05ac 100644 --- a/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java +++ b/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java @@ -170,13 +170,6 @@ public class MessagingControllerTest extends K9RobolectricTest { verify(localFolder).clearAllMessages(); } - @Test - public void clearFolderSynchronous_shouldCloseTheFolder() throws MessagingException { - controller.clearFolderSynchronous(account, FOLDER_ID); - - verify(localFolder, atLeastOnce()).close(); - } - @Test(expected = UnavailableAccountException.class) public void clearFolderSynchronous_whenStorageUnavailable_shouldThrowUnavailableAccountException() throws MessagingException { doThrow(new UnavailableStorageException("Test")).when(localFolder).open(); @@ -184,18 +177,6 @@ public class MessagingControllerTest extends K9RobolectricTest { controller.clearFolderSynchronous(account, FOLDER_ID); } - @Test() - public void clearFolderSynchronous_whenExceptionThrown_shouldStillCloseFolder() throws MessagingException { - doThrow(new RuntimeException("Test")).when(localFolder).open(); - - try { - controller.clearFolderSynchronous(account, FOLDER_ID); - } catch (Exception ignored){ - } - - verify(localFolder, atLeastOnce()).close(); - } - @Test public void refreshRemoteSynchronous_shouldCallBackend() throws MessagingException { controller.refreshFolderListSynchronous(account);
      ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java', 'app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java', 'app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java', 'app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      2,834,763
      558,975
      79,051
      424
      10,104
      1,850
      196
      3
      473
      74
      104
      22
      0
      0
      1970-01-01T00:26:28
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,606
      thundernest/k-9/4702/4100
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4100
      https://github.com/thundernest/k-9/pull/4702
      https://github.com/thundernest/k-9/pull/4702
      1
      fixes
      Remove placeholder in database when message deletion on server is finished
      The "Clear messages (Dangerous!)" option in mailbox action popup menu suggests that ALL messages are deleted (either for privacy or to recreate corrupted mail-queue). However the placeholders are not deleted - exposing potentially sensitive information about deleted conversations. I dont know if the clear() method here is used only by "Remove messages (dangerous!)" sub-menu so I decided to open an issue rather than simply removing "deleted = 0" from here: https://github.com/k9mail/k-9/blob/c053964fefe1c758251aeab902563f8ec7dc454c/app/core/src/main/java/com/fsck/k9/mailstore/LocalStore.java#L327
      447dbe1bf0c977e6bab0d03659a5807586ad2da4
      d33643ba99aa50b2d5de5c37e2afe327e910a9ed
      https://github.com/thundernest/k-9/compare/447dbe1bf0c977e6bab0d03659a5807586ad2da4...d33643ba99aa50b2d5de5c37e2afe327e910a9ed
      diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java index 13a25745f..1c6dfe0a9 100644 --- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -40,6 +40,7 @@ import com.fsck.k9.K9.Intents; import com.fsck.k9.Preferences; import com.fsck.k9.backend.BackendManager; import com.fsck.k9.backend.api.Backend; +import com.fsck.k9.backend.api.BuildConfig; import com.fsck.k9.backend.api.SyncConfig; import com.fsck.k9.backend.api.SyncListener; import com.fsck.k9.cache.EmailProviderCache; @@ -881,10 +882,13 @@ public class MessagingController { throw new RuntimeException("Unsupported messaging operation"); } - if (operation != MoveOrCopyFlavor.COPY && backend.getSupportsExpunge() - && account.getExpungePolicy() == Expunge.EXPUNGE_IMMEDIATELY) { - Timber.i("processingPendingMoveOrCopy expunging folder %s:%s", account.getDescription(), srcFolderServerId); - backend.expungeMessages(srcFolderServerId, uids); + if (operation != MoveOrCopyFlavor.COPY) { + if (backend.getSupportsExpunge() && account.getExpungePolicy() == Expunge.EXPUNGE_IMMEDIATELY) { + Timber.i("processingPendingMoveOrCopy expunging folder %s:%s", account.getDescription(), srcFolderServerId); + backend.expungeMessages(srcFolderServerId, uids); + } + + destroyPlaceholderMessages(localSourceFolder, uids); } // TODO: Change Backend interface to ensure we never receive null for remoteUidMap @@ -917,6 +921,26 @@ public class MessagingController { } } + private void destroyPlaceholderMessages(LocalFolder localFolder, List<String> uids) throws MessagingException { + for (String uid : uids) { + LocalMessage placeholderMessage = localFolder.getMessage(uid); + if (placeholderMessage == null) { + continue; + } + + if (placeholderMessage.isSet(Flag.DELETED)) { + placeholderMessage.destroy(); + } else { + Timber.w("Expected local message %s in folder %s to be a placeholder, but DELETE flag wasn't set", + uid, localFolder.getServerId()); + + if (BuildConfig.DEBUG) { + throw new AssertionError("Placeholder message must have the DELETED flag set"); + } + } + } + } + private void queueSetFlag(Account account, long folderId, boolean newState, Flag flag, List<String> uids) { putBackground("queueSetFlag", null, () -> { PendingCommand command = PendingSetFlag.create(folderId, newState, flag, uids);
      ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,838,565
      559,204
      79,086
      425
      1,647
      326
      32
      1
      607
      71
      141
      5
      1
      0
      1970-01-01T00:26:27
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,608
      thundernest/k-9/4686/4678
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/4678
      https://github.com/thundernest/k-9/pull/4686
      https://github.com/thundernest/k-9/pull/4686
      1
      fixes
      POP3: trash folder remains empty
      Hi, When i delete a mail, the trash folder remains empty [log.txt](https://github.com/k9mail/k-9/files/4505545/log.txt) ### Expected behavior Deleted mail should be found in the trash folder ### Actual behavior No mail is found in the trash folder ### Steps to reproduce 1. delete a mail 2. go to the trash folder 3. see if the deleted mail is in the folder ### Environment K-9 Mail version: 5.708 Android version: 10 Account type (IMAP, POP3, WebDAV/Exchange): pop3
      2530dea98acd8df04bbcac37c6451fe27df111db
      d1c3cca21373ba79eed444c654660097668f9d46
      https://github.com/thundernest/k-9/compare/2530dea98acd8df04bbcac37c6451fe27df111db...d1c3cca21373ba79eed444c654660097668f9d46
      diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java index 337b8c54a..785bd60e5 100644 --- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -2034,7 +2034,7 @@ public class MessagingController { localFolder = localStore.getFolder(folder); Map<String, String> uidMap = null; if (folder.equals(account.getTrashFolder()) || !account.hasTrashFolder() || - !backend.isDeleteMoveToTrash()) { + (backend.getSupportsTrashFolder() && !backend.isDeleteMoveToTrash())) { Timber.d("Not moving deleted messages to local Trash folder. Removing local copies."); if (!localOnlyMessages.isEmpty()) {
      ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,835,761
      558,523
      78,991
      418
      147
      29
      2
      1
      496
      74
      132
      23
      1
      0
      1970-01-01T00:26:27
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,609
      thundernest/k-9/4683/2705
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2705
      https://github.com/thundernest/k-9/pull/4683
      https://github.com/thundernest/k-9/pull/4683
      1
      fixes
      Deleted mail from inbox is doubled in trash directory
      Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue ### Expected behavior When deleting one or more mails from inbox, I expect every deleted mail one time in trash directory. ### Actual behavior When deleting one or more mails from inbox, every deleted mail exist in trash two times. ### Steps to reproduce 1. Wait for incomaing mail (or send a test mail) 2. Delete a mail from inbox using symbol 'trash can' on left bottom. 3. Change to 'trash' directory. In first moment the deleted mail appears only one time. After short time the deleted mail appears a second time in trash directory. After manually syncing the doubled mail disappears - the mail is only shown one time. ### Environment K-9 Mail version: 5.207 I use the same email account with thunderbird on my desktop pc. These problems do not occur using thunderbird on pc. Android version: 7.0.0 Account type (IMAP, POP3, WebDAV/Exchange): It is an IMAP Account.
      2530dea98acd8df04bbcac37c6451fe27df111db
      2dccbb7c480a0e6435580533b6f0caefc177e7aa
      https://github.com/thundernest/k-9/compare/2530dea98acd8df04bbcac37c6451fe27df111db...2dccbb7c480a0e6435580533b6f0caefc177e7aa
      diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java index 337b8c54a..1e49338d9 100644 --- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -89,6 +89,7 @@ import timber.log.Timber; import static com.fsck.k9.K9.MAX_SEND_ATTEMPTS; import static com.fsck.k9.helper.ExceptionHelper.getRootCauseMessage; +import static com.fsck.k9.helper.Preconditions.checkNotNull; import static com.fsck.k9.mail.Flag.X_REMOTE_COPY_STARTED; import static com.fsck.k9.search.LocalSearchExtensions.getAccountsFromLocalSearch; @@ -843,10 +844,10 @@ public class MessagingController { @VisibleForTesting void processPendingMoveOrCopy(Account account, String srcFolder, String destFolder, List<String> uids, MoveOrCopyFlavor operation, Map<String, String> newUidMap) throws MessagingException { - LocalFolder localDestFolder; + checkNotNull(newUidMap); LocalStore localStore = localStoreProvider.getInstance(account); - localDestFolder = localStore.getFolder(destFolder); + LocalFolder localDestFolder = localStore.getFolder(destFolder); Backend backend = getBackend(account); @@ -871,28 +872,32 @@ public class MessagingController { backend.expungeMessages(srcFolder, uids); } - /* - * This next part is used to bring the local UIDs of the local destination folder - * upto speed with the remote UIDs of remote destination folder. - */ - if (newUidMap != null && remoteUidMap != null && !remoteUidMap.isEmpty()) { - Timber.i("processingPendingMoveOrCopy: changing local uids of %d messages", remoteUidMap.size()); - for (Entry<String, String> entry : remoteUidMap.entrySet()) { - String remoteSrcUid = entry.getKey(); - String newUid = entry.getValue(); - String localDestUid = newUidMap.get(remoteSrcUid); - if (localDestUid == null) { - continue; - } + // TODO: Change Backend interface to ensure we never receive null for remoteUidMap + if (remoteUidMap == null) { + remoteUidMap = Collections.emptyMap(); + } - Message localDestMessage = localDestFolder.getMessage(localDestUid); - if (localDestMessage != null) { - localDestMessage.setUid(newUid); - localDestFolder.changeUid((LocalMessage) localDestMessage); - for (MessagingListener l : getListeners()) { - l.messageUidChanged(account, destFolder, localDestUid, newUid); - } + // Update local messages (that currently have local UIDs) with new server IDs + for (String uid : uids) { + String localUid = newUidMap.get(uid); + String newUid = remoteUidMap.get(uid); + + LocalMessage localMessage = localDestFolder.getMessage(localUid); + if (localMessage == null) { + // Local message no longer exists + continue; + } + + if (newUid != null) { + // Update local message with new server ID + localMessage.setUid(newUid); + localDestFolder.changeUid(localMessage); + for (MessagingListener l : getListeners()) { + l.messageUidChanged(account, destFolder, localUid, newUid); } + } else { + // New server ID wasn't provided. Remove local message. + localMessage.destroy(); } } }
      ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      2,835,761
      558,523
      78,991
      418
      2,557
      484
      49
      1
      1,116
      177
      259
      27
      1
      0
      1970-01-01T00:26:27
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,643
      thundernest/k-9/2862/2856
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2856
      https://github.com/thundernest/k-9/pull/2862
      https://github.com/thundernest/k-9/pull/2862
      1
      fixes
      5.301 plain-text body rendering issues
      It appears that somewhere between 5.208 and 5.301 some issues were introduced in the rendering the body of (single-part) plain-text messages. For instance, a message that ends with: Davide ------------------------------------------------------------------------------ Check out the vibrant tech community on one of the world's most engaging tech sites, Slashdot.org! http://sdm.link/slashdot _______________________________________________ Bacula-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/bacula-users is displayed in 5.301 as: DavideCheck out the vibrant tech community on one of the world's most engaging tech sites, Slashdot.org! http://sdm.link/slashdotBacula-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/bacula-users If I forward the message from a 5.301 client the bottom text block is displayed correctly in the draft. There additionally appears to be a problem with hyperlinking. If the "http://" or "https://"" starts in column one it is not hyperlinked. If it starts in column 2+ it is. In 5.208 the message renders correctly and all "http://" and "https://" urls are hyperlinked regardless of their column start position.
      27bc562ebe37bc139b84c13142681dbfe5640688
      77f821cbbe5b6e01742fd8ba8f556a735b0e818a
      https://github.com/thundernest/k-9/compare/27bc562ebe37bc139b84c13142681dbfe5640688...77f821cbbe5b6e01742fd8ba8f556a735b0e818a
      diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java index 1b9cbf737..fc74be844 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java +++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java @@ -13,7 +13,7 @@ public class HtmlSanitizer { HtmlSanitizer() { Whitelist whitelist = Whitelist.relaxed() - .addTags("font") + .addTags("font", "hr") .addAttributes("table", "align", "bgcolor", "border", "cellpadding", "cellspacing", "width") .addAttributes(":all", "class", "style", "id") .addProtocols("img", "src", "http", "https", "cid", "data"); diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java index 23714a4e8..f4b86c2a1 100644 --- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java +++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java @@ -158,4 +158,13 @@ public class HtmlSanitizerTest { "<tr><td>Hmailserver service shutdown:</td><td>Ok</td></tr>" + "</tbody></table></body></html>", toCompactString(result)); } + + @Test + public void shouldKeepHrTags() throws Exception { + String html = "<html><head></head><body>one<hr>two<hr />three</body></html>"; + + Document result = htmlSanitizer.sanitize(html); + + assertEquals("<html><head></head><body>one<hr>two<hr>three</body></html>", toCompactString(result)); + } }
      ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,600,094
      707,876
      98,981
      484
      73
      17
      2
      1
      1,342
      148
      282
      29
      4
      0
      1970-01-01T00:25:08
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,642
      thundernest/k-9/2863/2861
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2861
      https://github.com/thundernest/k-9/pull/2863
      https://github.com/thundernest/k-9/pull/2863
      1
      fixes
      URL at the beginning of a line in plain text body isn't linkified
      This happens because we first convert the plain text to HTML and end up with something like: ```html <br>http://uri.example.org<br> ``` But right now only supported schemes preceded by a space, a newline, or an opening parenthesis are candidates for linkifying. https://github.com/k9mail/k-9/blob/27bc562ebe37bc139b84c13142681dbfe5640688/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java#L16
      27bc562ebe37bc139b84c13142681dbfe5640688
      2e20ddf6a5a5783ee483a5070eadf4c8b98a1ee2
      https://github.com/thundernest/k-9/compare/27bc562ebe37bc139b84c13142681dbfe5640688...2e20ddf6a5a5783ee483a5070eadf4c8b98a1ee2
      diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java b/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java index 815acc5ce..3d2565f27 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java +++ b/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java @@ -13,7 +13,7 @@ import android.text.TextUtils; public class UriLinkifier { private static final Pattern URI_SCHEME; private static final Map<String, UriParser> SUPPORTED_URIS; - private static final String SCHEME_SEPARATORS = " (\\\\n"; + private static final String SCHEME_SEPARATORS = " (\\\\n>"; private static final String ALLOWED_SEPARATORS_PATTERN = "(?:^|[" + SCHEME_SEPARATORS + "])"; static { diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java index 3b02dc035..81abbbb34 100644 --- a/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java +++ b/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java @@ -136,4 +136,13 @@ public class UriLinkifierTest { "<a href=\\"http://uri2.example.org/path\\">http://uri2.example.org/path</a> postfix", outputBuffer.toString()); } + + @Test + public void uriSurroundedByHtmlTags() { + String text = "<br>http://uri.example.org<hr>"; + + UriLinkifier.linkifyText(text, outputBuffer); + + assertEquals("<br><a href=\\"http://uri.example.org\\">http://uri.example.org</a><hr>", outputBuffer.toString()); + } }
      ['k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java', 'k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,600,094
      707,876
      98,981
      484
      124
      32
      2
      1
      416
      41
      108
      9
      2
      1
      1970-01-01T00:25:08
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,648
      thundernest/k-9/2203/2143
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2143
      https://github.com/thundernest/k-9/pull/2203
      https://github.com/thundernest/k-9/pull/2203
      1
      fixes
      Clear local messages -> freeze
      ### Expected behavior "Clear local messages" should clear the locally stored messages, allowing one to re-download the messages from the server. ### Actual behavior Freeze. ### Steps to reproduce 1. Have a folder with some large amount of messages. A few hundred should suffice. 2. Make sure it's NOT up-to-date with the server 3. Clear its local messages. ### Environment K-9 Mail version: 5.203 Android version: 6.0.1 Account type (IMAP, POP3, WebDAV/Exchange): IMAP
      c150bafac3aa1137376af532bba1b13dfac85fd2
      4161b914415aef08ab645387893812d13356bda3
      https://github.com/thundernest/k-9/compare/c150bafac3aa1137376af532bba1b13dfac85fd2...4161b914415aef08ab645387893812d13356bda3
      diff --git a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java index 4235018bf..203b6eb54 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java @@ -476,31 +476,9 @@ public class FolderList extends K9ListActivity { } private void onClearFolder(Account account, String folderName) { - // There has to be a cheaper way to get at the localFolder object than this - LocalFolder localFolder = null; - try { - if (account == null || folderName == null || !account.isAvailable(FolderList.this)) { - Log.i(K9.LOG_TAG, "not clear folder of unavailable account"); - return; - } - localFolder = account.getLocalStore().getFolder(folderName); - localFolder.open(Folder.OPEN_MODE_RW); - localFolder.clearAllMessages(); - } catch (Exception e) { - Log.e(K9.LOG_TAG, "Exception while clearing folder", e); - } finally { - if (localFolder != null) { - localFolder.close(); - } - } - - onRefresh(!REFRESH_REMOTE); + MessagingController.getInstance(getApplication()).clearFolder(account, folderName, mAdapter.mListener); } - - - - private void sendMail(Account account) { MessagingController.getInstance(getApplication()).sendPendingMessages(account, mAdapter.mListener); } diff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java index 3f0af1a22..51d1d8a23 100644 --- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -53,6 +53,7 @@ import com.fsck.k9.K9; import com.fsck.k9.K9.Intents; import com.fsck.k9.Preferences; import com.fsck.k9.R; +import com.fsck.k9.activity.ActivityListener; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.activity.setup.AccountSetupCheckSettings.CheckDirection; import com.fsck.k9.cache.EmailProviderCache; @@ -3513,6 +3514,36 @@ public class MessagingController { }); } + public void clearFolder(final Account account, final String folderName, final ActivityListener listener) { + putBackground("clearFolder", listener, new Runnable() { + @Override + public void run() { + clearFolderSynchronous(account, folderName, listener); + } + }); + } + + @VisibleForTesting + protected void clearFolderSynchronous(Account account, String folderName, MessagingListener listener) { + LocalFolder localFolder = null; + try { + localFolder = account.getLocalStore().getFolder(folderName); + localFolder.open(Folder.OPEN_MODE_RW); + localFolder.clearAllMessages(); + } catch (UnavailableStorageException e) { + Log.i(K9.LOG_TAG, "Failed to clear folder because storage is not available - trying again later."); + throw new UnavailableAccountException(e); + } catch (Exception e) { + Log.e(K9.LOG_TAG, "clearFolder failed", e); + addErrorMessage(account, null, e); + } finally { + closeFolder(localFolder); + } + + listFoldersSynchronous(account, false, listener); + } + + /** * Find out whether the account type only supports a local Trash folder. * diff --git a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java index e0254d7a1..8429a6cea 100644 --- a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java +++ b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java @@ -13,6 +13,7 @@ import android.content.Context; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; +import com.fsck.k9.K9; import com.fsck.k9.K9RobolectricTestRunner; import com.fsck.k9.Preferences; import com.fsck.k9.helper.Contacts; @@ -26,6 +27,7 @@ import com.fsck.k9.mail.Store; import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.mailstore.LocalStore; +import com.fsck.k9.mailstore.UnavailableStorageException; import com.fsck.k9.notification.NotificationController; import com.fsck.k9.search.LocalSearch; import org.junit.After; @@ -51,6 +53,7 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -80,6 +83,8 @@ public class MessagingControllerTest { @Mock private LocalFolder localFolder; @Mock + private LocalFolder errorFolder; + @Mock private Folder remoteFolder; @Mock private LocalStore localStore; @@ -130,6 +135,62 @@ public class MessagingControllerTest { controller.stop(); } + @Test + public void clearFolderSynchronous_shouldOpenFolderForWriting() throws MessagingException { + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + + verify(localFolder).open(Folder.OPEN_MODE_RW); + } + + @Test + public void clearFolderSynchronous_shouldClearAllMessagesInTheFolder() throws MessagingException { + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + + verify(localFolder).clearAllMessages(); + } + + @Test + public void clearFolderSynchronous_shouldCloseTheFolder() throws MessagingException { + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + + verify(localFolder, atLeastOnce()).close(); + } + + @Test(expected = UnavailableAccountException.class) + public void clearFolderSynchronous_whenStorageUnavailable_shouldThrowUnavailableAccountException() throws MessagingException { + doThrow(new UnavailableStorageException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW); + + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + } + + @Test() + public void clearFolderSynchronous_whenExceptionThrown_shouldAddErrorMessage() throws MessagingException { + doThrow(new RuntimeException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW); + + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + + verify(errorFolder).appendMessages(any(List.class)); + } + + @Test() + public void clearFolderSynchronous_whenExceptionThrown_shouldStillCloseFolder() throws MessagingException { + doThrow(new RuntimeException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW); + + try { + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + } catch (Exception ignored){ + } + + verify(localFolder, atLeastOnce()).close(); + } + + @Test() + public void clearFolderSynchronous_shouldListFolders() throws MessagingException { + controller.clearFolderSynchronous(account, FOLDER_NAME, listener); + + verify(listener, atLeastOnce()).listFoldersStarted(account); + } + @Test public void listFoldersSynchronous_shouldNotifyTheListenerListingStarted() throws MessagingException { List<LocalFolder> folders = Collections.singletonList(localFolder); @@ -758,11 +819,15 @@ public class MessagingControllerTest { when(account.getLocalStore()).thenReturn(localStore); when(account.getStats(any(Context.class))).thenReturn(accountStats); when(account.getMaximumAutoDownloadMessageSize()).thenReturn(MAXIMUM_SMALL_MESSAGE_SIZE); + when(account.getErrorFolderName()).thenReturn(K9.ERROR_FOLDER_NAME); + when(account.getEmail()).thenReturn("[email protected]"); } - private void configureLocalStore() { + private void configureLocalStore() throws MessagingException { when(localStore.getFolder(FOLDER_NAME)).thenReturn(localFolder); when(localFolder.getName()).thenReturn(FOLDER_NAME); + when(localStore.getFolder(K9.ERROR_FOLDER_NAME)).thenReturn(errorFolder); + when(localStore.getPersonalNamespaces(false)).thenReturn(Collections.singletonList(localFolder)); } private void configureRemoteStoreWithFolder() throws MessagingException {
      ['k9mail/src/main/java/com/fsck/k9/activity/FolderList.java', 'k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java', 'k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      3,476,576
      690,051
      95,154
      439
      2,165
      412
      55
      2
      491
      73
      120
      18
      0
      0
      1970-01-01T00:24:46
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,636
      thundernest/k-9/3174/2164
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2164
      https://github.com/thundernest/k-9/pull/3174
      https://github.com/thundernest/k-9/pull/3174
      1
      fixes
      Drafts deleted when syncronizing with IMAP server
      Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue ### Expected behavior When "Save as Draft" is selected, draft should be remain saved either locally or on the server for future access. ### Actual behavior Either draft is automatically completely deleted and no longer available upon server sync, or the draft remains in the "drafts" folder but when opening the compose window, the text is no longer available. It seems this is dependent on the encryption setting; everytime I re-open the draft I have to re-select "Don't encrypt" because the default is always "encrypt if possible". The last selection should be remembered. If "encypt if possible" or "encrypt" is selected, the draft is deleted upon sync. If not, I can often no longer access the draft text. This happens regardless of account, and only started after upgrading to the latest K9 version and adding my keys to OpenKeychain (I was using a much older version of K9 prior to this, not sure which). ### Steps to reproduce 1. Create a draft email with text in the body. 2. Select "don't encrypt" 3. Save draft by selecting either "save draft" or by pressing back and "save draft". 4. Text is gone after server sync. OR 1. Create a draft email with text in the body. 2. Select "encrypt" or "encrypt if possible". 3. Save draft by selecting either "save draft" or by pressing back and "save draft". 4. Draft is gone after server sync. ### Environment K-9 Mail version: 5.203 Android version: 5.1.1 Account type (IMAP, POP3, WebDAV/Exchange): IMAP
      3009752cac4a0f7ea6341bbef01e41cf4ab27963
      f4147483e14bc42c7544a6336b2e40d34b43ebb4
      https://github.com/thundernest/k-9/compare/3009752cac4a0f7ea6341bbef01e41cf4ab27963...f4147483e14bc42c7544a6336b2e40d34b43ebb4
      diff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java index 0f42badfa..718c6efe1 100644 --- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java +++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java @@ -898,7 +898,7 @@ public class MessagingController { if (account.syncRemoteDeletions()) { List<String> destroyMessageUids = new ArrayList<>(); for (String localMessageUid : localUidMap.keySet()) { - if (remoteUidMap.get(localMessageUid) == null) { + if (!localMessageUid.startsWith(K9.LOCAL_UID_PREFIX) && remoteUidMap.get(localMessageUid) == null) { destroyMessageUids.add(localMessageUid); } } @@ -1761,9 +1761,15 @@ public class MessagingController { localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(Collections.singletonList(localMessage)); - localFolder.changeUid(localMessage); - for (MessagingListener l : getListeners()) { - l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); + if (localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { + // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded + // version will be downloaded during the next sync. + localFolder.destroyMessages(Collections.singletonList(localMessage)); + } else { + localFolder.changeUid(localMessage); + for (MessagingListener l : getListeners()) { + l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); + } } } else { /* @@ -1796,10 +1802,17 @@ public class MessagingController { localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(Collections.singletonList(localMessage)); - localFolder.changeUid(localMessage); - for (MessagingListener l : getListeners()) { - l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); + if (localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { + // We didn't get the server UID of the uploaded message. Remove the local message now. The + // uploaded version will be downloaded during the next sync. + localFolder.destroyMessages(Collections.singletonList(localMessage)); + } else { + localFolder.changeUid(localMessage); + for (MessagingListener l : getListeners()) { + l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); + } } + if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); if (Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) { @@ -3172,9 +3185,8 @@ public class MessagingController { private void deleteMessagesSynchronous(final Account account, final String folder, final List<? extends Message> messages, MessagingListener listener) { - Folder localFolder = null; - Folder localTrashFolder = null; - List<String> uids = getUidsFromMessages(messages); + LocalFolder localFolder = null; + LocalFolder localTrashFolder = null; try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved @@ -3183,13 +3195,32 @@ public class MessagingController { l.messageDeleted(account, folder, message); } } - Store localStore = account.getLocalStore(); + + List<Message> localOnlyMessages = new ArrayList<>(); + List<Message> syncedMessages = new ArrayList<>(); + List<String> syncedMessageUids = new ArrayList<>(); + for (Message message : messages) { + String uid = message.getUid(); + if (uid.startsWith(K9.LOCAL_UID_PREFIX)) { + localOnlyMessages.add(message); + } else { + syncedMessages.add(message); + syncedMessageUids.add(uid); + } + } + + LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); Map<String, String> uidMap = null; if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) { Timber.d("Deleting messages in trash folder or trash set to -None-, not copying"); - localFolder.setFlags(messages, Collections.singleton(Flag.DELETED), true); + if (!localOnlyMessages.isEmpty()) { + localFolder.destroyMessages(localOnlyMessages); + } + if (!syncedMessages.isEmpty()) { + localFolder.setFlags(syncedMessages, Collections.singleton(Flag.DELETED), true); + } } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); if (!localTrashFolder.exists()) { @@ -3221,18 +3252,21 @@ public class MessagingController { queuePendingCommand(account, command); } processPendingCommands(account); - } else if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) { - if (folder.equals(account.getTrashFolderName())) { - queueSetFlag(account, folder, true, Flag.DELETED, uids); + } else if (!syncedMessageUids.isEmpty()) { + if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) { + if (folder.equals(account.getTrashFolderName())) { + queueSetFlag(account, folder, true, Flag.DELETED, syncedMessageUids); + } else { + queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, + syncedMessageUids, uidMap); + } + processPendingCommands(account); + } else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) { + queueSetFlag(account, folder, true, Flag.SEEN, syncedMessageUids); + processPendingCommands(account); } else { - queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap); + Timber.d("Delete policy %s prevents delete from server", account.getDeletePolicy()); } - processPendingCommands(account); - } else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) { - queueSetFlag(account, folder, true, Flag.SEEN, uids); - processPendingCommands(account); - } else { - Timber.d("Delete policy %s prevents delete from server", account.getDeletePolicy()); } unsuppressMessages(account, messages); diff --git a/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java b/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java index c16869c47..ebfa32872 100644 --- a/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java +++ b/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java @@ -227,7 +227,7 @@ class ImapSync { if (account.syncRemoteDeletions()) { List<String> destroyMessageUids = new ArrayList<>(); for (String localMessageUid : localUidMap.keySet()) { - if (remoteUidMap.get(localMessageUid) == null) { + if (!localMessageUid.startsWith(K9.LOCAL_UID_PREFIX) && remoteUidMap.get(localMessageUid) == null) { destroyMessageUids.add(localMessageUid); } }
      ['k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java', 'k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,643,983
      713,898
      99,791
      492
      5,025
      882
      80
      2
      1,696
      276
      400
      29
      1
      0
      1970-01-01T00:25:18
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,637
      thundernest/k-9/3146/3004
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/3004
      https://github.com/thundernest/k-9/pull/3146
      https://github.com/thundernest/k-9/pull/3146
      1
      fixes
      Body in decrypted mails empty by reply or forwarding
      ### Expected behavior If I click reply or forward, the body of the original mail should be filled with the whole original text and maybe attachments by forwarding . ### Actual behavior There is only the header (Mailadress and so on) and the subject line of the original mail ### Steps to reproduce 1. Receive a encrypted mail 2. Decrypt this mail 3. Click reply or forward 4. See there is no quote and no attachment (by forwarding) ### Environment K-9 Mail version: 5.400 Android version: 7.0 Account type (IMAP, POP3, WebDAV/Exchange): IMAP
      6767f41505e6e784af03befd1a122a99f771ead1
      8b11a7284ee2e4c2dd1c9b43d05859bcd3468187
      https://github.com/thundernest/k-9/compare/6767f41505e6e784af03befd1a122a99f771ead1...8b11a7284ee2e4c2dd1c9b43d05859bcd3468187
      diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java index 6d6daccf7..bda32a1fc 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java @@ -37,10 +37,10 @@ public class MessageViewInfo { this.extraAttachments = extraAttachments; } - static MessageViewInfo createWithExtractedContent(Message message, boolean isMessageIncomplete, + static MessageViewInfo createWithExtractedContent(Message message, Part rootPart, boolean isMessageIncomplete, String text, List<AttachmentViewInfo> attachments, AttachmentResolver attachmentResolver) { return new MessageViewInfo( - message, isMessageIncomplete, message, text, attachments, null, attachmentResolver, null, + message, isMessageIncomplete, rootPart, text, attachments, null, attachmentResolver, null, Collections.<AttachmentViewInfo>emptyList()); } diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java index 975b56686..9956c2b9b 100644 --- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java +++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java @@ -124,7 +124,7 @@ public class MessageViewInfoExtractor { !message.isSet(Flag.X_DOWNLOADED_FULL) || MessageExtractor.hasMissingParts(message); return MessageViewInfo.createWithExtractedContent( - message, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver); + message, contentPart, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver); } private ViewableExtractedText extractViewableAndAttachments(List<Part> parts, diff --git a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java index a74910994..eae6f7aca 100644 --- a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java +++ b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java @@ -406,6 +406,8 @@ public class MessageViewInfoExtractorTest { assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text); assertSame(annotation, messageViewInfo.cryptoResultAnnotation); + assertSame(message, messageViewInfo.message); + assertSame(message, messageViewInfo.rootPart); assertTrue(messageViewInfo.attachments.isEmpty()); assertTrue(messageViewInfo.extraAttachments.isEmpty()); } @@ -427,6 +429,8 @@ public class MessageViewInfoExtractorTest { assertEquals("<pre class=\\"k9mail\\">replacement text</pre>", messageViewInfo.text); assertSame(annotation, messageViewInfo.cryptoResultAnnotation); + assertSame(message, messageViewInfo.message); + assertSame(replacementPart, messageViewInfo.rootPart); assertTrue(messageViewInfo.attachments.isEmpty()); assertTrue(messageViewInfo.extraAttachments.isEmpty()); }
      ['k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java', 'k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      3,656,715
      717,769
      100,395
      492
      643
      118
      6
      2
      566
      93
      137
      19
      0
      0
      1970-01-01T00:25:17
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,638
      thundernest/k-9/3130/3129
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/3129
      https://github.com/thundernest/k-9/pull/3130
      https://github.com/thundernest/k-9/pull/3130
      1
      fixes
      App crashes when I click on contact logo
      Hi, I've not found a recent issue related to my issue. Thanks for your answer ### Expected behavior It should be create a new message with the clicked contact, as recipient. ### Actual behavior Since the update, the app crashes when I click on contact logo square. ### Steps to reproduce 1. Open the app 2. Click on the logo square of any email 3. The app will crash ### Environment K-9 Mail version: 5.403 Android version: 5.1 with Flyme 6.2.0.0A Account type (IMAP, POP3, WebDAV/Exchange): IMAP with Gmail
      7c3b90b356ffe045c27b2ab5ceb0a4db3381a7b9
      2ec1b3fe29aa8ce745acd03169f70cf0978c5b20
      https://github.com/thundernest/k-9/compare/7c3b90b356ffe045c27b2ab5ceb0a4db3381a7b9...2ec1b3fe29aa8ce745acd03169f70cf0978c5b20
      diff --git a/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java b/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java index fbea32426..6a09fedca 100644 --- a/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java +++ b/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java @@ -1,6 +1,7 @@ package com.fsck.k9.ui; +import android.content.ActivityNotFoundException; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.Context; @@ -20,6 +21,9 @@ import android.view.View.OnClickListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.ImageView; +import android.widget.Toast; + +import com.fsck.k9.R; /** @@ -207,10 +211,14 @@ public class ContactBadge extends ImageView implements OnClickListener { getContext(), ContactBadge.this, lookupUri, QuickContact.MODE_LARGE, null); } else if (createUri != null) { // Prompt user to add this person to contacts - final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri); - extras.remove(EXTRA_URI_CONTENT); - intent.putExtras(extras); - getContext().startActivity(intent); + try { + final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri); + extras.remove(EXTRA_URI_CONTENT); + intent.putExtras(extras); + getContext().startActivity(intent); + } catch (ActivityNotFoundException e) { + Toast.makeText(getContext(), R.string.error_activity_not_found, Toast.LENGTH_LONG).show(); + } } } }
      ['k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,656,975
      718,237
      100,405
      492
      814
      131
      16
      1
      537
      89
      140
      23
      0
      0
      1970-01-01T00:25:16
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,639
      thundernest/k-9/3073/3065
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/3065
      https://github.com/thundernest/k-9/pull/3073
      https://github.com/thundernest/k-9/pull/3073
      1
      fixes
      tel URI links are stripped by HtmlSanitizer
      Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue ### Expected behavior Tell us what should happen Click to call link does not work since a few weeks. A click to call link is a hyperlink which is opened by a dialer-application. For Exampel: `<a href="tel:004955555">55555</a>` ### Actual behavior Tell us what happens instead Link is shown as plain text ### Steps to reproduce 1. Create a new mail with html code` <a href="tel:004955555">55555</a>` in it 2. Check for new mails in an old version of k9, or in thunderbird and look for the link 3. Check with current k9 mail, link is shown as plain-text. ### Environment K-9 Mail version: current 5.403 Android version: 7.0 (motorola) and 7.1.2 (lineage) verified Account type (IMAP, POP3, WebDAV/Exchange): does not matter
      e4467ef959d5dc13d84afb9e49029cc6676fe6f5
      11f6614a3b63371e2ce8b7d41623692990de2930
      https://github.com/thundernest/k-9/compare/e4467ef959d5dc13d84afb9e49029cc6676fe6f5...11f6614a3b63371e2ce8b7d41623692990de2930
      diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java index 63e9eaedb..2b197857a 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java +++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java @@ -25,7 +25,8 @@ public class HtmlSanitizer { "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width") .addAttributes(":all", "class", "style", "id") - .addProtocols("img", "src", "http", "https", "cid", "data"); + .addProtocols("img", "src", "http", "https", "cid", "data") + .addProtocols("a", "href", "tel", "sip", "bitcoin", "ethereum", "rtsp"); cleaner = new Cleaner(whitelist); headCleaner = new HeadCleaner(); diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java index 38d8d6e4f..3e9f6bf9c 100644 --- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java +++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java @@ -213,4 +213,31 @@ public class HtmlSanitizerTest { "<center><font face=\\"Arial\\" color=\\"red\\" size=\\"12\\">A</font></center>" + "</body></html>", toCompactString(result)); } + + @Test + public void shouldKeepUris() { + String html = "<html><body>" + + "<a href=\\"http://example.com/index.html\\">HTTP</a>" + + "<a href=\\"https://example.com/default.html\\">HTTPS</a>" + + "<a href=\\"mailto:[email protected]\\">Mailto</a>" + + "<a href=\\"tel:00442079460111\\">Telephone</a>" + + "<a href=\\"sip:[email protected]\\">SIP</a>" + + "<a href=\\"bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu\\">Bitcoin</a>" + + "<a href=\\"ethereum:0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7\\">Ethereum</a>" + + "<a href=\\"rtsp://example.com/media.mp4\\">RTSP</a>" + + "</body></html>"; + + Document result = htmlSanitizer.sanitize(html); + + assertEquals("<html><head></head><body>" + + "<a href=\\"http://example.com/index.html\\">HTTP</a>" + + "<a href=\\"https://example.com/default.html\\">HTTPS</a>" + + "<a href=\\"mailto:[email protected]\\">Mailto</a>" + + "<a href=\\"tel:00442079460111\\">Telephone</a>" + + "<a href=\\"sip:[email protected]\\">SIP</a>" + + "<a href=\\"bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu\\">Bitcoin</a>" + + "<a href=\\"ethereum:0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7\\">Ethereum</a>" + + "<a href=\\"rtsp://example.com/media.mp4\\">RTSP</a>" + + "</body></html>", toCompactString(result)); + } }
      ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,654,448
      717,970
      100,340
      492
      244
      73
      3
      1
      952
      147
      256
      24
      1
      0
      1970-01-01T00:25:15
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,647
      thundernest/k-9/2215/1500
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/1500
      https://github.com/thundernest/k-9/pull/2215
      https://github.com/thundernest/k-9/pull/2215
      1
      fix
      Webdav (Exchange) sending email is broken since v5.109 (alpha)
      Android version: 6.01 Using K-9 Mail v5.010 (stable) i could send emails using my old WEBDAV account. But never delete emails on the server. Then Updated to K-9 Mail v5.109 (alpha) / and also to K-9 Mail v5.110 (alpha). Now I can delete emails on the server, but I can not send emails any more. They end up on the outgoing folder. Sorry I can't tell you the error message. The message text is too long so it's truncated... Then Downgraded (titanium Backup / also the database) and sending emails is working again.
      c150bafac3aa1137376af532bba1b13dfac85fd2
      2cec47491d963b0e7493469aba1bf9497ccf2678
      https://github.com/thundernest/k-9/compare/c150bafac3aa1137376af532bba1b13dfac85fd2...2cec47491d963b0e7493469aba1bf9497ccf2678
      diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java index 7eda5d5b3..0f7d8da1b 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java @@ -27,6 +27,7 @@ import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -678,28 +679,8 @@ class WebDavFolder extends Folder<WebDavMessage> { Log.i(LOG_TAG, "Uploading message as " + messageURL); - httpmethod = new HttpGeneric(messageURL); - httpmethod.setMethod("PUT"); - httpmethod.setEntity(bodyEntity); + store.sendRequest(messageURL, "PUT", bodyEntity, null, true); - String mAuthString = store.getAuthString(); - - if (mAuthString != null) { - httpmethod.setHeader("Authorization", mAuthString); - } - - response = httpclient.executeOverride(httpmethod, store.getContext()); - statusCode = response.getStatusLine().getStatusCode(); - - if (statusCode < 200 || - statusCode > 300) { - - //TODO: Could we handle a login timeout here? - - throw new IOException("Error with status code " + statusCode - + " while sending/appending message. Response = " - + response.getStatusLine().toString() + " for message " + messageURL); - } WebDavMessage retMessage = new WebDavMessage(message.getUid(), this); retMessage.setUrl(messageURL); diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java index 3132904b3..44ed5fa04 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java @@ -830,7 +830,7 @@ public class WebDavStore extends RemoteStore { return mHttpClient; } - private InputStream sendRequest(String url, String method, StringEntity messageBody, + protected InputStream sendRequest(String url, String method, StringEntity messageBody, Map<String, String> headers, boolean tryAuth) throws MessagingException { if (url == null || method == null) { diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java index 69b18552a..e9a6d1a25 100644 --- a/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java +++ b/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java @@ -12,6 +12,7 @@ import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.BasicHttpEntity; +import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HttpContext; import org.junit.Before; import org.junit.Test; @@ -37,6 +38,7 @@ import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyMapOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -75,10 +77,16 @@ public class WebDavFolderTest { private StatusLine mockStatusLine; @Captor private ArgumentCaptor<Map<String, String>> headerCaptor; + @Captor + private ArgumentCaptor<String> urlCaptor; + @Captor + private ArgumentCaptor<StringEntity> entityCaptor; private WebDavFolder folder; private WebDavFolder destinationFolder; + private String storeUrl = "https://localhost/webDavStoreUrl"; + private String folderName = "testFolder"; private String moveOrCopyXml = "<xml>MoveOrCopyXml</xml>"; private HashMap<String, String> moveOrCopyHeaders; private List<WebDavMessage> messages; @@ -86,10 +94,10 @@ public class WebDavFolderTest { @Before public void before() throws MessagingException, IOException { MockitoAnnotations.initMocks(this); - when(mockStore.getUrl()).thenReturn("https://localhost/webDavStoreUrl"); + when(mockStore.getUrl()).thenReturn(storeUrl); when(mockStore.getHttpClient()).thenReturn(mockHttpClient); when(mockStore.getStoreConfig()).thenReturn(mockStoreConfig); - folder = new WebDavFolder(mockStore, "testFolder"); + folder = new WebDavFolder(mockStore, folderName); setupTempDirectory(); } @@ -514,9 +522,6 @@ public class WebDavFolderTest { @Test public void appendWebDavMessages_replaces_messages_with_WebDAV_versions() throws MessagingException, IOException { - when(mockHttpClient.executeOverride(any(HttpUriRequest.class), any(HttpContext.class))).thenReturn(mockHttpResponse); - when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine); - when(mockStatusLine.getStatusCode()).thenReturn(200); List<Message> existingMessages = new ArrayList<>(); Message existingMessage = mock(Message.class); existingMessages.add(existingMessage); @@ -529,4 +534,20 @@ public class WebDavFolderTest { assertEquals(WebDavMessage.class, response.get(0).getClass()); assertEquals(messageUid, response.get(0).getUid()); } + + @Test + public void appendWebDavMessages_sendsRequestUsingStore() throws MessagingException, IOException { + List<Message> existingMessages = new ArrayList<>(); + Message existingMessage = mock(Message.class); + existingMessages.add(existingMessage); + String messageUid = "testMessageUid"; + when(existingMessage.getUid()).thenReturn(messageUid); + + folder.appendWebDavMessages(existingMessages); + + verify(mockStore).sendRequest(urlCaptor.capture(), eq("PUT"), entityCaptor.capture(), + Matchers.<Map<String, String>>eq(null), eq(true)); + assertTrue(urlCaptor.getValue().startsWith(storeUrl + "/" + folderName + "/" + messageUid)); + assertTrue(urlCaptor.getValue().endsWith(".eml")); + } }
      ['k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      3,476,576
      690,051
      95,154
      439
      1,247
      207
      25
      2
      516
      93
      136
      11
      0
      0
      1970-01-01T00:24:46
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,646
      thundernest/k-9/2380/2282
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2282
      https://github.com/thundernest/k-9/pull/2380
      https://github.com/thundernest/k-9/pull/2380
      1
      fixes
      Crash in 5.205: Bug in ParcelableUtil.unmarshall()?
      Crash reported via Google Play. User messages: * crash when opening from 1x1 widget * using inbox icon to start k9 results in crash * force closes on start from widget ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.NullPointerException: Attempt to get length of null array at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) at android.app.ActivityThread.access$1100(ActivityThread.java:221) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7224) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.NullPointerException: Attempt to get length of null array at com.fsck.k9.helper.ParcelableUtil.unmarshall(ParcelableUtil.java:27) at com.fsck.k9.helper.ParcelableUtil.unmarshall(ParcelableUtil.java:19) at com.fsck.k9.activity.MessageList.decodeExtras(MessageList.java:437) at com.fsck.k9.activity.MessageList.onCreate(MessageList.java:225) at android.app.Activity.performCreate(Activity.java:6876) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206) ... 9 more ```
      7880e8396e9f4674a3728543742eec64ad389242
      5485f7a1bb8c5d816706e58b35a176cfd79c7de9
      https://github.com/thundernest/k-9/compare/7880e8396e9f4674a3728543742eec64ad389242...5485f7a1bb8c5d816706e58b35a176cfd79c7de9
      diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java index f1addf57f..28f4c0df3 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java @@ -72,8 +72,11 @@ public class MessageList extends K9Activity implements MessageListFragmentListen MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener, OnSwitchCompleteListener { - // for this activity - private static final String EXTRA_SEARCH = "search"; + @Deprecated + //TODO: Remove after 2017-09-11 + private static final String EXTRA_SEARCH_OLD = "search"; + + private static final String EXTRA_SEARCH = "search_bytes"; private static final String EXTRA_NO_THREADING = "no_threading"; private static final String ACTION_SHORTCUT = "shortcut"; @@ -431,6 +434,9 @@ public class MessageList extends K9Activity implements MessageListFragmentListen mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS); } } + } else if (intent.hasExtra(EXTRA_SEARCH_OLD)) { + mSearch = intent.getParcelableExtra(EXTRA_SEARCH_OLD); + mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false); } else { // regular LocalSearch object was passed mSearch = intent.hasExtra(EXTRA_SEARCH) ?
      ['k9mail/src/main/java/com/fsck/k9/activity/MessageList.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,498,297
      692,380
      95,953
      446
      469
      104
      10
      1
      1,647
      95
      371
      30
      0
      1
      1970-01-01T00:24:49
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,645
      thundernest/k-9/2521/2503
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2503
      https://github.com/thundernest/k-9/pull/2521
      https://github.com/thundernest/k-9/pull/2521
      1
      fixes
      Export settings does not export 'Support signing of unecrypted mail' setting
      If I set 'Support signing of unecrypted mail' option, then export the settings, then clear K9 mail app. data, then import the settings, the 'Support signing of unecrypted mail' option does not get set.
      231b46f27839f599d95ef3f62cd66f4a20e0e62e
      35a29ec4560a031c6ada2849be987aee08108e60
      https://github.com/thundernest/k-9/compare/231b46f27839f599d95ef3f62cd66f4a20e0e62e...35a29ec4560a031c6ada2849be987aee08108e60
      diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java b/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java index 14c77e63e..f1a799ed9 100644 --- a/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java +++ b/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java @@ -285,10 +285,10 @@ public class GlobalSettings { s.put("pgpSignOnlyDialogCounter", Settings.versions( new V(45, new IntegerRangeSetting(0, Integer.MAX_VALUE, 0)) )); - s.put("openpgpProvider", Settings.versions( + s.put("openPgpProvider", Settings.versions( new V(46, new StringSetting(K9.NO_OPENPGP_PROVIDER)) )); - s.put("openpgpSupportSignOnly", Settings.versions( + s.put("openPgpSupportSignOnly", Settings.versions( new V(47, new BooleanSetting(false)) ));
      ['k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      3,519,596
      691,880
      96,815
      464
      225
      56
      4
      1
      201
      34
      49
      1
      0
      0
      1970-01-01T00:24:53
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,640
      thundernest/k-9/3025/3018
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/3018
      https://github.com/thundernest/k-9/pull/3025
      https://github.com/thundernest/k-9/pull/3025
      1
      fixes
      Bad <hr> detection causes emails to appear empty
      Some emails displayed empty, despite there is text in the email body. Note: Email preview in notification window shows (part) of body; but email body seems empty in K9. This behavior has been introduced with the latest K9 update a few days ago. ### Expected behavior Email displayed correctly. ### Actual behavior Email shown empty. When using "Reply" on the mail, no email body is shown, the wait cursor is shown indefinitely. ### Steps to reproduce Not sure why some emails get not displayed. I could provide the emails not correctly shown if needed. ### Environment K-9 Mail version: 5.400 Android version: 7.1.1 and also 4.4.4 Account type (IMAP, POP3, WebDAV/Exchange): POP3
      1506c6d4c028586da0cac60d0688f6a2493ed1e5
      b49af84dc803c361244ece7e0333787d2e321573
      https://github.com/thundernest/k-9/compare/1506c6d4c028586da0cac60d0688f6a2493ed1e5...b49af84dc803c361244ece7e0333787d2e321573
      diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java index 9d5d27aa4..fb618e80d 100644 --- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java +++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java @@ -5,7 +5,6 @@ import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Set; -import java.util.regex.Pattern; import android.text.Annotation; import android.text.Editable; @@ -179,11 +178,6 @@ public class HtmlConverter { "style=\\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid $$COLOR$$; padding-left: 1ex;\\">"; private static final String HTML_BLOCKQUOTE_END = "</blockquote>"; private static final String HTML_NEWLINE = "<br />"; - private static final Pattern ASCII_PATTERN_FOR_HR = Pattern.compile( - "(^|\\\\Q" + HTML_NEWLINE + "\\\\E)\\\\s*((\\\\Q" + HTML_NEWLINE + "\\\\E)*" + - "((((\\\\Q" + HTML_NEWLINE + "\\\\E){0,2}([-=_]{3,})(\\\\Q" + HTML_NEWLINE + - "\\\\E){0,2})|(([-=_]{2,} ?)(8&lt;|<gt>8|%&lt;|<gt>%)" + - "( ?[-=_]{2,})))+(\\\\Q" + HTML_NEWLINE + "\\\\E|$)))"); /** * Convert a text string into an HTML document. @@ -276,7 +270,7 @@ public class HtmlConverter { HTML_BLOCKQUOTE_END + "$1" ); - text = ASCII_PATTERN_FOR_HR.matcher(text).replaceAll("<hr>"); + text = text.replaceAll("\\\\s*([-=_]{30,}+)\\\\s*", "<hr>"); StringBuffer sb = new StringBuffer(text.length() + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH); diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java index 9cd79b53d..b2dca89a9 100644 --- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java +++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java @@ -8,6 +8,7 @@ import java.io.IOException; import com.fsck.k9.K9RobolectricTestRunner; import org.apache.commons.io.IOUtils; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @@ -194,6 +195,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void issue2259Spec() { String text = "text\\n" + "---------------------------\\n" + @@ -225,6 +227,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void mergeConsecutiveBreaksIntoOne() { String text = "hello\\n------------\\n---------------\\nfoo bar"; String result = HtmlConverter.textToHtml(text); @@ -260,6 +263,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void anyTripletIsHRuledOut() { String text = "--=\\n-=-\\n===\\n___\\n\\n"; String result = HtmlConverter.textToHtml(text); @@ -267,6 +271,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void replaceSpaceSeparatedDashesWithHR() { String text = "hello\\n---------------------------\\nfoo bar"; String result = HtmlConverter.textToHtml(text); @@ -274,6 +279,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void replacementWithHRAtBeginning() { String text = "---------------------------\\nfoo bar"; String result = HtmlConverter.textToHtml(text); @@ -281,6 +287,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void replacementWithHRAtEnd() { String text = "hello\\n__________________________________"; String result = HtmlConverter.textToHtml(text); @@ -288,6 +295,7 @@ public class HtmlConverterTest { } @Test + @Ignore("Disabled due to temporary fix for issue #3018") public void replacementOfScissorsByHR() { String text = "hello\\n-- %< -------------- >8 --\\nworld\\n"; String result = HtmlConverter.textToHtml(text);
      ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,599,243
      707,505
      98,930
      484
      543
      178
      8
      1
      711
      112
      166
      23
      0
      0
      1970-01-01T00:25:14
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      9,641
      thundernest/k-9/2885/2846
      thundernest
      k-9
      https://github.com/thundernest/k-9/issues/2846
      https://github.com/thundernest/k-9/pull/2885
      https://github.com/thundernest/k-9/pull/2885
      1
      fixes
      Parsing email address list with invalid base64 encoded word crashes the app
      Test case: ```java Address.parse("=?utf-8?b?invalid#?= <[email protected]>"); ``` Exception: ``` java.lang.Error: java.io.IOException: Unexpected base64 byte at org.apache.james.mime4j.codec.DecoderUtil.decodeBase64(DecoderUtil.java:89) at org.apache.james.mime4j.codec.DecoderUtil.decodeB(DecoderUtil.java:106) at org.apache.james.mime4j.codec.DecoderUtil.tryDecodeEncodedWord(DecoderUtil.java:233) at org.apache.james.mime4j.codec.DecoderUtil.decodeEncodedWords(DecoderUtil.java:187) at org.apache.james.mime4j.codec.DecoderUtil.decodeEncodedWords(DecoderUtil.java:143) at org.apache.james.mime4j.field.address.Builder.buildAddress(Builder.java:71) at org.apache.james.mime4j.field.address.Builder.buildAddressList(Builder.java:51) at org.apache.james.mime4j.field.address.DefaultAddressParser.parseAddressList(DefaultAddressParser.java:69) at org.apache.james.mime4j.field.address.DefaultAddressParser.parseAddressList(DefaultAddressParser.java:73) at com.fsck.k9.mail.Address.parse(Address.java:145) [...] Caused by: java.io.IOException: Unexpected base64 byte at org.apache.james.mime4j.codec.Base64InputStream.read0(Base64InputStream.java:193) at org.apache.james.mime4j.codec.Base64InputStream.read(Base64InputStream.java:87) at org.apache.james.mime4j.codec.DecoderUtil.decodeBase64(DecoderUtil.java:80) ... 39 more ``` I'm not sure what the best way to handle this is. Probably using the personal part as is. However, the options in MIME4J are somewhat limited. It's either crashing with an `Error` or ignoring invalid characters when decoding the base64 payload. Since we don't like crashes we should probably start out with the latter option.
      d696723023d8eb2c5dde223fdbcef1d67bd49bb9
      ddcf1e257e43a9e08bb4bdcd237f93651c3651d5
      https://github.com/thundernest/k-9/compare/d696723023d8eb2c5dde223fdbcef1d67bd49bb9...ddcf1e257e43a9e08bb4bdcd237f93651c3651d5
      diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java b/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java index 042fbbf44..eb8183768 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java @@ -2,12 +2,14 @@ package com.fsck.k9.mail; import android.support.annotation.VisibleForTesting; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.apache.james.mime4j.MimeException; +import org.apache.james.mime4j.codec.DecodeMonitor; import org.apache.james.mime4j.codec.EncoderUtil; import org.apache.james.mime4j.dom.address.Mailbox; import org.apache.james.mime4j.dom.address.MailboxList; @@ -30,7 +32,6 @@ public class Address implements Serializable { private String mPersonal; - public Address(Address address) { mAddress = address.mAddress; mPersonal = address.mPersonal; @@ -142,7 +143,7 @@ public class Address implements Serializable { } List<Address> addresses = new ArrayList<>(); try { - MailboxList parsedList = DefaultAddressParser.DEFAULT.parseAddressList(addressList).flatten(); + MailboxList parsedList = DefaultAddressParser.DEFAULT.parseAddressList(addressList, DecodeMonitor.SILENT).flatten(); for (int i = 0, count = parsedList.size(); i < count; i++) { Mailbox mailbox = parsedList.get(i); diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java index 82a48be51..1fa329163 100644 --- a/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java +++ b/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java @@ -180,4 +180,10 @@ public class AddressTest { assertNull(result); } + + @Test + public void handlesInvalidBase64Encoding() throws Exception { + Address address = Address.parse("=?utf-8?b?invalid#?= <[email protected]>")[0]; + assertEquals("[email protected]", address.getAddress()); + } }
      ['k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/Address.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,600,355
      707,916
      98,987
      484
      296
      59
      5
      1
      1,711
      105
      408
      28
      0
      2
      1970-01-01T00:25:09
      8,156
      Kotlin
      {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946}
      Apache License 2.0
      670
      apache/shardingsphere-elasticjob/368/367
      apache
      shardingsphere-elasticjob
      https://github.com/apache/shardingsphere-elasticjob/issues/367
      https://github.com/apache/shardingsphere-elasticjob/pull/368
      https://github.com/apache/shardingsphere-elasticjob/pull/368
      1
      fixed
      Resuming Transient Job is abnormal
      ### Which version of Elastic-Job do you using? 2.1.4 ### Expected behavior Disable the job and then resume the job, then triggered by cron expression. ### Actual behavior Disable the job and then resume the job, immediately triggered several times. ### Steps to reproduce the behavior Disable the transient job(cron 0/30 * * * * ?) with "misfire" parameter, wait several minutes, then resume it.
      a3db7607ea9d33beb7b94c95ac0f56b7589d2b11
      064eca0ab1804af654599bb06eae2ad6a1e59ea5
      https://github.com/apache/shardingsphere-elasticjob/compare/a3db7607ea9d33beb7b94c95ac0f56b7589d2b11...064eca0ab1804af654599bb06eae2ad6a1e59ea5
      diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java index 0f9e58ae7..bccbb183a 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java @@ -70,7 +70,7 @@ public final class CloudJobConfigurationListener implements TreeCacheListener { if (!jobConfig.getTypeConfig().getCoreConfig().isMisfire()) { readyService.setMisfireDisabled(jobConfig.getJobName()); } - producerManager.reschedule(jobConfig); + producerManager.reschedule(jobConfig.getJobName()); } else if (isJobConfigNode(event, path, Type.NODE_REMOVED)) { String jobName = path.substring(CloudJobConfigurationNode.ROOT.length() + 1, path.length()); producerManager.unschedule(jobName); diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java index 527c58e1a..d27c36c53 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java @@ -172,12 +172,19 @@ public final class FacadeService { if (!jobConfigOptional.isPresent()) { return; } + if (isDisable(jobConfigOptional.get())) { + return; + } CloudJobConfiguration jobConfig = jobConfigOptional.get(); if (jobConfig.getTypeConfig().getCoreConfig().isFailover() || CloudJobExecutionType.DAEMON == jobConfig.getJobExecutionType()) { failoverService.add(taskContext); } } + private boolean isDisable(final CloudJobConfiguration jobConfiguration) { + return disableAppService.isDisabled(jobConfiguration.getAppName()) || disableJobService.isDisabled(jobConfiguration.getJobName()); + } + /** * 将瞬时作业放入待执行队列. * @@ -223,6 +230,13 @@ public final class FacadeService { * @param jobName 作业名称 */ public void addDaemonJobToReadyQueue(final String jobName) { + Optional<CloudJobConfiguration> jobConfigOptional = jobConfigService.load(jobName); + if (!jobConfigOptional.isPresent()) { + return; + } + if (isDisable(jobConfigOptional.get())) { + return; + } readyService.addDaemon(jobName); } diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java index 71d4c6d37..e681e656e 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java @@ -117,7 +117,7 @@ public final class ProducerManager { throw new JobConfigurationException("Cannot found job '%s', please register first.", jobConfig.getJobName()); } configService.update(jobConfig); - reschedule(jobConfig); + reschedule(jobConfig.getJobName()); } /** @@ -130,7 +130,6 @@ public final class ProducerManager { if (jobConfig.isPresent()) { disableJobService.remove(jobName); configService.remove(jobName); - transientProducerScheduler.deregister(jobConfig.get()); } unschedule(jobName); } @@ -162,16 +161,23 @@ public final class ProducerManager { } runningService.remove(jobName); readyService.remove(Lists.newArrayList(jobName)); + Optional<CloudJobConfiguration> jobConfig = configService.load(jobName); + if (jobConfig.isPresent()) { + transientProducerScheduler.deregister(jobConfig.get()); + } } /** * 重新调度作业. * - * @param jobConfig 作业配置 + * @param jobName 作业名称 */ - public void reschedule(final CloudJobConfiguration jobConfig) { - unschedule(jobConfig.getJobName()); - schedule(jobConfig); + public void reschedule(final String jobName) { + unschedule(jobName); + Optional<CloudJobConfiguration> jobConfig = configService.load(jobName); + if (jobConfig.isPresent()) { + schedule(jobConfig.get()); + } } /** diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java index bfb793cc0..93d379f9d 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java @@ -112,7 +112,7 @@ final class TransientProducerScheduler { return TriggerBuilder.newTrigger().withIdentity(cron).withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()).build(); } - void deregister(final CloudJobConfiguration jobConfig) { + synchronized void deregister(final CloudJobConfiguration jobConfig) { repository.remove(jobConfig.getJobName()); String cron = jobConfig.getTypeConfig().getCoreConfig().getCron(); if (!repository.containsKey(buildJobKey(cron))) { diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java index 5c2c7f6a2..9d849510e 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java @@ -186,6 +186,11 @@ public final class CloudAppRestfulApi { public void enable(@PathParam("appName") final String appName) throws JSONException { if (appConfigService.load(appName).isPresent()) { disableAppService.remove(appName); + for (CloudJobConfiguration each : jobConfigService.loadAll()) { + if (appName.equals(each.getAppName())) { + producerManager.reschedule(each.getJobName()); + } + } } } diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java index 2ad20f6db..2505b0435 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java @@ -184,8 +184,10 @@ public final class CloudJobRestfulApi { @DELETE @Path("/{jobName}/disable") public void enable(@PathParam("jobName") final String jobName) throws JSONException { - if (configService.load(jobName).isPresent()) { + Optional<CloudJobConfiguration> configOptional = configService.load(jobName); + if (configOptional.isPresent()) { facadeService.enableJob(jobName); + producerManager.reschedule(jobName); } } diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java index 99f7ae93e..e8dc9213b 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java @@ -58,7 +58,7 @@ public final class CloudJobConfigurationListenerTest { public void assertChildEventWhenDataIsNull() throws Exception { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, null)); verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any()); - verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any()); verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any()); } @@ -66,7 +66,7 @@ public final class CloudJobConfigurationListenerTest { public void assertChildEventWhenIsNotConfigPath() throws Exception { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/other/test_job", null, "".getBytes()))); verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any()); - verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any()); verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any()); } @@ -74,7 +74,7 @@ public final class CloudJobConfigurationListenerTest { public void assertChildEventWhenIsRootConfigPath() throws Exception { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_REMOVED, new ChildData("/config/job", null, "".getBytes()))); verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any()); - verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any()); verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any()); } @@ -82,7 +82,7 @@ public final class CloudJobConfigurationListenerTest { public void assertChildEventWhenStateIsAddAndIsConfigPathAndInvalidData() throws Exception { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, new ChildData("/config/job/test_job", null, "".getBytes()))); verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any()); - verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any()); verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any()); } @@ -96,7 +96,7 @@ public final class CloudJobConfigurationListenerTest { public void assertChildEventWhenStateIsUpdateAndIsConfigPathAndTransientJob() throws Exception { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson().getBytes()))); verify(readyService, times(0)).remove(Collections.singletonList("test_job")); - verify(producerManager).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager).reschedule(ArgumentMatchers.<String>any()); } @Test @@ -104,7 +104,7 @@ public final class CloudJobConfigurationListenerTest { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson(CloudJobExecutionType.DAEMON).getBytes()))); verify(readyService).remove(Collections.singletonList("test_job")); - verify(producerManager).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager).reschedule(ArgumentMatchers.<String>any()); } @Test @@ -112,7 +112,7 @@ public final class CloudJobConfigurationListenerTest { cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson(false).getBytes()))); verify(readyService).setMisfireDisabled("test_job"); - verify(producerManager).reschedule(ArgumentMatchers.<CloudJobConfiguration>any()); + verify(producerManager).reschedule(ArgumentMatchers.<String>any()); } @Test diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java index 35e44ccde..50cc09c4f 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java @@ -222,6 +222,7 @@ public final class FacadeServiceTest { @Test public void assertAddDaemonJobToReadyQueue() { + when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job"))); facadeService.addDaemonJobToReadyQueue("test_job"); verify(readyService).addDaemon("test_job"); } diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java index e1c902886..1956a5da2 100644 --- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java +++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java @@ -106,7 +106,7 @@ public final class CloudJobRestfulApiTest extends AbstractCloudRestfulApiTest { public void assertDeregister() throws Exception { when(getRegCenter().isExisted("/config/job/test_job")).thenReturn(false); assertThat(sentRequest("http://127.0.0.1:19000/api/job/deregister", "DELETE", "test_job"), is(204)); - verify(getRegCenter(), times(2)).get("/config/job/test_job"); + verify(getRegCenter(), times(3)).get("/config/job/test_job"); } @Test
      ['elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java']
      {'.java': 9}
      9
      9
      0
      0
      9
      841,618
      188,763
      24,229
      277
      2,092
      393
      45
      6
      411
      65
      93
      12
      0
      0
      1970-01-01T00:24:58
      7,920
      Java
      {'Java': 2266368, 'Shell': 3428, 'Dockerfile': 1094, 'Batchfile': 861}
      Apache License 2.0
      115
      spring-projects/spring-security/13276/13243
      spring-projects
      spring-security
      https://github.com/spring-projects/spring-security/issues/13243
      https://github.com/spring-projects/spring-security/pull/13276
      https://github.com/spring-projects/spring-security/pull/13276
      1
      fixes
      CasAuthenticationFilter.successfulAuthentication missing call to securityContextRepository.saveContext
      **Describe the bug** `org.springframework.security.cas.web.CasAuthenticationFilter.successfulAuthentication` seems to be missing a call to `securityContextRepository.saveContext` as per [the Spring 6 migration document](https://docs.spring.io/spring-security/reference/migration/servlet/session-management.html). I think this makes the filter completely unusable on Spring6/Boot3 and begs to question if the `CasAuthenticationFilter` code is production ready for Spring 6 otherwise. **To Reproduce** Use the filter **Expected behavior** SecurityContext is saved between requests :)
      537e10cf9c7feaf8c00d5523052823f3c469410d
      52b87f339c36eaa95d835f456aadd37425bbad02
      https://github.com/spring-projects/spring-security/compare/537e10cf9c7feaf8c00d5523052823f3c469410d...52b87f339c36eaa95d835f456aadd37425bbad02
      diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java index a951168f66..6f2920b3d0 100644 --- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java +++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java @@ -42,6 +42,7 @@ import org.springframework.security.web.authentication.AbstractAuthenticationPro import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; @@ -192,10 +193,12 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil private AuthenticationFailureHandler proxyFailureHandler = new SimpleUrlAuthenticationFailureHandler(); + private SecurityContextRepository securityContextRepository= new HttpSessionSecurityContextRepository(); + public CasAuthenticationFilter() { super("/login/cas"); setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()); - setSecurityContextRepository(new HttpSessionSecurityContextRepository()); + setSecurityContextRepository(this.securityContextRepository); } @Override @@ -211,6 +214,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authResult); SecurityContextHolder.setContext(context); + this.securityContextRepository.saveContext(context,request,response); if (this.eventPublisher != null) { this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); }
      ['cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      7,476,540
      1,614,247
      200,846
      1,671
      399
      56
      6
      1
      592
      57
      118
      9
      1
      0
      1970-01-01T00:28:05
      7,860
      Java
      {'Java': 16395664, 'Kotlin': 860788, 'Groovy': 47907, 'AspectJ': 16776, 'Ruby': 7008, 'PLSQL': 3180, 'XSLT': 2369, 'Shell': 811, 'Python': 129, 'HTML': 80, 'JavaScript': 10}
      Apache License 2.0
      51
      dropwizard/metrics/505/444
      dropwizard
      metrics
      https://github.com/dropwizard/metrics/issues/444
      https://github.com/dropwizard/metrics/pull/505
      https://github.com/dropwizard/metrics/pull/505
      1
      fix
      Another ClassCastException in metrics-jetty9's InstrumentedHandler
      I found another ClassCastException in metrics-jetty9. Commit 622ef9b which is included in 3.0.1 doesn't seem to completly fix issue #435 that I reported earlier. ``` java.lang.ClassCastException: org.atmosphere.cpr.AtmosphereRequest cannot be cast to org.eclipse.jetty.server.Request at com.codahale.metrics.jetty9.InstrumentedHandler$1.onComplete(InstrumentedHandler.java:140) ~[metrics-jetty9-3.0.1.jar:3.0.1] at org.eclipse.jetty.server.HttpChannelState.completed(HttpChannelState.java:470) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625] at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:315) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625] at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:228) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625] at org.eclipse.jetty.server.handler.ContextHandler.handle(ContextHandler.java:1143) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625] at org.eclipse.jetty.server.HttpChannelState.complete(HttpChannelState.java:432) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625] at org.eclipse.jetty.server.AsyncContextState.complete(AsyncContextState.java:90) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625] at org.atmosphere.container.Servlet30CometSupport.action(Servlet30CometSupport.java:157) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.container.Servlet30CometSupport.action(Servlet30CometSupport.java:79) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.cpr.AtmosphereResourceImpl.resume(AtmosphereResourceImpl.java:326) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.jersey.util.JerseyBroadcasterUtil.broadcast(JerseyBroadcasterUtil.java:161) ~[atmosphere-jersey-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.jersey.JerseyBroadcaster.invokeOnStateChange(JerseyBroadcaster.java:77) ~[atmosphere-jersey-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.cpr.DefaultBroadcaster.prepareInvokeOnStateChange(DefaultBroadcaster.java:1047) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.cpr.DefaultBroadcaster.executeAsyncWrite(DefaultBroadcaster.java:921) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at org.atmosphere.cpr.DefaultBroadcaster$3.run(DefaultBroadcaster.java:580) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_25] at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) ~[na:1.7.0_25] at java.util.concurrent.FutureTask.run(FutureTask.java:166) ~[na:1.7.0_25] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_25] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_25] at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25] ```
      32f19d565b2883d91a9a9dbc52684891d58a8cd0
      92f7d920deac3c0065ae504784a3b271d6b46fe7
      https://github.com/dropwizard/metrics/compare/32f19d565b2883d91a9a9dbc52684891d58a8cd0...92f7d920deac3c0065ae504784a3b271d6b46fe7
      diff --git a/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java b/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java index 56805cdc9..503e7867f 100644 --- a/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java +++ b/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java @@ -133,6 +133,8 @@ public class InstrumentedHandler extends HandlerWrapper { this.otherRequests = metricRegistry.timer(name(prefix, "other-requests")); this.listener = new AsyncListener() { + private long startTime; + @Override public void onTimeout(AsyncEvent event) throws IOException { asyncTimeouts.mark(); @@ -140,6 +142,7 @@ public class InstrumentedHandler extends HandlerWrapper { @Override public void onStartAsync(AsyncEvent event) throws IOException { + startTime = System.currentTimeMillis(); event.getAsyncContext().addListener(this); } @@ -150,8 +153,9 @@ public class InstrumentedHandler extends HandlerWrapper { @Override public void onComplete(AsyncEvent event) throws IOException { final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); - final Request request = (Request) state.getRequest(); - updateResponses(request); + final HttpServletRequest request = (HttpServletRequest) state.getRequest(); + final HttpServletResponse response = (HttpServletResponse) state.getResponse(); + updateResponses(request, response, startTime); if (!state.getHttpChannelState().isDispatched()) { activeSuspended.dec(); } @@ -197,7 +201,7 @@ public class InstrumentedHandler extends HandlerWrapper { } activeSuspended.inc(); } else if (state.isInitial()) { - updateResponses(request); + updateResponses(httpRequest, httpResponse, start); } // else onCompletion will handle it. } @@ -233,13 +237,13 @@ public class InstrumentedHandler extends HandlerWrapper { } } - private void updateResponses(Request request) { - final int response = request.getResponse().getStatus() / 100; - if (response >= 1 && response <= 5) { - responses[response - 1].mark(); + private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start) { + final int responseStatus = response.getStatus() / 100; + if (responseStatus >= 1 && responseStatus <= 5) { + responses[responseStatus - 1].mark(); } activeRequests.dec(); - final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp(); + final long elapsedTime = System.currentTimeMillis() - start; requests.update(elapsedTime, TimeUnit.MILLISECONDS); requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); } diff --git a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java index 3c31cb66f..27b03900a 100644 --- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java +++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java @@ -133,6 +133,8 @@ public class InstrumentedHandler extends HandlerWrapper { this.otherRequests = metricRegistry.timer(name(prefix, "other-requests")); this.listener = new AsyncListener() { + private long startTime; + @Override public void onTimeout(AsyncEvent event) throws IOException { asyncTimeouts.mark(); @@ -140,6 +142,7 @@ public class InstrumentedHandler extends HandlerWrapper { @Override public void onStartAsync(AsyncEvent event) throws IOException { + startTime = System.currentTimeMillis(); event.getAsyncContext().addListener(this); } @@ -150,8 +153,9 @@ public class InstrumentedHandler extends HandlerWrapper { @Override public void onComplete(AsyncEvent event) throws IOException { final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); - final Request request = (Request) state.getRequest(); - updateResponses(request); + final HttpServletRequest request = (HttpServletRequest) state.getRequest(); + final HttpServletResponse response = (HttpServletResponse) state.getResponse(); + updateResponses(request, response, startTime); if (state.getHttpChannelState().getState() != HttpChannelState.State.DISPATCHED) { activeSuspended.dec(); } @@ -197,7 +201,7 @@ public class InstrumentedHandler extends HandlerWrapper { } activeSuspended.inc(); } else if (state.isInitial()) { - updateResponses(request); + updateResponses(httpRequest, httpResponse, start); } // else onCompletion will handle it. } @@ -233,13 +237,13 @@ public class InstrumentedHandler extends HandlerWrapper { } } - private void updateResponses(Request request) { - final int response = request.getResponse().getStatus() / 100; - if (response >= 1 && response <= 5) { - responses[response - 1].mark(); + private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start) { + final int responseStatus = response.getStatus() / 100; + if (responseStatus >= 1 && responseStatus <= 5) { + responses[responseStatus - 1].mark(); } activeRequests.dec(); - final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp(); + final long elapsedTime = System.currentTimeMillis() - start; requests.update(elapsedTime, TimeUnit.MILLISECONDS); requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); }
      ['metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java', 'metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      394,935
      77,392
      11,434
      109
      2,454
      400
      40
      2
      2,933
      96
      957
      27
      0
      1
      1970-01-01T00:23:08
      7,744
      Java
      {'Java': 1542841, 'Shell': 1659, 'Python': 351}
      Apache License 2.0
      102
      swagger-api/swagger-core/1579/1578
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1578
      https://github.com/swagger-api/swagger-core/pull/1579
      https://github.com/swagger-api/swagger-core/pull/1579
      1
      fixes
      byte and binary properties are wrong
      It looks like these two commits are backwards: Addition of `binary` property: https://github.com/swagger-api/swagger-core/commit/a18409eb69d9c69435bb2f0bbec7b2540b46616d Addition of `byte` property: https://github.com/swagger-api/swagger-core/commit/4e7a8014d14a8d0dd54f31f825858ae072be1061
      05475b8552b8ac18864de841468f8665f8c3de10
      deda3feafc61377ccf55883cca0e396a07615bc5
      https://github.com/swagger-api/swagger-core/compare/05475b8552b8ac18864de841468f8665f8c3de10...deda3feafc61377ccf55883cca0e396a07615bc5
      diff --git a/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java b/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java index 8c4980987..237c592c2 100644 --- a/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java +++ b/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java @@ -1,19 +1,7 @@ package io.swagger.util; import com.fasterxml.jackson.databind.type.TypeFactory; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.ObjectProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import io.swagger.models.properties.UUIDProperty; +import io.swagger.models.properties.*; import java.lang.reflect.Type; import java.util.Collections; @@ -49,8 +37,17 @@ public enum PrimitiveType { */ BYTE(Byte.class, "byte") { @Override - public StringProperty createProperty() { - return new StringProperty(StringProperty.Format.BYTE); + public ByteArrayProperty createProperty() { + return new ByteArrayProperty(); + } + }, + /** + * Binary + */ + BINARY(Byte.class, "binary") { + @Override + public BinaryProperty createProperty() { + return new BinaryProperty(); } }, /** diff --git a/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java b/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java index b043684b1..ef27bd4cf 100644 --- a/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java +++ b/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java @@ -4,10 +4,17 @@ import io.swagger.converter.ModelConverters; import io.swagger.matchers.SerializationMatchers; import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BinaryProperty; +import io.swagger.models.properties.ByteArrayProperty; +import io.swagger.util.Json; import org.testng.annotations.Test; import java.util.Map; +import static org.testng.Assert.assertEquals; + public class ByteConverterTest { @Test @@ -30,6 +37,54 @@ public class ByteConverterTest { SerializationMatchers.assertEqualsToJson(models, json); } + @Test + public void testByteProperty() { + Model model = new ModelImpl() + .property("byteProperty", new ByteArrayProperty()); + + assertEquals(Json.pretty(model), "{\\n" + + " \\"properties\\" : {\\n" + + " \\"byteProperty\\" : {\\n" + + " \\"type\\" : \\"string\\",\\n" + + " \\"format\\" : \\"byte\\"\\n" + + " }\\n" + + " }\\n" + + "}"); + } + + @Test + public void testDeserializeByteProperty() throws Exception { + String json = "{\\n" + + " \\"properties\\" : {\\n" + + " \\"byteProperty\\" : {\\n" + + " \\"type\\" : \\"string\\",\\n" + + " \\"format\\" : \\"byte\\"\\n" + + " }\\n" + + " }\\n" + + "}"; + + Model model = Json.mapper().readValue(json, Model.class); + Json.prettyPrint(model); + } + + @Test + public void testByteArray() { + Model model = new ModelImpl() + .property("byteArray", new ArrayProperty(new BinaryProperty())); + + assertEquals(Json.pretty(model), "{\\n" + + " \\"properties\\" : {\\n" + + " \\"byteArray\\" : {\\n" + + " \\"type\\" : \\"array\\",\\n" + + " \\"items\\" : {\\n" + + " \\"type\\" : \\"string\\",\\n" + + " \\"format\\" : \\"binary\\"\\n" + + " }\\n" + + " }\\n" + + " }\\n" + + "}"); + } + class ByteConverterModel { public Byte[] myBytes = new Byte[0]; } diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java similarity index 74% rename from modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java rename to modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java index c80d984b9..c1e20c5ac 100644 --- a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java +++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java @@ -2,73 +2,52 @@ package io.swagger.models.properties; import io.swagger.models.Xml; -import java.util.ArrayList; import java.util.List; -public class ByteProperty extends AbstractProperty implements Property { +public class BinaryProperty extends AbstractProperty implements Property { private static final String TYPE = "string"; - - private static final String FORMAT = "byte"; - protected List<String> _enum; protected Integer minLength = null, maxLength = null; protected String pattern = null; protected String _default; - public ByteProperty() { - super.type = TYPE; - super.format = FORMAT; - } - - public ByteProperty _enum(String value) { - if (this._enum == null) { - this._enum = new ArrayList<String>(); - } - if (!_enum.contains(value)) { - _enum.add(value); - } - return this; - } - - public ByteProperty _enum(List<String> value) { - this._enum = value; - return this; + public BinaryProperty() { + super.type = "string"; + super.format = "binary"; } public static boolean isType(String type, String format) { - if (TYPE.equals(type) && FORMAT.equals(format)) { + if ("string".equals(type) && "binary".equals(format)) return true; - } else { - return false; - } + else return false; } - public ByteProperty xml(Xml xml) { + public BinaryProperty xml(Xml xml) { this.setXml(xml); return this; } - public ByteProperty minLength(Integer minLength) { + public BinaryProperty minLength(Integer minLength) { this.setMinLength(minLength); return this; } - public ByteProperty maxLength(Integer maxLength) { + public BinaryProperty maxLength(Integer maxLength) { this.setMaxLength(maxLength); return this; } - public ByteProperty pattern(String pattern) { + public BinaryProperty pattern(String pattern) { this.setPattern(pattern); return this; } - public ByteProperty _default(String _default) { + public BinaryProperty _default(String _default) { this._default = _default; return this; } - public ByteProperty vendorExtension(String key, Object obj) { + public BinaryProperty vendorExtension(String key, Object obj) { this.setVendorExtension(key, obj); return this; } @@ -130,10 +109,10 @@ public class ByteProperty extends AbstractProperty implements Property { if (!super.equals(obj)) { return false; } - if (!(obj instanceof ByteProperty)) { + if (!(obj instanceof BinaryProperty)) { return false; } - ByteProperty other = (ByteProperty) obj; + BinaryProperty other = (BinaryProperty) obj; if (_default == null) { if (other._default != null) { return false; diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java index 496a7ed05..c6ba49a34 100644 --- a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java +++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java @@ -2,18 +2,16 @@ package io.swagger.models.properties; import io.swagger.models.Xml; -import java.util.*; - public class ByteArrayProperty extends AbstractProperty implements Property { public ByteArrayProperty() { super.type = "string"; - super.format = "binary"; + super.format = "byte"; } public static boolean isType(String type, String format) { - if ("string".equals(type) && "binary".equals(format)) + if ("string".equals(type) && "byte".equals(format)) return true; else return false; } diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java index 750f788d2..8fb677dca 100644 --- a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java +++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java @@ -156,6 +156,17 @@ public class PropertyBuilder { return new ByteArrayProperty(); } }, + BINARY(BinaryProperty.class) { + @Override + protected boolean isType(String type, String format) { + return BinaryProperty.isType(type, format); + } + + @Override + protected BinaryProperty create() { + return new BinaryProperty(); + } + }, DATE(DateProperty.class) { @Override protected boolean isType(String type, String format) { diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java index 0dbb65ced..920ab1b3e 100644 --- a/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java +++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java @@ -17,7 +17,6 @@ public class StringProperty extends AbstractProperty implements Property { protected String _default; public enum Format { - BYTE("byte"), URI("uri"), URL("url"); diff --git a/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java b/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java index 19bf1ae6e..45be6930d 100644 --- a/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java +++ b/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java @@ -1,21 +1,17 @@ package io.swagger; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; - import io.swagger.models.properties.StringProperty; - import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; + public class StringPropertyTest { private static final String PROP_1 = "prop1"; private static final String PROP_2 = "prop2"; @Test public void testEquals() { - assertNotEquals(new StringProperty(StringProperty.Format.BYTE), new StringProperty(StringProperty.Format.URL)); - assertEquals(new StringProperty(StringProperty.Format.BYTE), new StringProperty(StringProperty.Format.BYTE)); - final StringProperty prop1 = new StringProperty(); prop1.setName(PROP_1); prop1.setRequired(true); diff --git a/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java b/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java index d32f3dc27..3c0ff8b69 100644 --- a/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java +++ b/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java @@ -1,17 +1,15 @@ package io.swagger.models.properties; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.Iterator; -import java.util.List; - +import io.swagger.models.properties.PropertyBuilder.PropertyId; +import io.swagger.models.properties.StringProperty.Format; import org.testng.Assert; - import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import io.swagger.models.properties.PropertyBuilder.PropertyId; -import io.swagger.models.properties.StringProperty.Format; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.List; public class PropertyBuilderTest { @@ -57,8 +55,8 @@ public class PropertyBuilderTest { {"number", "float", FloatProperty.class}, {"number", "double", DoubleProperty.class}, {"string", null, StringProperty.class}, - {"string", "byte", StringProperty.class}, // are this and the next one correct? - {"string", "binary", ByteArrayProperty.class}, + {"string", "byte", ByteArrayProperty.class}, + {"string", "binary", BinaryProperty.class}, {"boolean", null, BooleanProperty.class}, {"string", "date", DateProperty.class}, {"string", "date-time", DateTimeProperty.class},
      ['modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java', 'modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java', 'modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java', 'modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java']
      {'.java': 8}
      8
      8
      0
      0
      8
      578,968
      111,634
      18,293
      165
      1,727
      295
      45
      5
      293
      18
      96
      8
      2
      0
      1970-01-01T00:24:10
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      101
      swagger-api/swagger-core/1678/1512
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1512
      https://github.com/swagger-api/swagger-core/pull/1678
      https://github.com/swagger-api/swagger-core/pull/1678
      1
      fix
      swagger-servlet generating non-unique operationIds
      using swagger-servlet-1.5.4. first of all, @iushankin huuuge thanks for swagger-servlet migration with 1.5.4! works almost flawlessly. i noticed that swagger-servlet will use `@ApiOperation`s `nickname` attribute for path generation as well as for `operationId`. however, it may be necessary to have multiple operations with the same path (but different http methods). in this case, the `nickname` is correctly used multiple times as path for different operations but also as `operationId` which means the `operationId` is no longer unique. as a result, swagger editor - for example - shows errors: > Cannot have multiple operations with the same operationId: /myPath thanks, zyro
      9e93afaf1ee7a9a0130b262fd2112b3c20bbb825
      b2ae3198f993ac3d20446e4da7725153c19185b3
      https://github.com/swagger-api/swagger-core/compare/9e93afaf1ee7a9a0130b262fd2112b3c20bbb825...b2ae3198f993ac3d20446e4da7725153c19185b3
      diff --git a/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java b/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java index 5345b1a9f..5eaae4195 100644 --- a/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java +++ b/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java @@ -222,7 +222,7 @@ public class ServletReaderExtension implements ReaderExtension { final String operationPath = apiOperation == null ? null : apiOperation.nickname(); return PathUtils.collectPath(context.getParentPath(), apiAnnotation == null ? null : apiAnnotation.value(), - StringUtils.defaultIfBlank(operationPath, method.getName())); + method.getName()); } @Override diff --git a/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java b/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java index a48d65190..a36bacfe1 100644 --- a/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java +++ b/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java @@ -43,12 +43,12 @@ public class ReaderTest { Assert.assertEquals(swagger.getHost(), "host"); Assert.assertEquals(swagger.getBasePath(), "/api"); - Assert.assertNotNull(swagger.getPath("/resources/users")); + Assert.assertNotNull(swagger.getPath("/resources/testMethod3")); Assert.assertNotNull(swagger.getDefinitions().get("SampleData")); Assert.assertEquals(swagger.getExternalDocs().getDescription(), "docs"); Assert.assertEquals(swagger.getExternalDocs().getUrl(), "url_to_docs"); - Path path = swagger.getPath("/resources/users"); + Path path = swagger.getPath("/resources/testMethod3"); Assert.assertNotNull(path); Operation get = path.getGet(); Assert.assertNotNull( get ); diff --git a/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java b/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java index 4b643b073..3c1092335 100644 --- a/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java +++ b/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java @@ -13,7 +13,7 @@ public class PathGetterTest extends BaseServletReaderExtensionTest { return new Object[][]{ {"testMethod1", "/tests/resources/testMethod1"}, {"testMethod2", "/tests/resources/testMethod2"}, - {"testMethod3", "/tests/resources/users"}, + {"testMethod3", "/tests/resources/testMethod3"}, {"testMethod4", "/tests/resources/testMethod4"}, }; } @@ -23,7 +23,7 @@ public class PathGetterTest extends BaseServletReaderExtensionTest { return new Object[][]{ {"testMethod1", "/tests/testMethod1"}, {"testMethod2", "/tests/testMethod2"}, - {"testMethod3", "/tests/users"}, + {"testMethod3", "/tests/testMethod3"}, {"testMethod4", "/tests/testMethod4"}, }; }
      ['modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java', 'modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java', 'modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      601,624
      116,159
      18,969
      167
      114
      15
      2
      1
      686
      100
      159
      14
      0
      0
      1970-01-01T00:24:16
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      103
      swagger-api/swagger-core/1556/1526
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1526
      https://github.com/swagger-api/swagger-core/pull/1556
      https://github.com/swagger-api/swagger-core/pull/1556
      1
      fixes
      Example Value overwrites Parameter's DataType
      Hi, I encountered the following unexpected behavior. When specifying an example value in a `@ApiImplicitParam` annotation the parameter's dataType will be set to the example value. For instance annotation ``` java @ApiImplicitParam(name="id", paramType="path", dataType="string", example="123456") ``` will lead to JSON ``` json "parameters": [{"name":"id", "in":"path", "type":"123456", "x-example":"123456"}] ``` This behavior was observed on swagger 1.5.4. Cause is the `ParameterProcessor.applyAnnotations()` method. The following code found in the method overwrites the parameter's dataType: ``` java if (StringUtils.isNotEmpty(param.getExample())) { p.setType(param.getExample()); } ``` I am not really sure about the original intention of the code but it does not look right to me. The code was introduced by commit 62c100f33a54d7688e859cd011abb89a907e02ef "added example support for non-body params, implicits". Best regards, phosn
      436a9cb792be23fc835cf2dcbe1bdb087590f483
      edeca227123e85ab03666f3d5e131d6e2c457663
      https://github.com/swagger-api/swagger-core/compare/436a9cb792be23fc835cf2dcbe1bdb087590f483...edeca227123e85ab03666f3d5e131d6e2c457663
      diff --git a/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java b/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java index b75656013..adb4106f0 100644 --- a/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java +++ b/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java @@ -67,9 +67,6 @@ public class ParameterProcessor { p.setType(param.getDataType()); } } - if (StringUtils.isNotEmpty(param.getExample())) { - p.setType(param.getExample()); - } if (helper.getMinItems() != null) { p.setMinItems(helper.getMinItems()); } diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java b/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java index 63f6d5da6..fbf438d74 100644 --- a/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java +++ b/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java @@ -13,7 +13,7 @@ public class ResourceWithImplicitFileParam { @POST @Path("/testString") @ApiImplicitParams({ - @ApiImplicitParam(name = "sort", paramType = "form", dataType = "java.io.File", required = false, value = "file to upload") + @ApiImplicitParam(name = "sort", paramType = "form", dataType = "java.io.File", required = false, value = "file to upload") }) @ApiOperation("Test operation with implicit parameters") public void testImplicitFileParam() {
      ['modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java', 'modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      564,498
      108,724
      17,783
      163
      125
      19
      3
      1
      969
      116
      236
      36
      0
      3
      1970-01-01T00:24:08
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      104
      swagger-api/swagger-core/1453/1440
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1440
      https://github.com/swagger-api/swagger-core/pull/1453
      https://github.com/swagger-api/swagger-core/pull/1453
      1
      fixes
      The ApiOperation.nickname property does not work
      The reason: please check this class: io.swagger.jaxrs.Reader, line 711 I think there should be: operationId = apiOperation.nickname(); instead of: operationId = method.getName(); Sincerely yours Nazar
      4e6793564819457e5724464b27a782afad145e10
      91a4dbef7c3756ecc69f334bd5d7a89ecf4b5737
      https://github.com/swagger-api/swagger-core/compare/4e6793564819457e5724464b27a782afad145e10...91a4dbef7c3756ecc69f334bd5d7a89ecf4b5737
      diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java index 937ec0a52..464d77c2a 100644 --- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java +++ b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java @@ -714,7 +714,7 @@ public class Reader { return null; } if (!"".equals(apiOperation.nickname())) { - operationId = method.getName(); + operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());
      ['modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      532,171
      102,641
      16,824
      160
      104
      15
      2
      1
      203
      25
      49
      7
      0
      0
      1970-01-01T00:24:02
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      105
      swagger-api/swagger-core/1262/1175
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1175
      https://github.com/swagger-api/swagger-core/pull/1262
      https://github.com/swagger-api/swagger-core/pull/1262
      1
      fixes
      Change logging level to DEBUG for some messages in PropertyBuilder
      Change logging level for [this](https://github.com/swagger-api/swagger-core/blob/400662d7253c0c2efb14316f8948ddc61a60069e/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java#L569) message to DEBUG as these messages look confusing for [codegen](https://github.com/swagger-api/swagger-codegen) users (https://github.com/swagger-api/swagger-parser/issues/60).
      42056f20c52407e4c13283794a65d6d71b3a7e41
      183a6fccd65bc0cd6de129aa2c7b35b13bfd2797
      https://github.com/swagger-api/swagger-core/compare/42056f20c52407e4c13283794a65d6d71b3a7e41...183a6fccd65bc0cd6de129aa2c7b35b13bfd2797
      diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java index 41fbdf96a..660d11c86 100644 --- a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java +++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java @@ -566,7 +566,7 @@ public class PropertyBuilder { return item; } } - LOGGER.error("no property for " + type + ", " + format); + LOGGER.debug("no property for " + type + ", " + format); return null; }
      ['modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      438,099
      84,995
      14,008
      142
      139
      32
      2
      1
      392
      17
      96
      2
      3
      0
      1970-01-01T00:23:56
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      107
      swagger-api/swagger-core/1190/1185
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1185
      https://github.com/swagger-api/swagger-core/pull/1190
      https://github.com/swagger-api/swagger-core/pull/1190
      1
      fixes
      'hidden' variable is not used
      'hidden' variable is declared, but isn't used https://github.com/swagger-api/swagger-core/blob/9c67549cc4e30db916dac0165f0549485a6eb4c7/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java#L834-L837
      8999c5b5a862cc4b9f533d1692ba9db7858b1d5f
      a671881ac26a1df940012f2b2ff370d393f2dfee
      https://github.com/swagger-api/swagger-core/compare/8999c5b5a862cc4b9f533d1692ba9db7858b1d5f...a671881ac26a1df940012f2b2ff370d393f2dfee
      diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java index 1657326ca..145416564 100644 --- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java +++ b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java @@ -829,11 +829,6 @@ public class Reader { operation.setDeprecated(true); } - boolean hidden = false; - if (apiOperation != null) { - hidden = apiOperation.hidden(); - } - // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter);
      ['modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      431,150
      83,484
      13,753
      140
      127
      24
      5
      1
      211
      8
      66
      2
      1
      0
      1970-01-01T00:23:54
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      109
      swagger-api/swagger-core/1033/1000
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1000
      https://github.com/swagger-api/swagger-core/pull/1033
      https://github.com/swagger-api/swagger-core/pull/1033
      1
      fixes
      NPE without any class with @Api annotation
      If there is no class with `@Api` annotation trying to get `swagger.json` causes NPE. This may be very confusing at the beginning, when we are implementing Swagger step-by-step and get exception. Stack: ``` java.lang.NullPointerException at com.wordnik.swagger.jaxrs.config.BeanConfig.configure(BeanConfig.java:196) at com.wordnik.swagger.jaxrs.listing.ApiListingResource.scan(ApiListingResource.java:52) at com.wordnik.swagger.jaxrs.listing.ApiListingResource.getListingJson(ApiListingResource.java:79) ... ``` So we have to check for nulls somewhere in this area: https://github.com/swagger-api/swagger-core/blob/c4260bea041027f9887c67d5d6c6eb408c238969/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/config/BeanConfig.java#L197
      e9cad60100c883f171b6d2a989ee6eb398fd3a25
      e2e459b0a134e4310b91f60e2fb31625a40f57f0
      https://github.com/swagger-api/swagger-core/compare/e9cad60100c883f171b6d2a989ee6eb398fd3a25...e2e459b0a134e4310b91f60e2fb31625a40f57f0
      diff --git a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java index 0574c9891..23aea9a17 100644 --- a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java +++ b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java @@ -58,7 +58,7 @@ public class Reader { static ObjectMapper m = Json.mapper(); public Reader(Swagger swagger) { - this.swagger = swagger; + this.swagger = swagger == null ? new Swagger() : swagger; } public Swagger read(Set<Class<?>> classes) { @@ -76,8 +76,6 @@ public class Reader { } protected Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean readHidden, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters) { - if(swagger == null) - swagger = new Swagger(); Api api = (Api) cls.getAnnotation(Api.class); Map<String, SecurityScope> globalScopes = new HashMap<String, SecurityScope>();
      ['modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      887,167
      204,437
      29,102
      399
      148
      33
      4
      1
      764
      54
      192
      14
      1
      1
      1970-01-01T00:23:50
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      100
      swagger-api/swagger-core/1718/1714
      swagger-api
      swagger-core
      https://github.com/swagger-api/swagger-core/issues/1714
      https://github.com/swagger-api/swagger-core/pull/1718
      https://github.com/swagger-api/swagger-core/pull/1718
      1
      fix
      jersey2 listing resource broken
      1.5.8 seems to have broken the listing resource for jersey2. Now this class: ``` java package io.swagger.jersey.listing; /* */ @Path("/") public class ApiListingResourceJSON extends ApiListingResource { } ``` causes the swagger definition to appear only on `"/"` instead of `"/swagger.{type:json|yaml}"` as defined in the `io.swagger.jaxrs.listing.ApiListingResource` class The solution is to use `io.swagger.jaxrs.listing.ApiListingResource`, but for previous uses (like swagger-generator), the 1.5.8 changes break the resource. We should either fix the ApiListingResourceJSON, remove it, or make it clear how to update when going to 1.5.8.
      3e5a7e613daaa95028f3aeb45cd8545c14deaa8c
      2425b7f3aa36d7661777ca8819445180af792431
      https://github.com/swagger-api/swagger-core/compare/3e5a7e613daaa95028f3aeb45cd8545c14deaa8c...2425b7f3aa36d7661777ca8819445180af792431
      diff --git a/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java b/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java index 05a54d0cf..dbe40f642 100644 --- a/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java +++ b/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java @@ -2,9 +2,7 @@ package io.swagger.jersey.listing; import io.swagger.jaxrs.listing.ApiListingResource; -import javax.ws.rs.Path; - -@Path("/") +@Deprecated public class ApiListingResourceJSON extends ApiListingResource { } \\ No newline at end of file
      ['modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      618,360
      119,346
      19,394
      169
      52
      12
      4
      1
      656
      83
      164
      18
      0
      1
      1970-01-01T00:24:18
      7,244
      Java
      {'Java': 2870337, 'Shell': 9095, 'Python': 4538}
      Apache License 2.0
      8,978
      karatelabs/karate/1556/1555
      karatelabs
      karate
      https://github.com/karatelabs/karate/issues/1555
      https://github.com/karatelabs/karate/pull/1556
      https://github.com/karatelabs/karate/pull/1556
      1
      fixes
      `logPrettyResponse` configuration parameter is not considered
      `logPrettyResponse` is not considered when configured, either in `karate-config.js` or in the feature itself. Looking at the code I found the issue and will submit a PR to fix it.
      e2b4f3a875805da0a6f2531952af26540eb7c7c1
      d5abda97bfcd507f7bd1fcd5b31a876f564b5bc5
      https://github.com/karatelabs/karate/compare/e2b4f3a875805da0a6f2531952af26540eb7c7c1...d5abda97bfcd507f7bd1fcd5b31a876f564b5bc5
      diff --git a/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java b/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java index f6d7466cd..bc5464d12 100644 --- a/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java +++ b/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java @@ -69,7 +69,7 @@ public class HttpLogger { } Variable v = new Variable(body); String text; - if (config != null && config.isLogPrettyRequest()) { + if (config != null && needsPrettyLogging(config, request)) { text = v.getAsPrettyString(); } else { text = v.getAsString(); @@ -80,6 +80,18 @@ public class HttpLogger { sb.append(text); } + private static boolean needsPrettyLogging(Config config, boolean request) { + return logPrettyRequest(config, request) || logPrettyResponse(config, request); + } + + private static boolean logPrettyResponse(Config config, boolean request) { + return !request && config.isLogPrettyResponse(); + } + + private static boolean logPrettyRequest(Config config, boolean request) { + return request && config.isLogPrettyRequest(); + } + private static HttpLogModifier logModifier(Config config, String uri) { HttpLogModifier logModifier = config.getLogModifier(); return logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null;
      ['karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      1,614,061
      334,168
      47,449
      310
      601
      115
      14
      1
      182
      30
      42
      3
      0
      0
      1970-01-01T00:26:58
      7,226
      Java
      {'Java': 2164729, 'Gherkin': 262656, 'JavaScript': 70334, 'HTML': 44272, 'Scala': 13901, 'CSS': 7856, 'ANTLR': 4088, 'Shell': 3629, 'Dockerfile': 2919}
      MIT License
      8,977
      karatelabs/karate/2376/2259
      karatelabs
      karate
      https://github.com/karatelabs/karate/issues/2259
      https://github.com/karatelabs/karate/pull/2376
      https://github.com/karatelabs/karate/pull/2376
      1
      resolves
      Double Click and Right Click in Karate Robot framework for windows app
      Double click doesnt work in Karate Robot framework for windows app ``` locate('abc').doubleClick(0,0) ``` It clicks twice but does it slowly such that the double click does not really work. I found doubleClick() method in RobotBase.Java which has a 40ms delay between the clicks and i'm not sure if that is the reason behind the lag in clicks. Right Click also doesnt work as there is no method in Element.java but there is a rightClick() method in RobotBase.Java which calls Click(3) internally
      7e1f3b3bb0405847722f814d4ab8fed08e7f8832
      7ee8b8bd272a7e12a7e2318a193ab84b4c45da6a
      https://github.com/karatelabs/karate/compare/7e1f3b3bb0405847722f814d4ab8fed08e7f8832...7ee8b8bd272a7e12a7e2318a193ab84b4c45da6a
      diff --git a/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java b/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java index af420922a..0ee7dfbfc 100644 --- a/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java +++ b/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java @@ -277,7 +277,7 @@ public abstract class RobotBase implements Robot, Plugin { @Override public Robot rightClick() { - return click(3); + return click(2); } @Override @@ -299,9 +299,20 @@ public abstract class RobotBase implements Robot, Plugin { @Override public Robot doubleClick() { - click(); - delay(40); - click(); + if (highlight) { + getLocation().highlight(highlightDuration); + int toDelay = highlightDuration; + if (toDelay > 0) { + RobotUtils.delay(toDelay); + } + } + int clickType = mask(1); + robot.mousePress(clickType); + robot.mouseRelease(clickType); + RobotUtils.delay(100); + robot.mousePress(clickType); + robot.mouseRelease(clickType); + return this; }
      ['karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      1,727,793
      357,449
      50,168
      307
      562
      110
      19
      1
      504
      82
      115
      7
      0
      1
      1970-01-01T00:28:11
      7,226
      Java
      {'Java': 2164729, 'Gherkin': 262656, 'JavaScript': 70334, 'HTML': 44272, 'Scala': 13901, 'CSS': 7856, 'ANTLR': 4088, 'Shell': 3629, 'Dockerfile': 2919}
      MIT License
      3,321
      apache/beam/27699/27670
      apache
      beam
      https://github.com/apache/beam/issues/27670
      https://github.com/apache/beam/pull/27699
      https://github.com/apache/beam/pull/27699
      1
      fixes
      [Bug]: Storage Write API fails on Batch Pipelines on 2.49
      ### What happened? When writing to a BigQuery sink in a Batch pipeline using Storage Write API the pipeline fails due to the following error, ``` java.lang.RuntimeException: org.apache.beam.sdk.util.UserCodeException: java.lang.RuntimeException: Schema field not found: eventid at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowsParDoFn.java:187 ) at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:108 ) at org.apache.beam.runners.dataflow.worker.util.BatchGroupAlsoByWindowReshuffleFn.processElement ( org/apache.beam.runners.dataflow.worker.util/BatchGroupAlsoByWindowReshuffleFn.java:56 ) at org.apache.beam.runners.dataflow.worker.util.BatchGroupAlsoByWindowReshuffleFn.processElement ( org/apache.beam.runners.dataflow.worker.util/BatchGroupAlsoByWindowReshuffleFn.java:39 ) at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:121 ) at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:73 ) at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowsParDoFn.java:117 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( org/apache.beam.runners.dataflow.worker.util.common.worker/ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( org/apache.beam.runners.dataflow.worker.util.common.worker/OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop ( org/apache.beam.runners.dataflow.worker.util.common.worker/ReadOperation.java:218 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start ( org/apache.beam.runners.dataflow.worker.util.common.worker/ReadOperation.java:169 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute ( org/apache.beam.runners.dataflow.worker.util.common.worker/MapTaskExecutor.java:83 ) at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.executeWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:319 ) at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.doWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:291 ) at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.getAndPerformWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:221 ) at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:147 ) at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:127 ) at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:114 ) at java.util.concurrent.FutureTask.run ( java/util.concurrent/FutureTask.java:264 ) at org.apache.beam.sdk.util.UnboundedScheduledExecutorService$ScheduledFutureTask.run ( org/apache.beam.sdk.util/UnboundedScheduledExecutorService.java:163 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( java/util.concurrent/ThreadPoolExecutor.java:1128 ) at java.util.concurrent.ThreadPoolExecutor$Worker.run ( java/util.concurrent/ThreadPoolExecutor.java:628 ) at java.lang.Thread.run ( java/lang/Thread.java:834 ) Caused by: org.apache.beam.sdk.util.UserCodeException at org.apache.beam.sdk.util.UserCodeException.wrap ( UserCodeException.java:39 ) at org.apache.beam.sdk.io.gcp.bigquery.StorageApiConvertMessages$ConvertMessagesDoFn$DoFnInvoker.invokeProcessElement at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.AssignWindowsParDoFnFactory$AssignWindowsParDoFn.processElement ( AssignWindowsParDoFnFactory.java:115 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 ) at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement ( PrepareWrite.java:84 ) at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1$DoFnInvoker.invokeProcessElement at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:185 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 ) at org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn.processElement ( JdbcIO.java:1528 ) at org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn$DoFnInvoker.invokeProcessElement at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 ) at org.apache.beam.sdk.transforms.DoFnOutputReceivers$WindowedContextOutputReceiver.output ( DoFnOutputReceivers.java:76 ) at org.apache.beam.sdk.transforms.MapElements$2.processElement ( MapElements.java:151 ) at org.apache.beam.sdk.transforms.MapElements$2$DoFnInvoker.invokeProcessElement at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 ) at org.apache.beam.runners.dataflow.ReshuffleOverrideFactory$ReshuffleWithOnlyTrigger$1.processElement ( ReshuffleOverrideFactory.java:86 ) at org.apache.beam.runners.dataflow.ReshuffleOverrideFactory$ReshuffleWithOnlyTrigger$1$DoFnInvoker.invokeProcessElement at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 ) at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 ) at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 ) at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 ) at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output ( GroupAlsoByWindowsParDoFn.java:185 ) Caused by: java.lang.RuntimeException at org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto$SchemaInformation.getSchemaForField ( TableRowToStorageApiProto.java:371 ) at org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto.messageFromMap ( TableRowToStorageApiProto.java:472 ) at org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto.messageFromTableRow ( TableRowToStorageApiProto.java:625 ) at org.apache.beam.sdk.io.gcp.bigquery.StorageApiDynamicDestinationsTableRow$TableRowConverter.toMessage ( StorageApiDynamicDestinationsTableRow.java:170 ) at org.apache.beam.sdk.io.gcp.bigquery.StorageApiConvertMessages$ConvertMessagesDoFn.processElement ( StorageApiConvertMessages.java:159 ) ``` The field `eventId` exists but for some reason the case of the field changes. This does not occur in when using File Loads method. ### Issue Priority Priority: 1 (data loss / total loss of function) ### Issue Components - [ ] Component: Python SDK - [X] Component: Java SDK - [ ] Component: Go SDK - [ ] Component: Typescript SDK - [x] Component: IO connector - [ ] Component: Beam examples - [ ] Component: Beam playground - [ ] Component: Beam katas - [ ] Component: Website - [ ] Component: Spark Runner - [ ] Component: Flink Runner - [ ] Component: Samza Runner - [ ] Component: Twister2 Runner - [ ] Component: Hazelcast Jet Runner - [ ] Component: Google Cloud Dataflow Runner
      f35a6365e8a6a67e74e933f29789f5bbf5f59315
      2e958499e5d9060706d54b2fd99a347e48f3f1db
      https://github.com/apache/beam/compare/f35a6365e8a6a67e74e933f29789f5bbf5f59315...2e958499e5d9060706d54b2fd99a347e48f3f1db
      diff --git a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java index d231d84aea..d98f9115cb 100644 --- a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java +++ b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java @@ -344,7 +344,7 @@ public class TableRowToStorageApiProto { new SchemaInformation( field, Iterables.concat(this.parentSchemas, ImmutableList.of(this))); subFields.add(schemaInformation); - subFieldsByName.put(field.getName(), schemaInformation); + subFieldsByName.put(field.getName().toLowerCase(), schemaInformation); } } @@ -365,9 +365,9 @@ public class TableRowToStorageApiProto { } public SchemaInformation getSchemaForField(String name) { - SchemaInformation schemaInformation = subFieldsByName.get(name); + SchemaInformation schemaInformation = subFieldsByName.get(name.toLowerCase()); if (schemaInformation == null) { - throw new RuntimeException("Schema field not found: " + name); + throw new RuntimeException("Schema field not found: " + name.toLowerCase()); } return schemaInformation; } diff --git a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java index 534c1b0c36..6405c0599e 100644 --- a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java +++ b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java @@ -1824,7 +1824,7 @@ public class BigQueryIOWriteTest implements Serializable { new SimpleFunction<Long, TableRow>() { @Override public TableRow apply(Long input) { - return new TableRow().set("name", "name " + input).set("number", input); + return new TableRow().set("NaMe", "name " + input).set("numBEr", input); } })) .setCoder(TableRowJsonCoder.of());
      ['sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java', 'sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      26,087,797
      5,616,266
      667,143
      3,970
      461
      78
      6
      1
      12,687
      590
      2,911
      125
      0
      1
      1970-01-01T00:28:10
      7,039
      Java
      {'Java': 44997581, 'Python': 11684345, 'Go': 6460783, 'TypeScript': 2009450, 'Dart': 1436710, 'Groovy': 981282, 'Shell': 411640, 'SCSS': 319433, 'Kotlin': 251827, 'HCL': 233427, 'HTML': 200724, 'JavaScript': 122178, 'Cython': 75277, 'Dockerfile': 73608, 'Jupyter Notebook': 61209, 'Sass': 27577, 'FreeMarker': 7933, 'CSS': 7584, 'Rust': 5168, 'C': 3869, 'Lua': 3620, 'Thrift': 3260, 'Smarty': 2618, 'ANTLR': 1598, 'Scala': 1429}
      Apache License 2.0
      516
      google/closure-compiler/1409/1407
      google
      closure-compiler
      https://github.com/google/closure-compiler/issues/1407
      https://github.com/google/closure-compiler/pull/1409
      https://github.com/google/closure-compiler/pull/1409
      1
      fixes
      Cannot use globs when running the compiler.
      Since 62ca536... I am no longer able to use globs for files when running the compiler: Running this command used to work before that change: ``` java -jar ../../compiler/compiler.jar \\ --flagfile=options/compile.ini \\ --define "goog.json.USE_NATIVE_JSON=true" --define "goog.ui.Component.ALLOW_DETACHED_DECORATION=true" --define "goog.NATIVE_ARRAY_PROTOTYPES=true" --define "goog.array.ASSUME_NATIVE_FUNCTIONS=true" --define "goog.Promise.UNHANDLED_REJECTION_DELAY=-1" --define "app.settings.RUN_AS_USER=false" --externs=../externs/material.js --generate_exports --export_local_property_definitions --language_in=ECMASCRIPT6 --language_out=ES3 --use_types_for_optimization --output_wrapper="(function(){%output%})();" \\ --only_closure_dependencies \\ --closure_entry_point=app \\ --manage_closure_dependencies true \\ --output_manifest build/app.filelist.txt \\ --js_output_file /tmp/closure_compiler_build \\ --js="js/**.js" --js="tpl/en/**.js" --js="../../templates/soyutils_usegoog.js" --js="../../library/closure/goog/**.js" --js="../../library/third_party/closure/goog/mochikit/async/deferred.js" --js="../../library/third_party/closure/goog/mochikit/async/deferredlist.js" --js="../pstj/animation/**.js" --js="../pstj/app/**.js" --js="../pstj/autogenerated/**.js" --js="../pstj/cast/**.js" --js="../pstj/color/**.js" --js="../pstj/config/**.js" --js="../pstj/control/**.js" --js="../pstj/date/**.js" --js="../pstj/debug/**.js" --js="../pstj/ds/**.js" --js="../pstj/element/**.js" --js="../pstj/error/**.js" --js="../pstj/fx/**.js" --js="../pstj/graphics/**.js" --js="../pstj/material/**.js" --js="../pstj/math/**.js" --js="../pstj/mvc/**.js" --js="../pstj/ng/**.js" --js="../pstj/object/**.js" --js="../pstj/options/**.js" --js="../pstj/resource/**.js" --js="../pstj/sourcegen/**.js" --js="../pstj/storage/**.js" --js="../pstj/style/**.js" --js="../pstj/themes/**.js" --js="../pstj/ui/**.js" --js="../smjs/ds/**.js" --js="../smjs/element/**.js" --js="../smjs/persistence/**.js" --js="../smjs/player/**.js" --js="../smjs/remotecontrol/**.js" --js="../smjs/transport/**.js" --js="../smjs/tv/**.js" --js="../smjs/widgets/**.js" --js="!**_test.js" ``` Now (after the mentioned change) it gives this: ``` ERROR - Cannot read: !**_test.js ERROR - Cannot read: ../../library/closure/goog/**.js ERROR - Cannot read: ../pstj/animation/**.js ERROR - Cannot read: ../pstj/app/**.js ERROR - Cannot read: ../pstj/autogenerated/**.js ERROR - Cannot read: ../pstj/cast/**.js ERROR - Cannot read: ../pstj/color/**.js ERROR - Cannot read: ../pstj/config/**.js ERROR - Cannot read: ../pstj/control/**.js ERROR - Cannot read: ../pstj/date/**.js ERROR - Cannot read: ../pstj/debug/**.js ERROR - Cannot read: ../pstj/ds/**.js ERROR - Cannot read: ../pstj/element/**.js ERROR - Cannot read: ../pstj/error/**.js ERROR - Cannot read: ../pstj/fx/**.js ERROR - Cannot read: ../pstj/graphics/**.js ERROR - Cannot read: ../pstj/material/**.js ERROR - Cannot read: ../pstj/math/**.js ERROR - Cannot read: ../pstj/mvc/**.js ERROR - Cannot read: ../pstj/ng/**.js ERROR - Cannot read: ../pstj/object/**.js ERROR - Cannot read: ../pstj/options/**.js ERROR - Cannot read: ../pstj/resource/**.js ERROR - Cannot read: ../pstj/sourcegen/**.js ERROR - Cannot read: ../pstj/storage/**.js ERROR - Cannot read: ../pstj/style/**.js ERROR - Cannot read: ../pstj/themes/**.js ERROR - Cannot read: ../pstj/ui/**.js ERROR - Cannot read: ../smjs/ds/**.js ERROR - Cannot read: ../smjs/element/**.js ERROR - Cannot read: ../smjs/persistence/**.js ERROR - Cannot read: ../smjs/player/**.js ERROR - Cannot read: ../smjs/remotecontrol/**.js ERROR - Cannot read: ../smjs/transport/**.js ERROR - Cannot read: ../smjs/tv/**.js ERROR - Cannot read: ../smjs/widgets/**.js ERROR - Cannot read: js/**.js ERROR - Cannot read: tpl/en/**.js ERROR - required entry point "app" never provided 39 error(s), 0 warning(s) ```
      00adf761809e997aadadcf07050310d5d1dbad68
      dfd1853feeb252fd57cf245816cef4305d3e1fe8
      https://github.com/google/closure-compiler/compare/00adf761809e997aadadcf07050310d5d1dbad68...dfd1853feeb252fd57cf245816cef4305d3e1fe8
      diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java index 34c79d686..019b4d62e 100644 --- a/src/com/google/javascript/jscomp/CommandLineRunner.java +++ b/src/com/google/javascript/jscomp/CommandLineRunner.java @@ -26,8 +26,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.io.Files; -import com.google.javascript.jscomp.AbstractCommandLineRunner.FlagEntry; -import com.google.javascript.jscomp.AbstractCommandLineRunner.JsSourceType; import com.google.javascript.jscomp.SourceMap.LocationMapping; import com.google.javascript.rhino.TokenStream; import com.google.protobuf.TextFormat; @@ -47,8 +45,8 @@ import org.kohsuke.args4j.spi.StringOptionHandler; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.lang.reflect.AnnotatedElement; @@ -64,10 +62,10 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeSet; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -732,6 +730,28 @@ public class CommandLineRunner extends return allJsInputs; } + protected List<FlagEntry<JsSourceType>> getMixedJsSources() + throws CmdLineException, IOException { + List<FlagEntry<JsSourceType>> mixedSources = new ArrayList<>(); + for (FlagEntry<JsSourceType> source : Flags.mixedJsSources) { + if (source.value.endsWith(".zip")) { + mixedSources.add(source); + } else { + for (String filename : findJsFiles(Collections.singletonList(source.value))) { + mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename)); + } + } + } + List<String> fromArguments = findJsFiles(arguments); + for (String filename : fromArguments) { + mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename)); + } + if (!Flags.mixedJsSources.isEmpty() && !arguments.isEmpty() && mixedSources.isEmpty()) { + throw new CmdLineException(parser, "No inputs matched"); + } + return mixedSources; + } + List<SourceMap.LocationMapping> getSourceMapLocationMappings() throws CmdLineException { ImmutableList.Builder<LocationMapping> locationMappings = ImmutableList.builder(); @@ -1078,6 +1098,7 @@ public class CommandLineRunner extends Flags.mixedJsSources.clear(); List<String> jsFiles = null; + List<FlagEntry<JsSourceType>> mixedSources = null; List<LocationMapping> mappings = null; ImmutableMap<String, String> sourceMapInputs = null; try { @@ -1089,6 +1110,7 @@ public class CommandLineRunner extends } jsFiles = flags.getJsFiles(); + mixedSources = flags.getMixedJsSources(); mappings = flags.getSourceMapLocationMappings(); sourceMapInputs = flags.getSourceMapInputs(); } catch (CmdLineException e) { @@ -1207,7 +1229,7 @@ public class CommandLineRunner extends .setExterns(flags.externs) .setJs(jsFiles) .setJsZip(flags.jszip) - .setMixedJsSources(Flags.mixedJsSources) + .setMixedJsSources(mixedSources) .setJsOutputFile(flags.jsOutputFile) .setModule(flags.module) .setVariableMapOutputFile(flags.variableMapOutputFile) @@ -1437,7 +1459,7 @@ public class CommandLineRunner extends * within the directory and sub-directories. */ public static List<String> findJsFiles(Collection<String> patterns) throws IOException { - Set<String> allJsInputs = new LinkedHashSet<>(); + Set<String> allJsInputs = new TreeSet<>(); for (String pattern : patterns) { if (!pattern.contains("*") && !pattern.startsWith("!")) { File matchedFile = new File(pattern); @@ -1458,7 +1480,9 @@ public class CommandLineRunner extends throws IOException { FileSystem fs = FileSystems.getDefault(); final boolean remove = pattern.indexOf('!') == 0; - if (remove) pattern = pattern.substring(1); + if (remove) { + pattern = pattern.substring(1); + } if (File.separator.equals("\\\\")) { pattern = pattern.replace('\\\\', '/'); @@ -1473,18 +1497,20 @@ public class CommandLineRunner extends if (i == 0) { break; } else { - prefix = Joiner.on("/").join(patternParts.subList(0, i)); - pattern = Joiner.on("/").join(patternParts.subList(i, patternParts.size())); + prefix = Joiner.on(File.separator).join(patternParts.subList(0, i)); + pattern = Joiner.on(File.separator).join(patternParts.subList(i, patternParts.size())); } } } - final PathMatcher matcher = fs.getPathMatcher("glob:" + pattern); + final PathMatcher matcher = fs.getPathMatcher("glob:" + (prefix.equals(".") + ? pattern + : prefix + File.separator + pattern)); java.nio.file.Files.walkFileTree( fs.getPath(prefix), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile( Path p, BasicFileAttributes attrs) { - if (matcher.matches(p)) { + if (matcher.matches(p.normalize())) { if (remove) { allJsInputs.remove(p.toString()); } else { diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java index fbee0ec4e..09463a96c 100644 --- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java +++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java @@ -42,6 +42,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; +import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -1113,6 +1114,36 @@ public final class CommandLineRunnerTest extends TestCase { } } + public void testGlobJs1() throws IOException { + try { + FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;"); + FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;"); + // Move test2 to the same directory as test1, also make the filename of test2 + // lexicographically larger than test1 + new File(jsFile2.value).renameTo(new File( + new File(jsFile1.value).getParentFile() + File.separator + "utest2.js")); + String glob = new File(jsFile1.value).getParent() + File.separator + "**.js"; + compileFiles( + "var a;var b;", new FlagEntry<>(JsSourceType.JS, glob)); + } catch (FlagUsageException e) { + fail("Unexpected exception" + e); + } + } + + public void testGlobJs2() throws IOException { + try { + FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;"); + FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;"); + new File(jsFile2.value).renameTo(new File( + new File(jsFile1.value).getParentFile() + File.separator + "utest2.js")); + String glob = new File(jsFile1.value).getParent() + File.separator + "*test*.js"; + compileFiles( + "var a;var b;", new FlagEntry<>(JsSourceType.JS, glob)); + } catch (FlagUsageException e) { + fail("Unexpected exception" + e); + } + } + public void testSourceMapInputs() throws Exception { args.add("--js_output_file"); args.add("/path/to/out.js"); @@ -1875,7 +1906,8 @@ public final class CommandLineRunnerTest extends TestCase { private static FlagEntry<JsSourceType> createZipFile(Map<String, String> entryContentsByName) throws IOException { - File tempZipFile = File.createTempFile("testdata", ".js.zip"); + File tempZipFile = File.createTempFile("testdata", ".js.zip", + Files.createTempDirectory("jscomp").toFile()); try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempZipFile))) { for (Entry<String, String> entry : entryContentsByName.entrySet()) { @@ -1889,9 +1921,11 @@ public final class CommandLineRunnerTest extends TestCase { private FlagEntry<JsSourceType> createJsFile(String filename, String fileContent) throws IOException { - File tempJsFile = File.createTempFile(filename, ".js"); - FileOutputStream fileOutputStream = new FileOutputStream(tempJsFile); - fileOutputStream.write(fileContent.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + File tempJsFile = File.createTempFile(filename, ".js", + Files.createTempDirectory("jscomp").toFile()); + try (FileOutputStream fileOutputStream = new FileOutputStream(tempJsFile)) { + fileOutputStream.write(fileContent.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } return new FlagEntry<>(JsSourceType.JS, tempJsFile.getAbsolutePath()); }
      ['src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,125,544
      1,615,261
      217,124
      706
      2,277
      480
      48
      1
      3,904
      319
      1,206
      100
      0
      2
      1970-01-01T00:24:13
      7,031
      Java
      {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}
      Apache License 2.0
      515
      google/closure-compiler/1469/1407
      google
      closure-compiler
      https://github.com/google/closure-compiler/issues/1407
      https://github.com/google/closure-compiler/pull/1469
      https://github.com/google/closure-compiler/pull/1469
      1
      fixes
      Cannot use globs when running the compiler.
      Since 62ca536... I am no longer able to use globs for files when running the compiler: Running this command used to work before that change: ``` java -jar ../../compiler/compiler.jar \\ --flagfile=options/compile.ini \\ --define "goog.json.USE_NATIVE_JSON=true" --define "goog.ui.Component.ALLOW_DETACHED_DECORATION=true" --define "goog.NATIVE_ARRAY_PROTOTYPES=true" --define "goog.array.ASSUME_NATIVE_FUNCTIONS=true" --define "goog.Promise.UNHANDLED_REJECTION_DELAY=-1" --define "app.settings.RUN_AS_USER=false" --externs=../externs/material.js --generate_exports --export_local_property_definitions --language_in=ECMASCRIPT6 --language_out=ES3 --use_types_for_optimization --output_wrapper="(function(){%output%})();" \\ --only_closure_dependencies \\ --closure_entry_point=app \\ --manage_closure_dependencies true \\ --output_manifest build/app.filelist.txt \\ --js_output_file /tmp/closure_compiler_build \\ --js="js/**.js" --js="tpl/en/**.js" --js="../../templates/soyutils_usegoog.js" --js="../../library/closure/goog/**.js" --js="../../library/third_party/closure/goog/mochikit/async/deferred.js" --js="../../library/third_party/closure/goog/mochikit/async/deferredlist.js" --js="../pstj/animation/**.js" --js="../pstj/app/**.js" --js="../pstj/autogenerated/**.js" --js="../pstj/cast/**.js" --js="../pstj/color/**.js" --js="../pstj/config/**.js" --js="../pstj/control/**.js" --js="../pstj/date/**.js" --js="../pstj/debug/**.js" --js="../pstj/ds/**.js" --js="../pstj/element/**.js" --js="../pstj/error/**.js" --js="../pstj/fx/**.js" --js="../pstj/graphics/**.js" --js="../pstj/material/**.js" --js="../pstj/math/**.js" --js="../pstj/mvc/**.js" --js="../pstj/ng/**.js" --js="../pstj/object/**.js" --js="../pstj/options/**.js" --js="../pstj/resource/**.js" --js="../pstj/sourcegen/**.js" --js="../pstj/storage/**.js" --js="../pstj/style/**.js" --js="../pstj/themes/**.js" --js="../pstj/ui/**.js" --js="../smjs/ds/**.js" --js="../smjs/element/**.js" --js="../smjs/persistence/**.js" --js="../smjs/player/**.js" --js="../smjs/remotecontrol/**.js" --js="../smjs/transport/**.js" --js="../smjs/tv/**.js" --js="../smjs/widgets/**.js" --js="!**_test.js" ``` Now (after the mentioned change) it gives this: ``` ERROR - Cannot read: !**_test.js ERROR - Cannot read: ../../library/closure/goog/**.js ERROR - Cannot read: ../pstj/animation/**.js ERROR - Cannot read: ../pstj/app/**.js ERROR - Cannot read: ../pstj/autogenerated/**.js ERROR - Cannot read: ../pstj/cast/**.js ERROR - Cannot read: ../pstj/color/**.js ERROR - Cannot read: ../pstj/config/**.js ERROR - Cannot read: ../pstj/control/**.js ERROR - Cannot read: ../pstj/date/**.js ERROR - Cannot read: ../pstj/debug/**.js ERROR - Cannot read: ../pstj/ds/**.js ERROR - Cannot read: ../pstj/element/**.js ERROR - Cannot read: ../pstj/error/**.js ERROR - Cannot read: ../pstj/fx/**.js ERROR - Cannot read: ../pstj/graphics/**.js ERROR - Cannot read: ../pstj/material/**.js ERROR - Cannot read: ../pstj/math/**.js ERROR - Cannot read: ../pstj/mvc/**.js ERROR - Cannot read: ../pstj/ng/**.js ERROR - Cannot read: ../pstj/object/**.js ERROR - Cannot read: ../pstj/options/**.js ERROR - Cannot read: ../pstj/resource/**.js ERROR - Cannot read: ../pstj/sourcegen/**.js ERROR - Cannot read: ../pstj/storage/**.js ERROR - Cannot read: ../pstj/style/**.js ERROR - Cannot read: ../pstj/themes/**.js ERROR - Cannot read: ../pstj/ui/**.js ERROR - Cannot read: ../smjs/ds/**.js ERROR - Cannot read: ../smjs/element/**.js ERROR - Cannot read: ../smjs/persistence/**.js ERROR - Cannot read: ../smjs/player/**.js ERROR - Cannot read: ../smjs/remotecontrol/**.js ERROR - Cannot read: ../smjs/transport/**.js ERROR - Cannot read: ../smjs/tv/**.js ERROR - Cannot read: ../smjs/widgets/**.js ERROR - Cannot read: js/**.js ERROR - Cannot read: tpl/en/**.js ERROR - required entry point "app" never provided 39 error(s), 0 warning(s) ```
      f98608a07dc43fb3e950a730ca59906179386ffb
      16d143d67f4c27aa1435d3561a64acbe039dc972
      https://github.com/google/closure-compiler/compare/f98608a07dc43fb3e950a730ca59906179386ffb...16d143d67f4c27aa1435d3561a64acbe039dc972
      diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java index fbdc565a5..87f9c2037 100644 --- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java +++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java @@ -2542,6 +2542,16 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, this.flag = flag; this.value = value; } + + @Override + public boolean equals(Object o) { + if (o instanceof FlagEntry) { + FlagEntry<?> that = (FlagEntry<?>) o; + return that.flag.equals(this.flag) + && that.value.equals(this.value); + } + return false; + } } /** diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java index 47c87615d..1f83037d4 100644 --- a/src/com/google/javascript/jscomp/CommandLineRunner.java +++ b/src/com/google/javascript/jscomp/CommandLineRunner.java @@ -61,6 +61,7 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -745,12 +746,21 @@ public class CommandLineRunner extends protected List<FlagEntry<JsSourceType>> getMixedJsSources() throws CmdLineException, IOException { List<FlagEntry<JsSourceType>> mixedSources = new ArrayList<>(); + Set<String> excludes = new HashSet<>(); for (FlagEntry<JsSourceType> source : Flags.mixedJsSources) { if (source.value.endsWith(".zip")) { mixedSources.add(source); + } else if (source.value.startsWith("!")) { + for (String filename : findJsFiles( + Collections.singletonList(source.value.substring(1)))) { + excludes.add(filename); + mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename)); + } } else { for (String filename : findJsFiles(Collections.singletonList(source.value))) { - mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename)); + if (!excludes.contains(filename)) { + mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename)); + } } } } @@ -1475,23 +1485,25 @@ public class CommandLineRunner extends */ public static List<String> findJsFiles(Collection<String> patterns) throws IOException { Set<String> allJsInputs = new TreeSet<>(); + Set<String> excludes = new HashSet<>(); for (String pattern : patterns) { if (!pattern.contains("*") && !pattern.startsWith("!")) { File matchedFile = new File(pattern); if (matchedFile.isDirectory()) { - matchPaths(new File(matchedFile, "**.js").toString(), allJsInputs); - } else { + matchPaths(new File(matchedFile, "**.js").toString(), allJsInputs, excludes); + } else if (!excludes.contains(pattern)) { allJsInputs.add(pattern); } } else { - matchPaths(pattern, allJsInputs); + matchPaths(pattern, allJsInputs, excludes); } } return new ArrayList<>(allJsInputs); } - private static void matchPaths(String pattern, final Set<String> allJsInputs) + private static void matchPaths(String pattern, final Set<String> allJsInputs, + final Set<String> excludes) throws IOException { FileSystem fs = FileSystems.getDefault(); final boolean remove = pattern.indexOf('!') == 0; @@ -1526,10 +1538,12 @@ public class CommandLineRunner extends @Override public FileVisitResult visitFile( Path p, BasicFileAttributes attrs) { if (matcher.matches(p.normalize())) { + String pathString = p.toString(); if (remove) { - allJsInputs.remove(p.toString()); - } else { - allJsInputs.add(p.toString()); + excludes.add(pathString); + allJsInputs.remove(pathString); + } else if (!excludes.contains(pathString)) { + allJsInputs.add(pathString); } } return FileVisitResult.CONTINUE; diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java index 66b8ec811..0af52d6cb 100644 --- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java +++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java @@ -1139,6 +1139,34 @@ public final class CommandLineRunnerTest extends TestCase { } } + public void testGlobJs3() throws IOException, FlagUsageException { + FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;"); + FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;"); + new File(jsFile2.value).renameTo(new File( + new File(jsFile1.value).getParentFile() + File.separator + "test2.js")); + // Make sure test2.js is excluded from the inputs when the exclusion + // comes after the inclusion + String glob1 = new File(jsFile1.value).getParent() + File.separator + "**.js"; + String glob2 = "!" + new File(jsFile1.value).getParent() + File.separator + "**test2.js"; + compileFiles( + "var a;", new FlagEntry<>(JsSourceType.JS, glob1), + new FlagEntry<>(JsSourceType.JS, glob2)); + } + + public void testGlobJs4() throws IOException, FlagUsageException { + FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;"); + FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;"); + new File(jsFile2.value).renameTo(new File( + new File(jsFile1.value).getParentFile() + File.separator + "test2.js")); + // Make sure test2.js is excluded from the inputs when the exclusion + // comes before the inclusion + String glob1 = "!" + new File(jsFile1.value).getParent() + File.separator + "**test2.js"; + String glob2 = new File(jsFile1.value).getParent() + File.separator + "**.js"; + compileFiles( + "var a;", new FlagEntry<>(JsSourceType.JS, glob1), + new FlagEntry<>(JsSourceType.JS, glob2)); + } + public void testSourceMapInputs() throws Exception { args.add("--js_output_file"); args.add("/path/to/out.js");
      ['src/com/google/javascript/jscomp/AbstractCommandLineRunner.java', 'src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      7,155,232
      1,622,150
      217,888
      708
      1,800
      354
      40
      2
      3,904
      319
      1,206
      100
      0
      2
      1970-01-01T00:24:14
      7,031
      Java
      {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}
      Apache License 2.0
      514
      google/closure-compiler/1549/1548
      google
      closure-compiler
      https://github.com/google/closure-compiler/issues/1548
      https://github.com/google/closure-compiler/pull/1549
      https://github.com/google/closure-compiler/pull/1549
      2
      fixes
      File order not maintained
      I call the closure compiler like: ``` java.exe -jar dev\\jars\\closure\\compiler.jar --compilation_level WHITESPACE_ONLY --formatting PRETTY_PRINT --formatting PRINT_INPUT_DELIMITER --formatting SINGLE_QUOTES --js_output_file jQuery_a52d83c3.min.js --js jquery.js ui\\core.js ui\\widget.js ui\\mouse.js ui\\draggable.js ui\\droppable.js ui\\resizable.js ui\\selectable.js ui\\sortable.js ui\\button.js ui\\position.js ``` When I use the `compiler.jar` from github binary downloads `compiler-20151216.tar.gz` everything is fine. When I use `compiler-20160208.tar.gz` the file originial order is not maintained in the compressed file which breaks the code, as the js files have to be included in a specific order. I tried the new parameter `--dependency_mode NONE` but it changed nothing. According to the docs should NONE be the default. I'm on Windows 10, 64 bit JAVA 8 as provided by Oracle.
      4544359bba2cac67e0ff13fda514b6e52d9d29cb
      b193c1b5b10c1246877c384526fc01d9f0db448b
      https://github.com/google/closure-compiler/compare/4544359bba2cac67e0ff13fda514b6e52d9d29cb...b193c1b5b10c1246877c384526fc01d9f0db448b
      diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java index 65e615bdd..cd1896c4a 100644 --- a/src/com/google/javascript/jscomp/CommandLineRunner.java +++ b/src/com/google/javascript/jscomp/CommandLineRunner.java @@ -62,6 +62,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -757,7 +758,7 @@ public class CommandLineRunner extends mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename)); } } else { - for (String filename : findJsFiles(Collections.singletonList(source.value))) { + for (String filename : findJsFiles(Collections.singletonList(source.value), true)) { if (!excludes.contains(filename)) { mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename)); } @@ -1503,7 +1504,20 @@ public class CommandLineRunner extends * within the directory and sub-directories. */ public static List<String> findJsFiles(Collection<String> patterns) throws IOException { - Set<String> allJsInputs = new TreeSet<>(); + return findJsFiles(patterns, false); + } + + /** + * Returns all the JavaScript files from the set of patterns. + * + * @param patterns A collection of filename patterns. + * @param sortAlphabetically Whether the output filenames should be in alphabetical order. + * @return The list of JS filenames found by expanding the patterns. + */ + private static List<String> findJsFiles(Collection<String> patterns, boolean sortAlphabetically) + throws IOException { + Set<String> allJsInputs = sortAlphabetically + ? new TreeSet<String>() : new LinkedHashSet<String>(); Set<String> excludes = new HashSet<>(); for (String pattern : patterns) { if (!pattern.contains("*") && !pattern.startsWith("!")) { diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java index 114df7d5e..e270af668 100644 --- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java +++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java @@ -1094,9 +1094,11 @@ public final class CommandLineRunnerTest extends TestCase { } public void testInputMultipleJsFilesWithOneJsFlag() throws IOException, FlagUsageException { + // Test that file order is preserved with --js test3.js test2.js test1.js FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;"); FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;"); - compileJsFiles("var a;var b;", jsFile1, jsFile2); + FlagEntry<JsSourceType> jsFile3 = createJsFile("test3", "var c;"); + compileJsFiles("var c;var b;var a;", jsFile3, jsFile2, jsFile1); } public void testGlobJs1() throws IOException, FlagUsageException {
      ['src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,185,495
      1,629,249
      218,744
      712
      865
      174
      18
      1
      883
      109
      223
      11
      0
      1
      1970-01-01T00:24:15
      7,031
      Java
      {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}
      Apache License 2.0
      517
      google/closure-compiler/1322/1314
      google
      closure-compiler
      https://github.com/google/closure-compiler/issues/1314
      https://github.com/google/closure-compiler/pull/1322
      https://github.com/google/closure-compiler/pull/1322
      1
      fixes
      Unlike var statements, const statements do not support multiple types
      Code - ``` // ==ClosureCompiler== // @output_file_name default.js // @compilation_level ADVANCED_OPTIMIZATIONS // @language ECMASCRIPT6_STRICT // ==/ClosureCompiler== "use strict"; const /** @const {string} */ foo = "1", /** @const {number} */ bar = 1; const /** @type {string} */ baz = "1", /** @type {number} */ taz = 1; ``` Warnings - ``` JSC_MULTIPLE_VAR_DEF: declaration of multiple variables with shared type information at line 2 character 0 const ^ JSC_MULTIPLE_VAR_DEF: declaration of multiple variables with shared type information at line 6 character 0 const ^ ``` Note - changing them to `var` avoids the warnings, of course.
      0767ef6c3863cd188d1f5fe61b73967ea9e3c912
      7de586e22e0663c275f2320ad4ddac4e23abb145
      https://github.com/google/closure-compiler/compare/0767ef6c3863cd188d1f5fe61b73967ea9e3c912...7de586e22e0663c275f2320ad4ddac4e23abb145
      diff --git a/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java b/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java index 291ff9a2e..bf678d067 100644 --- a/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java +++ b/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java @@ -132,17 +132,26 @@ public final class Es6RewriteBlockScopedDeclaration extends AbstractPostOrderCal if (!letConsts.isEmpty()) { for (Node n : letConsts) { if (n.isConst()) { - JSDocInfo existingInfo = n.getJSDocInfo(); - if (existingInfo == null) { - existingInfo = n.getFirstChild().getJSDocInfo(); - n.getFirstChild().setJSDocInfo(null); + // Normalize declarations like "const x = 1, y = 2;" so that inline + // type annotations are preserved. + for (Node child : n.children()) { + Node declaration = IR.var(child.detachFromParent()); + declaration.useSourceInfoFrom(n); + JSDocInfo existingInfo = n.getJSDocInfo(); + if (existingInfo == null) { + existingInfo = child.getJSDocInfo(); + child.setJSDocInfo(null); + } + JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo); + builder.recordConstancy(); + JSDocInfo info = builder.build(); + declaration.setJSDocInfo(info); + n.getParent().addChildAfter(declaration, n); } - JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo); - builder.recordConstancy(); - JSDocInfo info = builder.build(); - n.setJSDocInfo(info); + n.detachFromParent(); + } else { + n.setType(Token.VAR); } - n.setType(Token.VAR); } compiler.reportCodeChange(); } diff --git a/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java b/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java index fcc8c663c..270c277b4 100644 --- a/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java +++ b/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java @@ -778,6 +778,10 @@ public final class Es6RewriteBlockScopedDeclarationTest extends CompilerTestCase testWarning("/** @type {number} */ const x = 'str';", TypeValidator.TYPE_MISMATCH_WARNING); testWarning("const /** number */ x = 'str';", TypeValidator.TYPE_MISMATCH_WARNING); testWarning("const /** @type {number} */ x = 'str';", TypeValidator.TYPE_MISMATCH_WARNING); + testWarning("const /** @type {string} */ x = 3, /** @type {number} */ y = 3;", + TypeValidator.TYPE_MISMATCH_WARNING); + testWarning("const /** @type {string} */ x = 'str', /** @type {string} */ y = 3;", + TypeValidator.TYPE_MISMATCH_WARNING); } public void testDoWhileForOfCapturedLetAnnotated() {
      ['test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java', 'src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,100,552
      1,609,557
      216,424
      705
      1,284
      278
      27
      1
      651
      96
      182
      31
      0
      2
      1970-01-01T00:24:10
      7,031
      Java
      {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}
      Apache License 2.0
      513
      google/closure-compiler/3988/3840
      google
      closure-compiler
      https://github.com/google/closure-compiler/issues/3840
      https://github.com/google/closure-compiler/pull/3988
      https://github.com/google/closure-compiler/pull/3988
      1
      fixes
      --create_source_map throws exception on windows when using input source maps and chunks
      Closure throws an exception when I try to build source maps for chunks: java.io.FileNotFoundException: .\\dist\\closure\\common.js.map (The system cannot find the path specified) It seems like there's a race condition issue if the source map of a depending module is built before the dependency. It seems to work properly if I run the build without `--create_source_map`, and then run it again _with_ `--create_source_map`. Reproducer is available here: https://github.com/DerGernTod/ts-esbuild-closure-reproducer/blob/main/index.js The used flags: --chunk common:2 --chunk_wrapper common:(function(){%s})() --source_map_input dist/esbuild/chunk-7THFJKJQ.js|dist/esbuild/chunk-7THFJKJQ.js.map --js dist/esbuild/chunk-7THFJKJQ.js --source_map_input dist/esbuild/filecommon.js|dist/esbuild/filecommon.js.map --js dist/esbuild/filecommon.js --chunk filea:1:common --chunk_wrapper filea:(function(){%s})() --source_map_input dist/esbuild/filea.js|dist/esbuild/filea.js.map --js dist/esbuild/filea.js --chunk fileb:1:common --chunk_wrapper fileb:(function(){%s})() --source_map_input dist/esbuild/fileb.js|dist/esbuild/fileb.js.map --js dist/esbuild/fileb.js --language_in ECMASCRIPT_2017 --language_out ECMASCRIPT_2017 --chunk_output_path_prefix ./dist/closure/ --rename_prefix_namespace myNamespace --compilation_level ADVANCED_OPTIMIZATIONS --create_source_map %outname%.map I also tried `--source_map_include_content`, but that doesn't seem to work either (even if you build it once without source maps to prevent the error mentioned above, and then build it with source maps). The source is not embedded at all.
      3784fba4f48519472ca66792d0ed318ee443d44a
      55e3c557a2d9aae7cffefdad42140911130c8551
      https://github.com/google/closure-compiler/compare/3784fba4f48519472ca66792d0ed318ee443d44a...55e3c557a2d9aae7cffefdad42140911130c8551
      diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java index e27089744..ad4fdaff2 100644 --- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java +++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java @@ -1139,12 +1139,9 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co @GwtIncompatible("Unnecessary") private static void maybeCreateDirsForPath(String pathPrefix) { if (!Strings.isNullOrEmpty(pathPrefix)) { - String dirName = - pathPrefix.charAt(pathPrefix.length() - 1) == File.separatorChar - ? pathPrefix.substring(0, pathPrefix.length() - 1) - : new File(pathPrefix).getParent(); - if (dirName != null) { - new File(dirName).mkdirs(); + File parent = new File(pathPrefix).getParentFile(); + if (parent != null) { + parent.mkdirs(); } } } @@ -1769,7 +1766,8 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co throws IOException { parsedModuleWrappers = parseModuleWrappers(config.moduleWrapper, modules); if (!isOutputInJson()) { - maybeCreateDirsForPath(config.moduleOutputPathPrefix); + // make sure the method generates all dirs up to the latest / + maybeCreateDirsForPath(config.moduleOutputPathPrefix + "dummy"); } // If the source map path is in fact a pattern for each
      ['src/com/google/javascript/jscomp/AbstractCommandLineRunner.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      9,466,863
      2,112,089
      269,013
      876
      600
      130
      12
      1
      1,643
      150
      423
      31
      1
      0
      1970-01-01T00:27:41
      7,031
      Java
      {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078}
      Apache License 2.0
      404
      gocd/gocd/9900/9890
      gocd
      gocd
      https://github.com/gocd/gocd/issues/9890
      https://github.com/gocd/gocd/pull/9900
      https://github.com/gocd/gocd/pull/9900
      1
      fixes
      Double-Checked Locking might be incorrect in PipelineGroups
      https://github.com/gocd/gocd/blob/86b555e57daccec6b53b246f0dcdd4d0090566ef/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java#L183-L187 Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment. Unfortunately, it will not work reliably in a platform independent way when implemented in Java, without additional synchronization. Modify the variable ‘packageToPipelineMap’ with volatile to tackle the problem.
      0c6b1a98742b3aaa1e019d52c670ad9a1be013a9
      9d8ecf50f70adb4b80987d15a3f857bb257b5349
      https://github.com/gocd/gocd/compare/0c6b1a98742b3aaa1e019d52c670ad9a1be013a9...9d8ecf50f70adb4b80987d15a3f857bb257b5349
      diff --git a/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java b/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java index 02747ee396..abaa4e98d8 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java +++ b/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java @@ -21,8 +21,6 @@ import com.thoughtworks.go.config.exceptions.RecordNotFoundException; import com.thoughtworks.go.config.exceptions.UnprocessableEntityException; import com.thoughtworks.go.config.materials.PackageMaterialConfig; import com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig; -import com.thoughtworks.go.config.materials.ScmMaterialConfig; -import com.thoughtworks.go.domain.materials.MaterialConfig; import com.thoughtworks.go.domain.packagerepository.PackageDefinition; import com.thoughtworks.go.domain.packagerepository.PackageRepository; import com.thoughtworks.go.domain.scm.SCM; @@ -33,8 +31,8 @@ import java.util.*; @ConfigCollection(value = BasicPipelineConfigs.class) public class PipelineGroups extends BaseCollection<PipelineConfigs> implements Validatable { private final ConfigErrors configErrors = new ConfigErrors(); - private Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> packageToPipelineMap; - private Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> pluggableSCMMaterialToPipelineMap; + private volatile Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> packageToPipelineMap; + private volatile Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> pluggableSCMMaterialToPipelineMap; public PipelineGroups() { } @@ -235,10 +233,7 @@ public class PipelineGroups extends BaseCollection<PipelineConfigs> implements V public boolean canDeletePluggableSCMMaterial(SCM scmConfig) { Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> packageUsageInPipelines = getPluggableSCMMaterialUsageInPipelines(); - if (packageUsageInPipelines.containsKey(scmConfig.getId())) { - return false; - } - return true; + return !packageUsageInPipelines.containsKey(scmConfig.getId()); } public PipelineGroups getLocal() { diff --git a/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java b/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java index 553ea6019b..93b5f1315f 100644 --- a/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java +++ b/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java @@ -22,6 +22,7 @@ import com.thoughtworks.go.util.command.CommandArgument; import com.thoughtworks.go.util.command.UrlArgument; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; +import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,7 +31,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; -import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; import java.util.jar.JarEntry; @@ -44,16 +44,13 @@ class TfsSDKCommandBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(TfsSDKCommandBuilder.class); private final File tempFolder = new File("data/tfs-sdk"); private final ClassLoader sdkLoader; - private static TfsSDKCommandBuilder ME; + private static volatile TfsSDKCommandBuilder ME; - private TfsSDKCommandBuilder() throws IOException, URISyntaxException { + private TfsSDKCommandBuilder() throws IOException { this.sdkLoader = initSdkLoader(); } - /* - * Used in tests - */ - @Deprecated + @VisibleForTesting TfsSDKCommandBuilder(ClassLoader sdkLoader) { this.sdkLoader = sdkLoader; } @@ -61,7 +58,7 @@ class TfsSDKCommandBuilder { TfsCommand buildTFSSDKCommand(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, final String computedWorkspaceName, String projectPath) { try { - return instantitateAdapter(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath); + return instantiateAdapter(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath); } catch (Exception e) { String message = "[TFS SDK] Could not create TFS SDK Command "; LOGGER.error(message, e); @@ -69,7 +66,7 @@ class TfsSDKCommandBuilder { } } - private TfsCommand instantitateAdapter(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, String computedWorkspaceName, String projectPath) throws ReflectiveOperationException { + private TfsCommand instantiateAdapter(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, String computedWorkspaceName, String projectPath) throws ReflectiveOperationException { Class<?> adapterClass = Class.forName(tfsSdkCommandTCLAdapterClassName(), true, sdkLoader); Constructor<?> constructor = adapterClass.getConstructor(String.class, CommandArgument.class, String.class, String.class, String.class, String.class, String.class); return (TfsCommand) constructor.newInstance(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath); @@ -79,7 +76,7 @@ class TfsSDKCommandBuilder { return "com.thoughtworks.go.tfssdk.TfsSDKCommandTCLAdapter"; } - static TfsSDKCommandBuilder getBuilder() throws IOException, URISyntaxException { + static TfsSDKCommandBuilder getBuilder() throws IOException { if (ME == null) { synchronized (TfsSDKCommandBuilder.class) { if (ME == null) {
      ['domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java', 'config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      15,875,936
      3,177,194
      374,335
      3,354
      2,008
      393
      28
      2
      523
      48
      119
      6
      1
      0
      1970-01-01T00:27:18
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      408
      gocd/gocd/1052/1045
      gocd
      gocd
      https://github.com/gocd/gocd/issues/1045
      https://github.com/gocd/gocd/pull/1052
      https://github.com/gocd/gocd/pull/1052
      1
      fixed
      Temporary console log issues
      1) ~~Even though console logs are available in 'Artifacts' tab, yet i see following message there which should not be happen~~ ~~"Artifacts for this job instance are unavailable as they may have been purged by Go or deleted externally. Re-run the stage or job to generate them again."~~ This is not an issue [@arikagoyal] 2) a) When a job is cancelled, its o/p looks like this - [go] Job Completed Console-testing/8/defaultStage/1/job213:30:25.194 [go] Start to execute cancel task: Kills child processes 13:30:25.383 [go] Task is cancelled Expected : "[go] Job Completed Console-testing/8/defaultStage/1/job2" should show up in the end of console log b) Also on specifying job timeout, the console o/p looks like this - [go] Job Completed Simple-console-testing/3/defaultStage/1/defaultJobGo cancelled this job as it has not generated any console output for more than 2 minute(s)10:15:54.829 [go] Start to execute cancel task: Kills child processes 10:15:54.891 [go] Task is cancelled Expected o/p : Go cancelled this job as it has not generated any console output for more than 1 minute(s) [go] Start to execute cancel task: Kills child processes [go] Task is cancelled [go] Job completed test/4/defaultStage/1/defaultJob on f9c423f70d26 [/var/lib/cruise-agent] at Wed Apr 15 20:43:26 UTC 2015 Also at times when a job is cancelled, sometimes logs do not get moved to the final artifact location. 3) ~~If temporary console logs fails to make to the final artifact location due to disk space issue or permissions issue, they continue to lie in the temporary location forever. There should be a way to get these temp logs moved over to the actual location once the issue is resolved with the actual artifact location. Some automatic retry mechanism or on demand retry mechanism should be in place ?? Maybe in later releases ?~~ Moved this to #1057
      dd9050b6c43282dfcb1d7684038ea9cd9934d819
      81080bc7ced42ef543338721f9ca582e85ac8aef
      https://github.com/gocd/gocd/compare/dd9050b6c43282dfcb1d7684038ea9cd9934d819...81080bc7ced42ef543338721f9ca582e85ac8aef
      diff --git a/common/src/com/thoughtworks/go/remote/work/BuildWork.java b/common/src/com/thoughtworks/go/remote/work/BuildWork.java index 2732b8543e..b6bc734e87 100644 --- a/common/src/com/thoughtworks/go/remote/work/BuildWork.java +++ b/common/src/com/thoughtworks/go/remote/work/BuildWork.java @@ -94,6 +94,8 @@ public class BuildWork implements Work { LOGGER.error("Agent UUID changed in the middle of the build.", e); } catch (Exception e) { reportFailure(e); + } finally { + goPublisher.stop(); } } @@ -110,9 +112,9 @@ public class BuildWork implements Work { private void reportCompletion(JobResult result) { try { builders.waitForCancelTasks(); - goPublisher.stop(); if (result == null) { goPublisher.reportCurrentStatus(JobState.Completed); + goPublisher.reportCompletedAction(); } else { goPublisher.reportCompleted(result); } diff --git a/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java b/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java index 36aece3d2d..b7d3e8b71e 100644 --- a/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java +++ b/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java @@ -16,11 +16,13 @@ package com.thoughtworks.go.work; +import java.io.File; + +import com.thoughtworks.go.domain.builder.FetchArtifactBuilder; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.JobResult; import com.thoughtworks.go.domain.JobState; import com.thoughtworks.go.domain.Property; -import com.thoughtworks.go.domain.builder.FetchArtifactBuilder; import com.thoughtworks.go.publishers.GoArtifactsManipulator; import com.thoughtworks.go.remote.AgentIdentifier; import com.thoughtworks.go.remote.BuildRepositoryRemote; @@ -32,8 +34,6 @@ import com.thoughtworks.go.util.TimeProvider; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.io.File; - import static java.lang.String.format; public class DefaultGoPublisher implements GoPublisher { @@ -107,6 +107,11 @@ public class DefaultGoPublisher implements GoPublisher { LOG.info(String.format("%s is reporting build result [%s] to Go Server for %s", agentIdentifier, result, jobIdentifier.toFullString())); remoteBuildRepository.reportCompleted(agentRuntimeInfo, jobIdentifier, result); + reportCompletedAction(); + } + + public void reportCompletedAction() { + reportAction("Job completed"); } public boolean isIgnored() { diff --git a/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java b/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java index 9a39151595..38643b1547 100644 --- a/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java +++ b/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java @@ -22,12 +22,9 @@ import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.JobInstance; import com.thoughtworks.go.server.domain.JobStatusListener; import com.thoughtworks.go.server.service.ConsoleService; -import com.thoughtworks.go.util.GoConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import static java.lang.String.format; - @Component public class ConsoleLogArtifactHandler implements JobStatusListener { private ConsoleService consoleService; @@ -43,9 +40,6 @@ public class ConsoleLogArtifactHandler implements JobStatusListener { try { JobIdentifier identifier = job.getIdentifier(); consoleService.moveConsoleArtifacts(identifier); - // TODO: Put correct timestamp of job completion the agent and the server maybe on different timezones. - consoleService.appendToConsoleLog(identifier, format("[%s] %s %s", GoConstants.PRODUCT_NAME, "Job Completed" - , identifier.buildLocatorForDisplay())); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/server/src/com/thoughtworks/go/server/service/ConsoleService.java b/server/src/com/thoughtworks/go/server/service/ConsoleService.java index 74609d7b3a..c55be1ec99 100644 --- a/server/src/com/thoughtworks/go/server/service/ConsoleService.java +++ b/server/src/com/thoughtworks/go/server/service/ConsoleService.java @@ -173,6 +173,7 @@ public class ConsoleService { public void moveConsoleArtifacts(LocatableEntity locatableEntity) { try { File from = chooser.temporaryConsoleFile(locatableEntity); + from.createNewFile(); // Job cancellation skips temporary file creation. Force create one if it does not exist. File to = chooser.findArtifact(locatableEntity, getConsoleOutputFolderAndFileName()); FileUtils.moveFile(from, to); } catch (IOException e) { diff --git a/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java b/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java index a7e297e068..86ab26af52 100644 --- a/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java +++ b/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java @@ -35,12 +35,6 @@ public class ConsoleLogArtifactHandlerTest { verify(consoleService, never()).moveConsoleArtifacts(buildingJobInstance.getIdentifier()); } - @Test - public void shouldReportJobAsCompletedOnConsole() throws Exception { - handler.jobStatusChanged(completedJobInstance); - verify(consoleService).appendToConsoleLog(completedJobInstance.getIdentifier(), "[go] Job Completed pipeline/label-1/stage/1/job"); - } - @Test public void shouldReportJobAsCompletedOnConsoleOnlyWhenStatusIsCompleted() throws Exception { handler.jobStatusChanged(buildingJobInstance);
      ['server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java', 'common/src/com/thoughtworks/go/work/DefaultGoPublisher.java', 'server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java', 'common/src/com/thoughtworks/go/remote/work/BuildWork.java', 'server/src/com/thoughtworks/go/server/service/ConsoleService.java']
      {'.java': 5}
      5
      5
      0
      0
      5
      7,843,133
      1,575,547
      204,493
      1,780
      967
      172
      22
      4
      1,861
      292
      454
      31
      0
      0
      1970-01-01T00:23:49
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      409
      gocd/gocd/1003/1000
      gocd
      gocd
      https://github.com/gocd/gocd/issues/1000
      https://github.com/gocd/gocd/pull/1003
      https://github.com/gocd/gocd/pull/1003
      1
      fixes
      handle special characters in material name in pipeline label template
      In XSD [here](https://github.com/gocd/gocd/blob/master/config/config-server/resources/cruise-config.xsd#L715) the label template allows special characters like `-` in material name inside `${ }`. But [here](https://github.com/gocd/gocd/blob/master/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java#L45) we don't match them in material name. causes `${git-repo}` to not get resolved to revision.
      0e31f680841b78cc06d851d731ff7da9ee1493ae
      ee180c73421285ee93905caa7c0db27166df1219
      https://github.com/gocd/gocd/compare/0e31f680841b78cc06d851d731ff7da9ee1493ae...ee180c73421285ee93905caa7c0db27166df1219
      diff --git a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java index 36e2d48f34..7a834ee52a 100644 --- a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java +++ b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java @@ -19,6 +19,7 @@ package com.thoughtworks.go.domain; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.materials.ScmMaterial; import com.thoughtworks.go.config.materials.mercurial.HgMaterial; +import com.thoughtworks.go.config.materials.svn.SvnMaterial; import com.thoughtworks.go.domain.label.PipelineLabel; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.helper.MaterialsMother; @@ -221,7 +222,7 @@ public class PipelineLabelTest { public void canMatchWithOneTruncationAsFirstRevision() throws Exception { final String[][] expectedGroups = { {"git", "4"}, { "svn" } }; String res = assertLabelGroupsMatchingAndReplace("release-${git[:4]}-${svn}", expectedGroups); - assertThat(res, is("release-" + GIT_REVISION.substring(0, 4) + "-" + SVN_REVISION)); + assertThat(res, is("release-" + GIT_REVISION.substring(0, 4) + "-" + SVN_REVISION)); } @Test @@ -231,6 +232,36 @@ public class PipelineLabelTest { assertThat(res, is("release-" + GIT_REVISION.substring(0, 5) + "-" + SVN_REVISION.substring(0, 3))); } + @Test + public void canNotMatchWithTruncationWhenMaterialNameHasAColon() throws Exception { + final String[][] expectedGroups = { { "git:one", "7" } }; + String res = assertLabelGroupsMatchingAndReplace("release-${git:one[:7]}", expectedGroups); + assertThat(res, is("release-${git:one[:7]}")); + } + + @Test + public void shouldReplaceTheTemplateWithSpecialCharacters() throws Exception { + ensureLabelIsReplaced("SVNMaterial"); + ensureLabelIsReplaced("SVN-Material"); + ensureLabelIsReplaced("SVN_Material"); + ensureLabelIsReplaced("SVN!Material"); + ensureLabelIsReplaced("SVN__##Material_1023_WithNumbers"); + ensureLabelIsReplaced("SVN_Material-_!!_"); + ensureLabelIsReplaced("svn_Material'WithQuote"); + ensureLabelIsReplaced("SVN_Material.With.Period"); + ensureLabelIsReplaced("SVN_Material#With#Hash"); + ensureLabelIsReplaced("SVN_Material:With:Colon"); + ensureLabelIsReplaced("SVN_Material~With~Tilde"); + + ensureLabelIsNOTReplaced("SVN*MATERIAL"); + ensureLabelIsNOTReplaced("SVN+Material"); + ensureLabelIsNOTReplaced("SVN^Material"); + ensureLabelIsNOTReplaced("SVN_Material(With)Parentheses"); + ensureLabelIsNOTReplaced("SVN_Material{With}Braces"); + ensureLabelIsNOTReplaced("SVN**Material"); + ensureLabelIsNOTReplaced("SVN\\\\Material_With_Backslash"); + } + @BeforeClass public static void setup() { MATERIAL_REVISIONS.put(new CaseInsensitiveString("svnRepo.verynice"), SVN_REVISION); @@ -285,4 +316,23 @@ public class PipelineLabelTest { } return builder.toString(); } + + private void ensureLabelIsReplaced(String name) { + PipelineLabel label = getReplacedLabelFor(name, String.format("release-${%s}", name)); + assertThat(label.toString(), is("release-" + ModificationsMother.currentRevision())); + } + + private void ensureLabelIsNOTReplaced(String name) { + String labelFormat = String.format("release-${%s}", name); + PipelineLabel label = getReplacedLabelFor(name, labelFormat); + assertThat(label.toString(), is(labelFormat)); + } + + private PipelineLabel getReplacedLabelFor(String name, String labelFormat) { + MaterialRevisions materialRevisions = ModificationsMother.oneUserOneFile(); + PipelineLabel label = PipelineLabel.create(labelFormat); + ((SvnMaterial) materialRevisions.getRevisions().get(0).getMaterial()).setName(new CaseInsensitiveString(name)); + label.updateLabel(materialRevisions.getNamedRevisions()); + return label; + } } diff --git a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java index 0b77ba92da..132a09b249 100644 --- a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java +++ b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java @@ -42,7 +42,7 @@ public class PipelineLabel implements Serializable { return label; } - public static final Pattern PATTERN = Pattern.compile("(?i)\\\\$\\\\{([\\\\w\\\\.]+)(\\\\[:(\\\\d+)\\\\])?\\\\}"); + public static final Pattern PATTERN = Pattern.compile("(?i)\\\\$\\\\{([a-zA-Z0-9_\\\\-\\\\.!~'#:]+)(\\\\[:(\\\\d+)\\\\])?\\\\}"); private String replaceRevisionsInLabel(Map<CaseInsensitiveString, String> materialRevisions) { final Matcher matcher = PATTERN.matcher(this.label);
      ['config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java', 'common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,829,565
      1,572,877
      204,139
      1,777
      222
      81
      2
      1
      420
      34
      106
      4
      2
      0
      1970-01-01T00:23:48
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      405
      gocd/gocd/9899/9889
      gocd
      gocd
      https://github.com/gocd/gocd/issues/9889
      https://github.com/gocd/gocd/pull/9899
      https://github.com/gocd/gocd/pull/9899
      1
      fixes
      Unreleased Resource: Streams in business continuity ViewResolver
      https://github.com/gocd/gocd/blob/86b555e57daccec6b53b246f0dcdd4d0090566ef/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java#L40 The program can potentially fail to release a system resource.
      c83d03b8ff7b4dd04915476f409c7625ce0c7602
      750effbf9f204a1c9203f4caefa7a9f5a768e483
      https://github.com/gocd/gocd/compare/c83d03b8ff7b4dd04915476f409c7625ce0c7602...750effbf9f204a1c9203f4caefa7a9f5a768e483
      diff --git a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java index d45bf86971..edd169b2c2 100644 --- a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java +++ b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java @@ -21,6 +21,7 @@ import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; +import java.util.Objects; import static java.text.MessageFormat.format; @@ -68,33 +69,20 @@ public class FileValidator implements Validator { String message = format("File {0} is not readable or writeable.", file.getAbsolutePath()); return validation.addError(new RuntimeException(message)); } - } else { - // Pull out the file from the class path - InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName); + } + // Pull out the file from the class path + try (InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName)) { if (input == null) { String message = format("Resource {0}/{1} does not exist in the classpath", srcDir, fileName); return validation.addError(new RuntimeException(message)); - } else { - FileOutputStream output = null; - try { - // Make sure the dir exists - file.getParentFile().mkdirs(); - output = new FileOutputStream(file); - IOUtils.copy(input, output); - } catch (Exception e) { - return handleExceptionDuringFileHandling(validation, e); - } finally { - try { - input.close(); - if (output != null) { - output.flush(); - output.close(); - } - } catch (Exception e) { - return handleExceptionDuringFileHandling(validation, e); - } - } } + // Make sure the dir exists + file.getParentFile().mkdirs(); + try (FileOutputStream output = new FileOutputStream(file)) { + IOUtils.copy(input, output); + } + } catch (Exception e) { + return handleExceptionDuringFileHandling(validation, e); } return Validation.SUCCESS; } @@ -112,9 +100,9 @@ public class FileValidator implements Validator { FileValidator that = (FileValidator) o; if (shouldReplace != that.shouldReplace) return false; - if (fileName != null ? !fileName.equals(that.fileName) : that.fileName != null) return false; - if (srcDir != null ? !srcDir.equals(that.srcDir) : that.srcDir != null) return false; - return destDir != null ? destDir.equals(that.destDir) : that.destDir == null; + if (!Objects.equals(fileName, that.fileName)) return false; + if (!Objects.equals(srcDir, that.srcDir)) return false; + return Objects.equals(destDir, that.destDir); } @Override diff --git a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java index f49ae008d3..63b4aed02d 100644 --- a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java +++ b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java @@ -23,7 +23,6 @@ import org.jdom2.input.SAXBuilder; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.io.InputStream; import java.text.ParseException; import java.util.HashMap; import java.util.List; @@ -69,10 +68,7 @@ public class SvnLogXmlParserTest { @Test public void shouldParseSvnLogContainingNullComments() throws IOException { - String xml; - try (InputStream stream = getClass().getResourceAsStream("jemstep_svn_log.xml")) { - xml = IOUtils.toString(stream, UTF_8); - } + String xml = IOUtils.toString(getClass().getResource("jemstep_svn_log.xml"), UTF_8); SvnLogXmlParser parser = new SvnLogXmlParser(); List<Modification> revisions = parser.parse(xml, "", new SAXBuilder()); diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java index 807a0edd83..f504b22c22 100644 --- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java +++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java @@ -35,7 +35,10 @@ import com.thoughtworks.go.config.remote.PartialConfig; import com.thoughtworks.go.config.rules.Allow; import com.thoughtworks.go.config.rules.Deny; import com.thoughtworks.go.config.rules.Rules; -import com.thoughtworks.go.config.validation.*; +import com.thoughtworks.go.config.validation.ArtifactDirValidator; +import com.thoughtworks.go.config.validation.GoConfigValidator; +import com.thoughtworks.go.config.validation.ServerIdImmutabilityValidator; +import com.thoughtworks.go.config.validation.TokenGenerationKeyImmutabilityValidator; import com.thoughtworks.go.domain.*; import com.thoughtworks.go.domain.config.*; import com.thoughtworks.go.domain.label.PipelineLabel; @@ -1690,15 +1693,6 @@ public class MagicalGoConfigXmlLoaderTest { ConfigMigrator.loadWithMigration(content); // should not fail with a validation exception } - @Test - void shouldLoadLargeConfigFileInReasonableTime() throws Exception { - String content = IOUtils.toString(getClass().getResourceAsStream("/data/big-cruise-config.xml"), UTF_8); -// long start = System.currentTimeMillis(); - GoConfigHolder configHolder = ConfigMigrator.loadWithMigration(content); -// assertThat(System.currentTimeMillis() - start, lessThan(new Long(2000))); - assertThat(configHolder.config.schemaVersion()).isEqualTo(CONFIG_SCHEMA_VERSION); - } - @Test void shouldLoadConfigWithPipelinesMatchingUpWithPipelineDefinitionCaseInsensitively() { String content = configWithEnvironments( @@ -3884,7 +3878,7 @@ public class MagicalGoConfigXmlLoaderTest { final CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(configXml).configForEdit; final ArtifactTypeConfigs artifactTypeConfigs = cruiseConfig.pipelineConfigByName( - new CaseInsensitiveString("up42")).getStage("up42_stage") + new CaseInsensitiveString("up42")).getStage("up42_stage") .getJobs().getJob(new CaseInsensitiveString("up42_job")).artifactTypeConfigs(); assertThat(artifactTypeConfigs).hasSize(1); @@ -4224,7 +4218,7 @@ public class MagicalGoConfigXmlLoaderTest { ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfo(pluginDescriptor, storeConfigSettings, publishArtifactSettings, fetchArtifactSettings, null, new Capabilities()); ArtifactMetadataStore.instance().setPluginInfo(artifactPluginInfo); - String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8)); + String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8)); CruiseConfig config = xmlLoader.loadConfigHolder(content).configForEdit; PipelineConfig ancestor = config.pipelineConfigByName(new CaseInsensitiveString("ancestor")); @@ -4484,7 +4478,7 @@ public class MagicalGoConfigXmlLoaderTest { MaterialConfig materialConfig = config .getPipelineConfigByName(new CaseInsensitiveString("pipeline")) .materialConfigs().get(0); - + assertThat(materialConfig).isInstanceOf(PluggableSCMMaterialConfig.class); assertThat(materialConfig.isInvertFilter()).isTrue(); } diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java index de03835525..94a55028ba 100644 --- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java +++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java @@ -55,14 +55,15 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.InputStream; import static com.thoughtworks.go.helper.MaterialConfigsMother.git; import static com.thoughtworks.go.helper.MaterialConfigsMother.tfs; import static com.thoughtworks.go.util.DataStructureUtils.m; import static com.thoughtworks.go.util.GoConstants.CONFIG_SCHEMA_VERSION; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.fail; @ExtendWith(ResetCipher.class) @@ -321,7 +322,9 @@ public class MagicalGoConfigXmlWriterTest { @Test public void shouldBeAValidXSD() throws Exception { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); - factory.newSchema(new StreamSource(getClass().getResourceAsStream("/cruise-config.xsd"))); + try (InputStream xsdStream = getClass().getResourceAsStream("/cruise-config.xsd")) { + factory.newSchema(new StreamSource(xsdStream)); + } } @Test diff --git a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java index 6c96c73262..2ab651bece 100644 --- a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java +++ b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java @@ -40,9 +40,9 @@ public class ConfigRepoMigrator { } private Chainr getTransformerFor(int targetVersion) { + String targetVersionFile = String.format("/config-repo/migrations/%s.json", targetVersion); try { - String targetVersionFile = String.format("/config-repo/migrations/%s.json", targetVersion); - String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(targetVersionFile), StandardCharsets.UTF_8); + String transformJSON = IOUtils.toString(this.getClass().getResource(targetVersionFile), StandardCharsets.UTF_8); return Chainr.fromSpec(JsonUtils.jsonToList(transformJSON)); } catch (Exception e) { throw new RuntimeException("Failed to migrate to version " + targetVersion, e); @@ -50,9 +50,9 @@ public class ConfigRepoMigrator { } private Map<String, Object> getContextMap(int targetVersion) { + String contextFile = String.format("/config-repo/contexts/%s.json", targetVersion); try { - String contextFile = String.format("/config-repo/contexts/%s.json", targetVersion); - String contextJSON = IOUtils.toString(this.getClass().getResourceAsStream(contextFile), StandardCharsets.UTF_8); + String contextJSON = IOUtils.toString(this.getClass().getResource(contextFile), StandardCharsets.UTF_8); return JsonUtils.jsonToMap(contextJSON); } catch (Exception e) { LOGGER.debug(String.format("No context file present for target version '%s'.", targetVersion)); diff --git a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java index 90885bd189..2cf16d1836 100644 --- a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java +++ b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java @@ -18,6 +18,7 @@ package com.thoughtworks.go.plugin.access.configrepo; import com.bazaarvoice.jolt.JsonUtils; import org.apache.commons.io.IOUtils; +import java.nio.charset.StandardCharsets; import java.util.Map; import static com.bazaarvoice.jolt.utils.JoltUtils.remove; @@ -41,7 +42,7 @@ class ConfigRepoDocumentMother { private Map<String, Object> getJSONFor(String fileName) { try { - String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(fileName), "UTF-8"); + String transformJSON = IOUtils.toString(this.getClass().getResource(fileName), StandardCharsets.UTF_8); return JsonUtils.jsonToMap(transformJSON); } catch (Exception e) { throw new RuntimeException(e); diff --git a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java index 44c809ffd6..d16eaadece 100644 --- a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java +++ b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java @@ -22,6 +22,7 @@ import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.Map; import static java.lang.String.format; @@ -36,9 +37,8 @@ public class ViewResolver { } public String resolveView(String viewName, Map<String, String> modelMap) { - try { - InputStream resourceAsStream = getResourceAsStream(viewName); - String template = IOUtils.toString(resourceAsStream, "UTF-8"); + try (InputStream resourceAsStream = getResourceAsStream(viewName)) { + String template = IOUtils.toString(resourceAsStream, StandardCharsets.UTF_8); for (String modelKey : modelMap.keySet()) { template = template.replaceAll(format("<<<%s>>>", modelKey), modelMap.get(modelKey)); } diff --git a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java index b2ae2982cb..0a66781184 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java @@ -118,7 +118,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin try { byte[] payload = Base64.getDecoder().decode(data.getBytes()); - byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResourceAsStream("/" + PLUGIN_ENDPOINT_JS)); + byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResource("/" + PLUGIN_ENDPOINT_JS)); try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(payload))) { String assetsHash = calculateHash(payload, pluginEndpointJsContent); @@ -139,7 +139,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin private void safeCopyExternalAssetsToPluginAssetRoot(final String pluginAssetsRoot) { Path externalAssetsPath = Paths.get(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS)); - if (externalAssetsPath == null || !Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) { + if (!Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) { LOGGER.debug("Analytics plugin external assets path ({}) does not exist or is not a directory. Not loading any assets.", externalAssetsPath); return; } @@ -184,9 +184,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin LOGGER.info("Deleting cached static assets for plugin: {}", pluginId); try { FileUtils.deleteDirectory(new File(pluginStaticAssetsRootDir(pluginId))); - if (pluginAssetPaths.containsKey(pluginId)) { - pluginAssetPaths.remove(pluginId); - } + pluginAssetPaths.remove(pluginId); } catch (Exception e) { LOGGER.error("Failed to delete cached static assets for plugin: {}", pluginId, e); ExceptionUtils.bomb(e); diff --git a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java index 4e750c430a..c71e9091a0 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java @@ -3,6 +3,7 @@ package com.thoughtworks.go.addon.businesscontinuity; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import static org.hamcrest.MatcherAssert.assertThat; @@ -20,7 +21,7 @@ class ViewResolverTest { modelMap.put("key2", "value2"); ViewResolver viewResolverSpy = spy(new ViewResolver()); - doReturn(IOUtils.toInputStream(template)).when(viewResolverSpy).getResourceAsStream("sample"); + doReturn(IOUtils.toInputStream(template, StandardCharsets.UTF_8)).when(viewResolverSpy).getResourceAsStream("sample"); String resolvedView = viewResolverSpy.resolveView("sample", modelMap); assertThat(resolvedView, is("<html><head><link href=\\"value1\\\\value2\\"/></head></html>")); diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java index 283cdda954..52e4ce6b62 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java @@ -24,7 +24,6 @@ import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -35,7 +34,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -76,7 +74,7 @@ public class AnalyticsPluginAssetsServiceTest { } @Test - public void shouldBeAPluginMetadataChangeListener() throws Exception { + public void shouldBeAPluginMetadataChangeListener() { verify(analyticsMetadataLoader).registerListeners(assetsService); } @@ -165,7 +163,7 @@ public class AnalyticsPluginAssetsServiceTest { assertTrue(pluginDirPath.toFile().exists()); assertTrue(actualPath.toFile().exists()); - byte[] expected = IOUtils.toByteArray(getClass().getResourceAsStream("/plugin-endpoint.js")); + byte[] expected = IOUtils.toByteArray(getClass().getResource("/plugin-endpoint.js")); assertArrayEquals(expected, Files.readAllBytes(actualPath), "Content of plugin-endpoint.js should be preserved"); } @@ -178,8 +176,8 @@ public class AnalyticsPluginAssetsServiceTest { when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive()); when(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS)).thenReturn(externalAssetsDir.getAbsolutePath()); - Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), "a.js"), "a".getBytes(StandardCharsets.UTF_8)); - Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), "b.js"), "b".getBytes(StandardCharsets.UTF_8)); + Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), "a.js"), "a"); + Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), "b.js"), "b"); assetsService.onPluginMetadataCreate(PLUGIN_ID); @@ -241,7 +239,7 @@ public class AnalyticsPluginAssetsServiceTest { } private String testDataZipArchive() throws IOException { - return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResourceAsStream("/plugin_cache_test.zip")))); + return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResource("/plugin_cache_test.zip")))); } private void addAnalyticsPluginInfoToStore(String pluginId) { diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java index 6c83d9839b..ed7c1caab2 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java @@ -32,7 +32,6 @@ import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.io.InputStream; import java.io.PrintWriter; import java.util.Optional; @@ -48,7 +47,6 @@ public class BackupFilterTest { private FilterChain chain; private BackupService backupService; private PrintWriter writer; - private InputStream inputStream; @BeforeEach public void setUp() throws ServletException, IOException { @@ -57,7 +55,6 @@ public class BackupFilterTest { res = mock(HttpServletResponse.class); backupService = mock(BackupService.class); chain = mock(FilterChain.class); - inputStream = BackupFilter.class.getClassLoader().getResourceAsStream("backup_in_progress.html"); writer = mock(PrintWriter.class); when(res.getWriter()).thenReturn(writer); this.backupFilter = new BackupFilter(backupService); @@ -99,7 +96,7 @@ public class BackupFilterTest { when(backupService.backupRunningSinceISO8601()).thenReturn(BACKUP_STARTED_AT); when(backupService.backupStartedBy()).thenReturn(BACKUP_STARTED_BY); - String content = IOUtils.toString(inputStream, UTF_8); + String content = IOUtils.toString(BackupFilter.class.getClassLoader().getResource("backup_in_progress.html"), UTF_8); content = backupFilter.replaceStringLiterals(content); Request request = request(HttpMethod.GET, "", "/go/agents"); diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java index e0a00b18b0..7417d7b1d6 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java @@ -54,7 +54,10 @@ import com.thoughtworks.go.serverhealth.HealthStateType; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.serverhealth.ServerHealthState; import com.thoughtworks.go.service.ConfigRepository; -import com.thoughtworks.go.util.*; +import com.thoughtworks.go.util.GoConstants; +import com.thoughtworks.go.util.ReflectionUtil; +import com.thoughtworks.go.util.SystemEnvironment; +import com.thoughtworks.go.util.TempDirUtils; import com.thoughtworks.go.util.command.CommandLine; import com.thoughtworks.go.util.command.ConsoleResult; import org.apache.commons.io.FileUtils; @@ -1200,7 +1203,7 @@ public class CachedGoConfigIntegrationTest { ArtifactStore artifactStore = new ArtifactStore("dockerhub", "cd.go.artifact.docker.registry"); artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult()); File configFile = new File(new SystemEnvironment().getCruiseConfigFile()); - String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8)); + String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8)); FileUtils.writeStringToFile(configFile, config, UTF_8); cachedGoConfig.forceReload(); @@ -1221,7 +1224,7 @@ public class CachedGoConfigIntegrationTest { ArtifactStore artifactStore = new ArtifactStore("dockerhub", "cd.go.artifact.docker.registry"); artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult()); File configFile = new File(new SystemEnvironment().getCruiseConfigFile()); - String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8)); + String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8)); FileUtils.writeStringToFile(configFile, config, UTF_8); cachedGoConfig.forceReload(); diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java index 2668a2a71e..32236b8585 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java +++ b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java @@ -41,8 +41,8 @@ import java.util.ArrayList; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; -import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { @@ -70,7 +70,7 @@ public abstract class FullConfigSaveFlowTestBase { public void setUp() throws Exception { configHelper = new GoConfigFileHelper(goConfigDao); configHelper.onSetUp(); - xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8)); + xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8)); loader = new MagicalGoConfigXmlLoader(configCache, registry); setupMetadataForPlugin(); } diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java index 6910f8d923..f9d8272ca5 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java @@ -27,7 +27,9 @@ import com.thoughtworks.go.security.ResetCipher; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.service.ConfigRepository; -import com.thoughtworks.go.util.*; +import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother; +import com.thoughtworks.go.util.SystemEnvironment; +import com.thoughtworks.go.util.TimeProvider; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.jdom2.Document; @@ -112,7 +114,7 @@ public class GoConfigMigrationIntegrationTest { @Test public void shouldMigrateToRevision22() throws Exception { - final String content = IOUtils.toString(getClass().getResourceAsStream("cruise-config-escaping-migration-test-fixture.xml"), UTF_8); + final String content = IOUtils.toString(getClass().getResource("cruise-config-escaping-migration-test-fixture.xml"), UTF_8); String migratedContent = ConfigMigrator.migrate(content, 21, 22); @@ -122,7 +124,7 @@ public class GoConfigMigrationIntegrationTest { @Test public void shouldMigrateToRevision28() throws Exception { - final String content = IOUtils.toString(getClass().getResourceAsStream("no-tracking-tool-group-holder-config.xml"), UTF_8); + final String content = IOUtils.toString(getClass().getResource("no-tracking-tool-group-holder-config.xml"), UTF_8); String migratedContent = migrateXmlString(content, 27); @@ -132,7 +134,7 @@ public class GoConfigMigrationIntegrationTest { @Test public void shouldMigrateToRevision34() throws Exception { - final String content = IOUtils.toString(getClass().getResourceAsStream("svn-p4-with-parameterized-passwords.xml"), UTF_8); + final String content = IOUtils.toString(getClass().getResource("svn-p4-with-parameterized-passwords.xml"), UTF_8); String migratedContent = ConfigMigrator.migrate(content, 22, 34); @@ -144,7 +146,7 @@ public class GoConfigMigrationIntegrationTest { @Test public void shouldMigrateToRevision35_escapeHash() throws Exception { - final String content = IOUtils.toString(getClass().getResourceAsStream("escape_param_for_nant_p4.xml"), UTF_8).trim(); + final String content = IOUtils.toString(getClass().getResource("escape_param_for_nant_p4.xml"), UTF_8).trim(); String migratedContent = ConfigMigrator.migrate(content, 22, 35); diff --git a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java index d8aba694df..d215589cb0 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java @@ -71,7 +71,7 @@ public class PipelineConfigsServiceIntegrationTest { @BeforeEach public void setUp() throws Exception { configHelper = new GoConfigFileHelper(); - xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/config_with_pluggable_artifacts_store.xml"), UTF_8)); + xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/config_with_pluggable_artifacts_store.xml"), UTF_8)); setupMetadataForPlugin(); configHelper.usingCruiseConfigDao(goConfigDao); @@ -201,7 +201,7 @@ public class PipelineConfigsServiceIntegrationTest { } private String groupSnippetWithSecurePropertiesBeforeEncryption() throws IOException { - return IOUtils.toString(getClass().getResourceAsStream("/data/pipeline_group_snippet_with_pluggable_artifacts.xml"), UTF_8); + return IOUtils.toString(getClass().getResource("/data/pipeline_group_snippet_with_pluggable_artifacts.xml"), UTF_8); } }
      ['server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java', 'plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java', 'server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java', 'base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java', 'server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java', 'server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java', 'server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java', 'plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java', 'config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java', 'common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java', 'config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java', 'server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java', 'server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java']
      {'.java': 15}
      15
      15
      0
      0
      15
      15,876,612
      3,177,279
      374,348
      3,354
      8,706
      1,665
      111
      11
      228
      11
      67
      3
      1
      0
      1970-01-01T00:27:18
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      403
      gocd/gocd/10087/10086
      gocd
      gocd
      https://github.com/gocd/gocd/issues/10086
      https://github.com/gocd/gocd/pull/10087
      https://github.com/gocd/gocd/pull/10087
      1
      fixes
      Test Drive/standalone GoCD fails to start when commit GPG signing is enabled at system/user level
      ##### Issue Type - Bug Report ##### Summary When I run Test Drive 21.4.0 (`gocd-21.4.0-13469-1477-osx`) which is current stable version, GoCD server couldn't be started. ##### Environment On my macbook ###### Basic environment details * Go Version: `21.4.0` * JAVA Version: `openjdk 15.0.4` * OS: `macOS 11.6` ##### Steps to Reproduce 1. Run `curl -fsSL 'https://www.gocd.org/test-drive-gocd/try.sh' | bash -s 'https://download.gocd.org/test-drive/installers/21.4.0/13469/gocd-21.4.0-13469-1477-osx.zip'` 2. Server hung with `Wating for the GoCD server to finish initializing.....` ##### Expected Results GoCD Server launched ##### Actual Results Starting server failed. ##### Log snippets ``` org.eclipse.jgit.api.errors.ServiceUnavailableException: Signing service is not available at org.eclipse.jgit.api.CommitCommand.sign(CommitCommand.java:290) at org.eclipse.jgit.api.CommitCommand.call(CommitCommand.java:247) at com.thoughtworks.go.service.ConfigRepository$1.run(ConfigRepository.java:125) at com.thoughtworks.go.util.VoidThrowingFn.call(VoidThrowingFn.java:25) at com.thoughtworks.go.service.ConfigRepository.doLocked(ConfigRepository.java:136) at com.thoughtworks.go.service.ConfigRepository.checkin(ConfigRepository.java:121) at com.thoughtworks.go.config.FullConfigSaveFlow.checkinToConfigRepo(FullConfigSaveFlow.java:79) at com.thoughtworks.go.config.FullConfigSaveNormalFlow.execute(FullConfigSaveNormalFlow.java:67) at com.thoughtworks.go.config.GoConfigMigrator.upgradeConfigFile(GoConfigMigrator.java:110) at com.thoughtworks.go.config.GoConfigMigrator.upgrade(GoConfigMigrator.java:96) at com.thoughtworks.go.config.GoConfigMigrator.migrate(GoConfigMigrator.java:87) at com.thoughtworks.go.config.CachedGoConfig.upgradeConfig(CachedGoConfig.java:149) at com.thoughtworks.go.server.initializers.ApplicationInitializer.onApplicationEvent(ApplicationInitializer.java:112) at com.thoughtworks.go.server.initializers.ApplicationInitializer.onApplicationEvent(ApplicationInitializer.java:49) at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393) at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347) at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1067) at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:572) at org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:996) at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:746) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:379) at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:910) at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46) at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188) at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:517) at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:157) at com.thoughtworks.go.server.Jetty9Server.startHandlers(Jetty9Server.java:179) at com.thoughtworks.go.server.Jetty9Server.start(Jetty9Server.java:129) at com.thoughtworks.go.server.GoServer.startServer(GoServer.java:62) at com.thoughtworks.go.server.GoServer.go(GoServer.java:54) at com.thoughtworks.go.server.util.GoLauncher.main(GoLauncher.java:42) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) at com.thoughtworks.gocd.Boot.run(Boot.java:90) at com.thoughtworks.gocd.Boot.main(Boot.java:56) 2022-01-14 20:54:16,934 WARN [main] GoConfigMigrator:98 - Error upgrading config file, trying to upgrade using the versioned config file. 2022-01-14 20:54:16,935 WARN [main] ConfigRepository:196 - [CONFIG REPOSITORY] No head exists in the config repository. 2022-01-14 20:54:16,935 WARN [main] GoConfigMigrator:116 - There is no versioned configuration to fallback for migration. 2022-01-14 20:54:16,944 ERROR [main] GoConfigMigrator:64 - There are errors in the Cruise config file. Please read the error message and correct the errors. Once fixed, please restart GoCD. Error: Signing service is not available ```
      fb73c589ce0052f30d576f115a8bafe101d1c1c3
      2db3a23f2bd8f4836e3db34bf7d80b7b242221e9
      https://github.com/gocd/gocd/compare/fb73c589ce0052f30d576f115a8bafe101d1c1c3...2db3a23f2bd8f4836e3db34bf7d80b7b242221e9
      diff --git a/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java b/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java index 8eb6f587f3..9f2520ca6b 100644 --- a/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java +++ b/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java @@ -78,10 +78,14 @@ public class ConfigRepository { workingDir = this.systemEnvironment.getConfigRepoDir(); File configRepoDir = new File(workingDir, ".git"); gitRepo = new FileRepositoryBuilder().setGitDir(configRepoDir).build(); - gitRepo.getConfig().setInt("gc", null, "auto", 0); + updateWithDefaults(gitRepo.getConfig()); git = new Git(gitRepo); } + private void updateWithDefaults(StoredConfig config) { + config.setInt(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_AUTO, 0); + config.setBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_GPGSIGN, false); + } public Repository getGitRepo() { return gitRepo; diff --git a/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java b/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java index 25fbac99ae..b40abe1b64 100644 --- a/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java +++ b/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java @@ -24,8 +24,11 @@ import com.thoughtworks.go.util.SystemEnvironment; import com.thoughtworks.go.util.TimeProvider; import org.eclipse.jgit.api.ListBranchCommand; import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.util.SystemReader; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,6 +38,7 @@ import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; +import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -70,6 +74,33 @@ public class ConfigRepositoryTest { assertThat(configRepo.getRevision("md5-v2").getContent(), is("v1 v2")); } + @Test + public void shouldBeAbleToCheckInWithGlobalGpgSigningEnabled() throws Exception { + try (UndoableUserGitConfig ignored = new UndoableUserGitConfig(c -> c.setBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_GPGSIGN, true))) { + configRepo = new ConfigRepository(systemEnvironment); + configRepo.initialize(); + configRepo.checkin(new GoConfigRevision("v1", "md5-v1", "user-name", "100.3.9", new TimeProvider())); + assertThat(configRepo.getRevision("md5-v1").getContent(), is("v1")); + assertThat(configRepo.getCurrentRevCommit().getRawGpgSignature(), nullValue()); + } + } + + private static class UndoableUserGitConfig implements AutoCloseable { + private final String originalConfig; + + public UndoableUserGitConfig(Consumer<StoredConfig> configConsumer) throws Exception { + StoredConfig config = SystemReader.getInstance().getUserConfig(); + originalConfig = config.toText(); + configConsumer.accept(config); + } + + @Override + public void close() throws Exception { + StoredConfig config = SystemReader.getInstance().getUserConfig(); + config.fromText(originalConfig); + } + } + @Test public void shouldGetCommitsCorrectly() throws Exception { configRepo.checkin(new GoConfigRevision("v1", "md5-v1", "user-name", "100.3.9", new TimeProvider())); @@ -110,7 +141,7 @@ public class ConfigRepositoryTest { } @Test - public void shouldReturnNullWhenThereAreNoCheckIns() throws GitAPIException, IOException { + public void shouldReturnNullWhenThereAreNoCheckIns() throws Exception { assertThat(configRepo.getRevision("current"), is(nullValue())); } @@ -317,7 +348,7 @@ public class ConfigRepositoryTest { } @Test - public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception, GitAPIException { + public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception { configRepo.checkin(goConfigRevision("v1", "md5-1")); configRepo.createBranch(ConfigRepository.BRANCH_AT_HEAD, configRepo.getCurrentRevCommit()); configRepo.createBranch(ConfigRepository.BRANCH_AT_REVISION, configRepo.getCurrentRevCommit()); @@ -376,10 +407,10 @@ public class ConfigRepositoryTest { public void shouldPerformGC() throws Exception { configRepo.checkin(goConfigRevision("v1", "md5-1")); Long numberOfLooseObjects = (Long) configRepo.git().gc().getStatistics().get("sizeOfLooseObjects"); - assertThat(numberOfLooseObjects > 0l, is(true)); + assertThat(numberOfLooseObjects > 0L, is(true)); configRepo.garbageCollect(); numberOfLooseObjects = (Long) configRepo.git().gc().getStatistics().get("sizeOfLooseObjects"); - assertThat(numberOfLooseObjects, is(0l)); + assertThat(numberOfLooseObjects, is(0L)); } @Test @@ -411,7 +442,7 @@ public class ConfigRepositoryTest { return new GoConfigRevision(fileContent, md5, "user-1", "13.2", new TimeProvider()); } - private String getLatestConfigAt(String branchName) throws GitAPIException, IOException { + private String getLatestConfigAt(String branchName) throws GitAPIException { configRepo.git().checkout().setName(branchName).call(); String content = configRepo.getCurrentRevision().getContent();
      ['config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java', 'config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      15,850,828
      3,172,153
      373,812
      3,347
      393
      83
      6
      1
      6,058
      278
      1,380
      89
      2
      1
      1970-01-01T00:27:22
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      402
      gocd/gocd/10649/10648
      gocd
      gocd
      https://github.com/gocd/gocd/issues/10648
      https://github.com/gocd/gocd/pull/10649
      https://github.com/gocd/gocd/pull/10649
      1
      fixes
      Plugin admin page can display stale plugin information after plugin upgrades
      ##### Issue Type - Bug Report ##### Summary <!--- Provide a brief summary of the issue --> When plugins are updated to new versions without changing which plugins are installed, `/go/admin/plugins` will display stale data in the browser until browser cache expiry. ###### Basic environment details <!--- We recommend providing the for us to reproduce the issue quicker --> * Go Version: `22.1.0` ##### Steps to Reproduce <!--- Provide a link to a live example, or an unambiguous set of steps to --> <!--- reproduce this bug include code to reproduce, if relevant --> 1. Load the plugins admin page 2. Update a plugin to a new version while changing nothing else 3. Bounce the server 4. Re-load the plugins admin page, not the old version. 5. Clear cache and/or force refresh and notice it changing. ##### Expected Results <!--- Tell us what should happen --> The page should be updated reliably when plugins are updated. ##### Actual Results <!--- Tell us what happens instead --> Stale data displayed for some indeterminate amount of time. ##### Possible Fix <!--- Not obligatory, but suggest a fix or reason for the bug --> It looks like the below defines a custom hash algorithm for `PluginInfo` which excludes `version`, `name` and other aspects of the plugin descriptor so if they are updated it won't cause a refresh. At the very least the `version` should be included so when a new version is released (which may have new values for other fields) the hash changes, and thus the entity `ETag`. https://github.com/gocd/gocd/blob/5c7c6c226dc2caa1fe729f5142536634912e795a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java#L107-L113
      c2293bcb6397761bc052789ae59facf315afbfe2
      85d5ba31393959d8328f5d0dec8e33b27afce6ce
      https://github.com/gocd/gocd/compare/c2293bcb6397761bc052789ae59facf315afbfe2...85d5ba31393959d8328f5d0dec8e33b27afce6ce
      diff --git a/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java b/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java index a75120a5a9..1568613acb 100644 --- a/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java +++ b/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java @@ -18,7 +18,6 @@ package com.thoughtworks.go.apiv7.plugininfos; import com.thoughtworks.go.api.ApiController; import com.thoughtworks.go.api.ApiVersion; import com.thoughtworks.go.api.spring.ApiAuthenticationHelper; -import com.thoughtworks.go.api.spring.ToggleRegisterLatest; import com.thoughtworks.go.apiv7.plugininfos.representers.PluginInfoRepresenter; import com.thoughtworks.go.apiv7.plugininfos.representers.PluginInfosRepresenter; import com.thoughtworks.go.config.exceptions.RecordNotFoundException; diff --git a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java b/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java index ebdffb96bd..870f071742 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java @@ -107,6 +107,7 @@ public class EntityHashes implements DigestMixin { JsonSerializer<PluginInfo> PLUGIN_INFO = (src, typeOfSrc, context) -> { final JsonObject result = new JsonObject(); result.addProperty("id", src.getDescriptor().id()); + result.addProperty("version", src.getDescriptor().version()); result.addProperty("extension", src.getExtensionName()); result.add("settings", context.serialize(src.getPluginSettings())); return result; diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java index 3459ec986a..ff9b142ec9 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java @@ -41,6 +41,7 @@ import java.util.List; import static com.thoughtworks.go.server.service.EntityHashingService.ETAG_CACHE_KEY; import static org.apache.commons.lang3.StringUtils.isNotBlank; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -72,29 +73,35 @@ public class EntityHashingServiceTest { @Test void digestsCombinedPluginInfoAndCollection() { - final CombinedPluginInfo info1 = new CombinedPluginInfo(new NotificationPluginInfo( - GoPluginDescriptor.builder().id("foo").build(), - new PluggableInstanceSettings(List.of(new PluginConfiguration("user", null))) - )); - final CombinedPluginInfo info2 = new CombinedPluginInfo(new NotificationPluginInfo( - GoPluginDescriptor.builder().id("bar").build(), - new PluggableInstanceSettings(List.of(new PluginConfiguration("user", null))) - )); + PluggableInstanceSettings testSettings = new PluggableInstanceSettings(List.of(new PluginConfiguration("user", null))); + final CombinedPluginInfo info1 = new CombinedPluginInfo( + new NotificationPluginInfo(GoPluginDescriptor.builder().id("foo").build(), testSettings) + ); + final CombinedPluginInfo info2 = new CombinedPluginInfo( + new NotificationPluginInfo(GoPluginDescriptor.builder().id("bar").build(), testSettings) + ); final Collection<CombinedPluginInfo> many = List.of(info1, info2); final String actual = service.hashForEntity(many); assertTrue(actual.matches("[a-f0-9]{64}")); assertEquals(digests.digest( - service.hashForEntity(info1), - service.hashForEntity(info2) + service.hashForEntity(info1), + service.hashForEntity(info2) ), actual); + + final CombinedPluginInfo info2v2 = new CombinedPluginInfo( + new NotificationPluginInfo(GoPluginDescriptor.builder().id("bar").version("2").build(), testSettings) + ); + + assertThat(service.hashForEntity(info2v2)).isNotEqualTo(service.hashForEntity(info2)); + } @Test @DisplayName("when plugin settings contain secret properties, the digest used for" + - "ETags should not change as long as the decrypted values remain the same, " + - "even if the crypto salt changes between requests") + "ETags should not change as long as the decrypted values remain the same, " + + "even if the crypto salt changes between requests") void digestIsConsistentForPluginSettingsWithSecretPropertiesEvenWhenCryptoSaltChanges() { TestIVProvider.with(new ProductionIVProvider(), () -> { final String id = "com.foo.plugin"; @@ -106,9 +113,9 @@ public class EntityHashingServiceTest { final PluginSettings p2 = pluginSettings(id, key, secret); assertNotEquals( - p1.getPluginSettingsProperties().get(0).getEncryptedValue(), - p2.getPluginSettingsProperties().get(0).getEncryptedValue(), - "both entities should have different cipherTexts even though the input values are equal" + p1.getPluginSettingsProperties().get(0).getEncryptedValue(), + p2.getPluginSettingsProperties().get(0).getEncryptedValue(), + "both entities should have different cipherTexts even though the input values are equal" ); final String expected = service.hashForEntity(p1); @@ -162,7 +169,7 @@ public class EntityHashingServiceTest { @Test @DisplayName("hashForEntity() can determine the proper overloaded method for implementations of " + - "EnvironmentConfig and List<EnvironmentConfig> without ambiguity") + "EnvironmentConfig and List<EnvironmentConfig> without ambiguity") void hashesEnvironmentConfigsWithoutClassAmbiguityIssues() { // important to test these when typed as the non-specific parent interface final EnvironmentConfig basic = new BasicEnvironmentConfig(new CaseInsensitiveString("hello")); @@ -175,11 +182,11 @@ public class EntityHashingServiceTest { // resolving the wrong overload might result in an exception indicating that the object "does not // have a ConfigTag" assertDoesNotThrow(() -> { - assertTrue(isNotBlank(service.hashForEntity(basic))); - assertTrue(isNotBlank(service.hashForEntity(merged))); - assertTrue(isNotBlank(service.hashForEntity(mult))); - assertTrue(isNotBlank(service.hashForEntity(nested))); - } + assertTrue(isNotBlank(service.hashForEntity(basic))); + assertTrue(isNotBlank(service.hashForEntity(merged))); + assertTrue(isNotBlank(service.hashForEntity(mult))); + assertTrue(isNotBlank(service.hashForEntity(nested))); + } ); } @@ -190,8 +197,8 @@ public class EntityHashingServiceTest { MergeEnvironmentConfig merged = new MergeEnvironmentConfig(env1, env2); when(goCache.get(ETAG_CACHE_KEY, "com.thoughtworks.go.config.BasicEnvironmentConfig.env")). - thenReturn("foo"). - thenReturn("bar"); + thenReturn("foo"). + thenReturn("bar"); final String type = MergeEnvironmentConfig.class.getSimpleName(); assertEquals(digests.digest(type, "foo", "bar"), service.hashForEntity(merged));
      ['server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java', 'api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java', 'server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      15,791,732
      3,160,232
      372,429
      3,334
      3,440
      626
      55
      3
      1,709
      257
      382
      39
      1
      0
      1970-01-01T00:27:39
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      401
      gocd/gocd/10676/10036
      gocd
      gocd
      https://github.com/gocd/gocd/issues/10036
      https://github.com/gocd/gocd/pull/10676
      https://github.com/gocd/gocd/pull/10676
      1
      fixes
      HTTP 500 when using external authorization plugins and GoCD site urls are blank
      ##### Issue Type - Bug Report ##### Summary When using GoCD GitLab or GitHub authentication plugins, the server site URLs must be set properly in the server configuration, otherwise the GoCD will fail with HTTP 500. ##### Environment Discovered on 21.2.0, Java 15. I suppose it is not related to the GoCD or Java version. ###### Basic environment details * Go Version: 21.2.0 * JAVA Version: 15.0.2 * OS: Linux 4.19.0-17-amd64 ##### Steps to Reproduce 1. Put a GitLab or GitHub plugin JAR into the appropriate folder and restart the server 2. Create a new authorization configuration with the desired plugin 3. Make sure that both server site urls are not set OR at least the second one (Secure site URL) is not set 4. Try to login via plugin ##### Expected Results Should be redirected to the external IDP properly ##### Actual Results GoCD throws an HTTP500 ##### Possible Fix Use at least the site url which is set or something default, like http://localhost:8153 ##### Log snippets In the go-server.log you can see following: ``` 2022-01-03 10:25:48,470 WARN [qtp679525351-29] HttpChannel:673 - handleException /go/plugin/cd.go.authorization.gitlab/login java.net.MalformedURLException: no protocol: ```
      4fae75d5c7e6e6dcfcacaea0577eafb193e6f29b
      5b7c362731eae1fd8deec665bc025c2e99cba3be
      https://github.com/gocd/gocd/compare/4fae75d5c7e6e6dcfcacaea0577eafb193e6f29b...5b7c362731eae1fd8deec665bc025c2e99cba3be
      diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java index 0fef04a87e..51f01b601b 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java +++ b/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java @@ -294,15 +294,12 @@ public class ServerConfig implements Validatable { public ServerSiteUrlConfig getSiteUrlPreferablySecured() { - SiteUrl siteUrl = getSiteUrl(); - SecureSiteUrl secureSiteUrlConfig = getSecureSiteUrl(); - if (secureSiteUrlConfig.hasNonNullUrl()) { - return secureSiteUrlConfig; - } - if (!secureSiteUrlConfig.hasNonNullUrl()) { - return siteUrl; + SecureSiteUrl secureSiteUrl = getSecureSiteUrl(); + if (!secureSiteUrl.isBlank()) { + return secureSiteUrl; + } else { + return getSiteUrl(); } - return new SiteUrl(); } public ServerSiteUrlConfig getHttpsUrl() { @@ -311,7 +308,7 @@ public class ServerConfig implements Validatable { } public boolean hasAnyUrlConfigured() { - return getSiteUrl().hasNonNullUrl() || getSecureSiteUrl().hasNonNullUrl(); + return !getSiteUrl().isBlank() || !getSecureSiteUrl().isBlank(); } public Double getPurgeStart() { diff --git a/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java index b350abcc9b..c978d4c873 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java +++ b/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java @@ -16,6 +16,7 @@ package com.thoughtworks.go.domain; import com.thoughtworks.go.config.ConfigValue; +import org.apache.commons.lang3.StringUtils; import java.net.URI; import java.net.URISyntaxException; @@ -32,8 +33,8 @@ public abstract class ServerSiteUrlConfig { this.url = url; } - public boolean hasNonNullUrl() { - return getUrl() != null; + public boolean isBlank() { + return StringUtils.isBlank(url); } public String getUrl() { @@ -68,14 +69,22 @@ public abstract class ServerSiteUrlConfig { } public String siteUrlFor(String givenUrl, boolean honorGivenHostName) throws URISyntaxException { - if (url == null || isPath(givenUrl)) { + if (isBlank() || isPath(givenUrl)) { return givenUrl; //it is a path } URI baseUri = new URI(url); URI givenUri = new URI(givenUrl); - return new URI(baseUri.getScheme(), getOrDefault(givenUri, baseUri, URI::getUserInfo), honorGivenHostName ? givenUri.getHost() : baseUri.getHost(), baseUri.getPort(), getOrDefault(givenUri, baseUri, URI::getPath), getOrDefault(givenUri, baseUri, URI::getQuery), getOrDefault(givenUri, baseUri, URI::getFragment)).toString(); + return new URI( + baseUri.getScheme(), + getOrDefault(givenUri, baseUri, URI::getUserInfo), + honorGivenHostName ? givenUri.getHost() : baseUri.getHost(), + baseUri.getPort(), + getOrDefault(givenUri, baseUri, URI::getPath), + getOrDefault(givenUri, baseUri, URI::getQuery), + getOrDefault(givenUri, baseUri, URI::getFragment) + ).toString(); } private boolean isPath(String givenUrl) { @@ -88,7 +97,7 @@ public abstract class ServerSiteUrlConfig { } public boolean isAHttpsUrl() { - return url != null && url.matches(HTTPS_URL_REGEX); + return !isBlank() && url.matches(HTTPS_URL_REGEX); } interface Getter { @@ -97,7 +106,7 @@ public abstract class ServerSiteUrlConfig { @Override public String toString() { - return hasNonNullUrl() ? url : ""; + return isBlank() ? "" : url; } } diff --git a/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java b/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java index ccc451b193..14968fde88 100644 --- a/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java +++ b/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java @@ -61,11 +61,11 @@ public class ServerConfigTest { public void shouldReturnBlankUrlBothSiteUrlAndSecureSiteUrlIsNotDefined() { defaultServerConfig.setSiteUrl(null); defaultServerConfig.setSecureSiteUrl(null); - assertThat(defaultServerConfig.getSiteUrlPreferablySecured().hasNonNullUrl(), is(false)); + assertThat(defaultServerConfig.getSiteUrlPreferablySecured().isBlank(), is(true)); } @Test - public void shouldReturnAnEmptyForSecureSiteUrlIfOnlySiteUrlIsConfigured() throws Exception { + public void shouldReturnAnEmptyForSecureSiteUrlIfOnlySiteUrlIsConfigured() { ServerConfig serverConfig = new ServerConfig(null, null, new SiteUrl("http://foo.bar:813"), new SecureSiteUrl()); assertThat(serverConfig.getHttpsUrl(), is(new SecureSiteUrl())); } diff --git a/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java b/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java index 46826f047d..dfb2286558 100644 --- a/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java +++ b/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java @@ -16,11 +16,14 @@ package com.thoughtworks.go.domain; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import java.net.URISyntaxException; -import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class ServerSiteUrlConfigTest { @Test @@ -77,9 +80,14 @@ public class ServerSiteUrlConfigTest { assertThat(url.toString(), is("http://someurl.com")); } - @Test - public void shouldReturnEmptyStringForToStringWhenTheUrlIsNotSet() throws Exception { - ServerSiteUrlConfig url = new SiteUrl(); + @ParameterizedTest + @NullSource + @ValueSource(strings = {"", " "}) + public void shouldHandleBlankUrlsConsistently(String input) throws Exception { + ServerSiteUrlConfig url = new SiteUrl(input); assertThat(url.toString(), is("")); + assertThat(url.isBlank(), is(true)); + assertThat(url.isAHttpsUrl(), is(false)); + assertThat(url.siteUrlFor("http://test.host/foo/bar?foo=bar#quux"), is("http://test.host/foo/bar?foo=bar#quux")); } } diff --git a/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java b/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java index daf9d31e81..ef23185c10 100644 --- a/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java +++ b/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java @@ -88,12 +88,12 @@ public class WebBasedPluginAuthenticationProvider extends AbstractPluginAuthenti return new AuthenticationToken<>(userPrinciple, credentials, pluginId, clock.currentTimeMillis(), authConfigId); } - private String getRootUrl(String string) { + private String rootUrlFrom(String urlString) { try { - final URL url = new URL(string); + final URL url = new URL(urlString); return new URL(url.getProtocol(), url.getHost(), url.getPort(), "").toString(); } catch (MalformedURLException e) { - throw new RuntimeException(e); + throw new RuntimeException(String.format("Configured siteUrl [%s] does not appear to be a valid URL", urlString), e); } } @@ -107,11 +107,12 @@ public class WebBasedPluginAuthenticationProvider extends AbstractPluginAuthenti return goConfigService.security().securityAuthConfigs().findByPluginId(pluginId); } - public String getAuthorizationServerUrl(String pluginId, String rootURL) { - if (goConfigService.serverConfig().hasAnyUrlConfigured()) { - rootURL = getRootUrl(goConfigService.serverConfig().getSiteUrlPreferablySecured().getUrl()); - } - return authorizationExtension.getAuthorizationServerUrl(pluginId, getAuthConfigs(pluginId), rootURL); + public String getAuthorizationServerUrl(String pluginId, String alternateRootUrl) { + String chosenRootUrl = + goConfigService.serverConfig().hasAnyUrlConfigured() + ? rootUrlFrom(goConfigService.serverConfig().getSiteUrlPreferablySecured().getUrl()) + : alternateRootUrl; + return authorizationExtension.getAuthorizationServerUrl(pluginId, getAuthConfigs(pluginId), chosenRootUrl); } } diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java index 03988934a9..3c63a1d1b5 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java @@ -41,6 +41,8 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; +import java.net.MalformedURLException; + import static com.thoughtworks.go.server.security.GoAuthority.ROLE_USER; import static java.util.Arrays.asList; import static java.util.Collections.*; @@ -322,6 +324,19 @@ class WebBasedPluginAuthenticationProviderTest { verify(authorizationExtension).getAuthorizationServerUrl(PLUGIN_ID, singletonList(githubSecurityAuthconfig), "https://example.com"); } + @Test + void shouldThrowUsefulErrorIfAuthorizationServerUrlIsBad() { + final ServerConfig serverConfig = mock(ServerConfig.class); + when(goConfigService.serverConfig()).thenReturn(serverConfig); + when(serverConfig.hasAnyUrlConfigured()).thenReturn(true); + when(serverConfig.getSiteUrlPreferablySecured()).thenReturn(new SecureSiteUrl("https://badurl:3434:")); + + assertThatThrownBy(() -> authenticationProvider.getAuthorizationServerUrl(PLUGIN_ID, "https://example.com")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("does not appear to be a valid URL") + .hasCauseInstanceOf(MalformedURLException.class); + } + @Test void shouldFetchAccessTokenFromPlugin() { when(authorizationExtension.fetchAccessToken(PLUGIN_ID, emptyMap(), singletonMap("code", "some-code"), singletonList(githubSecurityAuthconfig))).thenReturn(singletonMap("access_token", "some-access-token"));
      ['config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java', 'server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java', 'config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java', 'config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java']
      {'.java': 6}
      6
      6
      0
      0
      6
      15,770,573
      3,155,800
      372,021
      3,332
      3,869
      815
      68
      4
      1,275
      188
      312
      47
      1
      1
      1970-01-01T00:27:39
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      400
      gocd/gocd/11262/11260
      gocd
      gocd
      https://github.com/gocd/gocd/issues/11260
      https://github.com/gocd/gocd/pull/11262
      https://github.com/gocd/gocd/pull/11262
      1
      fixes
      Loading materials admin page creates syntax error on MySQL 8.0
      ### Issue Type - Bug Report ### Summary the error occurs after start go-server: ``` 2023-01-31 11:17:15,621 ERROR [qtp338329632-38] JDBCExceptionReporter:234 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mo' at line 1 ``` ### Environment my system env: ``` Centos 7 - kernel-3.10.0-693 go-server-22.3.0-15301 MySQL 8.0.23 ``` db.properties: ``` # /etc/go/db.properties db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://127.0.0.1:3301/gocd?useUnicode=true&characterEncoding=utf8&useSSL=false db.user=user_gocd db.password=xxxxxxxx db.maxActive=32 db.maxIdle=32 ``` ### Steps to Reproduce 1. start go-server 2. click the `AGENTS` OR `MATERIALS` button on the gocd web 3. check the error file /var/log/go-server/go-server.log ### mysql query ``` 2023-01-31 11:17:15| cli -> ser |【Query】 SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id; 2023-01-31 11:17:15| ser -> cli |【Err】 Err code:1064,Err msg:42000You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mo' at line 1 ``` ### Possible Fix read more from [mysql8-select](https://dev.mysql.com/doc/refman/8.0/en/select.html). Use of an unqualified * with other items in the select list may produce a parse error. For example: ``` SELECT id, * FROM t1 ``` to avoid this problem, use a qualified tbl_name.* reference: ``` SELECT id, t1.* FROM t1 ``` So we should change the sql: ``` SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id; ==> SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, modifications.* FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id; ```
      b3a6bad328f3e0e7e6739e6913f13499725c605c
      c173255552af0656a9adbbd7c725d93ba8f62ab3
      https://github.com/gocd/gocd/compare/b3a6bad328f3e0e7e6739e6913f13499725c605c...c173255552af0656a9adbbd7c725d93ba8f62ab3
      diff --git a/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java b/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java index 8fe5c7ba3d..162fc4e57c 100644 --- a/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java +++ b/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java @@ -1031,7 +1031,7 @@ public class MaterialRepository extends HibernateDaoSupport { public List<Modification> getLatestModificationForEachMaterial() { String queryString = "SELECT mods.* " + "FROM (" + - " SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * " + + " SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, modifications.* " + " FROM modifications " + ") mods " + "JOIN materials m ON mods.materialid=m.id " +
      ['server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      15,411,055
      3,088,725
      363,908
      3,249
      181
      45
      2
      1
      2,265
      300
      632
      72
      1
      7
      1970-01-01T00:27:55
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      397
      gocd/gocd/11874/11868
      gocd
      gocd
      https://github.com/gocd/gocd/issues/11868
      https://github.com/gocd/gocd/pull/11874
      https://github.com/gocd/gocd/pull/11874
      1
      fixes
      `runOnAllAgents="true"` added to jobs at GoCD startup
      ##### Issue Type <!--- Please specify the issue type to help us categorize the issue, mention any one of the below types --> - Bug Report ##### Summary <!--- Provide a brief summary of the issue --> GoCD surprisingly adds `runOnAllAgents="true"` to jobs. ##### Environment <!--- Describe the environment in which you encountered this issue. Details of the environment GoCD is running in can be fetched from the GoCD support api - http://<go-server-host>/go/api/support. If you are pasting plain text, please surround it with 3 backticks on each side ```plain paste any text output to prevent formatting ``` --> 👋 Let me know if you need this and I can share this individually, as it might contain sensitive information. ###### Basic environment details <!--- We recommend providing the for us to reproduce the issue quicker --> * Go Version: `23.1.0 (16080-54a6971915ff8d402c9fea8cd2ceeb6e31c8cdc8)` * JAVA Version: `17.0.6` * OS: `Linux 5.10.176+` ###### Additional Environment Details <!-- More environment details captured from the support API or other sources can be shared here --> ##### Steps to Reproduce 1. Restarting GoCD ##### Expected Results 1. GoCD config behaving like before. ##### Actual Results 1. GoCD surprisingly adds `runOnAllAgents="true"` to jobs. ##### Possible Fix <!--- Not obligatory, but suggest a fix or reason for the bug --> 🤷 ##### Log snippets <!--- If you could find any information/exceptions from the logs do provide it here. Do mask any confidential information which you don't want to be shared. Remember to surround them in 3 backticks like this — ``` long log lines go here ``` --> ##### Code snippets/Screenshots Here is an example of a commit GoCD makes: ```diff commit a29ab7eddd8a8d864f33a656f96ad1291abe53b7 Author: Upgrade <[email protected]> Date: Fri Aug 11 05:11:37 2023 +0000 user:Upgrade|timestamp:1691730697644|schema_version:139|go_edition:OpenSource|go_version:23.1.0 (16080-54a6971915ff8d402c9fea8cd2ceeb6e31c8cdc8)|md5:536dedf85183254cabe2192eb1f7c5e2 diff --git a/cruise-config.xml b/cruise-config.xml index 5234ae934..65a8023b5 100644 --- a/cruise-config.xml +++ b/cruise-config.xml @@ -34838,7 +34838,7 @@ fi</arg> <artifact type="test" src="some-tests/target/logs/docker" dest="logs" /> </artifacts> </job> - <job name="some-tests"> + <job name="some-tests" runOnAllAgents="true"> <tasks> <fetchartifact artifactOrigin="gocd" srcfile="tag" stage="build" job="defaultJob" /> <exec command="/bin/bash"> ``` ##### Any other info <!--- Provide any other information you would like to share to explain this issue more better -->
      9a9a12047df94036b92106d4296555278eb7bce6
      04e6ccb02476a095b12ff09f909a93bee210d2dd
      https://github.com/gocd/gocd/compare/9a9a12047df94036b92106d4296555278eb7bce6...04e6ccb02476a095b12ff09f909a93bee210d2dd
      diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java b/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java index 3087dc0b1f..de6c0c0a5f 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java +++ b/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java @@ -19,7 +19,6 @@ import com.thoughtworks.go.config.parser.GoConfigFieldTypeConverter; import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry; import com.thoughtworks.go.util.ConfigUtil; import org.jdom2.Element; -import org.springframework.beans.SimpleTypeConverter; import org.springframework.beans.TypeMismatchException; import java.lang.reflect.Field; @@ -33,23 +32,17 @@ public class GoConfigFieldWriter { private final ConfigUtil configUtil = new ConfigUtil("magic"); private final Field configField; private final Object value; - private final SimpleTypeConverter typeConverter; private final ConfigCache configCache; private final ConfigElementImplementationRegistry registry; - public GoConfigFieldWriter(Field declaredField, Object value, SimpleTypeConverter converter, ConfigCache configCache, final ConfigElementImplementationRegistry registry) { + public GoConfigFieldWriter(Field declaredField, Object value, ConfigCache configCache, final ConfigElementImplementationRegistry registry) { this.configField = declaredField; this.value = value; this.configField.setAccessible(true); - this.typeConverter = converter; this.configCache = configCache; this.registry = registry; } - public GoConfigFieldWriter(Field declaredField, Object value, ConfigCache configCache, final ConfigElementImplementationRegistry registry) { - this(declaredField, value, new GoConfigFieldTypeConverter(), configCache, registry); - } - public Field getConfigField() { return configField; } @@ -78,7 +71,7 @@ public class GoConfigFieldWriter { try { setFieldIfNotNull(configField, o, val); } catch (TypeMismatchException e1) { - final String message = format("Could not set value [{0}] on Field [{1}] of type [{2}] ", val, + final String message = format("Could not set value [{0}] on field [{1}] of type [{2}] ", val, configField.getName(), configField.getType()); throw new RuntimeException(message, e1); } @@ -87,9 +80,7 @@ public class GoConfigFieldWriter { private void bombIfNullAndNotAllowed(Field field, Object instance, ConfigAttribute attribute) { try { if (!attribute.allowNull()) { - bombIfNull(field.get(instance), - () -> "Field '" + field.getName() + "' is still set to null. " - + "Must give a default value."); + bombIfNull(field.get(instance), () -> "Field '" + field.getName() + "' is still set to null. Must give a default value."); } } catch (IllegalAccessException e) { throw bomb("Error getting configField: " + field.getName(), e); @@ -99,7 +90,7 @@ public class GoConfigFieldWriter { private void setFieldIfNotNull(Field field, Object instance, Object val) { try { if (val != null) { - Object convertedValue = typeConverter.convertIfNecessary(val, configField.getType()); + Object convertedValue = GoConfigFieldTypeConverter.forThread().convertIfNecessary(val, configField.getType()); field.set(instance, convertedValue); } } catch (IllegalAccessException e) { @@ -107,15 +98,15 @@ public class GoConfigFieldWriter { } } -@SuppressWarnings({"DataFlowIssue", "unchecked"}) -private Collection<?> parseCollection(Element e, Class<?> collectionType) { + @SuppressWarnings({"DataFlowIssue", "unchecked"}) + private Collection<?> parseCollection(Element e, Class<?> collectionType) { ConfigCollection collection = collectionType.getAnnotation(ConfigCollection.class); Class<?> type = collection.value(); Object o = newInstance(collectionType); bombUnless(o instanceof Collection, - () -> "Must be some sort of list. Was: " + collectionType.getName()); + () -> "Must be some sort of list. Was: " + collectionType.getName()); Collection<Object> baseCollection = (Collection<Object>) o; for (Element childElement : e.getChildren()) { @@ -124,7 +115,7 @@ private Collection<?> parseCollection(Element e, Class<?> collectionType) { } } bombIf(baseCollection.size() < collection.minimum(), - () -> "Required at least " + collection.minimum() + " subelements to '" + e.getName() + "'. " + () -> "Required at least " + collection.minimum() + " subelements to '" + e.getName() + "'. " + "Found " + baseCollection.size() + "."); return baseCollection; } @@ -192,7 +183,7 @@ private Collection<?> parseCollection(Element e, Class<?> collectionType) { ConfigTag tag = configTag(field.getType()); boolean optional = field.getAnnotation(ConfigSubtag.class).optional(); boolean isMissingElement = !configUtil.hasChild(e, tag); - if(!optional && isMissingElement) { + if (!optional && isMissingElement) { throw bomb("Non optional tag '" + tag + "' is not in config file. Found: " + configUtil.elementOutput(e)); } return optional && isMissingElement; @@ -201,7 +192,7 @@ private Collection<?> parseCollection(Element e, Class<?> collectionType) { private boolean optionalAndMissingAttribute(Element e, ConfigAttribute attribute) { boolean optional = attribute.optional(); boolean isMissingAttribute = !configUtil.hasAttribute(e, attribute.value()); - if(!optional && isMissingAttribute) { + if (!optional && isMissingAttribute) { throw bomb("Non optional attribute '" + attribute.value() + "' is not in element: " + configUtil.elementOutput(e)); } return optional && isMissingAttribute; diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java b/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java index d7c9ff96b2..40b88dd33a 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java +++ b/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java @@ -15,16 +15,25 @@ */ package com.thoughtworks.go.config.parser; -import java.io.File; - +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.SimpleTypeConverter; +import org.springframework.beans.TypeConverter; import org.springframework.beans.propertyeditors.FileEditor; -import org.apache.commons.lang3.StringUtils; + +import java.io.File; public class GoConfigFieldTypeConverter extends SimpleTypeConverter { + public static TypeConverter forThread() { + return typeConverter.get(); + } + private static final CustomizedFileEditor propertyEditor = new CustomizedFileEditor(); + // Type converters are NOT thread safe. Should be OK to cache them per thread as not too large and don't think + // we have too many threads that will be doing so? + private static final ThreadLocal<TypeConverter> typeConverter = ThreadLocal.withInitial(GoConfigFieldTypeConverter::new); + public GoConfigFieldTypeConverter() { super(); this.registerCustomEditor(File.class, propertyEditor); diff --git a/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java b/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java deleted file mode 100644 index 6a70e36071..0000000000 --- a/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2023 Thoughtworks, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.thoughtworks.go.config.parser; - -import java.beans.PropertyEditor; -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import com.thoughtworks.go.util.ReflectionUtil; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class GoConfigFieldTypeConverterTest { - @Test - public void shouldOnlyCreateOneInstanceOfCustomizedFileEditorAndUseIt() throws Exception { - GoConfigFieldTypeConverter converter = new GoConfigFieldTypeConverter(); - Field expectedField = converter.getClass().getDeclaredField("propertyEditor"); - int modifier = expectedField.getModifiers(); - assertThat(Modifier.isStatic(modifier), is(true)); - assertThat(Modifier.isFinal(modifier), is(true)); - PropertyEditor actual = converter.findCustomEditor(File.class, null); - assertThat(actual, is(ReflectionUtil.getStaticField(converter.getClass(), "propertyEditor"))); - } -} diff --git a/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java b/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java index 8891250284..e90d5fb7ba 100644 --- a/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java +++ b/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java @@ -20,14 +20,13 @@ import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry; import com.thoughtworks.go.security.GoCipher; import org.jdom2.Attribute; import org.jdom2.Element; -import org.springframework.beans.SimpleTypeConverter; import org.springframework.beans.TypeMismatchException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import static com.thoughtworks.go.config.ConfigCache.isAnnotationPresent; import static com.thoughtworks.go.config.parser.GoConfigAttributeLoader.attributeParser; @@ -38,8 +37,7 @@ import static com.thoughtworks.go.util.ExceptionUtils.bomb; import static java.text.MessageFormat.format; public class GoConfigFieldLoader<T> { - private static final Map<Field, Boolean> implicits = new HashMap<>(); - private static final SimpleTypeConverter typeConverter = new GoConfigFieldTypeConverter(); + private static final Map<Field, Boolean> implicits = new ConcurrentHashMap<>(); private final Element e; private final T instance; @@ -49,7 +47,7 @@ public class GoConfigFieldLoader<T> { private final ConfigElementImplementationRegistry registry; public static <T> GoConfigFieldLoader<T> fieldParser(Element e, T instance, Field field, ConfigCache configCache, final ConfigElementImplementationRegistry registry, - ConfigReferenceElements configReferenceElements) { + ConfigReferenceElements configReferenceElements) { return new GoConfigFieldLoader<>(e, instance, field, configCache, registry, configReferenceElements); } @@ -93,11 +91,8 @@ public class GoConfigFieldLoader<T> { } private boolean isImplicitCollection() { - if (!implicits.containsKey(field)) { - implicits.put(field, ConfigCache.isAnnotationPresent(field, ConfigSubtag.class) - && GoConfigClassLoader.isImplicitCollection(field.getType())); - } - return implicits.get(field); + return implicits.computeIfAbsent(field, + f -> ConfigCache.isAnnotationPresent(f, ConfigSubtag.class) && GoConfigClassLoader.isImplicitCollection(f.getType())); } private void setValue(Object val) { @@ -109,13 +104,12 @@ public class GoConfigFieldLoader<T> { field.set(instance, constructor.newInstance(val)); } } else if (val != null) { - Object convertedValue = typeConverter.convertIfNecessary(val, field.getType()); - field.set(instance, convertedValue); + field.set(instance, GoConfigFieldTypeConverter.forThread().convertIfNecessary(val, field.getType())); } } catch (IllegalAccessException e) { throw bomb("Error setting configField: " + field.getName(), e); } catch (TypeMismatchException e) { - final String message = format("Could not set value [{0}] on Field [{1}] of type [{2}] ", + final String message = format("Could not set value [{0}] on field [{1}] of type [{2}] ", val, field.getName(), field.getType()); throw bomb(message, e); } catch (NoSuchMethodException e) { diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java deleted file mode 100644 index 7d221b5f32..0000000000 --- a/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2023 Thoughtworks, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.thoughtworks.go.config.parser; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import org.junit.jupiter.api.Test; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class GoConfigFieldLoaderTest { - - @Test - public void shouldOnlyCreateOneInstanceOfSimpleTypeConverterAndUseIt() throws Exception { - Integer dummyValue = 0; - Field randomField = dummyValue.getClass().getDeclaredFields()[0]; // Random field because I can't mock java.lang.reflect.Field (Sachin) - GoConfigFieldLoader loader = GoConfigFieldLoader.fieldParser(null, null, randomField, null, null, new ConfigReferenceElements()); - Field expectedField = loader.getClass().getDeclaredField("typeConverter"); - int modifier = expectedField.getModifiers(); - assertThat(Modifier.isStatic(modifier), is(true)); - assertThat(Modifier.isFinal(modifier), is(true)); - } -} -
      ['config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java', 'config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java', 'config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java']
      {'.java': 5}
      5
      5
      0
      0
      5
      15,198,620
      3,045,503
      359,172
      3,182
      4,463
      843
      64
      3
      2,831
      347
      748
      97
      1
      3
      1970-01-01T00:28:12
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      395
      gocd/gocd/631/548
      gocd
      gocd
      https://github.com/gocd/gocd/issues/548
      https://github.com/gocd/gocd/pull/631
      https://github.com/gocd/gocd/issues/548#issuecomment-58576865
      2
      fixes
      Polling and builds fail when a git submodule URL changes
      This causes `git submodule update --init` to fail which means material updates fail and builds running on the agent fail if they have the stale submodule url: ``` git submodule update --init --- Environment --- {} --- INPUT ---- --OUTPUT --- <cut> ERROR: fatal: reference is not a tree: 176026c856dd4cecd80fcdd5fe904fbc9f4c1385 ERROR: Unable to checkout '176026c856dd4cecd80fcdd5fe904fbc9f4c1385' in submodule path 'src/gnatsd' ``` `git submodule sync` is needed to refresh the submodule url. This is time consuming to recover from because the fix involves running git submodule sync on the flyweights on the server and all copies on the agents which have stale urls.
      c08ce3bedd2bccb769537e6d811283a57782a842
      89442cfbb75236c00391d846bf2364ef4beef4cd
      https://github.com/gocd/gocd/compare/c08ce3bedd2bccb769537e6d811283a57782a842...89442cfbb75236c00391d846bf2364ef4beef4cd
      diff --git a/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java b/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java index 65d377c49a..849470b65d 100644 --- a/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java +++ b/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java @@ -149,7 +149,7 @@ public class GitCommand extends SCMCommand { run(gitCmd, outputStreamConsumer); } - private void resetHard(ProcessOutputStreamConsumer outputStreamConsumer, Revision revision) { + public void resetHard(ProcessOutputStreamConsumer outputStreamConsumer, Revision revision) { outputStreamConsumer.stdOutput("[GIT] Updating working copy to revision " + revision.getRevision()); String[] args = new String[]{"reset", "--hard", revision.getRevision()}; CommandLine gitCmd = git().withArgs(args).withWorkingDir(workingDir); @@ -172,9 +172,17 @@ public class GitCommand extends SCMCommand { return; } outputStreamConsumer.stdOutput("[GIT] Updating git sub-modules"); - String[] args = new String[]{"submodule", "update", "--init"}; - CommandLine gitCmd = git().withArgs(args).withWorkingDir(workingDir); - runOrBomb(gitCmd); + + String[] initArgs = new String[]{"submodule", "init"}; + CommandLine initCmd = git().withArgs(initArgs).withWorkingDir(workingDir); + runOrBomb(initCmd); + + submoduleSync(); + + String[] updateArgs = new String[]{"submodule", "update"}; + CommandLine updateCmd = git().withArgs(updateArgs).withWorkingDir(workingDir); + runOrBomb(updateCmd); + outputStreamConsumer.stdOutput("[GIT] Cleaning unversioned files and sub-modules"); printSubmoduleStatus(outputStreamConsumer); } @@ -259,7 +267,7 @@ public class GitCommand extends SCMCommand { runOrBomb(gitCmd); } - private void fetch(ProcessOutputStreamConsumer outputStreamConsumer) { + public void fetch(ProcessOutputStreamConsumer outputStreamConsumer) { outputStreamConsumer.stdOutput("[GIT] Fetching changes"); CommandLine gitFetch = git().withArgs("fetch", "origin").withWorkingDir(workingDir); @@ -357,4 +365,20 @@ public class GitCommand extends SCMCommand { ConsoleResult consoleResult = runOrBomb(getCurrentBranchCommand); return consoleResult.outputAsString(); } + + public void changeSubmoduleUrl(String submoduleName, String newUrl) { + String[] args = new String[]{"config", "--file", ".gitmodules", "submodule." + submoduleName + ".url", newUrl}; + CommandLine gitConfig = git().withArgs(args).withWorkingDir(workingDir); + runOrBomb(gitConfig); + } + + public void submoduleSync() { + String[] syncArgs = new String[]{"submodule", "sync"}; + CommandLine syncCmd = git().withArgs(syncArgs).withWorkingDir(workingDir); + runOrBomb(syncCmd); + + String[] foreachArgs = new String[]{"submodule", "foreach", "--recursive", "git", "submodule", "sync"}; + CommandLine foreachCmd = git().withArgs(foreachArgs).withWorkingDir(workingDir); + runOrBomb(foreachCmd); + } } diff --git a/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java b/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java index 7094807e96..36a7804cc2 100644 --- a/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java +++ b/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java @@ -445,6 +445,24 @@ public class GitCommandTest { clonedCopy.fetchAndReset(outputStreamConsumer, new StringRevision("HEAD")); } + @Test + public void shouldAllowSubmoduleUrlstoChange() throws Exception { + InMemoryStreamConsumer outputStreamConsumer = inMemoryConsumer(); + GitSubmoduleRepos submoduleRepos = new GitSubmoduleRepos(); + String submoduleDirectoryName = "local-submodule"; + File cloneDirectory = createTempWorkingDirectory(); + + File remoteSubmoduleLocation = submoduleRepos.addSubmodule(SUBMODULE, submoduleDirectoryName); + + GitCommand clonedCopy = new GitCommand(null, cloneDirectory, GitMaterialConfig.DEFAULT_BRANCH, false); + clonedCopy.cloneFrom(outputStreamConsumer, submoduleRepos.mainRepo().getUrl()); + clonedCopy.fetchAndResetToHead(outputStreamConsumer); + + submoduleRepos.changeSubmoduleUrl(submoduleDirectoryName); + + clonedCopy.fetchAndResetToHead(outputStreamConsumer); + } + private List<File> allFilesIn(File directory, String prefixOfFiles) { return new ArrayList<File>(FileUtils.listFiles(directory, andFileFilter(fileFileFilter(), prefixFileFilter(prefixOfFiles)), null)); } diff --git a/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java b/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java index 6f4787a81b..423ad2fa4f 100644 --- a/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java +++ b/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java @@ -21,6 +21,7 @@ import com.thoughtworks.go.config.materials.git.GitMaterialConfig; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext; import com.thoughtworks.go.domain.materials.git.GitCommand; +import com.thoughtworks.go.domain.materials.mercurial.StringRevision; import com.thoughtworks.go.util.TestFileUtil; import org.apache.commons.io.FileUtils; @@ -137,4 +138,18 @@ public class GitSubmoduleRepos extends TestRepo { @Override public GitMaterial material() { return new GitMaterial(remoteRepoDir.getAbsolutePath()); } + + public void changeSubmoduleUrl(String submoduleName) throws Exception { + File newSubmodule = createRepo("new-submodule"); + addAndCommitNewFile(newSubmodule, "new", "make a commit"); + + git(remoteRepoDir).changeSubmoduleUrl(submoduleName, newSubmodule.getAbsolutePath()); + git(remoteRepoDir).submoduleSync(); + + git(new File(remoteRepoDir, "local-submodule")).fetch(inMemoryConsumer()); + git(new File(remoteRepoDir, "local-submodule")).resetHard(inMemoryConsumer(), new StringRevision("origin/master")); + git(remoteRepoDir).add(new File(".gitmodules")); + git(remoteRepoDir).add(new File("local-submodule")); + git(remoteRepoDir).commit("change submodule url"); + } }
      ['common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java', 'common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java', 'common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      7,018,116
      1,409,995
      184,079
      1,644
      1,700
      362
      34
      1
      673
      101
      174
      19
      0
      1
      1970-01-01T00:23:32
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      407
      gocd/gocd/7738/7737
      gocd
      gocd
      https://github.com/gocd/gocd/issues/7737
      https://github.com/gocd/gocd/pull/7738
      https://github.com/gocd/gocd/pull/7738
      1
      fixes
      Issues with moving pipelines between groups
      ##### Issue Type - Bug Report ##### Summary Moving pipelines between groups on the pipelines page fails if the given pipeline has a dependency material defined and uses parameters to define the upstream pipeline. If a dependency material is defined without a name, the name defaults to the pipeline name. If the name of the upstream pipeline is a parameter then on update(in this pipeline group move) to the pipeline would fail for material name validation, as the material can only be alphanumeric.
      fbe640c871dfe4bff5b3e3ddead658e6ca9694a0
      504b1403e2f25ab90650f9590fd6f0562ce55c4b
      https://github.com/gocd/gocd/compare/fbe640c871dfe4bff5b3e3ddead658e6ca9694a0...504b1403e2f25ab90650f9590fd6f0562ce55c4b
      diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java index b1e9b4bf15..d86ea9bef4 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java +++ b/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java @@ -80,11 +80,6 @@ public class DependencyMaterialConfig extends AbstractMaterialConfig implements this.ignoreForScheduling = ignoreForScheduling; } - @Override - public CaseInsensitiveString getName() { - return super.getName() == null ? pipelineName : super.getName(); - } - public String getUserName() { return "cruise"; } @@ -207,7 +202,8 @@ public class DependencyMaterialConfig extends AbstractMaterialConfig implements @Override public String getDisplayName() { - return CaseInsensitiveString.str(getName()); + CaseInsensitiveString name = getName() == null ? pipelineName : getName(); + return name.toString(); } @Override diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java index 7d23231b7b..d8f4d38e79 100644 --- a/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java +++ b/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java @@ -26,8 +26,9 @@ import com.thoughtworks.go.domain.materials.dependency.NewGoConfigMother; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother; import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -36,18 +37,17 @@ import java.util.Map; import static com.thoughtworks.go.helper.MaterialConfigsMother.p4; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; -public class DependencyMaterialConfigTest { +class DependencyMaterialConfigTest { private MagicalGoConfigXmlWriter writer; private MagicalGoConfigXmlLoader loader; private CruiseConfig config; private PipelineConfig pipelineConfig; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { writer = new MagicalGoConfigXmlWriter(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins()); loader = new MagicalGoConfigXmlLoader(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins()); config = GoConfigMother.configWithPipelines("pipeline1", "pipeline2", "pipeline3", "go"); @@ -55,16 +55,16 @@ public class DependencyMaterialConfigTest { } @Test - public void shouldBeAbleToLoadADependencyMaterialFromConfig() throws Exception { + void shouldBeAbleToLoadADependencyMaterialFromConfig() throws Exception { String xml = "<pipeline pipelineName=\\"pipeline-name\\" stageName=\\"stage-name\\" />"; DependencyMaterialConfig material = loader.fromXmlPartial(xml, DependencyMaterialConfig.class); - assertThat(material.getPipelineName(), is(new CaseInsensitiveString("pipeline-name"))); - assertThat(material.getStageName(), is(new CaseInsensitiveString("stage-name"))); - assertThat(writer.toXmlPartial(material), is(xml)); + assertThat(material.getPipelineName()).isEqualTo(new CaseInsensitiveString("pipeline-name")); + assertThat(material.getStageName()).isEqualTo(new CaseInsensitiveString("stage-name")); + assertThat(writer.toXmlPartial(material)).isEqualTo(xml); } @Test - public void shouldBeAbleToSaveADependencyMaterialToConfig() throws Exception { + void shouldBeAbleToSaveADependencyMaterialToConfig() throws Exception { DependencyMaterialConfig originalMaterial = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-name"), new CaseInsensitiveString("stage-name")); NewGoConfigMother mother = new NewGoConfigMother(); @@ -79,13 +79,13 @@ public class DependencyMaterialConfigTest { CruiseConfig config = loader.loadConfigHolder(IOUtils.toString(inputStream, UTF_8)).config; DependencyMaterialConfig material = (DependencyMaterialConfig) config.pipelineConfigByName(new CaseInsensitiveString("dependent")).materialConfigs().get(1); - assertThat(material, is(originalMaterial)); - assertThat(material.getPipelineName(), is(new CaseInsensitiveString("pipeline-name"))); - assertThat(material.getStageName(), is(new CaseInsensitiveString("stage-name"))); + assertThat(material).isEqualTo(originalMaterial); + assertThat(material.getPipelineName()).isEqualTo(new CaseInsensitiveString("pipeline-name")); + assertThat(material.getStageName()).isEqualTo(new CaseInsensitiveString("stage-name")); } @Test - public void shouldBeAbleToHaveADependencyAndOneOtherMaterial() throws Exception { + void shouldBeAbleToHaveADependencyAndOneOtherMaterial() throws Exception { NewGoConfigMother mother = new NewGoConfigMother(); mother.addPipeline("pipeline-name", "stage-name", "job-name"); PipelineConfig pipelineConfig = mother.addPipeline("dependent", "stage-name", "job-name", @@ -102,62 +102,62 @@ public class DependencyMaterialConfigTest { CruiseConfig config = loader.loadConfigHolder(IOUtils.toString(inputStream, UTF_8)).config; MaterialConfigs materialConfigs = config.pipelineConfigByName(new CaseInsensitiveString("dependent")).materialConfigs(); - assertThat(materialConfigs.get(0), is(instanceOf(DependencyMaterialConfig.class))); - assertThat(materialConfigs.get(1), is(instanceOf(P4MaterialConfig.class))); + assertThat(materialConfigs.get(0)).isInstanceOf(DependencyMaterialConfig.class); + assertThat(materialConfigs.get(1)).isInstanceOf(P4MaterialConfig.class); } @Test - public void shouldAddErrorForInvalidMaterialName() { + void shouldAddErrorForInvalidMaterialName() { DependencyMaterialConfig materialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("wrong name"), new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar")); materialConfig.validate(ConfigSaveValidationContext.forChain(new BasicCruiseConfig(), pipelineConfig)); - assertThat(materialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME), is("Invalid material name 'wrong name'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.")); + assertThat(materialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME)).isEqualTo("Invalid material name 'wrong name'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."); } @Test - public void shouldAddErrorWhenInvalidPipelineNameStage() { + void shouldAddErrorWhenInvalidPipelineNameStage() { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(); Map<String, String> configMap = new HashMap<>(); configMap.put(DependencyMaterialConfig.PIPELINE_STAGE_NAME, "invalid pipeline stage"); dependencyMaterialConfig.setConfigAttributes(configMap); - assertThat(dependencyMaterialConfig.getPipelineStageName(), is("invalid pipeline stage")); - assertThat(dependencyMaterialConfig.errors().isEmpty(), is(false)); - assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), is("'invalid pipeline stage' should conform to the pattern 'pipeline [stage]'")); + assertThat(dependencyMaterialConfig.getPipelineStageName()).isEqualTo("invalid pipeline stage"); + assertThat(dependencyMaterialConfig.errors().isEmpty()).isFalse(); + assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).isEqualTo("'invalid pipeline stage' should conform to the pattern 'pipeline [stage]'"); } @Test - public void shouldNotBombValidationWhenMaterialNameIsNotSet() { + void shouldNotBombValidationWhenMaterialNameIsNotSet() { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar")); dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(new BasicCruiseConfig(), pipelineConfig)); - assertThat(dependencyMaterialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME), is(nullValue())); + assertThat(dependencyMaterialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME)).isNull(); } @Test - public void shouldNOTBeValidIfThePipelineExistsButTheStageDoesNot() throws Exception { + void shouldNOTBeValidIfThePipelineExistsButTheStageDoesNot() throws Exception { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline2"), new CaseInsensitiveString("stage-not-existing does not exist!")); dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(config, pipelineConfig)); ConfigErrors configErrors = dependencyMaterialConfig.errors(); - assertThat(configErrors.isEmpty(), is(false)); - assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), containsString("Stage with name 'stage-not-existing does not exist!' does not exist on pipeline 'pipeline2'")); + assertThat(configErrors.isEmpty()).isFalse(); + assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).contains("Stage with name 'stage-not-existing does not exist!' does not exist on pipeline 'pipeline2'"); } @Test - public void shouldNOTBeValidIfTheReferencedPipelineDoesNotExist() throws Exception { + void shouldNOTBeValidIfTheReferencedPipelineDoesNotExist() throws Exception { CruiseConfig config = GoConfigMother.configWithPipelines("pipeline1", "pipeline2", "pipeline3", "go"); DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-not-exist"), new CaseInsensitiveString("stage")); dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(config, pipelineConfig)); ConfigErrors configErrors = dependencyMaterialConfig.errors(); - assertThat(configErrors.isEmpty(), is(false)); - assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), containsString("Pipeline with name 'pipeline-not-exist' does not exist")); + assertThat(configErrors.isEmpty()).isFalse(); + assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).contains("Pipeline with name 'pipeline-not-exist' does not exist"); } @Test - public void setConfigAttributes_shouldPopulateFromConfigAttributes() { + void setConfigAttributes_shouldPopulateFromConfigAttributes() { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(""), new CaseInsensitiveString("")); - assertThat(dependencyMaterialConfig.getPipelineStageName(), is(nullValue())); - assertThat(dependencyMaterialConfig.ignoreForScheduling(), is(false)); + assertThat(dependencyMaterialConfig.getPipelineStageName()).isNull(); + assertThat(dependencyMaterialConfig.ignoreForScheduling()).isFalse(); HashMap<String, String> configMap = new HashMap<>(); configMap.put(AbstractMaterialConfig.MATERIAL_NAME, "name1"); configMap.put(DependencyMaterialConfig.PIPELINE_STAGE_NAME, "pipeline-1 [stage-1]"); @@ -165,30 +165,64 @@ public class DependencyMaterialConfigTest { dependencyMaterialConfig.setConfigAttributes(configMap); - assertThat(dependencyMaterialConfig.getMaterialName(), is(new CaseInsensitiveString("name1"))); - assertThat(dependencyMaterialConfig.getPipelineName(), is(new CaseInsensitiveString("pipeline-1"))); - assertThat(dependencyMaterialConfig.getStageName(), is(new CaseInsensitiveString("stage-1"))); - assertThat(dependencyMaterialConfig.getPipelineStageName(), is("pipeline-1 [stage-1]")); - assertThat(dependencyMaterialConfig.ignoreForScheduling(), is(true)); + assertThat(dependencyMaterialConfig.getMaterialName()).isEqualTo(new CaseInsensitiveString("name1")); + assertThat(dependencyMaterialConfig.getPipelineName()).isEqualTo(new CaseInsensitiveString("pipeline-1")); + assertThat(dependencyMaterialConfig.getStageName()).isEqualTo(new CaseInsensitiveString("stage-1")); + assertThat(dependencyMaterialConfig.getPipelineStageName()).isEqualTo("pipeline-1 [stage-1]"); + assertThat(dependencyMaterialConfig.ignoreForScheduling()).isTrue(); } @Test - public void setConfigAttributes_shouldNotPopulateNameFromConfigAttributesIfNameIsEmptyOrNull() { + void setConfigAttributes_shouldNotPopulateNameFromConfigAttributesIfNameIsEmptyOrNull() { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("name2"), new CaseInsensitiveString("pipeline"), new CaseInsensitiveString("stage")); HashMap<String, String> configMap = new HashMap<>(); configMap.put(AbstractMaterialConfig.MATERIAL_NAME, ""); dependencyMaterialConfig.setConfigAttributes(configMap); - assertThat(dependencyMaterialConfig.getMaterialName(), is(nullValue())); + assertThat(dependencyMaterialConfig.getMaterialName()).isNull(); } @Test - public void shouldValidateTree() { + void shouldValidateTree() { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("upstream_stage"), new CaseInsensitiveString("upstream_pipeline"), new CaseInsensitiveString("stage")); PipelineConfig pipeline = new PipelineConfig(new CaseInsensitiveString("p"), new MaterialConfigs()); pipeline.setOrigin(new FileConfigOrigin()); dependencyMaterialConfig.validateTree(PipelineConfigSaveValidationContext.forChain(true, "group", config, pipeline)); - assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), is("Pipeline with name 'upstream_pipeline' does not exist, it is defined as a dependency for pipeline 'p' (cruise-config.xml)")); + assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).isEqualTo("Pipeline with name 'upstream_pipeline' does not exist, it is defined as a dependency for pipeline 'p' (cruise-config.xml)"); + } + + @Nested + class getName { + @Test + void shouldBeSameAsConfiguredName() { + DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("material name"), new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage")); + + assertThat(dependencyMaterialConfig.getName()).isEqualTo(new CaseInsensitiveString("material name")); + } + + @Test + void shouldBeEmptyIfNotSet() { + DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage")); + + assertThat(dependencyMaterialConfig.getName()).isNull(); + } + } + + @Nested + class displayName { + @Test + void shouldBeSameSameAsNameIfConfigured() { + DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("material name"), new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage")); + + assertThat(dependencyMaterialConfig.getDisplayName()).isEqualTo("material name"); + } + + @Test + void shouldBePipelineNameIfNameNotSet() { + DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage")); + + assertThat(dependencyMaterialConfig.getDisplayName()).isEqualTo("#{upstream_pipeline}"); + } } }
      ['config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      15,603,778
      3,124,659
      370,187
      3,319
      314
      58
      8
      1
      513
      83
      94
      9
      0
      0
      1970-01-01T00:26:21
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      396
      gocd/gocd/1869/1799
      gocd
      gocd
      https://github.com/gocd/gocd/issues/1799
      https://github.com/gocd/gocd/pull/1869
      https://github.com/gocd/gocd/pull/1869#issuecomment-194664589
      2
      close
      pipeline config API: cannot create pipeline with dependency on an upstream with a template
      Pipeline "upstream" uses some template that has a stage called "run". Using the pipeline config API, try to create a pipeline "downstream" with a material that points to the upstream pipeline. ``` "materials": [ some_git_repo, {"attributes": {"auto_update": true, "name": "upstream", "pipeline": "upstream", "stage": "run"}, "type": "dependency"}], ``` I get the following error: ``` Validations failed for pipeline 'downstream'.... errors: pipeline: "Stage with name 'run' does not exist on pipeline 'upstream'" ```
      68e97393b25c016f55f58e9ba37d808c5577b429
      e075da259f523da22a32fe0f663c9ef516abc1aa
      https://github.com/gocd/gocd/compare/68e97393b25c016f55f58e9ba37d808c5577b429...e075da259f523da22a32fe0f663c9ef516abc1aa
      diff --git a/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java b/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java index a9821da177..d3e1e95df0 100644 --- a/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java +++ b/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 ThoughtWorks, Inc. + * Copyright 2016 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -184,7 +184,7 @@ public class PipelineConfigService implements PipelineConfigChangedListener, Ini @Override public void onConfigChange(CruiseConfig newCruiseConfig) { - PipelineConfigurationCache.getInstance().onConfigChange(goConfigService.getConfigForEditing()); + PipelineConfigurationCache.getInstance().onConfigChange(goConfigService.cruiseConfig()); if (goCache.get(GO_PIPELINE_CONFIGS_ETAGS_CACHE) != null) { goCache.remove(GO_PIPELINE_CONFIGS_ETAGS_CACHE); } diff --git a/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java b/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java index ad9f249ddd..6d5423aa56 100644 --- a/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java +++ b/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java @@ -51,6 +51,7 @@ import java.util.Arrays; import java.util.UUID; import static com.thoughtworks.go.util.TestUtils.contains; +import static junit.framework.Assert.assertTrue; import static junit.framework.TestCase.assertFalse; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; @@ -148,6 +149,49 @@ public class PipelineConfigServiceIntegrationTest { assertThat(configRepository.getCurrentRevision().getUsername(), is(user.getDisplayName())); } + @Test + public void shouldUpdatePipelineConfigWhenDependencyMaterialHasTemplateDefined() throws Exception { + CaseInsensitiveString templateName = new CaseInsensitiveString("template_with_param"); + saveTemplateWithParamToConfig(templateName); + + pipelineConfig.clear(); + pipelineConfig.setTemplateName(templateName); + pipelineConfig.addParam(new ParamConfig("SOME_PARAM", "SOME_VALUE")); + + CruiseConfig cruiseConfig = goConfigDao.loadConfigHolder().configForEdit; + cruiseConfig.update(groupName, pipelineConfig.name().toString(), pipelineConfig); + saveConfig(cruiseConfig); + + PipelineConfig downstream = GoConfigMother.createPipelineConfigWithMaterialConfig("downstream", new DependencyMaterialConfig(pipelineConfig.name(), new CaseInsensitiveString("stage"))); + pipelineConfigService.createPipelineConfig(user, downstream, result, groupName); + + assertThat(result.toString(), result.isSuccessful(), is(true)); + assertTrue(downstream.materialConfigs().first().errors().isEmpty()); + } + + @Test + public void shouldUpdatePipelineConfigWhenFetchTaskFromUpstreamHasPipelineWithTemplateDefined() throws Exception { + CaseInsensitiveString templateName = new CaseInsensitiveString("template_with_param"); + saveTemplateWithParamToConfig(templateName); + + pipelineConfig.clear(); + pipelineConfig.setTemplateName(templateName); + pipelineConfig.addParam(new ParamConfig("SOME_PARAM", "SOME_VALUE")); + + CaseInsensitiveString stage = new CaseInsensitiveString("stage"); + CaseInsensitiveString job = new CaseInsensitiveString("job"); + CruiseConfig cruiseConfig = goConfigDao.loadConfigHolder().configForEdit; + cruiseConfig.update(groupName, pipelineConfig.name().toString(), pipelineConfig); + saveConfig(cruiseConfig); + + PipelineConfig downstream = GoConfigMother.createPipelineConfigWithMaterialConfig("downstream", new DependencyMaterialConfig(pipelineConfig.name(), stage)); + downstream.getStage(stage).getJobs().first().addTask(new FetchTask(pipelineConfig.name(), stage, job, "src", "dest")); + pipelineConfigService.createPipelineConfig(user, downstream, result, groupName); + + assertThat(result.toString(), result.isSuccessful(), is(true)); + assertTrue(downstream.materialConfigs().first().errors().isEmpty()); + } + @Test public void shouldNotCreatePipelineConfigWhenAPipelineBySameNameAlreadyExists() throws GitAPIException { GoConfigHolder goConfigHolderBeforeUpdate = goConfigDao.loadConfigHolder();
      ['server/src/com/thoughtworks/go/server/service/PipelineConfigService.java', 'server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,502,322
      1,499,524
      198,300
      1,822
      278
      52
      4
      1
      524
      71
      132
      14
      0
      2
      1970-01-01T00:24:14
      6,872
      Java
      {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474}
      Apache License 2.0
      428
      real-logic/aeron/145/29
      real-logic
      aeron
      https://github.com/real-logic/aeron/issues/29
      https://github.com/real-logic/aeron/pull/145
      https://github.com/real-logic/aeron/pull/145
      1
      fixes
      ReceiverTest setUp() method throws exception
      OS (uname -a): Linux 3.5.0-51-generic #77~precise1-Ubuntu SMP Thu Jun 5 00:48:28 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux Thanks for open sourcing this library. I hope to learn a lot about high performance messaging from it. I noticed that the ReceiverTest tearDown() method was throwing NPEs when closing the receiveChannelEndpoint so I wrapped the creation of the ReceiveChannelEndpoint in the ReceiverTest's setUp() method with a try/catch that printed the exception and I got this: Exception: java.lang.IllegalStateException: Failed to set SO_RCVBUF: attempted=131072, actual=131071 Looks like UdpChannelTransport's constructor is throwing the exception. % sysctl net | grep 131071 net.core.rmem_max = 131071 net.core.wmem_max = 131071 Looks like there's a hard limit we're hitting up against. Thanks!
      fb68c69719010f56b9698572bbeb2dac0b597f2e
      308142d22d1afb0efdefce2867b5097ba0b2dbc4
      https://github.com/real-logic/aeron/compare/fb68c69719010f56b9698572bbeb2dac0b597f2e...308142d22d1afb0efdefce2867b5097ba0b2dbc4
      diff --git a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java index e3430f374..dfd794552 100644 --- a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java +++ b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java @@ -35,6 +35,11 @@ import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBuffer; import java.io.File; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; + +import java.nio.channels.DatagramChannel; +import java.net.StandardSocketOptions; +import java.io.IOException; + import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -103,6 +108,8 @@ public final class MediaDriver implements AutoCloseable ensureDirectoriesAreRecreated(); + warnOnInsufficentSocketBuffers(); + ctx.unicastSenderFlowControl(Configuration::unicastFlowControlStrategy) .multicastSenderFlowControl(Configuration::multicastFlowControlStrategy) .conductorTimerWheel(Configuration.newConductorTimerWheel()) @@ -247,6 +254,38 @@ public final class MediaDriver implements AutoCloseable return this; } + private void warnOnInsufficentSocketBuffers() + { + try (DatagramChannel probe = DatagramChannel.open()) + { + + probe.setOption(StandardSocketOptions.SO_SNDBUF, Integer.MAX_VALUE); + final int maxSoSndbuf = probe.getOption(StandardSocketOptions.SO_SNDBUF); + + if (maxSoSndbuf < Configuration.SOCKET_SNDBUF_LENGTH) + { + System.err.println( + String.format("WARNING: Could not get desired SO_SNDBUF: attempted=%d, actual=%d", + Configuration.SOCKET_SNDBUF_LENGTH, maxSoSndbuf)); + } + + probe.setOption(StandardSocketOptions.SO_RCVBUF, Integer.MAX_VALUE); + final int maxSoRcvbuf = probe.getOption(StandardSocketOptions.SO_RCVBUF); + + if (maxSoRcvbuf < Configuration.SOCKET_RCVBUF_LENGTH) + { + System.err.println( + String.format("WARNING: Could not get desired SO_RCVBUF: attempted=%d, actual=%d", + Configuration.SOCKET_RCVBUF_LENGTH, maxSoRcvbuf)); + } + } + catch (final IOException ex) + { + throw new RuntimeException( + String.format("probe socket: %s", ex.toString()), ex); + } + } + private void ensureDirectoriesAreRecreated() { final BiConsumer<String, String> callback = diff --git a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java index 045ae88a8..0b8d56182 100644 --- a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java +++ b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java @@ -78,25 +78,11 @@ public abstract class UdpChannelTransport implements AutoCloseable if (0 != Configuration.SOCKET_SNDBUF_LENGTH) { datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, Configuration.SOCKET_SNDBUF_LENGTH); - final int soSndbuf = datagramChannel.getOption(StandardSocketOptions.SO_SNDBUF); - - if (soSndbuf != Configuration.SOCKET_SNDBUF_LENGTH) - { - throw new IllegalStateException(String.format( - "Failed to set SO_SNDBUF: attempted=%d, actual=%d", Configuration.SOCKET_SNDBUF_LENGTH, soSndbuf)); - } } if (0 != Configuration.SOCKET_RCVBUF_LENGTH) { datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, Configuration.SOCKET_RCVBUF_LENGTH); - final int soRcvbuf = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF); - - if (soRcvbuf != Configuration.SOCKET_RCVBUF_LENGTH) - { - throw new IllegalStateException(String.format( - "Failed to set SO_RCVBUF: attempted=%d, actual=%d", Configuration.SOCKET_RCVBUF_LENGTH, soRcvbuf)); - } } datagramChannel.configureBlocking(false);
      ['aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java', 'aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      1,023,943
      209,160
      30,104
      188
      2,273
      459
      53
      2
      813
      112
      212
      18
      0
      0
      1970-01-01T00:23:53
      6,607
      Java
      {'Java': 7808647, 'C++': 2885942, 'C': 2193186, 'CMake': 83950, 'Shell': 66446, 'Batchfile': 43311, 'Dockerfile': 3239}
      Apache License 2.0
      258
      alluxio/alluxio/14635/14620
      alluxio
      alluxio
      https://github.com/Alluxio/alluxio/issues/14620
      https://github.com/Alluxio/alluxio/pull/14635
      https://github.com/Alluxio/alluxio/pull/14635
      1
      solve
      workerFuse stressbench write Input/output error
      **Alluxio Version:** Current master branch **Describe the bug** Fuse stress bench with workerFuse writing data errors out. Not tuning MaxDirectMemorySize, all threads fail. Logs from `worker.out`: ``` io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 16777216 byte(s) of direct memory (used: 4278190359, max: 4294967296) at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:754) at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:709) at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:645) at io.netty.buffer.PoolArena$DirectArena.newChunk(PoolArena.java:621) at io.netty.buffer.PoolArena.allocateNormal(PoolArena.java:204) at io.netty.buffer.PoolArena.tcacheAllocateNormal(PoolArena.java:188) at io.netty.buffer.PoolArena.allocate(PoolArena.java:138) at io.netty.buffer.PoolArena.allocate(PoolArena.java:128) at io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:378) at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:187) at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:178) at io.netty.buffer.AbstractByteBufAllocator.buffer(AbstractByteBufAllocator.java:115) at alluxio.client.block.stream.BlockOutStream.allocateBuffer(BlockOutStream.java:294) at alluxio.client.block.stream.BlockOutStream.updateCurrentChunk(BlockOutStream.java:252) at alluxio.client.block.stream.BlockOutStream.write(BlockOutStream.java:141) at alluxio.client.file.AlluxioFileOutStream.writeInternal(AlluxioFileOutStream.java:271) at alluxio.client.file.AlluxioFileOutStream.write(AlluxioFileOutStream.java:229) at alluxio.fuse.AlluxioJniFuseFileSystem.writeInternal(AlluxioJniFuseFileSystem.java:438) at alluxio.fuse.AlluxioJniFuseFileSystem.lambda$write$6(AlluxioJniFuseFileSystem.java:413) at alluxio.fuse.AlluxioFuseUtils.call(AlluxioFuseUtils.java:278) at alluxio.fuse.AlluxioJniFuseFileSystem.write(AlluxioJniFuseFileSystem.java:413) at alluxio.jnifuse.AbstractFuseFileSystem.writeCallback(AbstractFuseFileSystem.java:316) ``` With following java options in `alluxio-env.sh`: `ALLUXIO_WORKER_JAVA_OPTS+=" -Xmx24G -Xms24G -XX:MaxDirectMemorySize=18g" `, only some threads report failure, and no logs in `worker.out`. **To Reproduce** Using ec2 instance r5.2xlarge which has 64GB memory. Using the following properties in `alluxio-site.properties`: ``` alluxio.master.hostname=localhost alluxio.master.mount.table.root.ufs=s3://xxxxx aws.accessKeyId=xxxxxxxxx aws.secretKey=xxxxxxxxxxxxxxx alluxio.worker.ramdisk.size=15GB alluxio.worker.fuse.enabled=true alluxio.worker.fuse.mount.alluxio.path=/fuseTest alluxio.worker.fuse.mount.point=/home/centos/fuseTest # User properties alluxio.user.file.writetype.default=MUST_CACHE alluxio.user.block.size.bytes.default=200k alluxio.client.cache.async.write.enabled=false alluxio.user.file.passive.cache.enabled=false ``` Run Fuse stress bench with: ``` bin/alluxio runClass alluxio.stress.cli.fuse.FuseIOBench --local-path /home/centos/fuseTest --operation Write --threads 32 --num-dirs 100 --num-files-per-dir 1000 --file-size 100k ``` **Additional information** Standalone Fuse has no such issue.
      4325774f94b2acb2019adeaf3d53713529209e5d
      eecfcd4358dfa2cac0ae6b0275d8e7eb09f85c90
      https://github.com/alluxio/alluxio/compare/4325774f94b2acb2019adeaf3d53713529209e5d...eecfcd4358dfa2cac0ae6b0275d8e7eb09f85c90
      diff --git a/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java b/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java index 0076f9b427..ffe84c9b91 100644 --- a/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java +++ b/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java @@ -92,18 +92,23 @@ public final class BlockWorkerDataWriter implements DataWriter { @Override public void writeChunk(final ByteBuf buf) throws IOException { - if (mReservedBytes < pos() + buf.readableBytes()) { - try { - long bytesToReserve = Math.max(mBufferSize, pos() + buf.readableBytes() - mReservedBytes); - // Allocate enough space in the existing temporary block for the write. - mBlockWorker.requestSpace(mSessionId, mBlockId, bytesToReserve); - } catch (Exception e) { - throw new IOException(e); + try { + if (mReservedBytes < pos() + buf.readableBytes()) { + try { + long bytesToReserve = Math.max(mBufferSize, pos() + buf.readableBytes() + - mReservedBytes); + // Allocate enough space in the existing temporary block for the write. + mBlockWorker.requestSpace(mSessionId, mBlockId, bytesToReserve); + } catch (Exception e) { + throw new IOException(e); + } } + long append = mBlockWriter.append(buf); + MetricsSystem.counter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT.getName()).inc(append); + MetricsSystem.meter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT_THROUGHPUT.getName()).mark(append); + } finally { + buf.release(); } - long append = mBlockWriter.append(buf); - MetricsSystem.counter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT.getName()).inc(append); - MetricsSystem.meter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT_THROUGHPUT.getName()).mark(append); } @Override
      ['core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      9,523,936
      2,143,288
      272,269
      1,621
      1,346
      309
      25
      1
      3,483
      169
      871
      60
      0
      3
      1970-01-01T00:27:18
      6,326
      Java
      {'Java': 15817407, 'TypeScript': 340217, 'Shell': 175186, 'Go': 79288, 'C++': 47930, 'Mustache': 15785, 'Ruby': 15044, 'SCSS': 12027, 'JavaScript': 9992, 'C': 7326, 'Roff': 5919, 'Python': 4554, 'Dockerfile': 3642, 'Handlebars': 3633, 'HTML': 3412, 'Makefile': 2362}
      Apache License 2.0
      1,432
      micronaut-projects/micronaut-core/1273/1272
      micronaut-projects
      micronaut-core
      https://github.com/micronaut-projects/micronaut-core/issues/1272
      https://github.com/micronaut-projects/micronaut-core/pull/1273
      https://github.com/micronaut-projects/micronaut-core/pull/1273
      1
      fixes
      Regression on bean with preDestroy
      My project has a factory that replaces the `DefaultMongoClientFactory`: ```kotlin @Requirements(Requires(beans = [DefaultMongoConfiguration::class]), Requires(classes = [MongoClient::class])) @Replaces(factory = DefaultMongoClientFactory::class) @Factory class KMongoClientFactory { companion object: KLogging() @Bean(preDestroy = "close") @Singleton fun kmongoClient(configuration: DefaultMongoConfiguration): MongoClient { logger.debug { "===== KMongo creating client for ${configuration.uri}" } val client = KMongo.createClient(MongoClientURI(configuration.uri)) return client } } ``` This was working last week, but I am now seeing this error: ``` $ ./gradlew test $ ./gradlew test e: /Users/mmindenhall/projects/micronaut-examples/hello-world-kotlin/build/tmp/kapt3/stubs/main/example/KMongoClientFactory.java:19: error: @Bean method defines a preDestroy method that does not exist or is not public: close public final com.mongodb.MongoClient kmongoClient(@org.jetbrains.annotations.NotNull() ^ ``` It seems likely that this was caused by the recent fix for #1267. ### Task List - [x] Steps to reproduce provided - [x] Stacktrace (if present) provided - [x] Example that reproduces the problem uploaded to Github - [x] Full description of the issue provided (see below) ### Steps to Reproduce 1. Clone [my fork of micronaut-examples](https://github.com/mmindenhall/micronaut-examples) 1. `cd micronaut-examples` 1. `git checkout pre-destroy-regression` 1. `cd hello-world-kotlin` 1. `./gradlew test` Note that if this is executed against micronaut 1.1.0.M1 instead of 1.1.0.BUILD-SNAPSHOT, the tests all pass: 1. Edit `gradle.properties` 1. Change micronaut version (comment out line 2, uncomment line 3), save changes 1. `./gradlew test` ### Expected Behaviour Everything passes. ### Actual Behaviour The factory returns an instance of `MongoClient`, which implements the `Closeable` interface (and therefore the public `close` method). Micronaut is erroneously reporting the error above. ### Environment Information - **Operating System**: macOS 10.14.3 - **Micronaut Version:** 1.1.0.BUILD-SNAPSHOT - **JDK Version:** 1.8.0_191 ### Example Application See steps to reproduce above.
      bb11cd1e6e5b1d1360f9c0f941df8bcbf57363a7
      6985a5886137dbd18d8be09a0cc12dbd386b200a
      https://github.com/micronaut-projects/micronaut-core/compare/bb11cd1e6e5b1d1360f9c0f941df8bcbf57363a7...6985a5886137dbd18d8be09a0cc12dbd386b200a
      diff --git a/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java b/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java index 0929252063..4696741dd0 100644 --- a/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java +++ b/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java @@ -202,7 +202,7 @@ public class ModelUtils { * @return The executable element */ Optional<ExecutableElement> findAccessibleNoArgumentInstanceMethod(TypeElement classElement, String methodName) { - return ElementFilter.methodsIn(classElement.getEnclosedElements()) + return ElementFilter.methodsIn(elementUtils.getAllMembers(classElement)) .stream().filter(m -> m.getSimpleName().toString().equals(methodName) && !isPrivate(m) && !isStatic(m)) .findFirst(); }
      ['inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      6,970,541
      1,407,026
      198,293
      1,950
      157
      26
      2
      1
      2,372
      259
      569
      72
      1
      2
      1970-01-01T00:25:50
      5,790
      Java
      {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}
      Apache License 2.0
      1,426
      micronaut-projects/micronaut-core/2153/2152
      micronaut-projects
      micronaut-core
      https://github.com/micronaut-projects/micronaut-core/issues/2152
      https://github.com/micronaut-projects/micronaut-core/pull/2153
      https://github.com/micronaut-projects/micronaut-core/pull/2153
      1
      fixes
      HTTP client pool caches dns lookup forever
      When the DefaultHttpClient creates it's poolMap instance a DNS lookup is made and stored in the bootstrap instance: ` Bootstrap newBootstrap = bootstrap.clone(group); newBootstrap.remoteAddress(key.getRemoteAddress()); ` The remoteAddress is never updated, which means that if the ip is recycled (very common for AWS hosted services), the pool will continue to try to create connections to the original ip. ### Task List - [x] Steps to reproduce provided - [x] Stacktrace (if present) provided - [x] Example that reproduces the problem uploaded to Github - [x] Full description of the issue provided (see below) ### Steps to Reproduce https://github.com/luckyswede/micronaut-dnstest ### Expected Behaviour When new connections are created a new DNS lookup should take place ### Actual Behaviour The original DNS lookup result is reused ### Environment Information - **Operating System**: All - **Micronaut Version:** 1.2.2 - **JDK Version:** 11 ### Example Application https://github.com/luckyswede/micronaut-dnstest
      11e6988348ea8ae0c740d74e91b28c4f13937472
      601d4e69dfd188ac8ae8ca376bee3407c858cb05
      https://github.com/micronaut-projects/micronaut-core/compare/11e6988348ea8ae0c740d74e91b28c4f13937472...601d4e69dfd188ac8ae8ca376bee3407c858cb05
      diff --git a/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java b/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java index f46d23daad..760d142124 100644 --- a/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java +++ b/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java @@ -260,7 +260,6 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr Bootstrap newBootstrap = bootstrap.clone(group); newBootstrap.remoteAddress(key.getRemoteAddress()); - AbstractChannelPoolHandler channelPoolHandler = newPoolHandler(key); final Long acquireTimeoutMillis = connectionPoolConfiguration.getAcquireTimeout().map(Duration::toMillis).orElse(-1L); return new FixedChannelPool( @@ -281,6 +280,7 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr protected ChannelPool newPool(RequestKey key) { Bootstrap newBootstrap = bootstrap.clone(group); newBootstrap.remoteAddress(key.getRemoteAddress()); + AbstractChannelPoolHandler channelPoolHandler = newPoolHandler(key); return new SimpleChannelPool( newBootstrap, @@ -2303,7 +2303,7 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr } public InetSocketAddress getRemoteAddress() { - return new InetSocketAddress(host, port); + return InetSocketAddress.createUnresolved(host, port); } public boolean isSecure() {
      ['http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      7,131,028
      1,428,690
      200,862
      1,797
      126
      21
      4
      1
      1,100
      141
      240
      30
      2
      0
      1970-01-01T00:26:09
      5,790
      Java
      {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}
      Apache License 2.0
      1,421
      micronaut-projects/micronaut-core/9427/9423
      micronaut-projects
      micronaut-core
      https://github.com/micronaut-projects/micronaut-core/issues/9423
      https://github.com/micronaut-projects/micronaut-core/pull/9427
      https://github.com/micronaut-projects/micronaut-core/pull/9427
      1
      fixes
      New allowed-origins-regex property not working..?
      ### Expected Behavior With 3.9.0 allowed-origins no longer supports a regex value for the cors configuration. Instead you now need to use a new property called allowed-origins-regex. When replacing allowed-origins with allowed-origins-regex using the same regular expression and previously, it's expected that calls from an Origin matching the pattern are allowed through. ### Actual Behaviour Calls with a matching Origin header are no longer accepted and a 403 forbidden is returned. ### Steps To Reproduce Start a 3.8.9 micronaut server with a configuration set to ``` micronaut: application: name: testApp server: cors: enabled: true configurations: web: allowed-origins: - ^http(|s):\\/\\/(\\w*\\.)*integration\\.mydomain\\.com$ ``` Make a call to an endpoint on that server specifying an Origin value in the header of "https://www.integration.mydomain.com" You should receive a 200 okay. Now change the configuration to the below and the version of Micronaut to 3.9.x ``` micronaut: application: name: testApp server: cors: enabled: true configurations: web: allowed-origins-regex: ^http(|s):\\/\\/(\\w*\\.)*integration\\.mydomain\\.com$ ``` Make the same call to an endpoint and you should receive a 403 Forbidden. (Expected that you receive a 200) ### Environment Information macOS JDK 17 Micronaut 3.8.9 and 3.9.2 ### Example Application _No response_ ### Version 3.9.2
      2c1bee6be0af723c66e8ce790590f4f7d22a84d3
      5d60708289271499c5435b7558880f01b6941656
      https://github.com/micronaut-projects/micronaut-core/compare/2c1bee6be0af723c66e8ce790590f4f7d22a84d3...5d60708289271499c5435b7558880f01b6941656
      diff --git a/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java b/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java index 6dc7342aad..33278f69cc 100644 --- a/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java +++ b/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2022 original authors + * Copyright 2017-2023 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -184,22 +184,42 @@ public class CorsSimpleRequestTest { "micronaut.server.cors.configurations.foo.allowed-origins", Collections.singletonList("https://foo.com") ), createRequest("https://foo.com"), - (server, request) -> { + CorsSimpleRequestTest::isSuccessfulCorsAssertion + ); + } - RefreshCounter refreshCounter = server.getApplicationContext().getBean(RefreshCounter.class); - assertEquals(0, refreshCounter.getRefreshCount()); + /** + * CORS Simple request for localhost can be allowed via configuration of a regex. + * @throws IOException may throw the try for resources + */ + @Test + // "https://github.com/micronaut-projects/micronaut-core/issues/9423") + void corsSimpleRequestForLocalhostCanBeAllowedViaRegexConfiguration() throws IOException { + asserts(SPECNAME, + CollectionUtils.mapOf( + PROPERTY_MICRONAUT_SERVER_CORS_ENABLED, StringUtils.TRUE, + "micronaut.server.cors.configurations.foo.allowed-origins-regex", Collections.singletonList("^http(|s):\\\\/\\\\/foo\\\\.com$") + ), + createRequest("https://foo.com"), + CorsSimpleRequestTest::isSuccessfulCorsAssertion + ); + } - AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() - .status(HttpStatus.OK) - .assertResponse(response -> CorsAssertion.builder() - .vary("Origin") - .allowCredentials() - .allowOrigin("https://foo.com") - .build() - .validate(response)) - .build()); - assertEquals(1, refreshCounter.getRefreshCount()); - }); + /** + * CORS Simple request for localhost can be forbidden via configuration of a regex. + * @throws IOException may throw the try for resources + */ + @Test + // "https://github.com/micronaut-projects/micronaut-core/issues/9423") + void corsSimpleRequestForLocalhostForbiddenViaRegexConfiguration() throws IOException { + asserts(SPECNAME, + CollectionUtils.mapOf( + PROPERTY_MICRONAUT_SERVER_CORS_ENABLED, StringUtils.TRUE, + "micronaut.server.cors.configurations.foo.allowed-origins-regex", Collections.singletonList("^http(|s):\\\\/\\\\/foo\\\\.com$") + ), + createRequest("https://bar.com"), + CorsSimpleRequestTest::isForbidden + ); } private RequestSupplier createRequestFor(String host, String origin) { @@ -225,6 +245,21 @@ public class CorsSimpleRequestTest { assertEquals(1, refreshCounter.getRefreshCount()); } + static void isSuccessfulCorsAssertion(ServerUnderTest server, HttpRequest<?> request) { + RefreshCounter refreshCounter = server.getApplicationContext().getBean(RefreshCounter.class); + assertEquals(0, refreshCounter.getRefreshCount()); + AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() + .status(HttpStatus.OK) + .assertResponse(response -> CorsAssertion.builder() + .vary("Origin") + .allowCredentials() + .allowOrigin("https://foo.com") + .build() + .validate(response)) + .build()); + assertEquals(1, refreshCounter.getRefreshCount()); + } + static HttpRequest<?> createRequest(String origin) { return createRequest("/refresh", origin); } diff --git a/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java b/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java index 7bf75191a3..52601235db 100644 --- a/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java +++ b/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 original authors + * Copyright 2017-2023 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,6 +62,7 @@ import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN; */ @Filter(MATCH_ALL_PATTERN) public class CorsFilter implements HttpServerFilter { + private static final Logger LOG = LoggerFactory.getLogger(CorsFilter.class); private static final ArgumentConversionContext<HttpMethod> CONVERSION_CONTEXT_HTTP_METHOD = ImmutableArgumentConversionContext.of(HttpMethod.class); @@ -140,7 +141,7 @@ public class CorsFilter implements HttpServerFilter { return false; } String host = httpHostResolver.resolve(request); - return isAny(corsOriginConfiguration.getAllowedOrigins()) && isHostLocal(host); + return isAnyOrigin(corsOriginConfiguration.getAllowedOriginsRegex().isPresent(), corsOriginConfiguration.getAllowedOrigins()) && isHostLocal(host); } /** @@ -351,6 +352,11 @@ public class CorsFilter implements HttpServerFilter { return m.matches(); } + private static boolean isAnyOrigin(boolean isAllowedOriginsRegexConfigured, List<String> values) { + // True if a regular expression has not been set for origin, and the allowed hosts are still ANY + return !isAllowedOriginsRegexConfigured && isAny(values); + } + private static boolean isAny(List<String> values) { return values == CorsOriginConfiguration.ANY; }
      ['http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java', 'http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      9,143,135
      1,805,359
      250,070
      1,907
      615
      132
      10
      1
      1,611
      190
      369
      59
      1
      2
      1970-01-01T00:28:06
      5,790
      Java
      {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}
      Apache License 2.0
      1,434
      micronaut-projects/micronaut-core/623/618
      micronaut-projects
      micronaut-core
      https://github.com/micronaut-projects/micronaut-core/issues/618
      https://github.com/micronaut-projects/micronaut-core/pull/623
      https://github.com/micronaut-projects/micronaut-core/pull/623
      1
      fixes
      Inconsistent @Body handling in browser
      Body is occasionally lost when uploaded from browser ### Steps to Reproduce See sample ### Expected Behaviour Body handling should work ### Actual Behaviour Occasional: ``` i.m.h.s.netty.RoutingInBoundHandler - Encoding emitted response object [ /command - Required argument [LoginCommand command] not specified] using codec: io.micronaut.jackson.codec.JsonMediaTypeCodec@3ee39da0 ``` ### Example Application https://github.com/liwujun0513/micronaut_demo
      2c286aba5a06c3b684ba3475d39ca6be48ed2d2f
      454e9d34b5d7968931b92b59600029da5fac911f
      https://github.com/micronaut-projects/micronaut-core/compare/2c286aba5a06c3b684ba3475d39ca6be48ed2d2f...454e9d34b5d7968931b92b59600029da5fac911f
      diff --git a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java index cffc0be9cf..6c91f26c8e 100644 --- a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java +++ b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java @@ -173,7 +173,7 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { - if (inClass.isInstance(msg)) { + if (isValidInMessage(msg)) { receivedInMessage(ctx); final In inMsg = inClass.cast(msg); @@ -279,7 +279,7 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag @Override public void write(final ChannelHandlerContext ctx, Object msg, final ChannelPromise promise) throws Exception { - if (outClass.isInstance(msg)) { + if (isValidOutMessage(msg)) { Outgoing out = new Outgoing(outClass.cast(msg), promise); receivedOutMessage(ctx); @@ -404,6 +404,22 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag } } + /** + * @param msg The message + * @return True if the handler should write the message + */ + protected boolean isValidOutMessage(Object msg) { + return outClass.isInstance(msg); + } + + /** + * @param msg The message + * @return True if the handler should read the message + */ + protected boolean isValidInMessage(Object msg) { + return inClass.isInstance(msg); + } + /** * The outgoing class. */ @@ -420,4 +436,5 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag this.promise = promise; } } + } diff --git a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java index 69b1e028a0..6b464abd05 100644 --- a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java +++ b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java @@ -22,15 +22,7 @@ import io.micronaut.http.netty.reactive.HandlerSubscriber; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpContent; -import io.netty.handler.codec.http.HttpHeaderNames; -import io.netty.handler.codec.http.HttpRequest; -import io.netty.handler.codec.http.HttpResponse; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpUtil; -import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketVersion; @@ -185,6 +177,11 @@ public class HttpStreamsServerHandler extends HttpStreamsHandler<HttpRequest, Ht } } + @Override + protected boolean isValidOutMessage(Object msg) { + return msg instanceof FullHttpResponse || msg instanceof StreamedHttpResponse || msg instanceof WebSocketHttpResponse; + } + private boolean canHaveBody(HttpResponse message) { HttpResponseStatus status = message.status(); // All 1xx (Informational), 204 (No Content), and 304 (Not Modified) diff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java index 31319e04c2..884125f275 100644 --- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java +++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java @@ -69,6 +69,7 @@ import io.netty.handler.codec.http.multipart.DiskFileUpload; import io.netty.handler.flow.FlowControlHandler; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; +import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GlobalEventExecutor; @@ -104,6 +105,7 @@ import java.util.function.BiConsumer; @Singleton public class NettyHttpServer implements EmbeddedServer, WebSocketSessionRepository { public static final String HTTP_STREAMS_CODEC = "http-streams-codec"; + public static final String HTTP_CHUNKED_HANDLER = "http-chunked-handler"; @SuppressWarnings("WeakerAccess") public static final String HTTP_CODEC = "http-codec"; @SuppressWarnings("WeakerAccess") @@ -260,6 +262,7 @@ public class NettyHttpServer implements EmbeddedServer, WebSocketSessionReposito pipeline.addLast(HTTP_KEEP_ALIVE_HANDLER, new HttpServerKeepAliveHandler()); pipeline.addLast(HTTP_COMPRESSOR, new SmartHttpContentCompressor()); pipeline.addLast(HTTP_STREAMS_CODEC, new HttpStreamsServerHandler()); + pipeline.addLast(HTTP_CHUNKED_HANDLER, new ChunkedWriteHandler()); pipeline.addLast(HttpRequestDecoder.ID, new HttpRequestDecoder( NettyHttpServer.this, environment, diff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java index de30bb8f82..ffadc22f02 100644 --- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java +++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java @@ -19,7 +19,6 @@ package io.micronaut.http.server.netty.types.files; import io.micronaut.http.HttpRequest; import io.micronaut.http.MutableHttpResponse; import io.micronaut.http.netty.NettyMutableHttpResponse; -import io.micronaut.http.server.netty.NettyHttpServer; import io.micronaut.http.server.netty.types.NettyFileCustomizableResponseType; import io.micronaut.http.server.types.files.StreamedFile; import io.netty.channel.ChannelHandlerContext; @@ -27,11 +26,9 @@ import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpChunkedInput; import io.netty.handler.stream.ChunkedStream; -import io.netty.handler.stream.ChunkedWriteHandler; import java.io.InputStream; import java.net.URL; -import java.util.Optional; /** * Writes an {@link InputStream} to the Netty context. @@ -76,11 +73,6 @@ public class NettyStreamedFileCustomizableResponseType extends StreamedFile impl if (response instanceof NettyMutableHttpResponse) { FullHttpResponse nettyResponse = ((NettyMutableHttpResponse) response).getNativeResponse(); - //The streams codec prevents non full responses from being written - Optional - .ofNullable(context.pipeline().get(NettyHttpServer.HTTP_STREAMS_CODEC)) - .ifPresent(handler -> context.pipeline().replace(handler, "chunked-handler", new ChunkedWriteHandler())); - // Write the request data context.write(new DefaultHttpResponse(nettyResponse.protocolVersion(), nettyResponse.status(), nettyResponse.headers()), context.voidPromise()); context.writeAndFlush(new HttpChunkedInput(new ChunkedStream(getInputStream()))); diff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java index b120b6e0f4..7c3bd17646 100644 --- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java +++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java @@ -19,7 +19,6 @@ package io.micronaut.http.server.netty.types.files; import io.micronaut.http.HttpRequest; import io.micronaut.http.MutableHttpResponse; import io.micronaut.http.netty.NettyMutableHttpResponse; -import io.micronaut.http.server.netty.NettyHttpServer; import io.micronaut.http.server.netty.SmartHttpContentCompressor; import io.micronaut.http.server.netty.types.NettyFileCustomizableResponseType; import io.micronaut.http.server.types.CustomizableResponseTypeException; @@ -29,12 +28,10 @@ import io.netty.channel.DefaultFileRegion; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpChunkedInput; -import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedFile; -import io.netty.handler.stream.ChunkedWriteHandler; import java.io.File; import java.io.FileNotFoundException; @@ -112,11 +109,6 @@ public class NettySystemFileCustomizableResponseType extends SystemFileCustomiza FullHttpResponse nettyResponse = ((NettyMutableHttpResponse) response).getNativeResponse(); - //The streams codec prevents non full responses from being written - Optional - .ofNullable(context.pipeline().get(NettyHttpServer.HTTP_STREAMS_CODEC)) - .ifPresent(handler -> context.pipeline().replace(handler, "chunked-handler", new ChunkedWriteHandler())); - // Write the request data HttpHeaders headers = nettyResponse.headers(); context.write(new DefaultHttpResponse(nettyResponse.protocolVersion(), nettyResponse.status(), headers), context.voidPromise()); @@ -124,12 +116,6 @@ public class NettySystemFileCustomizableResponseType extends SystemFileCustomiza // Write the content. if (context.pipeline().get(SslHandler.class) == null && SmartHttpContentCompressor.shouldSkip(headers)) { // SSL not enabled - can use zero-copy file transfer. - // Remove the content compressor to prevent incorrect behavior with zero-copy - HttpContentCompressor compressor = context.pipeline().get(HttpContentCompressor.class); - if (compressor != null) { - context.pipeline().remove(HttpContentCompressor.class); - } - context.write(new DefaultFileRegion(raf.getChannel(), 0, getLength()), context.newProgressivePromise()); context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else {
      ['http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java', 'http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java', 'http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java', 'http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java', 'http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java']
      {'.java': 5}
      5
      5
      0
      0
      5
      6,796,725
      1,368,789
      195,312
      2,007
      2,798
      532
      61
      5
      487
      49
      108
      23
      1
      1
      1970-01-01T00:25:37
      5,790
      Java
      {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}
      Apache License 2.0
      1,423
      micronaut-projects/micronaut-core/2984/2934
      micronaut-projects
      micronaut-core
      https://github.com/micronaut-projects/micronaut-core/issues/2934
      https://github.com/micronaut-projects/micronaut-core/pull/2984
      https://github.com/micronaut-projects/micronaut-core/pull/2984
      1
      fixes
      AmazonComputeInstanceMetadataResolver has an invalid path
      While connecting the application to a consul running in a different ec2 instance (same VPC) the following error occurs in the logs `i.m.d.c.a.AmazonComputeInstanceMetadataResolver - error getting public host name from:http://169.254.169.254//latest/meta-data/publicHostname java.io.FileNotFoundException: http://169.254.169.254//latest/meta-data/public-hostname` double // is included in path.
      bd51d3353b629abddfbc3ad9f909c135ab47c150
      4876cc6f12e22b0e99acd59105550a8d546db82a
      https://github.com/micronaut-projects/micronaut-core/compare/bd51d3353b629abddfbc3ad9f909c135ab47c150...4876cc6f12e22b0e99acd59105550a8d546db82a
      diff --git a/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java b/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java index 8fb8db8f8d..779a3499e3 100644 --- a/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java +++ b/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java @@ -46,7 +46,7 @@ public class AmazonMetadataConfiguration implements Toggleable { * The default url value. */ @SuppressWarnings("WeakerAccess") - public static final String DEFAULT_URL = "http://169.254.169.254/"; + public static final String DEFAULT_URL = "http://169.254.169.254"; private String url = DEFAULT_URL; private String metadataUrl;
      ['runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      7,542,554
      1,507,719
      211,614
      1,858
      144
      38
      2
      1
      414
      38
      99
      7
      2
      0
      1970-01-01T00:26:25
      5,790
      Java
      {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14}
      Apache License 2.0
      386
      raphw/byte-buddy/528/527
      raphw
      byte-buddy
      https://github.com/raphw/byte-buddy/issues/527
      https://github.com/raphw/byte-buddy/pull/528
      https://github.com/raphw/byte-buddy/pull/528
      1
      fixes
      Using MethodCall onField with field locator pointing to different class fails
      ```java DynamicType.Loaded<Object> loaded = new ByteBuddy() .subclass(Object.class) .invokable(isTypeInitializer()) .intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class))) .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with("")) .make() .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); loaded.getLoaded().getDeclaredConstructor().newInstance(); ``` The code above fails with the error below: ``` java.lang.VerifyError: Local variable table overflow Exception Details: Location: net/bytebuddy/renamed/java/lang/Object$ByteBuddy$XtBtrrHJ.<clinit>()V @0: aload_0 Reason: Local index 0 is invalid Bytecode: 0x0000000: 2ab2 000f 1211 b600 17b1 ``` Relevant bytecode: ``` static <clinit>()V ALOAD 0 GETSTATIC java/lang/System.out : Ljava/io/PrintStream; LDC "" INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V RETURN MAXSTACK = 3 MAXLOCALS = 0 } ```
      0f9f5d84a878b3f04cd52475c48215dbd53e5053
      7abdaf36e9ba49e5aae30e421344d30728e68cf8
      https://github.com/raphw/byte-buddy/compare/0f9f5d84a878b3f04cd52475c48215dbd53e5053...7abdaf36e9ba49e5aae30e421344d30728e68cf8
      diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java index 9b06dc57a6..6c241dc565 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java @@ -1770,9 +1770,10 @@ public class MethodCall implements Implementation.Composable { if (!stackManipulation.isValid()) { throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + resolution.getField()); } - return new StackManipulation.Compound(invokedMethod.isStatic() + return new StackManipulation.Compound(invokedMethod.isStatic() || resolution.getField().isStatic() ? StackManipulation.Trivial.INSTANCE - : MethodVariableAccess.loadThis(), FieldAccess.forField(resolution.getField()).read(), stackManipulation); + : MethodVariableAccess.loadThis(), + FieldAccess.forField(resolution.getField()).read(), stackManipulation); } @Override diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java index a92ee06c90..eec5b5a728 100644 --- a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java +++ b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java @@ -7,6 +7,7 @@ import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.dynamic.scaffold.FieldLocator; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.implementation.bytecode.constant.TextConstant; @@ -276,6 +277,38 @@ public class MethodCallTest { .make(); } + @Test + public void testStaticOnStaticFieldFromAnotherClass() throws Exception { + DynamicType.Loaded<Object> loaded = new ByteBuddy() + .subclass(Object.class) + .invokable(isTypeInitializer()) + .intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class))) + .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with("")) + .make() + .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); + assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); + assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0)); + assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); + Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); + assertThat(instance, instanceOf(Object.class)); + } + + @Test + public void testOnStaticFieldFromAnotherClass() throws Exception { + DynamicType.Loaded<Object> loaded = new ByteBuddy() + .subclass(Object.class) + .defineMethod("foo", void.class) + .intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class))) + .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with("fooCall")) + .make() + .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); + assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); + assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); + assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); + Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); + assertThat(instance, instanceOf(Object.class)); + } + @Test public void testOnFieldUsingMatcher() throws Exception { DynamicType.Loaded<MethodCallOnField> loaded = new ByteBuddy()
      ['byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      5,630,943
      947,133
      125,923
      304
      484
      80
      5
      1
      1,111
      76
      287
      37
      0
      3
      1970-01-01T00:25:35
      5,668
      Java
      {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}
      Apache License 2.0
      385
      raphw/byte-buddy/951/948
      raphw
      byte-buddy
      https://github.com/raphw/byte-buddy/issues/948
      https://github.com/raphw/byte-buddy/pull/951
      https://github.com/raphw/byte-buddy/pull/951
      2
      fix
      JavaConstant.MethodHandle.getDescriptor() returns wrong value for PUT_FIELD and PUT_FIELD_STATIC cases
      As always, thanks for this project. I am nervous filing this bug because there are so few bugs in ByteBuddy that I feel like this can't actually be one! But I think it is. For background, see https://stackoverflow.com/questions/64296731/how-do-i-install-and-use-a-constant-methodhandle-in-bytebuddy. In the case of `PUT_FIELD` and `PUT_FIELD_STATIC` `HandleType`s, I think that the wrong value is being returned from the default implementation of `getDescriptor()`. Specifically, this will return `V` in "field setter" cases, because of this code: https://github.com/raphw/byte-buddy/blob/291a512c609b647edccfdead540764ee402abd00/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L695-L696 For a "field setter" method handle, this will always return `V`, and that will cause a `ClassFormatError` that resembles the following: ``` java.lang.ClassFormatError: Field "fortyTwo" in class com/foo/bar/GeneratedSubclassOf$com$foo$bar$Baz$26753A95 has illegal signature "V" ``` This is because the return type of a "field setter" method handle as acquired via `JavaConstant.MethodHandle.ofSetter(FieldDescription.InDefinedShape)` will always be `void`, which is correct (see line 626 below): https://github.com/raphw/byte-buddy/blob/291a512c609b647edccfdead540764ee402abd00/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L623-L627 But [section 5.4.3.5 of the JVM specification](https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.5-240) indicates that if your method handle is of types 1 through 4 inclusive (which `PUT_FIELD` and `PUT_STATIC_FIELD` are), then resolution of the constant must follow the rules of field resolution. [Those rules](https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.2) indicate that the descriptor of the field reference needs to be used. ByteBuddy is instead using the method handle's return type descriptor, which, in the case of field setter method handles, anyway, is `V`. The workaround that seems to get around this problem is to create a subclass of `JavaConstant.MethodHandle` that overrides the `getDescriptor()` method to do the right thing: ```java @Override public final String getDescriptor() { // See https://stackoverflow.com/questions/64296731/how-do-i-install-and-use-a-constant-methodhandle-in-bytebuddy. switch (this.getHandleType()) { case PUT_FIELD: case PUT_STATIC_FIELD: // In the case of "field setter" method handles use the sole parameter type's descriptor // to follow the rules prescribed by // https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.5-240 return this.getParameterTypes().getOnly().getDescriptor(); default: return super.getDescriptor(); } } ``` With this override, I can avoid the `ClassFormatError`. (I don't know if it is best to solve the problem here or in `asConstantPoolValue()`.) I'll attempt to put together a PR shortly. Thanks again for a great project.
      291a512c609b647edccfdead540764ee402abd00
      3795ee8733b2f8d0904fe28121a550c5e2b95997
      https://github.com/raphw/byte-buddy/compare/291a512c609b647edccfdead540764ee402abd00...3795ee8733b2f8d0904fe28121a550c5e2b95997
      diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java index 51ad4443c8..5e0e4e2bb6 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java @@ -692,9 +692,11 @@ public interface JavaConstant { * @return The method descriptor of this method handle representation. */ public String getDescriptor() { - if (handleType.isField()) { - return returnType.getDescriptor(); - } else { + switch (handleType) { + case PUT_FIELD: + case PUT_STATIC_FIELD: + return parameterTypes.get(0).getDescriptor(); + default: StringBuilder stringBuilder = new StringBuilder().append('('); for (TypeDescription parameterType : parameterTypes) { stringBuilder.append(parameterType.getDescriptor()); diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java index b0b482f049..71b8ed1c47 100644 --- a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java +++ b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.when; public class JavaConstantMethodHandleTest { - private static final String BAR = "bar", QUX = "qux"; + private static final String BAR = "bar", FROB = "frob", QUX = "qux"; @Rule public MethodRule javaVersionRule = new JavaVersionRule(); @@ -106,12 +106,13 @@ public class JavaConstantMethodHandleTest { @Test @SuppressWarnings("unchecked") public void testMethodHandleOfSetter() throws Exception { - JavaConstant.MethodHandle methodHandle = JavaConstant.MethodHandle.ofSetter(Foo.class.getDeclaredField(BAR)); + JavaConstant.MethodHandle methodHandle = JavaConstant.MethodHandle.ofSetter(Foo.class.getDeclaredField(FROB)); assertThat(methodHandle.getHandleType(), is(JavaConstant.MethodHandle.HandleType.PUT_FIELD)); - assertThat(methodHandle.getName(), is(BAR)); + assertThat(methodHandle.getName(), is(FROB)); assertThat(methodHandle.getOwnerType(), is((TypeDescription) TypeDescription.ForLoadedType.of(Foo.class))); assertThat(methodHandle.getReturnType(), is(TypeDescription.VOID)); - assertThat(methodHandle.getParameterTypes(), is((List<TypeDescription>) new TypeList.ForLoadedTypes(Void.class))); + assertThat(methodHandle.getParameterTypes(), is((List<TypeDescription>) new TypeList.ForLoadedTypes(Integer.class))); + assertThat(methodHandle.getDescriptor(), is(methodHandle.getParameterTypes().getOnly().getDescriptor())); } @Test @@ -123,6 +124,7 @@ public class JavaConstantMethodHandleTest { assertThat(methodHandle.getOwnerType(), is((TypeDescription) TypeDescription.ForLoadedType.of(Foo.class))); assertThat(methodHandle.getReturnType(), is(TypeDescription.VOID)); assertThat(methodHandle.getParameterTypes(), is((List<TypeDescription>) new TypeList.ForLoadedTypes(Void.class))); + assertThat(methodHandle.getDescriptor(), is(methodHandle.getParameterTypes().getOnly().getDescriptor())); } @Test @@ -195,6 +197,8 @@ public class JavaConstantMethodHandleTest { public Void bar; + public Integer frob; + public Foo(Void value) { /* empty*/ }
      ['byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,028,418
      1,179,473
      163,217
      353
      299
      51
      8
      1
      3,029
      321
      786
      42
      7
      2
      1970-01-01T00:26:42
      5,668
      Java
      {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}
      Apache License 2.0
      384
      raphw/byte-buddy/955/954
      raphw
      byte-buddy
      https://github.com/raphw/byte-buddy/issues/954
      https://github.com/raphw/byte-buddy/pull/955
      https://github.com/raphw/byte-buddy/pull/955
      1
      fixes
      The type assignability check in JavaConstant.Dynamic.ofInvocation() is too strict
      Hi; it's me again; sorry! For background: https://stackoverflow.com/questions/64360249/is-type-assignability-too-strict-in-javaconstant-dynamic-ofinvocation In very concrete terms, I think that this assignability check: https://github.com/raphw/byte-buddy/blob/e4ce4af1bab578a7ac3497d07449e50628d050e7/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L1636-L1638 …is too strict given that it prevents a method from being invoked that uses varargs. Specifically, `iterator.next()` will, in such a case, return something like `Glorp[]`, and (let's say) `Glorp` is not assignable to `Glorp[]`. Suppose I have: ``` static final JavaConstant toJavaConstant(final Glorp[] glorps) { final JavaConstant[] javaConstants = new JavaConstant[glorps.length]; for (int i = 0; i < javaConstants.length; i++) { javaConstants[i] = toJavaConstant(glorps[i]); // another version of this method that works on scalars } return JavaConstant.Dynamic.ofInvocation(SOME_METHOD_THAT_ACCEPTS_A_VARARGS_OF_THINGS, javaConstants); } ``` …and `SOME_METHOD_THAT_ACCEPTS_A_VARARGS_OF_THINGS` is a `MethodDescription.InDefinedShape` that resolves to something like this: ``` public static final Glorp[] toGlorps(final Glorp... glorps) { return glorps; } ``` Currently, ByteBuddy will not allow this because of that type assignability check. If I comment out lines 1636 through 1638, i.e. if I disable the type assignability check, this construction works just fine (probably thanks to all the `MethodHandle` argument conversion machinery happening at constant resolution time). I'll file a PR shortly.
      e4ce4af1bab578a7ac3497d07449e50628d050e7
      9c7ce054a3607820241310f85a2fe44ed45e6473
      https://github.com/raphw/byte-buddy/compare/e4ce4af1bab578a7ac3497d07449e50628d050e7...9c7ce054a3607820241310f85a2fe44ed45e6473
      diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java index 51ad4443c8..b4b1b108ca 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java @@ -1602,7 +1602,7 @@ public interface JavaConstant { public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List<?> constants) { if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) { throw new IllegalArgumentException("Bootstrap method is no constructor or non-void static factory: " + methodDescription); - } else if (methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) { + } else if (!methodDescription.isVarArgs() && methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) { throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription); } List<Object> arguments = new ArrayList<Object>(constants.size()); @@ -1633,8 +1633,13 @@ public interface JavaConstant { throw new IllegalArgumentException("Not a compile-time constant: " + constant); } } - if (!typeDescription.isAssignableTo(iterator.next())) { - throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription); + if (iterator.hasNext()) { + TypeDescription next = iterator.next(); + if (!typeDescription.isAssignableTo(next)) { + if (!methodDescription.isVarArgs() || iterator.hasNext() || !next.isArray() || !typeDescription.isAssignableTo(next.getComponentType())) { + throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription); + } + } } } return new Dynamic(new ConstantDynamic("invoke", diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java index f95547b3e1..faaa07f74a 100644 --- a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java +++ b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java @@ -1,5 +1,7 @@ package net.bytebuddy.utility; +import java.lang.reflect.Method; + import net.bytebuddy.ByteBuddy; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; @@ -478,6 +480,24 @@ public class JavaConstantDynamicTest { assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo))); } + @Test + @JavaVersionRule.Enforce(11) + public void testInvocationOfVarargsMethod() throws Exception { + final Integer[] sourceIntegers = new Integer[] { Integer.valueOf(1), Integer.valueOf(2) }; + Class<? extends Foo> baz = new ByteBuddy() + .subclass(Foo.class) + .method(isDeclaredBy(Foo.class)) + .intercept(FixedValue.value(toJavaConstant(sourceIntegers))) + .make() + .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); + assertThat(baz.getDeclaredFields().length, is(0)); + assertThat(baz.getDeclaredMethods().length, is(1)); + Foo foo = baz.getDeclaredConstructor().newInstance(); + assertThat((Integer[])baz.getDeclaredMethod(FOO).invoke(foo), equalTo(sourceIntegers)); + assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo))); + } + @Test @JavaVersionRule.Enforce(11) public void testStaticFieldVarHandle() throws Exception { @@ -649,6 +669,7 @@ public class JavaConstantDynamicTest { public Object bar() { return null; } + } private static Object methodHandle() throws Exception { @@ -660,4 +681,24 @@ public class JavaConstantDynamicTest { private static Object methodType() throws Exception { return Class.forName("java.lang.invoke.MethodType").getMethod("methodType", Class.class).invoke(null, void.class); } + + private static JavaConstant toJavaConstant(Integer[] integers) throws Exception { + // This is convoluted and exists only to test issue #954. + JavaConstant[] constants = new JavaConstant[integers.length]; + for (int i = 0; i < integers.length; i++) { + constants[i] = toJavaConstant(integers[i]); + } + return JavaConstant.Dynamic.ofInvocation(JavaConstantDynamicTest.class.getDeclaredMethod("toIntegers", Integer[].class), constants); + } + + private static JavaConstant toJavaConstant(Integer i) throws Exception { + // This is convoluted and exists only to test issue #954. + return JavaConstant.Dynamic.ofInvocation(Integer.class.getMethod("valueOf", String.class), i.toString()); + } + + public static Integer[] toIntegers(final Integer... varargs) { + // This is convoluted and exists only to test issue #954. + return varargs; + } + }
      ['byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      7,028,418
      1,179,473
      163,217
      353
      1,062
      189
      11
      1
      1,640
      176
      421
      31
      2
      2
      1970-01-01T00:26:42
      5,668
      Java
      {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}
      Apache License 2.0
      383
      raphw/byte-buddy/958/957
      raphw
      byte-buddy
      https://github.com/raphw/byte-buddy/issues/957
      https://github.com/raphw/byte-buddy/pull/958
      https://github.com/raphw/byte-buddy/pull/958
      2
      fixes
      JavaConstant.Dynamic.ofInvocation() doesn't seem to permit interface default methods as bootstrap methods
      Using JDK 15, if I try to use `List#of(E[])` (a `static` interface method declared on `List` itself) as a bootstrap method, I get: ``` java.lang.IncompatibleClassChangeError: Inconsistent constant pool data in classfile for class java/util/List. Method 'java.util.List of(java.lang.Object[])' at index 19 is CONSTANT_MethodRef and should be CONSTANT_InterfaceMethodRef at java.base/java.lang.invoke.MethodHandleNatives.copyOutBootstrapArguments(Native Method) at java.base/java.lang.invoke.BootstrapMethodInvoker$VM_BSCI.copyConstants(BootstrapMethodInvoker.java:402) at java.base/java.lang.invoke.BootstrapMethodInvoker$VM_BSCI.fillCache(BootstrapMethodInvoker.java:377) at java.base/java.lang.invoke.AbstractConstantGroup$WithCache.get(AbstractConstantGroup.java:278) at java.base/java.lang.invoke.BootstrapMethodInvoker$PullAdapter.pullFromBootstrapMethod(BootstrapMethodInvoker.java:509) at java.base/java.lang.invoke.BootstrapMethodInvoker.invoke(BootstrapMethodInvoker.java:117) at java.base/java.lang.invoke.ConstantBootstraps.makeConstant(ConstantBootstraps.java:72) at java.base/java.lang.invoke.MethodHandleNatives.linkDynamicConstantImpl(MethodHandleNatives.java:327) at java.base/java.lang.invoke.MethodHandleNatives.linkDynamicConstant(MethodHandleNatives.java:319) ``` I've edited this bug description to remove what I thought was the problem. Now I just don't know what the problem is at all. 😄
      e4ce4af1bab578a7ac3497d07449e50628d050e7
      265b0c623ffe1c323d524f0ffdbdf104adba1071
      https://github.com/raphw/byte-buddy/compare/e4ce4af1bab578a7ac3497d07449e50628d050e7...265b0c623ffe1c323d524f0ffdbdf104adba1071
      diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java index 51ad4443c8..85769d7735 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java @@ -1610,7 +1610,7 @@ public interface JavaConstant { methodDescription.getDeclaringType().getInternalName(), methodDescription.getInternalName(), methodDescription.getDescriptor(), - false)); + methodDescription.getDeclaringType().isInterface())); Iterator<TypeDescription> iterator = (methodDescription.isStatic() || methodDescription.isConstructor() ? methodDescription.getParameters().asTypeList().asErasures() : CompoundList.of(methodDescription.getDeclaringType(), methodDescription.getParameters().asTypeList().asErasures())).iterator();
      ['byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      7,028,418
      1,179,473
      163,217
      353
      104
      14
      2
      1
      1,434
      91
      318
      14
      0
      1
      1970-01-01T00:26:42
      5,668
      Java
      {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742}
      Apache License 2.0
      8,968
      wiremock/wiremock/2277/2085
      wiremock
      wiremock
      https://github.com/wiremock/wiremock/issues/2085
      https://github.com/wiremock/wiremock/pull/2277
      https://github.com/wiremock/wiremock/pull/2277
      1
      closes
      Result (emptyJson) returned immediately without being stored in a variable, if any
      https://github.com/wiremock/wiremock/blob/25b82f9f97f3cc09136097b249cfd37aef924c36/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java#L60 Result (emptyJson) returned immediately without being stored in a variable, if any
      7b8a7d351255342d8d22cb5217b6847cc8ddaa29
      831fc3090d83148420aee214bb0bb892163d87f5
      https://github.com/wiremock/wiremock/compare/7b8a7d351255342d8d22cb5217b6847cc8ddaa29...831fc3090d83148420aee214bb0bb892163d87f5
      diff --git a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java index 6260fa064..e7f42f687 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java +++ b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Thomas Akehurst + * Copyright (C) 2021-2023 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,13 +57,13 @@ public class ParseJsonHelper extends HandlebarsHelper<Object> { // Edge case if JSON object is empty {} String jsonAsStringWithoutSpace = jsonAsString.replaceAll("\\\\s", ""); if (jsonAsStringWithoutSpace.equals("{}") || jsonAsStringWithoutSpace.equals("")) { - return result; - } - - if (jsonAsString.startsWith("[") && jsonAsString.endsWith("]")) { - result = Json.read(jsonAsString, new TypeReference<List<Object>>() {}); + result = new HashMap<String, Object>(); } else { - result = Json.read(jsonAsString, new TypeReference<Map<String, Object>>() {}); + if (jsonAsString.startsWith("[") && jsonAsString.endsWith("]")) { + result = Json.read(jsonAsString, new TypeReference<List<Object>>() {}); + } else { + result = Json.read(jsonAsString, new TypeReference<Map<String, Object>>() {}); + } } } diff --git a/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java b/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java index ad973c9da..2f3195651 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java +++ b/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java @@ -33,9 +33,7 @@ import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -/** - * @deprecated this is the legacy recorder and will be removed before 3.x is out of beta - */ +/** @deprecated this is the legacy recorder and will be removed before 3.x is out of beta */ @Deprecated public class StubMappingJsonRecorder implements RequestListener { diff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java index 2ac9bd44d..fadedf8c6 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java @@ -914,6 +914,26 @@ public class ResponseTemplateTransformerTest { assertThat(transform("{{parseJson}}"), is("[ERROR: Missing required JSON string parameter]")); } + @Test + public void parsesEmptyJsonLiteralToAnEmptyMap() { + String result = transform("{{#parseJson 'parsedObj'}}\\n" + "{\\n" + "}\\n" + "{{/parseJson}}\\n"); + + assertThat(result, equalToCompressingWhiteSpace("")); + } + + @Test + public void parsesEmptyJsonVariableToAnEmptyMap() { + String result = + transform( + "{{#assign 'json'}}\\n" + + "{\\n" + + "}\\n" + + "{{/assign}}\\n" + + "{{parseJson json 'parsedObj'}}\\n"); + + assertThat(result, equalToCompressingWhiteSpace("")); + } + @Test public void conditionalBranchingOnStringMatchesRegexInline() { assertThat(transform("{{#if (matches '123' '[0-9]+')}}YES{{/if}}"), is("YES")); diff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java index b5caba622..0bf38da67 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Thomas Akehurst + * Copyright (C) 2021-2023 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,16 @@ package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - +import static org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.nullValue; + +import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Options; import com.github.jknack.handlebars.TagType; import com.github.jknack.handlebars.Template; @@ -116,10 +124,54 @@ public class ParseJsonHelperTest extends HandlebarsHelperTestBase { @Test public void parsesEmptyJsonIfSection() throws Exception { + String inputJson = ""; + String variableName = "parsedObject"; + Template template = new Handlebars().compileInline(inputJson); + Options options = + new Options.Builder(null, null, TagType.SECTION, createContext(), template) + .setParams(new Object[] {}) + .build(); + Object output = render(variableName, options); + + // Check that it returns null + assertThat(output, is(nullValue())); + + /* Check that it stores parsed json (an empty map in this case because json is empty) + * in given variable name */ + Object storedData = options.data(variableName); + assertThat(storedData, isA(Map.class)); + Map<String, Object> castedData = (Map<String, Object>) storedData; + assertThat(castedData, is(aMapWithSize(0))); + } + + @Test + public void parsesEmptyJsonWithBracesIfSection() throws Exception { String inputJson = "{}"; - Object output = render(inputJson, new Object[] {}, TagType.SECTION); + String variableName = "parsedObject"; + Template template = new Handlebars().compileInline(inputJson); + Options options = + new Options.Builder(null, null, TagType.SECTION, createContext(), template) + .setParams(new Object[] {}) + .build(); + Object output = render(variableName, options); + + // Check that it returns null + assertThat(output, is(nullValue())); + + /* Check that it stores parsed json (an empty map in this case because json is empty) + * in given variable name */ + Object storedData = options.data(variableName); + assertThat(storedData, isA(Map.class)); + Map<String, Object> castedData = (Map<String, Object>) storedData; + assertThat(castedData, is(aMapWithSize(0))); + } - // Check that it returns empty object + @Test + public void parsesEmptyJsonIfSectionIfVariableNameNull() throws Exception { + String variableName = null; + Object output = render(variableName, new Object[] {}, TagType.SECTION); + + // Check that it returns empty object because variable name is null assertThat(output, instanceOf(Map.class)); Map<String, Object> result = (Map<String, Object>) output; assertThat(result, aMapWithSize(0)); @@ -127,20 +179,68 @@ public class ParseJsonHelperTest extends HandlebarsHelperTestBase { @Test public void parsesEmptyJsonIfNotSection() throws Exception { + String inputJson = ""; + String variableName = "parsedObject"; + Object[] params = {variableName}; + Options options = + new Options.Builder(null, null, TagType.VAR, createContext(), Template.EMPTY) + .setParams(params) + .build(); + Object output = render(inputJson, options); + + // Check that it returns empty object + assertThat(output, is(nullValue())); + + /* Check that it stores parsed json (an empty map in this case because json is empty) + * in given variable name */ + Object storedData = options.data(variableName); + assertThat(storedData, isA(Map.class)); + Map<String, Object> castedData = (Map<String, Object>) storedData; + assertThat(castedData, is(aMapWithSize(0))); + } + + @Test + public void parsesEmptyJsonWithBracesIfNotSection() throws Exception { String inputJson = "{}"; - Object output = render(inputJson, new Object[] {}, TagType.VAR); + String variableName = "parsedObject"; + Object[] params = {variableName}; + Options options = + new Options.Builder(null, null, TagType.VAR, createContext(), Template.EMPTY) + .setParams(params) + .build(); + Object output = render(inputJson, options); // Check that it returns empty object + assertThat(output, is(nullValue())); + + /* Check that it stores parsed json (an empty map in this case because json is empty) + * in given variable name */ + Object storedData = options.data(variableName); + assertThat(storedData, isA(Map.class)); + Map<String, Object> castedData = (Map<String, Object>) storedData; + assertThat(castedData, is(aMapWithSize(0))); + } + + @Test + public void parsesEmptyJsonIfNotSectionIfVariableNameAbsent() throws Exception { + String inputJson = "{}"; + Object output = render(inputJson, new Object[] {}, TagType.VAR); + + // Check that it returns empty object because variable name is null assertThat(output, instanceOf(Map.class)); Map<String, Object> result = (Map<String, Object>) output; assertThat(result, aMapWithSize(0)); } private Object render(Object context, Object[] params, TagType tagType) throws IOException { - return helper.apply( + return render( context, new Options.Builder(null, null, tagType, createContext(), Template.EMPTY) .setParams(params) .build()); } + + private Object render(Object context, Options options) throws IOException { + return helper.apply(context, options); + } }
      ['src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java', 'src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java', 'src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java', 'src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      1,437,077
      305,440
      43,967
      518
      878
      190
      18
      2
      276
      13
      80
      3
      1
      0
      1970-01-01T00:28:09
      5,664
      Java
      {'Java': 3153326, 'SCSS': 65082, 'XSLT': 14502, 'HTML': 11389, 'Scala': 6556, 'JavaScript': 1343, 'Shell': 1066, 'Ruby': 117}
      Apache License 2.0
      9,220
      shopify/react-native-skia/814/813
      shopify
      react-native-skia
      https://github.com/Shopify/react-native-skia/issues/813
      https://github.com/Shopify/react-native-skia/pull/814
      https://github.com/Shopify/react-native-skia/pull/814
      1
      fixes
      Android: Multitouch not working as expected
      ### Description Multitouch example (API/Touch) is not working on Android. ### Version 0.1.139 ### Steps to reproduce Run the API/Touch Handling on Android in the Example app and perform one or more touches on the screen with multiple fingers. Expected: Each finger should have a colored ring that follows your finger Observed: Only the first finger has a correct ring, all other moves and touches looks very wrong ### Snack, code example, screenshot, or link to a repository https://github.com/Shopify/react-native-skia
      1612227e4dcfc5662a40ef887b2d93409657e8a1
      f81d6327163661096155788f502322ce762e9008
      https://github.com/shopify/react-native-skia/compare/1612227e4dcfc5662a40ef887b2d93409657e8a1...f81d6327163661096155788f502322ce762e9008
      diff --git a/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java b/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java index 4df19305..540b77e1 100644 --- a/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java +++ b/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java @@ -2,7 +2,6 @@ package com.shopify.reactnative.skia; import android.content.Context; import android.graphics.SurfaceTexture; -import android.util.Log; import android.view.Surface; import android.view.TextureView; import android.view.MotionEvent; @@ -56,37 +55,74 @@ public class SkiaDrawView extends TextureView implements TextureView.SurfaceText @Override public boolean onTouchEvent(MotionEvent ev) { - int action = ev.getAction(); - int count = ev.getPointerCount(); + // https://developer.android.com/training/gestures/multi + int action = ev.getActionMasked(); + MotionEvent.PointerCoords r = new MotionEvent.PointerCoords(); - double[] points = new double[count*5]; - for (int i = 0; i < count; i++) { - ev.getPointerCoords(i, r); - points[i] = r.x; - points[i+1] = r.y; - points[i+2] = ev.getPressure(i); - switch (action) { - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_POINTER_DOWN: - points[i+3] = 0; - break; - case MotionEvent.ACTION_MOVE: - points[i+3] = 1; - break; - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: - points[i+3] = 2; - break; - case MotionEvent.ACTION_CANCEL: - points[i+3] = 3; - break; + + double[] points; + + // If this is a pointer_up/down event we need to handle it a bit specialized + switch (action) { + case MotionEvent.ACTION_POINTER_DOWN: + case MotionEvent.ACTION_POINTER_UP: { + points = new double[5]; + int pointerIndex = ev.getActionIndex(); + ev.getPointerCoords(pointerIndex, r); + points[0] = r.x; + points[1] = r.y; + points[2] = ev.getPressure(pointerIndex); + points[3] = motionActionToType(action); + points[4] = ev.getPointerId(pointerIndex); + + updateTouchPoints(points); + + break; + } + default: { + // For the rest we can just handle it like expected + int count = ev.getPointerCount(); + int pointerIndex = 0; + points = new double[5 * count]; + for (int i = 0; i < count; i++) { + ev.getPointerCoords(i, r); + points[pointerIndex++] = r.x; + points[pointerIndex++] = r.y; + points[pointerIndex++] = ev.getPressure(i); + points[pointerIndex++] = motionActionToType(action); + points[pointerIndex++] = ev.getPointerId(i); + } + + updateTouchPoints(points); + + break; } - points[i+4] = ev.getPointerId(i); } - updateTouchPoints(points); + return true; } + private static int motionActionToType(int action) { + int actionType = 3; + switch (action) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_POINTER_DOWN: + actionType = 0; + break; + case MotionEvent.ACTION_MOVE: + actionType = 1; + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_POINTER_UP: + actionType = 2; + break; + case MotionEvent.ACTION_CANCEL: + actionType = 3; + break; + } + return actionType; + } + @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { mSurface = new Surface(surface);
      ['package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      32,586
      6,587
      992
      12
      3,252
      615
      88
      1
      531
      79
      119
      18
      1
      0
      1970-01-01T00:27:40
      5,300
      TypeScript
      {'TypeScript': 1013030, 'C++': 584955, 'Java': 36511, 'Objective-C++': 26443, 'JavaScript': 16557, 'Objective-C': 9224, 'CMake': 6620, 'Ruby': 3879, 'Starlark': 602, 'HTML': 428, 'C': 104}
      MIT License
      10,190
      StarRocks/starrocks/23320/2527
      StarRocks
      starrocks
      https://github.com/StarRocks/starrocks/issues/2527
      https://github.com/StarRocks/starrocks/pull/23320
      https://github.com/StarRocks/starrocks/pull/23320
      1
      fixes
      Wrong result return while date type of column is `datetime`.
      <!-- (At least include the following, feel free to add if you have more content) --> insert and delete error. 1. Precision problem of `datetime` when insert into table values. 2. Delete error('ERROR 1064 (HY000): Invalid column value[null] for column k2') ### Steps to reproduce the behavior (Required) ``` mysql> CREATE TABLE test_string2 (`k1` string not null,k2 datetime) ENGINE=OLAP duplicate key(k1) DISTRIBUTED BY HASH(`k1`) BUCKETS 3 PROPERTIES ("replication_num" = "1"); Query OK, 0 rows affected (0.01 sec) mysql> insert into test_string2 values('2021-12-29 16:58:56.032000','2021-12-29 16:58:56.032000'); Query OK, 1 row affected (0.03 sec) {'label':'insert_5e9563d2-689f-11ec-8fab-00163e10c9d6', 'status':'VISIBLE', 'txnId':'33055'} mysql> select * from test_string2; +----------------------------+----------------------------+ | k1 | k2 | +----------------------------+----------------------------+ | 2021-12-29 16:58:56.032000 | 2021-12-29 16:58:56.032000 | +----------------------------+----------------------------+ 1 row in set (0.01 sec) mysql> delete from test_string2 where k2='2021-12-29 16:58:56.032000'; ERROR 1064 (HY000): Invalid column value[null] for column k2 mysql> delete from test_string2 where k1='2021-12-29 16:58:56.032000'; Query OK, 0 rows affected (0.02 sec) {'label':'delete_a088fb14-0748-44ce-b354-18e3b66fc20d', 'status':'VISIBLE', 'txnId':'33056'} mysql> select * from test_string2; Empty set (0.00 sec) ``` -mysql ``` mysql> CREATE TABLE test_string2 (`k1` datetime not null,k2 datetime); Query OK, 0 rows affected (0.02 sec) mysql> insert into test_string2 values('2021-12-29 16:58:56.032000','2021-12-29 16:58:56.032000'); Query OK, 1 row affected (0.00 sec) mysql> select * from test_string2; +---------------------+---------------------+ | k1 | k2 | +---------------------+---------------------+ | 2021-12-29 16:58:56 | 2021-12-29 16:58:56 | +---------------------+---------------------+ 1 row in set (0.00 sec) ``` ### Expected behavior (Required) ``` mysql> select * from test_string2; +---------------------+---------------------+ | k1 | k2 | +---------------------+---------------------+ | 2021-12-29 16:58:56 | 2021-12-29 16:58:56 | +---------------------+---------------------+ 1 row in set (0.00 sec) ``` ### Real behavior (Required) ``` mysql> select * from test_string2; +----------------------------+----------------------------+ | k1 | k2 | +----------------------------+----------------------------+ | 2021-12-29 16:58:56.032000 | 2021-12-29 16:58:56.032000 | +----------------------------+----------------------------+ 1 row in set (0.01 sec) ``` ### StarRocks version (Required) - You can get the StarRocks version by executing SQL `select current_version()` - 2.1
      3585258b549767bff6c4638d379c8e67a697e923
      1836a3a138a9ea19ff8795e0315bf04e1373a2d1
      https://github.com/StarRocks/starrocks/compare/3585258b549767bff6c4638d379c8e67a697e923...1836a3a138a9ea19ff8795e0315bf04e1373a2d1
      diff --git a/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java b/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java index 42f8a622dd..406ea029fc 100644 --- a/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java +++ b/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java @@ -64,6 +64,13 @@ public class MarkedCountDownLatch<K, V> extends CountDownLatch { return false; } + public synchronized boolean markedCountDown(K key, V value, Status status) { + if (st.ok()) { + st = status; + } + return markedCountDown(key, value); + } + public synchronized List<Entry<K, V>> getLeftMarks() { return Lists.newArrayList(marks.entries()); } diff --git a/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java b/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java index 146cf68054..16921c61da 100644 --- a/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java +++ b/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java @@ -224,12 +224,26 @@ public class LeaderImpl { String errMsg = "task type: " + taskType + ", status_code: " + taskStatus.getStatus_code().toString() + ", backendId: " + backendId + ", signature: " + signature; task.setErrorMsg(errMsg); + LOG.warn(errMsg); // We start to let FE perceive the task's error msg if (taskType != TTaskType.MAKE_SNAPSHOT && taskType != TTaskType.UPLOAD && taskType != TTaskType.DOWNLOAD && taskType != TTaskType.MOVE && taskType != TTaskType.CLONE && taskType != TTaskType.PUBLISH_VERSION && taskType != TTaskType.CREATE && taskType != TTaskType.UPDATE_TABLET_META_INFO && taskType != TTaskType.DROP_AUTO_INCREMENT_MAP) { + if (taskType == TTaskType.REALTIME_PUSH) { + PushTask pushTask = (PushTask) task; + if (pushTask.getPushType() == TPushType.DELETE) { + LOG.info("remove push replica. tabletId: {}, backendId: {}", task.getSignature(), + pushTask.getBackendId()); + + String failMsg = "Backend: " + task.getBackendId() + "Tablet: " + pushTask.getTabletId() + + " error msg: " + taskStatus.getError_msgs().toString(); + pushTask.countDownLatch(pushTask.getBackendId(), pushTask.getTabletId(), failMsg); + AgentTaskQueue.removeTask(pushTask.getBackendId(), TTaskType.REALTIME_PUSH, + task.getSignature()); + } + } return result; } } diff --git a/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java b/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java index 4c8b8f32df..11c9cc3836 100644 --- a/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java +++ b/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java @@ -54,6 +54,7 @@ import com.starrocks.common.DdlException; import com.starrocks.common.FeConstants; import com.starrocks.common.MarkedCountDownLatch; import com.starrocks.common.MetaNotFoundException; +import com.starrocks.common.Status; import com.starrocks.common.UserException; import com.starrocks.qe.QueryStateException; import com.starrocks.server.GlobalStateMgr; @@ -183,6 +184,7 @@ public class OlapDeleteJob extends DeleteJob { } finally { db.readUnlock(); } + LOG.info("countDownLatch count: {}", countDownLatch.getCount()); long timeoutMs = getTimeoutMs(); LOG.info("waiting delete Job finish, signature: {}, timeout: {}", getTransactionId(), timeoutMs); @@ -208,59 +210,65 @@ public class OlapDeleteJob extends DeleteJob { } catch (InterruptedException e) { LOG.warn("InterruptedException: ", e); } + LOG.info("delete job finish, countDownLatch count: {}", countDownLatch.getCount()); + + String errMsg = ""; + List<Map.Entry<Long, Long>> unfinishedMarks = countDownLatch.getLeftMarks(); + Status st = countDownLatch.getStatus(); + // only show at most 5 results + List<Map.Entry<Long, Long>> subList = unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5)); + if (!subList.isEmpty()) { + errMsg = "unfinished replicas: " + Joiner.on(", ").join(subList); + } else if (!st.ok()) { + errMsg = st.toString(); + } + LOG.warn(errMsg); - if (!ok) { - String errMsg = ""; - List<Map.Entry<Long, Long>> unfinishedMarks = countDownLatch.getLeftMarks(); - // only show at most 5 results - List<Map.Entry<Long, Long>> subList = unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5)); - if (!subList.isEmpty()) { - errMsg = "unfinished replicas: " + Joiner.on(", ").join(subList); - } - LOG.warn(errMsg); - - try { - checkAndUpdateQuorum(); - } catch (MetaNotFoundException e) { - cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage()); - throw new DdlException(e.getMessage(), e); - } - DeleteState state = getState(); - switch (state) { - case DELETING: - LOG.warn("delete job timeout: transactionId {}, timeout {}, {}", getTransactionId(), timeoutMs, - errMsg); + try { + checkAndUpdateQuorum(); + } catch (MetaNotFoundException e) { + cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage()); + throw new DdlException(e.getMessage(), e); + } + DeleteState state = getState(); + switch (state) { + case DELETING: + LOG.warn("delete job failed: transactionId {}, timeout {}, {}", getTransactionId(), timeoutMs, + errMsg); + if (countDownLatch.getCount() > 0) { cancel(DeleteHandler.CancelType.TIMEOUT, "delete job timeout"); - throw new DdlException("failed to execute delete. transaction id " + getTransactionId() + - ", timeout(ms) " + timeoutMs + ", " + errMsg); - case QUORUM_FINISHED: - case FINISHED: - try { - long nowQuorumTimeMs = System.currentTimeMillis(); - long endQuorumTimeoutMs = nowQuorumTimeMs + timeoutMs / 2; - // if job's state is quorum_finished then wait for a period of time and commit it. - while (getState() == DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs) { - checkAndUpdateQuorum(); - Thread.sleep(1000); - nowQuorumTimeMs = System.currentTimeMillis(); - LOG.debug("wait for quorum finished delete job: {}, txn_id: {}", getId(), - getTransactionId()); - } - } catch (MetaNotFoundException e) { - cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage()); - throw new DdlException(e.getMessage(), e); - } catch (InterruptedException e) { - cancel(DeleteHandler.CancelType.UNKNOWN, e.getMessage()); - throw new DdlException(e.getMessage(), e); + } else { + cancel(DeleteHandler.CancelType.UNKNOWN, "delete job failed"); + } + throw new DdlException("failed to execute delete. transaction id " + getTransactionId() + + ", timeout(ms) " + timeoutMs + ", " + errMsg); + case QUORUM_FINISHED: + case FINISHED: + try { + long nowQuorumTimeMs = System.currentTimeMillis(); + long endQuorumTimeoutMs = nowQuorumTimeMs + timeoutMs / 2; + // if job's state is quorum_finished then wait for a period of time and commit it. + while (getState() == DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs + && countDownLatch.getCount() > 0) { + checkAndUpdateQuorum(); + Thread.sleep(1000); + nowQuorumTimeMs = System.currentTimeMillis(); + LOG.debug("wait for quorum finished delete job: {}, txn_id: {}", getId(), + getTransactionId()); } - commit(db, timeoutMs); - break; - default: - throw new IllegalStateException("wrong delete job state: " + state.name()); - } - } else { - commit(db, timeoutMs); + } catch (MetaNotFoundException e) { + cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage()); + throw new DdlException(e.getMessage(), e); + } catch (InterruptedException e) { + cancel(DeleteHandler.CancelType.UNKNOWN, e.getMessage()); + throw new DdlException(e.getMessage(), e); + } + commit(db, timeoutMs); + break; + default: + throw new IllegalStateException("wrong delete job state: " + state.name()); } + } /** diff --git a/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java b/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java index bc5b8884a5..12a862afb6 100644 --- a/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java +++ b/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java @@ -43,6 +43,7 @@ import com.starrocks.analysis.LiteralExpr; import com.starrocks.analysis.Predicate; import com.starrocks.analysis.SlotRef; import com.starrocks.common.MarkedCountDownLatch; +import com.starrocks.common.Status; import com.starrocks.thrift.TBrokerScanRange; import com.starrocks.thrift.TCondition; import com.starrocks.thrift.TDescriptorTable; @@ -50,6 +51,7 @@ import com.starrocks.thrift.TPriority; import com.starrocks.thrift.TPushReq; import com.starrocks.thrift.TPushType; import com.starrocks.thrift.TResourceInfo; +import com.starrocks.thrift.TStatusCode; import com.starrocks.thrift.TTabletType; import com.starrocks.thrift.TTaskType; import org.apache.logging.log4j.LogManager; @@ -219,6 +221,15 @@ public class PushTask extends AgentTask { } } + public void countDownLatch(long backendId, long tabletId, String errMsg) { + if (this.latch != null) { + if (latch.markedCountDown(backendId, tabletId, new Status(TStatusCode.INTERNAL_ERROR, errMsg))) { + LOG.info("pushTask current latch count: {}. backend: {}, tablet:{}", + latch.getCount(), backendId, tabletId); + } + } + } + public long getReplicaId() { return replicaId; }
      ['fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java', 'fe/fe-core/src/main/java/com/starrocks/task/PushTask.java', 'fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java', 'fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      18,914,418
      3,826,410
      461,671
      2,365
      7,414
      1,353
      138
      4
      2,968
      304
      846
      71
      0
      4
      1970-01-01T00:28:03
      5,115
      Java
      {'Java': 29776837, 'C++': 27957184, 'C': 338709, 'Python': 280032, 'Thrift': 259942, 'CMake': 170285, 'Shell': 104253, 'ANTLR': 86095, 'HTML': 26561, 'Dockerfile': 24829, 'JavaScript': 10136, 'Makefile': 7808, 'CSS': 6187, 'Yacc': 4189, 'Lex': 1752, 'Mustache': 959}
      Apache License 2.0
      1,075
      reactor/reactor-core/206/204
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/204
      https://github.com/reactor/reactor-core/pull/206
      https://github.com/reactor/reactor-core/pull/206
      1
      fixes
      Self Suppression IllegalArgumentException when 'onErrorResume' propagates existing exception
      Sometime conditional logic is required to determine if an error signal should be handled or propagated. The easiest and most flexible way to do this is via the use of something like this: ``` flux.onErrorResume(e -> { if(something){ return just(someValue); else { throw propagate(e); }); ``` In this above example the else clause propagates the existing exception. This fails though due to FluxResume attempting to do `e.addSuppressed(e)` [here](https://github.com/reactor/reactor-core/blob/master/src/main/java/reactor/core/publisher/FluxResume.java#L92)
      de3a2bbbdadc767ba568373feec5d5a72a568e65
      6327441f30b599594a31db4d5e1a4604274e5219
      https://github.com/reactor/reactor-core/compare/de3a2bbbdadc767ba568373feec5d5a72a568e65...6327441f30b599594a31db4d5e1a4604274e5219
      diff --git a/src/main/java/reactor/core/publisher/FluxResume.java b/src/main/java/reactor/core/publisher/FluxResume.java index 17120d9d6..cdd99d31f 100644 --- a/src/main/java/reactor/core/publisher/FluxResume.java +++ b/src/main/java/reactor/core/publisher/FluxResume.java @@ -89,7 +89,9 @@ final class FluxResume<T> extends FluxSource<T, T> { p = nextFactory.apply(t); } catch (Throwable e) { Throwable _e = Operators.onOperatorError(e); - _e.addSuppressed(t); + if(t != _e) { + _e.addSuppressed(t); + } subscriber.onError(_e); return; } diff --git a/src/test/java/reactor/core/publisher/FluxResumeTest.java b/src/test/java/reactor/core/publisher/FluxResumeTest.java index 58977f228..016c00fe5 100644 --- a/src/test/java/reactor/core/publisher/FluxResumeTest.java +++ b/src/test/java/reactor/core/publisher/FluxResumeTest.java @@ -18,6 +18,7 @@ package reactor.core.publisher; import org.junit.Assert; import org.junit.Test; import reactor.test.subscriber.AssertSubscriber; +import reactor.core.Exceptions; public class FluxResumeTest { /* @@ -222,4 +223,18 @@ public class FluxResumeTest { .assertError(NullPointerException.class); } + @Test + public void errorPropagated() { + AssertSubscriber<Integer> ts = AssertSubscriber.create(0); + + Exception exception = new NullPointerException("forced failure"); + Flux.<Integer>error(exception).onErrorResumeWith(v -> { + throw Exceptions.propagate(v); + }).subscribe(ts); + + ts.assertNoValues() + .assertNotComplete() + .assertErrorWith(e -> Assert.assertSame(exception, e)); + } + }
      ['src/test/java/reactor/core/publisher/FluxResumeTest.java', 'src/main/java/reactor/core/publisher/FluxResume.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      1,977,113
      488,605
      75,285
      258
      83
      27
      4
      1
      581
      68
      131
      13
      1
      1
      1970-01-01T00:24:36
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,067
      reactor/reactor-core/3492/3359
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/3359
      https://github.com/reactor/reactor-core/pull/3492
      https://github.com/reactor/reactor-core/pull/3492
      1
      closes
      EmitterProcessor queue not cleared on immediate cancellation
      `EmitterProcessor#remove` has support to discard the buffer once the last subscriber is gone. However, it returns early if the subscribers array is already `EMPTY`. For cases where the subscription is immediately cancelled (e.g. `.take(0)`) this may leak the buffered elements. Here is a repro case: ``` @Test void shouldClearBufferOnCancellation() { BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); Many<Integer> sink = Sinks.many().unicast().onBackpressureBuffer(queue); sink.tryEmitNext(1); sink.tryEmitNext(2); sink.tryEmitNext(3); assertThat(queue).hasSize(3); sink.asFlux().take(0).blockLast(); assertThat(queue).isEmpty(); } ``` As a workaround `.takeWhile(x -> false)` does make the test pass for example.
      75d48b443b2e0038519e362063417a79d544e200
      258e2852c0ffffa710b0ae745315d151b0185cab
      https://github.com/reactor/reactor-core/compare/75d48b443b2e0038519e362063417a79d544e200...258e2852c0ffffa710b0ae745315d151b0185cab
      diff --git a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java index cedbf7d68..47ffd686e 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java +++ b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.function.Consumer; import java.util.stream.Stream; import org.reactivestreams.Publisher; @@ -33,6 +34,8 @@ import reactor.core.Exceptions; import reactor.core.Fuseable; import reactor.core.Scannable; import reactor.core.publisher.Sinks.EmitResult; +import reactor.util.Logger; +import reactor.util.Loggers; import reactor.util.annotation.Nullable; import reactor.util.concurrent.Queues; import reactor.util.context.Context; @@ -70,6 +73,8 @@ import static reactor.core.publisher.FluxPublish.PublishSubscriber.TERMINATED; public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements InternalManySink<T>, Sinks.ManyWithUpstream<T> { + static final Logger log = Loggers.getLogger(EmitterProcessor.class); + @SuppressWarnings("rawtypes") static final FluxPublish.PubSubInner[] EMPTY = new FluxPublish.PublishInner[0]; @@ -133,13 +138,32 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In */ @Deprecated public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel) { - return new EmitterProcessor<>(autoCancel, bufferSize); + return new EmitterProcessor<>(autoCancel, bufferSize, null); + } + + /** + * Create a new {@link EmitterProcessor} using the provided backlog size and auto-cancellation. + * + * @param <E> Type of processed signals + * @param bufferSize the internal buffer size to hold signals + * @param autoCancel automatically cancel + * + * @return a fresh processor + * @deprecated use {@link Sinks.MulticastSpec#onBackpressureBuffer(int, boolean) Sinks.many().multicast().onBackpressureBuffer(bufferSize, autoCancel)} + * (or the unsafe variant if you're sure about external synchronization). To be removed in 3.5. + */ + @Deprecated + public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel, Consumer<? super E> onDiscardHook) { + return new EmitterProcessor<>(autoCancel, bufferSize, onDiscardHook); } final int prefetch; final boolean autoCancel; + @Nullable + final Consumer<? super T> onDiscard; + volatile Subscription s; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater<EmitterProcessor, Subscription> S = @@ -182,12 +206,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In Throwable.class, "error"); - EmitterProcessor(boolean autoCancel, int prefetch) { + EmitterProcessor(boolean autoCancel, int prefetch, @Nullable Consumer<? super T> onDiscard) { if (prefetch < 1) { throw new IllegalArgumentException("bufferSize must be strictly positive, " + "was: " + prefetch); } this.autoCancel = autoCancel; this.prefetch = prefetch; + this.onDiscard = onDiscard; //doesn't use INIT/CANCELLED distinction, contrary to FluxPublish) //see remove() SUBSCRIBERS.lazySet(this, EMPTY); @@ -200,7 +225,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In @Override public Context currentContext() { - return Operators.multiSubscribersContext(subscribers); + if (onDiscard != null) { + return Operators.enableOnDiscard(Operators.multiSubscribersContext(subscribers), onDiscard); + } + else { + return Operators.multiSubscribersContext(subscribers); + } } @@ -213,9 +243,18 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In done = true; CancellationException detachException = new CancellationException("the ManyWithUpstream sink had a Subscription to an upstream which has been manually cancelled"); if (ERROR.compareAndSet(EmitterProcessor.this, null, detachException)) { + if (WIP.getAndIncrement(this) != 0) { + return true; + } Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + discardQueue(q, hook); + } + else { + q.clear(); + } } for (FluxPublish.PubSubInner<T> inner : terminate()) { inner.actual.onError(detachException); @@ -250,7 +289,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (inner.isCancelled()) { remove(inner); } - drain(); + drain(null); } else { Throwable e = error; @@ -275,7 +314,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return EmitResult.FAIL_TERMINATED; } done = true; - drain(); + drain(null); return EmitResult.OK; } @@ -292,7 +331,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In } if (Exceptions.addThrowable(ERROR, this, t)) { done = true; - drain(); + drain(null); return EmitResult.OK; } else { @@ -303,7 +342,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In @Override public void onNext(T t) { if (sourceMode == Fuseable.ASYNC) { - drain(); + drain(t); return; } emitNext(t, Sinks.EmitFailureHandler.FAIL_FAST); @@ -340,7 +379,8 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (!q.offer(t)) { return subscribers == EMPTY ? EmitResult.FAIL_ZERO_SUBSCRIBER : EmitResult.FAIL_OVERFLOW; } - drain(); + + drain(t); return EmitResult.OK; } @@ -387,7 +427,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (m == Fuseable.SYNC) { sourceMode = m; queue = f; - drain(); + drain(null); return; } else if (m == Fuseable.ASYNC) { @@ -443,8 +483,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return super.scanUnsafe(key); } - final void drain() { + final void drain(@Nullable T dataSignalOfferedBeforeDrain) { if (WIP.getAndIncrement(this) != 0) { + Consumer<? super T> discardHook = this.onDiscard; + if (dataSignalOfferedBeforeDrain != null) { + if (discardHook != null && isCancelled()) { + try { + discardHook.accept(dataSignalOfferedBeforeDrain); + } + catch (Throwable t) { + log.warn("Error in discard hook", t); + } + } + else if (done) { + Operators.onNextDropped(dataSignalOfferedBeforeDrain, + currentContext()); + } + } return; } @@ -458,11 +513,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In boolean empty = q == null || q.isEmpty(); - if (checkTerminated(d, empty)) { + if (checkTerminated(d, empty, null)) { return; } FluxPublish.PubSubInner<T>[] a = subscribers; + Consumer<? super T> onDiscardHook = onDiscard; if (a != EMPTY && !empty) { long maxRequested = Long.MAX_VALUE; @@ -492,9 +548,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In d = true; v = null; } - if (checkTerminated(d, v == null)) { + empty = v == null; + if (checkTerminated(d, empty, v)) { return; } + if (!empty && onDiscardHook != null) { + discard(v, onDiscardHook); + } if (sourceMode != Fuseable.SYNC) { s.request(1); } @@ -519,7 +579,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In empty = v == null; - if (checkTerminated(d, empty)) { + if (checkTerminated(d, empty, v)) { return; } @@ -528,7 +588,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (sourceMode == Fuseable.SYNC) { //the q is empty done = true; - checkTerminated(true, true); + checkTerminated(true, true, null); } break; } @@ -555,7 +615,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In } else if ( sourceMode == Fuseable.SYNC ) { done = true; - if (checkTerminated(true, empty)) { //empty can be true if no subscriber + if (checkTerminated(true, empty, null)) { //empty can be true if no subscriber break; } } @@ -572,13 +632,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return SUBSCRIBERS.getAndSet(this, TERMINATED); } - boolean checkTerminated(boolean d, boolean empty) { + boolean checkTerminated(boolean d, boolean empty, @Nullable T value) { if (s == Operators.cancelledSubscription()) { if (autoCancel) { terminate(); + Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + if (value != null) { + discard(value, hook); + } + discardQueue(q, hook); + } + else { + q.clear(); + } } } return true; @@ -588,7 +658,16 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (e != null && e != Exceptions.TERMINATED) { Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + if (value != null) { + discard(value, hook); + } + discardQueue(q, hook); + } + else { + q.clear(); + } } for (FluxPublish.PubSubInner<T> inner : terminate()) { inner.actual.onError(e); @@ -605,6 +684,31 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return false; } + static <T> void discardQueue(Queue<T> q, Consumer<? super T> hook) { + for (; ; ) { + T toDiscard = q.poll(); + if (toDiscard == null) { + break; + } + + try { + hook.accept(toDiscard); + } + catch (Throwable t) { + log.warn("Error while discarding a queue element, continuing with next queue element", t); + } + } + } + + static <T> void discard(T value, Consumer<? super T> hook) { + try { + hook.accept(value); + } + catch (Throwable t) { + log.warn("Error while discarding a queue element, continuing with next queue element", t); + } + } + final boolean add(EmitterInner<T> inner) { for (; ; ) { FluxPublish.PubSubInner<T>[] a = subscribers; @@ -624,7 +728,27 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In final void remove(FluxPublish.PubSubInner<T> inner) { for (; ; ) { FluxPublish.PubSubInner<T>[] a = subscribers; - if (a == TERMINATED || a == EMPTY) { + if (a == EMPTY) { + // means cancelled without adding + if (autoCancel && Operators.terminate(S, this)) { + if (WIP.getAndIncrement(this) != 0) { + return; + } + terminate(); + Queue<T> q = queue; + if (q != null) { + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + discardQueue(q, hook); + } + else { + q.clear(); + } + } + } + return; + } + else if (a == TERMINATED) { return; } int n = a.length; @@ -659,7 +783,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In terminate(); Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + discardQueue(q, hook); + } + else { + q.clear(); + } } } return; @@ -683,13 +813,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In @Override void drainParent() { - parent.drain(); + parent.drain(null); } @Override void removeAndDrainParent() { parent.remove(this); - parent.drain(); + parent.drain(null); } } diff --git a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java index e9183e4ba..16ceea978 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java +++ b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package reactor.core.publisher; import java.time.Duration; import java.util.Queue; +import java.util.function.Consumer; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; @@ -420,6 +421,31 @@ public final class Sinks { * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels */ <T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel); + + /** + * A {@link Sinks.ManyWithUpstream} with the following characteristics: + * <ul> + * <li>Multicast</li> + * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize} + * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li> + * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case + * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}: + * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li> + * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting} + * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul> + * </li> + * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber} + * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements + * that have been buffered due to backpressure/warm up.</li> + * </ul> + * <p> + * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt=""> + * + * @param bufferSize the maximum queue size + * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels + * @param onDiscardHook should be called when values from queue are cleared + */ + <T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook); } /** @@ -557,6 +583,31 @@ public final class Sinks { */ <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel); + /** + * A {@link Sinks.Many} with the following characteristics: + * <ul> + * <li>Multicast</li> + * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize} + * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li> + * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case + * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}: + * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li> + * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting} + * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul> + * </li> + * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber} + * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements + * that have been buffered due to backpressure/warm up.</li> + * </ul> + * <p> + * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt=""> + * + * @param bufferSize the maximum queue size + * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels + * @param onDiscardHook should be called when values from queue are cleared + */ + <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook); + /** A {@link Sinks.Many} with the following characteristics: * <ul> diff --git a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java index 33d6f45ce..cb4d48f70 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java +++ b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import java.time.Duration; import java.util.Queue; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.function.Consumer; import reactor.core.Disposable; import reactor.core.publisher.Sinks.Empty; @@ -109,17 +110,22 @@ final class SinksSpecs { @Override public <T> Sinks.Many<T> onBackpressureBuffer() { - return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE); + return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null); } @Override public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize) { - return new SinkManyEmitterProcessor<>(true, bufferSize); + return new SinkManyEmitterProcessor<>(true, bufferSize, null); } @Override public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel) { - return new SinkManyEmitterProcessor<>(autoCancel, bufferSize); + return new SinkManyEmitterProcessor<>(autoCancel, bufferSize, null); + } + + @Override + public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) { + return new EmitterProcessor<>(autoCancel, bufferSize, hook); } @Override @@ -179,12 +185,17 @@ final class SinksSpecs { @Override public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer() { - return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE); + return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null); } @Override public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel) { - return new SinkManyEmitterProcessor<>(autoCancel, bufferSize); + return new SinkManyEmitterProcessor<>(autoCancel, bufferSize, null); + } + + @Override + public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) { + return new EmitterProcessor<>(autoCancel, bufferSize, hook); } } @@ -252,6 +263,13 @@ final class SinksSpecs { return wrapMany(new SinkManyEmitterProcessor<>(autoCancel, bufferSize)); } + @Override + public <T> Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook) { + @SuppressWarnings("deprecation") // EmitterProcessor will be removed in 3.5. + final EmitterProcessor<T> original = EmitterProcessor.create(bufferSize, autoCancel, onDiscardHook); + return wrapMany(original); + } + @Override public <T> Many<T> directAllOrNothing() { final SinkManyBestEffort<T> original = SinkManyBestEffort.createAllOrNothing(); @@ -351,6 +369,7 @@ final class SinksSpecs { } @Override + public <T> Many<T> onBackpressureBuffer(Queue<T> queue) { final SinkManyUnicast<T> original = SinkManyUnicast.create(queue); return wrapMany(original); diff --git a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java index d32f9e7f1..fc8556136 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java +++ b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -530,9 +530,9 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T> this.actual = actual; if (cancelled) { this.hasDownstream = false; - } else { - drain(null); } + + drain(null); } else { Operators.error(actual, new IllegalStateException("UnicastProcessor " + "allows only a single Subscriber")); @@ -556,7 +556,7 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T> doTerminate(); - if (WIP.getAndIncrement(this) == 0) { + if (actual != null && WIP.getAndIncrement(this) == 0) { if (!outputFused) { // discard MUST be happening only and only if there is no racing on elements consumption // which is guaranteed by the WIP guard here in case non-fused output diff --git a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java index f1cc13d99..acffdc76b 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java @@ -172,6 +172,12 @@ public class OnDiscardShouldNotLeakTest { DiscardScenario.sinkSource("unicastSink", Sinks.unsafe().many().unicast()::onBackpressureBuffer, null), DiscardScenario.sinkSource("unicastSinkAndPublishOn", Sinks.unsafe().many().unicast()::onBackpressureBuffer, f -> f.publishOn(Schedulers.immediate())), + DiscardScenario.sinkSource("multicastBufferSink", + () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release), + null), + DiscardScenario.sinkSource("multicastBufferSinkAndPublishOn", + () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release), + f -> f.publishOn(Schedulers.immediate())), DiscardScenario.fluxSource("singleOrEmpty", f -> f.singleOrEmpty().onErrorReturn(Tracked.RELEASED)), DiscardScenario.fluxSource("collect", f -> f.collect(ArrayList::new, ArrayList::add) .doOnSuccess(l -> l.forEach(Tracked::safeRelease)) @@ -656,7 +662,11 @@ public class OnDiscardShouldNotLeakTest { Sinks.Many<Tracked> sink = sinksManySupplier.get(); //noinspection CallingSubscribeInNonBlockingScope main.flux().subscribe( - v -> sink.emitNext(v, FAIL_FAST), + v -> { + if (sink.tryEmitNext(v) != Sinks.EmitResult.OK) { + v.release(); + } + }, e -> sink.emitError(e, FAIL_FAST), () -> sink.emitComplete(FAIL_FAST)); Flux<Tracked> finalFlux = sink.asFlux(); diff --git a/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java b/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java index 449d47892..9b72087e5 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * 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 java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; +import org.assertj.core.api.Assertions; import org.awaitility.Awaitility; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -40,6 +41,7 @@ import reactor.core.Scannable; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import reactor.test.AutoDisposingExtension; +import reactor.test.MemoryUtils; import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; import reactor.test.subscriber.AssertSubscriber; @@ -62,6 +64,21 @@ class SinkManyEmitterProcessorTest { @RegisterExtension AutoDisposingExtension afterTest = new AutoDisposingExtension(); + //https://github.com/reactor/reactor-core/issues/3359 + @Test + void shouldClearBufferOnCancellation() { + MemoryUtils.OffHeapDetector tracker = new MemoryUtils.OffHeapDetector(); + EmitterProcessor<MemoryUtils.Tracked> source = EmitterProcessor.create(32, true, MemoryUtils.Tracked::release); + + Assertions.assertThat(source.tryEmitNext(tracker.track(1))).isEqualTo(Sinks.EmitResult.OK); + Assertions.assertThat(source.tryEmitNext(tracker.track(2))).isEqualTo(Sinks.EmitResult.OK); + Assertions.assertThat(source.tryEmitNext(tracker.track(3))).isEqualTo(Sinks.EmitResult.OK); + + source.take(0).blockLast(); + + tracker.assertNoLeaks(); + } + @Test void smokeTestManyWithUpstream() { @@ -862,7 +879,7 @@ class SinkManyEmitterProcessorTest { AssertSubscriber<Object> testSubscriber1 = new AssertSubscriber<>(Context.of("key", "value1")); AssertSubscriber<Object> testSubscriber2 = new AssertSubscriber<>(Context.of("key", "value2")); - SinkManyEmitterProcessor<Object> sinkManyEmitterProcessor = new SinkManyEmitterProcessor<>(false, 1); + SinkManyEmitterProcessor<Object> sinkManyEmitterProcessor = new SinkManyEmitterProcessor<>(false, 1, null); sinkManyEmitterProcessor.subscribe(testSubscriber1); sinkManyEmitterProcessor.subscribe(testSubscriber2); diff --git a/reactor-core/src/test/java/reactor/test/MemoryUtils.java b/reactor-core/src/test/java/reactor/test/MemoryUtils.java index 55223eeb3..e32ba8420 100644 --- a/reactor-core/src/test/java/reactor/test/MemoryUtils.java +++ b/reactor-core/src/test/java/reactor/test/MemoryUtils.java @@ -18,6 +18,7 @@ package reactor.test; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; +import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; @@ -170,6 +171,8 @@ public class MemoryUtils { */ public static final Tracked RELEASED = new Tracked("RELEASED", true); + final List<String> touches = new ArrayList<>(); + /** * Check if an arbitrary object is a {@link Tracked}, and if so release it. * @@ -210,6 +213,10 @@ public class MemoryUtils { set(true); } + public void touch(String msg) { + touches.add(msg); + } + /** * Check if this {@link Tracked} object has been released. * @@ -221,6 +228,10 @@ public class MemoryUtils { @Override public boolean equals(Object o) { + if (o instanceof String) { + touch(o.toString()); + return false; + } if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; @@ -237,10 +248,16 @@ public class MemoryUtils { //NOTE: AssertJ has a special representation of AtomicBooleans, so we override it in AssertionsUtils @Override public String toString() { - return "Tracked{" + - " id=" + identifier + - " released=" + get() + - " }"; + return get() + ? "Tracked{" + + " id=" + identifier + + " released=" + get() + + " }" + : "Tracked{" + + " id=" + identifier + + " released=" + get() + + " touches=" + touches + + " }"; } } }
      ['reactor-core/src/main/java/reactor/core/publisher/Sinks.java', 'reactor-core/src/test/java/reactor/test/MemoryUtils.java', 'reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java', 'reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java', 'reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java']
      {'.java': 7}
      7
      7
      0
      0
      7
      4,080,238
      1,014,099
      138,124
      496
      10,881
      2,762
      270
      4
      770
      80
      186
      23
      0
      1
      1970-01-01T00:28:06
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,068
      reactor/reactor-core/3486/3359
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/3359
      https://github.com/reactor/reactor-core/pull/3486
      https://github.com/reactor/reactor-core/pull/3486
      1
      closes
      EmitterProcessor queue not cleared on immediate cancellation
      `EmitterProcessor#remove` has support to discard the buffer once the last subscriber is gone. However, it returns early if the subscribers array is already `EMPTY`. For cases where the subscription is immediately cancelled (e.g. `.take(0)`) this may leak the buffered elements. Here is a repro case: ``` @Test void shouldClearBufferOnCancellation() { BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); Many<Integer> sink = Sinks.many().unicast().onBackpressureBuffer(queue); sink.tryEmitNext(1); sink.tryEmitNext(2); sink.tryEmitNext(3); assertThat(queue).hasSize(3); sink.asFlux().take(0).blockLast(); assertThat(queue).isEmpty(); } ``` As a workaround `.takeWhile(x -> false)` does make the test pass for example.
      8549191d09486a6baf94712f1ec6ca6bf1e76ccf
      236c84f7e96c7e5426cf1c25bbece4584d8ad088
      https://github.com/reactor/reactor-core/compare/8549191d09486a6baf94712f1ec6ca6bf1e76ccf...236c84f7e96c7e5426cf1c25bbece4584d8ad088
      diff --git a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java index fbd251e96..82319a6d3 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java +++ b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.function.Consumer; import java.util.stream.Stream; import org.reactivestreams.Publisher; @@ -33,6 +34,8 @@ import reactor.core.Exceptions; import reactor.core.Fuseable; import reactor.core.Scannable; import reactor.core.publisher.Sinks.EmitResult; +import reactor.util.Logger; +import reactor.util.Loggers; import reactor.util.annotation.Nullable; import reactor.util.concurrent.Queues; import reactor.util.context.Context; @@ -70,6 +73,8 @@ import static reactor.core.publisher.FluxPublish.PublishSubscriber.TERMINATED; public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements InternalManySink<T>, Sinks.ManyWithUpstream<T> { + static final Logger log = Loggers.getLogger(EmitterProcessor.class); + @SuppressWarnings("rawtypes") static final FluxPublish.PubSubInner[] EMPTY = new FluxPublish.PublishInner[0]; @@ -133,13 +138,32 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In */ @Deprecated public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel) { - return new EmitterProcessor<>(autoCancel, bufferSize); + return new EmitterProcessor<>(autoCancel, bufferSize, null); + } + + /** + * Create a new {@link EmitterProcessor} using the provided backlog size and auto-cancellation. + * + * @param <E> Type of processed signals + * @param bufferSize the internal buffer size to hold signals + * @param autoCancel automatically cancel + * + * @return a fresh processor + * @deprecated use {@link Sinks.MulticastSpec#onBackpressureBuffer(int, boolean) Sinks.many().multicast().onBackpressureBuffer(bufferSize, autoCancel)} + * (or the unsafe variant if you're sure about external synchronization). To be removed in 3.5. + */ + @Deprecated + public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel, Consumer<? super E> onDiscardHook) { + return new EmitterProcessor<>(autoCancel, bufferSize, onDiscardHook); } final int prefetch; final boolean autoCancel; + @Nullable + final Consumer<? super T> onDiscard; + volatile Subscription s; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater<EmitterProcessor, Subscription> S = @@ -182,12 +206,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In Throwable.class, "error"); - EmitterProcessor(boolean autoCancel, int prefetch) { + EmitterProcessor(boolean autoCancel, int prefetch, @Nullable Consumer<? super T> onDiscard) { if (prefetch < 1) { throw new IllegalArgumentException("bufferSize must be strictly positive, " + "was: " + prefetch); } this.autoCancel = autoCancel; this.prefetch = prefetch; + this.onDiscard = onDiscard; //doesn't use INIT/CANCELLED distinction, contrary to FluxPublish) //see remove() SUBSCRIBERS.lazySet(this, EMPTY); @@ -200,7 +225,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In @Override public Context currentContext() { - return Operators.multiSubscribersContext(subscribers); + if (onDiscard != null) { + return Operators.enableOnDiscard(Operators.multiSubscribersContext(subscribers), onDiscard); + } + else { + return Operators.multiSubscribersContext(subscribers); + } } @@ -213,9 +243,18 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In done = true; CancellationException detachException = new CancellationException("the ManyWithUpstream sink had a Subscription to an upstream which has been manually cancelled"); if (ERROR.compareAndSet(EmitterProcessor.this, null, detachException)) { + if (WIP.getAndIncrement(this) != 0) { + return true; + } Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + discardQueue(q, hook); + } + else { + q.clear(); + } } for (FluxPublish.PubSubInner<T> inner : terminate()) { inner.actual.onError(detachException); @@ -250,7 +289,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (inner.isCancelled()) { remove(inner); } - drain(); + drain(null); } else { Throwable e = error; @@ -275,7 +314,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return EmitResult.FAIL_TERMINATED; } done = true; - drain(); + drain(null); return EmitResult.OK; } @@ -292,7 +331,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In } if (Exceptions.addThrowable(ERROR, this, t)) { done = true; - drain(); + drain(null); return EmitResult.OK; } else { @@ -303,7 +342,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In @Override public void onNext(T t) { if (sourceMode == Fuseable.ASYNC) { - drain(); + drain(t); return; } emitNext(t, Sinks.EmitFailureHandler.FAIL_FAST); @@ -340,7 +379,8 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (!q.offer(t)) { return subscribers == EMPTY ? EmitResult.FAIL_ZERO_SUBSCRIBER : EmitResult.FAIL_OVERFLOW; } - drain(); + + drain(t); return EmitResult.OK; } @@ -387,7 +427,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (m == Fuseable.SYNC) { sourceMode = m; queue = f; - drain(); + drain(null); return; } else if (m == Fuseable.ASYNC) { @@ -443,8 +483,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return super.scanUnsafe(key); } - final void drain() { + final void drain(@Nullable T dataSignalOfferedBeforeDrain) { if (WIP.getAndIncrement(this) != 0) { + Consumer<? super T> discardHook = this.onDiscard; + if (dataSignalOfferedBeforeDrain != null) { + if (discardHook != null && isCancelled()) { + try { + discardHook.accept(dataSignalOfferedBeforeDrain); + } + catch (Throwable t) { + log.warn("Error in discard hook", t); + } + } + else if (done) { + Operators.onNextDropped(dataSignalOfferedBeforeDrain, + currentContext()); + } + } return; } @@ -458,11 +513,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In boolean empty = q == null || q.isEmpty(); - if (checkTerminated(d, empty)) { + if (checkTerminated(d, empty, null)) { return; } FluxPublish.PubSubInner<T>[] a = subscribers; + Consumer<? super T> onDiscardHook = onDiscard; if (a != EMPTY && !empty) { long maxRequested = Long.MAX_VALUE; @@ -492,9 +548,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In d = true; v = null; } - if (checkTerminated(d, v == null)) { + empty = v == null; + if (checkTerminated(d, empty, v)) { return; } + if (!empty && onDiscardHook != null) { + discard(v, onDiscardHook); + } if (sourceMode != Fuseable.SYNC) { s.request(1); } @@ -519,7 +579,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In empty = v == null; - if (checkTerminated(d, empty)) { + if (checkTerminated(d, empty, v)) { return; } @@ -528,7 +588,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (sourceMode == Fuseable.SYNC) { //the q is empty done = true; - checkTerminated(true, true); + checkTerminated(true, true, null); } break; } @@ -555,7 +615,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In } else if ( sourceMode == Fuseable.SYNC ) { done = true; - if (checkTerminated(true, empty)) { //empty can be true if no subscriber + if (checkTerminated(true, empty, null)) { //empty can be true if no subscriber break; } } @@ -572,13 +632,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return SUBSCRIBERS.getAndSet(this, TERMINATED); } - boolean checkTerminated(boolean d, boolean empty) { + boolean checkTerminated(boolean d, boolean empty, @Nullable T value) { if (s == Operators.cancelledSubscription()) { if (autoCancel) { terminate(); + Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + if (value != null) { + discard(value, hook); + } + discardQueue(q, hook); + } + else { + q.clear(); + } } } return true; @@ -588,7 +658,16 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In if (e != null && e != Exceptions.TERMINATED) { Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + if (value != null) { + discard(value, hook); + } + discardQueue(q, hook); + } + else { + q.clear(); + } } for (FluxPublish.PubSubInner<T> inner : terminate()) { inner.actual.onError(e); @@ -605,6 +684,31 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In return false; } + static <T> void discardQueue(Queue<T> q, Consumer<? super T> hook) { + for (; ; ) { + T toDiscard = q.poll(); + if (toDiscard == null) { + break; + } + + try { + hook.accept(toDiscard); + } + catch (Throwable t) { + log.warn("Error while discarding a queue element, continuing with next queue element", t); + } + } + } + + static <T> void discard(T value, Consumer<? super T> hook) { + try { + hook.accept(value); + } + catch (Throwable t) { + log.warn("Error while discarding a queue element, continuing with next queue element", t); + } + } + final boolean add(EmitterInner<T> inner) { for (; ; ) { FluxPublish.PubSubInner<T>[] a = subscribers; @@ -624,7 +728,27 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In final void remove(FluxPublish.PubSubInner<T> inner) { for (; ; ) { FluxPublish.PubSubInner<T>[] a = subscribers; - if (a == TERMINATED || a == EMPTY) { + if (a == EMPTY) { + // means cancelled without adding + if (autoCancel && Operators.terminate(S, this)) { + if (WIP.getAndIncrement(this) != 0) { + return; + } + terminate(); + Queue<T> q = queue; + if (q != null) { + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + discardQueue(q, hook); + } + else { + q.clear(); + } + } + } + return; + } + else if (a == TERMINATED) { return; } int n = a.length; @@ -659,7 +783,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In terminate(); Queue<T> q = queue; if (q != null) { - q.clear(); + Consumer<? super T> hook = this.onDiscard; + if (hook != null) { + discardQueue(q, hook); + } + else { + q.clear(); + } } } return; @@ -683,13 +813,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In @Override void drainParent() { - parent.drain(); + parent.drain(null); } @Override void removeAndDrainParent() { parent.remove(this); - parent.drain(); + parent.drain(null); } } diff --git a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java index e9183e4ba..16ceea978 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java +++ b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package reactor.core.publisher; import java.time.Duration; import java.util.Queue; +import java.util.function.Consumer; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; @@ -420,6 +421,31 @@ public final class Sinks { * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels */ <T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel); + + /** + * A {@link Sinks.ManyWithUpstream} with the following characteristics: + * <ul> + * <li>Multicast</li> + * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize} + * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li> + * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case + * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}: + * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li> + * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting} + * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul> + * </li> + * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber} + * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements + * that have been buffered due to backpressure/warm up.</li> + * </ul> + * <p> + * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt=""> + * + * @param bufferSize the maximum queue size + * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels + * @param onDiscardHook should be called when values from queue are cleared + */ + <T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook); } /** @@ -557,6 +583,31 @@ public final class Sinks { */ <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel); + /** + * A {@link Sinks.Many} with the following characteristics: + * <ul> + * <li>Multicast</li> + * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize} + * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li> + * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case + * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}: + * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li> + * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting} + * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul> + * </li> + * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber} + * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements + * that have been buffered due to backpressure/warm up.</li> + * </ul> + * <p> + * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt=""> + * + * @param bufferSize the maximum queue size + * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels + * @param onDiscardHook should be called when values from queue are cleared + */ + <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook); + /** A {@link Sinks.Many} with the following characteristics: * <ul> diff --git a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java index e72e7fec0..f5242dcb2 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java +++ b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import java.time.Duration; import java.util.Queue; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.function.Consumer; import reactor.core.Disposable; import reactor.core.publisher.Sinks.Empty; @@ -109,17 +110,22 @@ final class SinksSpecs { @Override public <T> Sinks.Many<T> onBackpressureBuffer() { - return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE); + return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null); } @Override public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize) { - return new EmitterProcessor<>(true, bufferSize); + return new EmitterProcessor<>(true, bufferSize, null); } @Override public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel) { - return new EmitterProcessor<>(autoCancel, bufferSize); + return new EmitterProcessor<>(autoCancel, bufferSize, null); + } + + @Override + public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) { + return new EmitterProcessor<>(autoCancel, bufferSize, hook); } @Override @@ -179,12 +185,17 @@ final class SinksSpecs { @Override public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer() { - return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE); + return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null); } @Override public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel) { - return new EmitterProcessor<>(autoCancel, bufferSize); + return new EmitterProcessor<>(autoCancel, bufferSize, null); + } + + @Override + public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) { + return new EmitterProcessor<>(autoCancel, bufferSize, hook); } } @@ -258,6 +269,13 @@ final class SinksSpecs { return wrapMany(original); } + @Override + public <T> Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook) { + @SuppressWarnings("deprecation") // EmitterProcessor will be removed in 3.5. + final EmitterProcessor<T> original = EmitterProcessor.create(bufferSize, autoCancel, onDiscardHook); + return wrapMany(original); + } + @Override public <T> Many<T> directAllOrNothing() { final SinkManyBestEffort<T> original = SinkManyBestEffort.createAllOrNothing(); @@ -367,6 +385,7 @@ final class SinksSpecs { } @Override + public <T> Many<T> onBackpressureBuffer(Queue<T> queue) { @SuppressWarnings("deprecation") // UnicastProcessor will be removed in 3.5. final UnicastProcessor<T> original = UnicastProcessor.create(queue); diff --git a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java index d21f4280b..5f11a4140 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java +++ b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -530,9 +530,9 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T> this.actual = actual; if (cancelled) { this.hasDownstream = false; - } else { - drain(null); } + + drain(null); } else { Operators.error(actual, new IllegalStateException("UnicastProcessor " + "allows only a single Subscriber")); @@ -556,7 +556,7 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T> doTerminate(); - if (WIP.getAndIncrement(this) == 0) { + if (actual != null && WIP.getAndIncrement(this) == 0) { if (!outputFused) { // discard MUST be happening only and only if there is no racing on elements consumption // which is guaranteed by the WIP guard here in case non-fused output diff --git a/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java b/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java index bd04e9936..3f7c69a8b 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; +import org.assertj.core.api.Assertions; import org.awaitility.Awaitility; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -42,6 +43,7 @@ import reactor.core.Scannable; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import reactor.test.AutoDisposingExtension; +import reactor.test.MemoryUtils; import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; import reactor.test.subscriber.AssertSubscriber; @@ -65,6 +67,21 @@ public class EmitterProcessorTest { @RegisterExtension AutoDisposingExtension afterTest = new AutoDisposingExtension(); + //https://github.com/reactor/reactor-core/issues/3359 + @Test + void shouldClearBufferOnCancellation() { + MemoryUtils.OffHeapDetector tracker = new MemoryUtils.OffHeapDetector(); + EmitterProcessor<MemoryUtils.Tracked> source = EmitterProcessor.create(32, true, MemoryUtils.Tracked::release); + + Assertions.assertThat(source.tryEmitNext(tracker.track(1))).isEqualTo(Sinks.EmitResult.OK); + Assertions.assertThat(source.tryEmitNext(tracker.track(2))).isEqualTo(Sinks.EmitResult.OK); + Assertions.assertThat(source.tryEmitNext(tracker.track(3))).isEqualTo(Sinks.EmitResult.OK); + + source.take(0).blockLast(); + + tracker.assertNoLeaks(); + } + @Test void smokeTestManyWithUpstream() { @@ -1012,7 +1029,7 @@ public class EmitterProcessorTest { AssertSubscriber<Object> testSubscriber1 = new AssertSubscriber<>(Context.of("key", "value1")); AssertSubscriber<Object> testSubscriber2 = new AssertSubscriber<>(Context.of("key", "value2")); - EmitterProcessor<Object> emitterProcessor = new EmitterProcessor<>(false, 1); + EmitterProcessor<Object> emitterProcessor = new EmitterProcessor<>(false, 1, null); emitterProcessor.subscribe(testSubscriber1); emitterProcessor.subscribe(testSubscriber2); diff --git a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java index f0cbb8abb..0d6b4f822 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -152,6 +152,12 @@ public class OnDiscardShouldNotLeakTest { DiscardScenario.sinkSource("unicastSink", Sinks.unsafe().many().unicast()::onBackpressureBuffer, null), DiscardScenario.sinkSource("unicastSinkAndPublishOn", Sinks.unsafe().many().unicast()::onBackpressureBuffer, f -> f.publishOn(Schedulers.immediate())), + DiscardScenario.sinkSource("multicastBufferSink", + () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release), + null), + DiscardScenario.sinkSource("multicastBufferSinkAndPublishOn", + () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release), + f -> f.publishOn(Schedulers.immediate())), DiscardScenario.fluxSource("singleOrEmpty", f -> f.singleOrEmpty().onErrorReturn(Tracked.RELEASED)), DiscardScenario.fluxSource("collect", f -> f.collect(ArrayList::new, ArrayList::add) .doOnSuccess(l -> l.forEach(Tracked::safeRelease)) @@ -617,7 +623,11 @@ public class OnDiscardShouldNotLeakTest { Sinks.Many<Tracked> sink = sinksManySupplier.get(); //noinspection CallingSubscribeInNonBlockingScope main.flux().subscribe( - v -> sink.emitNext(v, FAIL_FAST), + v -> { + if (sink.tryEmitNext(v) != Sinks.EmitResult.OK) { + v.release(); + } + }, e -> sink.emitError(e, FAIL_FAST), () -> sink.emitComplete(FAIL_FAST)); Flux<Tracked> finalFlux = sink.asFlux(); diff --git a/reactor-core/src/test/java/reactor/test/MemoryUtils.java b/reactor-core/src/test/java/reactor/test/MemoryUtils.java index 54084c403..289cd9e23 100644 --- a/reactor-core/src/test/java/reactor/test/MemoryUtils.java +++ b/reactor-core/src/test/java/reactor/test/MemoryUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2018-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
      ['reactor-core/src/main/java/reactor/core/publisher/Sinks.java', 'reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java', 'reactor-core/src/test/java/reactor/test/MemoryUtils.java', 'reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java', 'reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java']
      {'.java': 7}
      7
      7
      0
      0
      7
      3,793,901
      946,852
      129,078
      463
      10,801
      2,752
      270
      4
      770
      80
      186
      23
      0
      1
      1970-01-01T00:28:05
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,071
      reactor/reactor-core/3156/3137
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/3137
      https://github.com/reactor/reactor-core/pull/3156
      https://github.com/reactor/reactor-core/pull/3156
      2
      closes
      ClassCastException when using Hooks
      <!--- Provide a general summary of the issue in the Title above --> We have a registered Hook for metrics purposes, which transforms Monos and Fluxes. When using in in conjunction with `collectList` and `flatMap`, we get a `ClassCastException` (see example below): ``` java.lang.ClassCastException: class reactor.core.publisher.FluxDoFinally$DoFinallySubscriber cannot be cast to class reactor.core.Fuseable$QueueSubscription (reactor.core.publisher.FluxDoFinally$DoFinallySubscriber and reactor.core.Fuseable$QueueSubscription are in unnamed module of loader 'app') at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:177) at reactor.core.publisher.FluxDoFinally$DoFinallySubscriber.onSubscribe(FluxDoFinally.java:107) at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:178) at reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onSubscribe(MonoCollectList.java:78) at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53) at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59) at reactor.core.publisher.Mono.subscribe(Mono.java:4397) at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:200) at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53) at reactor.core.publisher.Mono.subscribe(Mono.java:4382) at reactor.core.publisher.Mono.block(Mono.java:1706) at com.aviloo.testing.actor.HookProblemTest.reproduceClassCastExceptionWithHooks(HookProblemTest.java:27) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54) Suppressed: java.lang.Exception: #block terminated with an error at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99) at reactor.core.publisher.Mono.block(Mono.java:1707) ... 71 more ``` It seems that the hook transforms the subscription such that it does not implement `QueueSubscription` anymore. ## Expected Behavior No exception. ## Actual Behavior See description. ## Steps to Reproduce This is the most minimal example I could come up with. ```java @Test public void reproduceClassCastExceptionWithHooks() throws Exception { Hooks.onLastOperator(objectPublisher -> { if (objectPublisher instanceof Mono) { return Hooks.convertToMonoBypassingHooks(objectPublisher, false) .doOnSubscribe(subscription -> { }) .doFinally(signalType -> { }); } else { return objectPublisher; } }); Mono.just(1) .flatMap(fsm -> Flux.just(1, 2, 3).collectList()) // .flatMap(Mono::just) // this will solve the ClassCastException --> workaround .block(); } ``` ## Possible Solution Workaround: Add a "kind of no-op" transformation. See comment in unit test. Still, this is very uggly, since you would have to add this to every such occurence... Is there anything else we could do? Or did we miss something? How do you think about it? ## Your Environment Ubuntu 22.04 Java temurin-17.0.4 reactor 3.4.21
      4768c43f0e6cd3ff2806e6cfc8e659f88b39b513
      ff5769678f6d7c498aa5bb547e7116f131bdf965
      https://github.com/reactor/reactor-core/compare/4768c43f0e6cd3ff2806e6cfc8e659f88b39b513...ff5769678f6d7c498aa5bb547e7116f131bdf965
      diff --git a/reactor-core/src/main/java/reactor/core/publisher/Flux.java b/reactor-core/src/main/java/reactor/core/publisher/Flux.java index 6ac402e20..222ad4336 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/Flux.java +++ b/reactor-core/src/main/java/reactor/core/publisher/Flux.java @@ -8445,6 +8445,10 @@ public abstract class Flux<T> implements CorePublisher<T> { CorePublisher publisher = Operators.onLastAssembly(this); CoreSubscriber subscriber = Operators.toCoreSubscriber(actual); + if (subscriber instanceof Fuseable.QueueSubscription && this != publisher && this instanceof Fuseable && !(publisher instanceof Fuseable)) { + subscriber = new FluxHide.SuppressFuseableSubscriber<>(subscriber); + } + try { if (publisher instanceof OptimizableOperator) { OptimizableOperator operator = (OptimizableOperator) publisher; diff --git a/reactor-core/src/main/java/reactor/core/publisher/Mono.java b/reactor-core/src/main/java/reactor/core/publisher/Mono.java index c665a457a..f79e56640 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/Mono.java +++ b/reactor-core/src/main/java/reactor/core/publisher/Mono.java @@ -4375,6 +4375,10 @@ public abstract class Mono<T> implements CorePublisher<T> { CorePublisher publisher = Operators.onLastAssembly(this); CoreSubscriber subscriber = Operators.toCoreSubscriber(actual); + if (subscriber instanceof Fuseable.QueueSubscription && this != publisher && this instanceof Fuseable && !(publisher instanceof Fuseable)) { + subscriber = new FluxHide.SuppressFuseableSubscriber<>(subscriber); + } + try { if (publisher instanceof OptimizableOperator) { OptimizableOperator operator = (OptimizableOperator) publisher; diff --git a/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java b/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java index 63a1a612b..b1920212f 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,6 @@ public class HooksTest { } } - @Test public void staticActivationOfOperatorDebug() { String oldProp = System.setProperty("reactor.trace.operatorStacktrace", "true"); @@ -142,6 +141,7 @@ public class HooksTest { Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> p; Hooks.onEachOperator(hook); + assertThat(Hooks.onEachOperatorHook).isSameAs(hook); } @@ -1254,4 +1254,30 @@ public class HooksTest { } }; } + + // https://github.com/reactor/reactor-core/issues/3137 + @Test + public void reproduceClassCastExceptionWithHooks() { + Hooks.onLastOperator(objectPublisher -> { + if (objectPublisher instanceof Mono) { + return Hooks.convertToMonoBypassingHooks(objectPublisher, false) + .doFinally(signalType -> { + }); + } else { + return objectPublisher; + } + }); + + try { + Mono.just(1) + .flatMap(fsm -> Mono.just(1) + .doOnSubscribe(subscription -> { + })) + .doOnSubscribe(subscription -> { + }) + .block(); + } finally { + Hooks.resetOnLastOperator(); + } + } }
      ['reactor-core/src/test/java/reactor/core/publisher/HooksTest.java', 'reactor-core/src/main/java/reactor/core/publisher/Mono.java', 'reactor-core/src/main/java/reactor/core/publisher/Flux.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      3,738,196
      932,081
      127,518
      458
      444
      86
      8
      2
      10,536
      394
      2,208
      144
      0
      2
      1970-01-01T00:27:40
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,069
      reactor/reactor-core/3351/3336
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/3336
      https://github.com/reactor/reactor-core/pull/3351
      https://github.com/reactor/reactor-core/pull/3351
      1
      closes
      FlatMapDelayError hangs on callable source error
      <!--- Provide a general summary of the issue in the Title above --> FlatMapDelayError does not propagate an onError signal when a callable source produces an error. It also does not cancel the upstream subscription. This results in a hanging flux that can never complete because it does not process any more values from the upstream publisher nor does it signal a termination to downstream subscribers. Notably this only occurs when the error is from a callable source. When the mapping function throws the error directly then the behavior is as expected where the backlog is consumed and the flux terminates with an error. However when the operator is modified with onErrorConsume the error is properly swallowed and processing continues. This does not affect concatMapDelayError as far as I have been able to test <!--- /!\\ Make sure to follow the Contribution Guidelines, notably for security issues and questions: https://github.com/reactor/.github/blob/main/CONTRIBUTING.md https://pivotal.io/security https://github.com/reactor/.github/blob/main/CONTRIBUTING.md#question-do-you-have-a-question --> ## Expected Behavior <!--- Tell us what you think should happen. --> FlatMapDelayError should cancel the upstream subscription, process the backlog, then emit an onError response ## Actual Behavior <!--- Tell us what happens instead of the expected behavior. --> FlatMapDelayError never completes when callable source throws an error ## Possible Solution <!--- Not obligatory, but you can suggest a fix/reason for the bug. --> This behavior seems to have been introduced here https://github.com/reactor/reactor-core/commit/af0cb628ece3c0a543512ea9913c4ff72ba18566#diff-3ad99cc26a2bc1707dda2203da9a667ccf3abdd52aac45ee6b2c4cea438a842fR361-R363. However I do not know the side effects well enough to give a full solution. Additionally it appears that this is caused by some optimization around the flatMap operator as there is a current test which utilizes .hide() on the error flux and completes successfully linked here https://github.com/reactor/reactor-core/blob/912441f7d36adfb84f06595cecd8895b7518d8c9/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java#L604 A difference when using hide though is that the upstream subscription is still never cancelled so there is still a deviation of behavior from the thrown case as this would cause hot infinite publishers to never propagate the error and continue requesting events. ## Steps to Reproduce <!---Provide a link to a live example, or an unambiguous set of steps to reproduce this bug, eg. a unit test. Include code to reproduce, if relevant. Most projects use JUnit5 now (like in snippet below; otherwise use JUnit4). --> Below are examples for the direct throw vs callable source ```java @Test void workingFlatMapDelayError() { Flux.just(0, 1, 2, 3).log() .flatMapDelayError(integer -> { throw new RuntimeException(); // Cancels upstream subscription after consuming one event }, 1, 1) .as(StepVerifier::create) .expectError() .verify(Duration.ofSeconds(1)); // Completes as expected } @Test void hangingFlatMapDelayError() { Flux.just(0, 1, 2, 3).log() .flatMapDelayError(integer -> { return Flux.error(new RuntimeException()); // Does not cancel upstream subscription }, 1, 1) .as(StepVerifier::create) .expectError() .verify(Duration.ofSeconds(1)); // Triggers timeout } @Test void deoptimizedFlatMapDelayError() { Flux.just(0, 1, 2, 3).log() .flatMapDelayError(integer -> { return Flux.error(new RuntimeException()).hide(); // Does not cancel upstream subscription }, 1, 1) .as(StepVerifier::create) .expectError() .verify(Duration.ofSeconds(1)); // Completes after consuming all events } ``` ## Your Environment <!--- Include as many relevant details about the environment you experienced the bug in. --> <!--- Especially, always include the version(s) of Reactor library/libraries you used! --> * Reactor version(s) used: reactor-core 3.5.2, reactor-test 3.5.2 * Other relevant libraries versions (eg. `netty`, ...): N/A * JVM version (`java -version`): 17 * OS and version (eg `uname -a`): Windows 11
      3dbc0701a061f7e20e304e0475a5ddac1745bddd
      075639613aeec1890f7d10ba4e747a261da6adde
      https://github.com/reactor/reactor-core/compare/3dbc0701a061f7e20e304e0475a5ddac1745bddd...075639613aeec1890f7d10ba4e747a261da6adde
      diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java b/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java index f3959edd3..e14d6eb1f 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java +++ b/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -416,6 +416,7 @@ final class FluxFlatMap<T, R> extends InternalFluxOperator<T, R> { onError(Operators.onOperatorError(s, e_, t, ctx)); } Operators.onDiscard(t, ctx); + tryEmitScalar(null); return; } tryEmitScalar(v); diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java index 7176da584..599772402 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,6 @@ import reactor.core.Scannable; import reactor.core.TestLoggerExtension; import reactor.core.publisher.FluxPeekFuseableTest.AssertQueueSubscription; import reactor.core.scheduler.Schedulers; -import reactor.test.util.LoggerUtils; import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; import reactor.test.subscriber.AssertSubscriber; @@ -1869,4 +1868,41 @@ public class FluxFlatMapTest { .expectError(NoSuchMethodException.class) .verify(); } + + static class FluxFlatMapDelayError3336Test { + + @Test + void workingFlatMapDelayError() { + Flux.just(0, 1, 2, 3) + .flatMapDelayError(integer -> { + throw new RuntimeException(); // Cancels upstream subscription after consuming one event + }, 1, 1) + .as(StepVerifier::create) + .expectError() + .verify(Duration.ofSeconds(1)); // Completes as expected + } + + @Test + void hangingFlatMapDelayError() { + Flux.just(0, 1, 2, 3) + .flatMapDelayError(integer -> { + return Flux.error(new RuntimeException()); // Does not cancel upstream subscription + }, 1, 1) + .as(StepVerifier::create) + .expectError() + .verify(Duration.ofSeconds(1)); // Triggers timeout + } + + @Test + void deoptimizedFlatMapDelayError() { + Flux.just(0, 1, 2, 3) + .flatMapDelayError(integer -> { + return Flux.error(new RuntimeException()) + .hide(); // Does not cancel upstream subscription + }, 1, 1) + .as(StepVerifier::create) + .expectError() + .verify(Duration.ofSeconds(1)); // Completes after consuming all events + } + } }
      ['reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,998,388
      995,207
      135,651
      489
      186
      51
      3
      1
      4,430
      532
      1,016
      88
      5
      1
      1970-01-01T00:27:56
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,070
      reactor/reactor-core/3262/3253
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/3253
      https://github.com/reactor/reactor-core/pull/3262
      https://github.com/reactor/reactor-core/pull/3262
      1
      closes
      Mono and Flux with onErrorContinue hangs on network errors (thrown by Netty)
      When I use an `onErrorContinue` on a `Mono` or a `Flux` that gets its input from a `WebClient`, the whole chain hangs in case a network error is thrown. I've seen this behaviour with errors caused by a connection timeout, read timeout, unknown host and a refused connection. Please note that I created this bug in reactor-core, because this is the place where `onErrorContinue` is defined. I suspect that this bug is not specific to the netty http client, but I haven't tested that. ## Expected Behavior I expect the program to continue and not to cause any thread to hang. ## Actual Behavior The thread that executes the Mono (or Flux) blocks forever. ## Steps to Reproduce You can use the following junit 5 tests (one for Mono and one for Flux) to reproduce this issue. This test instantiates a WebClient with a 200ms response timeout. This client is then used to do a call to "https://httpstat.us/200?sleep=500" that will return a 200 response only after 500ms. This way we force a response timeout to be thrown. A failing test means that the `block()` did not return any result within 5 seconds. ```java public class NettyReactorTest { private final WebClient webClient; public NettyReactorTest() { final ReactorClientHttpConnector httpConnector = new ReactorClientHttpConnector( HttpClient.create().responseTimeout(Duration.ofMillis(200))); this.webClient = WebClient.builder() .baseUrl("https://httpstat.us") .clientConnector(httpConnector) .build(); } @Test public void testMonoOnErrorContinueDoesNotHangOnTimeouts() { Mono<ResponseEntity<Void>> call = webClient.get() .uri("/200?sleep=500") .retrieve() .toBodilessEntity() .onErrorContinue((e, o) -> { }); Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> call.block()); } @Test public void testFluxOnErrorContinueDoesNotHangOnTimeouts() { Mono<ResponseEntity<Void>> call = webClient.get() .uri("/200?sleep=500") .retrieve() .toBodilessEntity(); Mono<List<ResponseEntity<Void>>> calls = Flux.fromIterable(List.of(1, 2, 3)) .flatMap(i -> call) .onErrorContinue((e, o) -> {}) .collectList(); Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> calls.block()); } } ``` ## Extra information When we take a thread dump a little while after we run the test (that blocks) we see that the thread that calls `block()` is stuck on the `Mono.block()` operator: ``` junit-timeout-thread-1 jdk.internal.misc.Unsafe.park(boolean, long) Unsafe.java (native) java.util.concurrent.locks.LockSupport.park(Object) LockSupport.java:194 java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt() AbstractQueuedSynchronizer.java:885 java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(int) AbstractQueuedSynchronizer.java:1039 java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(int) AbstractQueuedSynchronizer.java:1345 java.util.concurrent.CountDownLatch.await() CountDownLatch.java:232 reactor.core.publisher.BlockingSingleSubscriber.blockingGet() BlockingSingleSubscriber.java:87 reactor.core.publisher.Mono.block() Mono.java:1707 NettyReactorTest.lambda$testMonoOnErrorContinueDoesNotHangOnTimeouts$1(Mono) NettyReactorTest.java:52 NettyReactorTest$$Lambda$529.get() org.junit.jupiter.api.AssertTimeout.lambda$assertTimeoutPreemptively$4(AtomicReference, ThrowingSupplier) AssertTimeout.java:138 org.junit.jupiter.api.AssertTimeout$$Lambda$530.call() java.util.concurrent.FutureTask.run() FutureTask.java:264 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) ThreadPoolExecutor.java:1128 java.util.concurrent.ThreadPoolExecutor$Worker.run() ThreadPoolExecutor.java:628 java.lang.Thread.run() Thread.java:829 ``` ## Possible Solution Not a solution, but more of a way to mitigate the impact. I am aware that `onErrorContinue` is a specialised operator and that for my specific case I could (and should) have used `onErrorResume`. Indeed, replacing `onErrorContinue` with `onErrorResume` in the above tests makes the problem go away. So, perhaps I am just another case of someone using it wrongly and "tripping up on it" (https://github.com/reactor/reactor-core/issues/2184). Yet, this seemingly innocent code causes a rather nasty issue that should either be: * fixed if this is indeed a bug or * prevented if this is an unjust use of the `onErrorContinue` operator. For the latter, I like @simonbasle's suggestion to move this operator to an `unsafe()` subgroup. This would have prevented me from using it and use `onErrorResume` instead as suggested in the documentation. ## Your Environment * Reactor version(s) used: 3.4.22 * Other relevant libraries versions (eg. `netty`, ...): ** netty: 1.0.22 ** spring / spring-web: 5.3.22 * JVM version (`java -version`): OpenJDK Runtime Environment Zulu11.58+15-CA (build 11.0.16+8-LTS) * OS and version (eg `uname -a`): Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64 x86_64 (macOS Monterey)
      b31b331e1c37bf468320185474d39bc504afea99
      0cc9e9831f1609f268c9f45de7d0782615cc0309
      https://github.com/reactor/reactor-core/compare/b31b331e1c37bf468320185474d39bc504afea99...0cc9e9831f1609f268c9f45de7d0782615cc0309
      diff --git a/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java b/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java index 3283bd781..540501b5c 100644 --- a/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java +++ b/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import reactor.util.annotation.Nullable; +import reactor.util.context.Context; import reactor.util.context.ContextView; /** @@ -539,69 +540,73 @@ public final class RetryBackoffSpec extends Retry { @Override public Flux<Long> generateCompanion(Flux<RetrySignal> t) { validateArguments(); - return t.concatMap(retryWhenState -> { - //capture the state immediately - RetrySignal copy = retryWhenState.copy(); - Throwable currentFailure = copy.failure(); - long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries(); - - if (currentFailure == null) { - return Mono.error(new IllegalStateException("Retry.RetrySignal#failure() not expected to be null")); - } - - if (!errorFilter.test(currentFailure)) { - return Mono.error(currentFailure); - } - - if (iteration >= maxAttempts) { - return Mono.error(retryExhaustedGenerator.apply(this, copy)); - } - - Duration nextBackoff; - try { - nextBackoff = minBackoff.multipliedBy((long) Math.pow(2, iteration)); - if (nextBackoff.compareTo(maxBackoff) > 0) { + return Flux.deferContextual(cv -> + t.contextWrite(cv) + .concatMap(retryWhenState -> { + //capture the state immediately + RetrySignal copy = retryWhenState.copy(); + Throwable currentFailure = copy.failure(); + long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries(); + + if (currentFailure == null) { + return Mono.error(new IllegalStateException("Retry.RetrySignal#failure() not expected to be null")); + } + + if (!errorFilter.test(currentFailure)) { + return Mono.error(currentFailure); + } + + if (iteration >= maxAttempts) { + return Mono.error(retryExhaustedGenerator.apply(this, copy)); + } + + Duration nextBackoff; + try { + nextBackoff = minBackoff.multipliedBy((long) Math.pow(2, iteration)); + if (nextBackoff.compareTo(maxBackoff) > 0) { + nextBackoff = maxBackoff; + } + } + catch (ArithmeticException overflow) { nextBackoff = maxBackoff; } - } - catch (ArithmeticException overflow) { - nextBackoff = maxBackoff; - } - - //short-circuit delay == 0 case - if (nextBackoff.isZero()) { - return RetrySpec.applyHooks(copy, Mono.just(iteration), + + //short-circuit delay == 0 case + if (nextBackoff.isZero()) { + return RetrySpec.applyHooks(copy, Mono.just(iteration), + syncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry); + } + + ThreadLocalRandom random = ThreadLocalRandom.current(); + + long jitterOffset; + try { + jitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor)) + .dividedBy(100) + .toMillis(); + } + catch (ArithmeticException ae) { + jitterOffset = Math.round(Long.MAX_VALUE * jitterFactor); + } + long lowBound = Math.max(minBackoff.minus(nextBackoff) + .toMillis(), -jitterOffset); + long highBound = Math.min(maxBackoff.minus(nextBackoff) + .toMillis(), jitterOffset); + + long jitter; + if (highBound == lowBound) { + if (highBound == 0) jitter = 0; + else jitter = random.nextLong(highBound); + } + else { + jitter = random.nextLong(lowBound, highBound); + } + Duration effectiveBackoff = nextBackoff.plusMillis(jitter); + return RetrySpec.applyHooks(copy, Mono.delay(effectiveBackoff, + backoffSchedulerSupplier.get()), syncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry); - } - - ThreadLocalRandom random = ThreadLocalRandom.current(); - - long jitterOffset; - try { - jitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor)) - .dividedBy(100) - .toMillis(); - } - catch (ArithmeticException ae) { - jitterOffset = Math.round(Long.MAX_VALUE * jitterFactor); - } - long lowBound = Math.max(minBackoff.minus(nextBackoff) - .toMillis(), -jitterOffset); - long highBound = Math.min(maxBackoff.minus(nextBackoff) - .toMillis(), jitterOffset); - - long jitter; - if (highBound == lowBound) { - if (highBound == 0) jitter = 0; - else jitter = random.nextLong(highBound); - } - else { - jitter = random.nextLong(lowBound, highBound); - } - Duration effectiveBackoff = nextBackoff.plusMillis(jitter); - return RetrySpec.applyHooks(copy, Mono.delay(effectiveBackoff, - backoffSchedulerSupplier.get()), - syncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry); - }); + }) + .contextWrite(c -> Context.empty()) + ); } } diff --git a/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java b/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java index 55c3ae989..710ff4de8 100644 --- a/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java +++ b/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved. * * 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 java.util.function.Predicate; import reactor.core.Exceptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.util.context.Context; import reactor.util.context.ContextView; /** @@ -353,25 +354,30 @@ public final class RetrySpec extends Retry { @Override public Flux<Long> generateCompanion(Flux<RetrySignal> flux) { - return flux.concatMap(retryWhenState -> { - //capture the state immediately - RetrySignal copy = retryWhenState.copy(); - Throwable currentFailure = copy.failure(); - long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries(); + return Flux.deferContextual(cv -> + flux + .contextWrite(cv) + .concatMap(retryWhenState -> { + //capture the state immediately + RetrySignal copy = retryWhenState.copy(); + Throwable currentFailure = copy.failure(); + long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries(); - if (currentFailure == null) { - return Mono.error(new IllegalStateException("RetryWhenState#failure() not expected to be null")); - } - else if (!errorFilter.test(currentFailure)) { - return Mono.error(currentFailure); - } - else if (iteration >= maxAttempts) { - return Mono.error(retryExhaustedGenerator.apply(this, copy)); - } - else { - return applyHooks(copy, Mono.just(iteration), doPreRetry, doPostRetry, asyncPreRetry, asyncPostRetry); - } - }); + if (currentFailure == null) { + return Mono.error(new IllegalStateException("RetryWhenState#failure() not expected to be null")); + } + else if (!errorFilter.test(currentFailure)) { + return Mono.error(currentFailure); + } + else if (iteration >= maxAttempts) { + return Mono.error(retryExhaustedGenerator.apply(this, copy)); + } + else { + return applyHooks(copy, Mono.just(iteration), doPreRetry, doPostRetry, asyncPreRetry, asyncPostRetry); + } + }) + .contextWrite(c -> Context.empty()) + ); } //=================== diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java index ceab36edb..1eb0dbad5 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java @@ -58,6 +58,33 @@ public class FluxRetryWhenTest { Flux<Integer> rangeError = Flux.concat(Flux.range(1, 2), Flux.error(new RuntimeException("forced failure 0"))); + @Test + //https://github.com/reactor/reactor-core/issues/3253 + public void shouldFailWhenOnErrorContinueEnabled() { + Mono.create(sink -> { + throw new RuntimeException("blah"); + }) + .retryWhen(Retry.indefinitely().filter(t -> false)) + .onErrorContinue((e, o) -> {}) + .as(StepVerifier::create) + .expectError() + .verify(Duration.ofSeconds(10)); + } + + @Test + //https://github.com/reactor/reactor-core/issues/3253 + public void shouldWorkAsExpected() { + Mono.just(1) + .map(v -> { // ensure original context is propagated + throw new RuntimeException("boom"); + }) + .retryWhen(Retry.indefinitely().filter(t -> false)) + .onErrorContinue((e, o) -> {}) + .as(StepVerifier::create) + .expectComplete() + .verify(Duration.ofSeconds(10)); + } + @Test public void dontRepeat() { AssertSubscriber<Integer> ts = AssertSubscriber.create();
      ['reactor-core/src/main/java/reactor/util/retry/RetrySpec.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java', 'reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      3,974,838
      989,269
      134,931
      486
      6,265
      1,511
      173
      2
      5,454
      534
      1,293
      102
      3
      2
      1970-01-01T00:27:47
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,066
      reactor/reactor-core/3555/3554
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/3554
      https://github.com/reactor/reactor-core/pull/3555
      https://github.com/reactor/reactor-core/pull/3555
      2
      closes
      `FluxGroupBy`'s `GroupedFlux` does not propagate the `Subscription` to the second (rejected) `Subscriber`
      When calling flatMap on a Publisher which throws an exception upon subscription, there are certain cases where checkTerminated throws a NPE and masks the actual exception. Furthermore flatMap never terminates. ## Expected Behavior flatMap terminates with the actual Error ## Actual Behavior NPE and no Termination. Stacktrace from the example below ``` 2023-08-02 13:04:02 ERROR Operators - Operator called default onErrorDropped java.lang.NullPointerException: null at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:840) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:609) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:589) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxFlatMap$FlatMapMain.onError(FluxFlatMap.java:452) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxGroupBy$UnicastGroupedFlux.subscribe(FluxGroupBy.java:721) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxRetry$RetrySubscriber.resubscribe(FluxRetry.java:117) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxRetry.subscribeOrReturn(FluxRetry.java:52) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.Flux.subscribe(Flux.java:8759) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:427) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxGroupBy$GroupByMain.drainLoop(FluxGroupBy.java:393) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxGroupBy$GroupByMain.drain(FluxGroupBy.java:329) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxGroupBy$GroupByMain.onNext(FluxGroupBy.java:207) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxArray$ArraySubscription.slowPath(FluxArray.java:127) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxArray$ArraySubscription.request(FluxArray.java:100) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxGroupBy$GroupByMain.onSubscribe(FluxGroupBy.java:171) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.core.publisher.Flux.subscribe(Flux.java:8773) ~[reactor-core-3.5.8.jar:3.5.8] at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.toVerifierAndSubscribe(DefaultStepVerifierBuilder.java:891) ~[reactor-test-3.5.8.jar:3.5.8] at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:831) ~[reactor-test-3.5.8.jar:3.5.8] at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:823) ~[reactor-test-3.5.8.jar:3.5.8] at reactor.test.DefaultStepVerifierBuilder.verifyErrorSatisfies(DefaultStepVerifierBuilder.java:685) ~[reactor-test-3.5.8.jar:3.5.8] ``` ## Steps to Reproduce ```kotlin @Test fun flatMapExceptionTest() { StepVerifier.create(Flux.just(1, 2, 3, 4, 5, 6) .groupBy { it > 3 } .flatMap { it.flatMap<Int> { Mono.error(Error("whoopsies")) }.retry(2) } ).verifyErrorSatisfies { assertThat(it).hasMessage("whoopsies") } } ``` The actual error here (GroupedFlux allows only one Subscriber) is hidden by the NPE ## Possible Solution Null check? Not sure if there is more behind it. ## Your Environment * Reactor version(s) used: 3.5.8 * JVM version (`java -version`): openjdk version "11.0.17" 2022-10-18 LTS * OS and version (eg `uname -a`): Linux S0155454 6.2.0-26-generic
      b38936e387c31c36044f55448dce5033c580bc9c
      91a201de9651a2242d4ec66cda310d9b18f125fc
      https://github.com/reactor/reactor-core/compare/b38936e387c31c36044f55448dce5033c580bc9c...91a201de9651a2242d4ec66cda310d9b18f125fc
      diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java b/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java index 30cad47c3..08092c8e0 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java +++ b/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -718,7 +718,7 @@ final class FluxGroupBy<T, K, V> extends InternalFluxOperator<T, GroupedFlux<K, drain(); } else { - actual.onError(new IllegalStateException( + Operators.error(actual, new IllegalStateException( "GroupedFlux allows only one Subscriber")); } } diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java index fdfeb524d..00d974d06 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved. + * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,6 +47,16 @@ import static org.assertj.core.api.Assertions.fail; public class FluxGroupByTest extends FluxOperatorTest<String, GroupedFlux<Integer, String>> { + @Test + // see https://github.com/reactor/reactor-core/issues/3554 + void flatMapExceptionTest() { + Flux.just(1, 2, 3, 4, 5, 6) + .groupBy(it -> it > 3) + .flatMap(it -> it.flatMap(__ -> Mono.error(new RuntimeException("whoopsies"))).retry(2)) + .as(StepVerifier::create) + .verifyErrorSatisfies(it -> assertThat(it).hasMessage("GroupedFlux allows only one Subscriber")); + } + @Test @Tag("slow") //see https://github.com/reactor/reactor-core/issues/2730
      ['reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      3,812,390
      951,638
      129,701
      464
      262
      59
      4
      1
      3,961
      222
      1,214
      61
      0
      2
      1970-01-01T00:28:11
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      1,072
      reactor/reactor-core/2216/2196
      reactor
      reactor-core
      https://github.com/reactor/reactor-core/issues/2196
      https://github.com/reactor/reactor-core/pull/2216
      https://github.com/reactor/reactor-core/pull/2216
      1
      fix
      repeatWhenEmpty hangs on cancel when discard hook is present
      ## Expected Behavior It should be safe to cancel the sequence. ## Actual Behavior Cancelling a sequence which is in a `repeatWhenEmpty()` loop will cause issues when a discard hook has been registered. In that case `Operators.onDiscardMultiple()` is invoked with the iterator used to keep track of the current iteration and the hook would be called for every remaining number up to `Long.MAX_VALUE`. ## Steps to Reproduce This test case will succeed when removing the `doOnDiscard()` operator. ```java @Test public void shouldCompleteEventually() { StepVerifier.create(Mono.empty() .repeatWhenEmpty(Repeat.once()) .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release)) .thenAwait() .thenCancel() .verify(Duration.ofSeconds(5)); } ``` ## Possible Solution Probably we should treat the remaining iterations in a way that they can be safely discarded without bothering any application level hooks. Also, I guess `FluxStream` should not be considered "knownToBeFinite" if its size is `Long.MAX_VALUE`. ## Your Environment * Reactor version(s) used: 3.3.6.RELEASE
      19d1c1c9808641b2d50922a3c9cc800fbc33d4c6
      f6a5f5b920aec6a55b7887e252feb5aa112e4392
      https://github.com/reactor/reactor-core/compare/19d1c1c9808641b2d50922a3c9cc800fbc33d4c6...f6a5f5b920aec6a55b7887e252feb5aa112e4392
      diff --git a/reactor-core/src/main/java/reactor/core/publisher/Mono.java b/reactor-core/src/main/java/reactor/core/publisher/Mono.java index 6cd3bd838..14e668db1 100644 --- a/reactor-core/src/main/java/reactor/core/publisher/Mono.java +++ b/reactor-core/src/main/java/reactor/core/publisher/Mono.java @@ -27,6 +27,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; @@ -133,9 +134,9 @@ public abstract class Mono<T> implements Publisher<T> { * } * } * }; - * + * * client.addListener(listener); - * + * * sink.onDispose(() -&gt; client.removeListener(listener)); * }); * </code></pre> @@ -2675,7 +2676,7 @@ public abstract class Mono<T> implements Publisher<T> { /** * Hides the identity of this {@link Mono} instance. - * + * * <p>The main purpose of this operator is to prevent certain identity-based * optimizations from happening, mostly for diagnostic purposes. * @@ -2684,7 +2685,7 @@ public abstract class Mono<T> implements Publisher<T> { public final Mono<T> hide() { return onAssembly(new MonoHide<>(this)); } - + /** * Ignores onNext signal (dropping it) and only propagates termination events. * @@ -3416,23 +3417,16 @@ public abstract class Mono<T> implements Publisher<T> { * as long as the companion {@link Publisher} produces an onNext signal and the maximum number of repeats isn't exceeded. */ public final Mono<T> repeatWhenEmpty(int maxRepeat, Function<Flux<Long>, ? extends Publisher<?>> repeatFactory) { - return Mono.defer(() -> { - Flux<Long> iterations; - - if(maxRepeat == Integer.MAX_VALUE) { - iterations = Flux.fromStream(LongStream.range(0, Long.MAX_VALUE).boxed()); + return Mono.defer(() -> this.repeatWhen(o -> { + if (maxRepeat == Integer.MAX_VALUE) { + return repeatFactory.apply(o.index().map(Tuple2::getT1)); } else { - iterations = Flux - .range(0, maxRepeat) - .map(Integer::longValue) - .concatWith(Flux.error(new IllegalStateException("Exceeded maximum number of repeats"), true)); + return repeatFactory.apply(o.index().map(Tuple2::getT1) + .take(maxRepeat) + .concatWith(Flux.error(new IllegalStateException("Exceeded maximum number of repeats"), true))); } - - return this.repeatWhen(o -> repeatFactory.apply(o - .zipWith(iterations, 1, (c, i) -> i))) - .next(); - }); + }).next()); } diff --git a/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java b/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java index 3bff20b94..e000821f5 100644 --- a/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java +++ b/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java @@ -18,8 +18,10 @@ package reactor.core.publisher; import org.junit.Assert; import org.junit.Test; +import reactor.test.StepVerifier; import reactor.test.subscriber.AssertSubscriber; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -91,4 +93,13 @@ public class MonoRepeatWhenEmptyTest { Assert.assertEquals(Arrays.asList(0L, 1L), iterations); } + @Test(timeout = 1000L) + public void gh2196_discardHandlerHang() { + StepVerifier.create(Mono.empty() + .repeatWhenEmpty(f -> f.next()) + .doOnDiscard(Object.class, System.out::println)) + .thenAwait() + .thenCancel() + .verify(); + } }
      ['reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java', 'reactor-core/src/main/java/reactor/core/publisher/Mono.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      2,953,786
      734,107
      104,103
      385
      947
      237
      30
      1
      1,209
      139
      252
      28
      0
      1
      1970-01-01T00:26:32
      4,602
      Java
      {'Java': 8928316, 'Kotlin': 48023}
      Apache License 2.0
      3,322
      vespa-engine/vespa/14164/14153
      vespa-engine
      vespa
      https://github.com/vespa-engine/vespa/issues/14153
      https://github.com/vespa-engine/vespa/pull/14164
      https://github.com/vespa-engine/vespa/pull/14164
      1
      resolves
      bm25 does not give any relevance score for fields defined outside the document
      /search/?yql=select%20*%20from%20sources%20*%20where%20titlebest%20contains%20"best"%3B&ranking=titlebest => `"relevance": 0,` /search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20"best"%3B&ranking=title => `"relevance": 0.31872690041420326,` Schema: ``` schema music { document music { field title type string { indexing: summary | index index: enable-bm25 } } field titlebest type string { stemming: best indexing: input title | summary | index index: enable-bm25 } rank-profile title { first-phase { expression: bm25(title) } } rank-profile titlebest {` first-phase { expression: bm25(titlebest) } } } ```
      f454184d22c6c46d23710f7cfda988ee40efa641
      5fa9bce02e30aa93cf986a3d946363df35a50cc0
      https://github.com/vespa-engine/vespa/compare/f454184d22c6c46d23710f7cfda988ee40efa641...5fa9bce02e30aa93cf986a3d946363df35a50cc0
      diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java index 0ab8a2308a4..3a60a75f75f 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java @@ -394,6 +394,9 @@ public class Search implements ImmutableSearch { if (current.isPrefix()) { consolidated.setPrefix(true); } + if (current.useInterleavedFeatures()) { + consolidated.setInterleavedFeatures(true); + } if (consolidated.getRankType() == null) { consolidated.setRankType(current.getRankType()); diff --git a/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java b/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java index f992d5ee0ba..1734c58ddc9 100644 --- a/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java +++ b/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java @@ -8,7 +8,9 @@ import org.junit.Test; import java.io.IOException; +import static com.yahoo.config.model.test.TestUtil.joinLines; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Rank settings @@ -34,4 +36,27 @@ public class IndexSettingsTestCase extends SchemaTestCase { assertEquals(Stemming.MULTIPLE, multiStemmed.getStemming(search)); } + @Test + public void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException { + SearchBuilder builder = SearchBuilder.createFromString(joinLines( + "search test {", + " document test {", + " field content type string {", + " indexing: index | summary", + " index: enable-bm25", + " }", + " }", + " field extra type string {", + " indexing: input content | index | summary", + " index: enable-bm25", + " }", + "}" + )); + Search search = builder.getSearch(); + Index contentIndex = search.getIndex("content"); + assertTrue(contentIndex.useInterleavedFeatures()); + Index extraIndex = search.getIndex("extra"); + assertTrue(extraIndex.useInterleavedFeatures()); + } + }
      ['config-model/src/main/java/com/yahoo/searchdefinition/Search.java', 'config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      20,798,737
      4,247,905
      549,412
      5,592
      127
      22
      3
      1
      748
      66
      222
      35
      0
      1
      1970-01-01T00:26:38
      4,562
      Java
      {'Java': 42949616, 'C++': 30143509, 'Go': 685517, 'CMake': 604483, 'Shell': 271272, 'JavaScript': 73336, 'Python': 56537, 'C': 54788, 'HTML': 54520, 'CSS': 40916, 'TLA': 36167, 'Perl': 23134, 'Roff': 17506, 'Yacc': 14735, 'Objective-C': 12547, 'Lex': 11499, 'Ruby': 10690, 'ANTLR': 7984, 'LLVM': 6152, 'Makefile': 5906, 'PigLatin': 5724, 'Raku': 3729, 'GAP': 3312, 'Kotlin': 1870, 'Emacs Lisp': 91}
      Apache License 2.0
      3,812
      muzei/muzei/46/45
      muzei
      muzei
      https://github.com/muzei/muzei/issues/45
      https://github.com/muzei/muzei/pull/46
      https://github.com/muzei/muzei/pull/46
      2
      fixes
      Bad image URL crashes Muzei
      I'm writing an extension, which pulls the image URLs from a web site. When the URL is formatted incorrectly, Muzei crashes. It should be made more error tolerant. Most of the time this shouldn't be a problem, but if the web site designer changes the site, the code retrieving the image URLs could be bad/incorrect until the extension can be updated. To duplicate, publish artwork using a URI like "www.example.com". Here is the stack trace: 03-06 22:48:08.053 20350-5944/? E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[TaskQueueService] Process: net.nurik.roman.muzei, PID: 20350 java.lang.NullPointerException at com.google.android.apps.muzei.util.IOUtil.readFullyWriteToOutputStream(IOUtil.java:210) at com.google.android.apps.muzei.util.IOUtil.readFullyWriteToFile(IOUtil.java:202) at com.google.android.apps.muzei.ArtworkCache.maybeDownloadCurrentArtworkSync(ArtworkCache.java:122) at com.google.android.apps.muzei.TaskQueueService.onHandleIntent(TaskQueueService.java:56) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.os.HandlerThread.run(HandlerThread.java:61)
      a9d2ccfaeccabad26f9c6eba26355882654cc4c1
      bb64b9572c3c66d656bd6301fc231cec083d1111
      https://github.com/muzei/muzei/compare/a9d2ccfaeccabad26f9c6eba26355882654cc4c1...bb64b9572c3c66d656bd6301fc231cec083d1111
      diff --git a/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java b/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java index efffc15e..225ae342 100644 --- a/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java +++ b/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java @@ -58,6 +58,10 @@ public class IOUtil { } String scheme = uri.getScheme(); + if (scheme == null) { + throw new OpenUriException(false, new IOException("Uri had no scheme")); + } + InputStream in = null; if ("content".equals(scheme)) { try { @@ -118,7 +122,6 @@ public class IOUtil { } catch (MalformedURLException e) { throw new OpenUriException(false, e); - } catch (IOException e) { if (conn != null && responseCode > 0) { throw new OpenUriException(
      ['main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      552,584
      113,670
      14,734
      78
      131
      26
      5
      1
      1,328
      103
      311
      17
      0
      0
      1970-01-01T00:23:14
      4,519
      Kotlin
      {'Kotlin': 1044847, 'Python': 283216, 'Java': 116450, 'HTML': 36975, 'JavaScript': 32588, 'SCSS': 30501, 'CSS': 23867}
      Apache License 2.0
      1,441
      geysermc/geyser/316/307
      geysermc
      geyser
      https://github.com/GeyserMC/Geyser/issues/307
      https://github.com/GeyserMC/Geyser/pull/316
      https://github.com/GeyserMC/Geyser/pull/316
      1
      closes
      Xbox, Switch crashes when loading in a dimension that is not the overworld
      <!--- Please follow this format COMPLETELY and make sure the bug you are reporting has not been reported yet. Reports should contain as much information or context as possible to help us find the problem. Simply creating an issue on a vague topic will not help us at all, and if you are unsure if something should belong here, please contact us on [Discord](http://discord.geysermc.org).--> <!--- Issues pertaining to connection problem, or anything of that covered on the [Common Issues](https://github.com/GeyserMC/Geyser/wiki/Common-Issues) do not belong here and only clutter this issue tracker. --> **Describe the bug** Xbox crashes when the player is joining into The Nether or The End. **To Reproduce** Join Geyser on Xbox with your player loading into The End or The Nether. **Expected behavior** Minecraft does not crash. **Server Version** Paper 161 **Geyser Version** Master 25, Inventory 11 **Minecraft: Bedrock Edition Version** 1.14.30 Xbox
      e5f08403357add9dc1d1800b9c117d3864ab7f83
      f04a267d98c1edc03ab5af0e2d392992f4c78deb
      https://github.com/geysermc/geyser/compare/e5f08403357add9dc1d1800b9c117d3864ab7f83...f04a267d98c1edc03ab5af0e2d392992f4c78deb
      diff --git a/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java b/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java index 6fffcda8..cf6c2ee2 100644 --- a/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java +++ b/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java @@ -27,6 +27,7 @@ package org.geysermc.connector.network; import com.nukkitx.protocol.bedrock.BedrockPacket; import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.common.AuthType; import org.geysermc.common.IGeyserConfiguration; import org.geysermc.connector.GeyserConnector; import org.geysermc.connector.network.session.GeyserSession; @@ -107,7 +108,7 @@ public class UpstreamPacketHandler extends LoggingPacketHandler { @Override public boolean handle(MovePlayerPacket packet) { - if (!session.isLoggedIn() && !session.isLoggingIn()) { + if (!session.isLoggedIn() && !session.isLoggingIn() && session.getConnector().getAuthType() == AuthType.ONLINE) { // TODO it is safer to key authentication on something that won't change (UUID, not username) if (!couldLoginUserByName(session.getAuthData().getName())) { LoginEncryptionUtils.showLoginWindow(session); diff --git a/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java b/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java index 749dacb2..d5b2e75d 100644 --- a/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java +++ b/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java @@ -149,15 +149,6 @@ public class GeyserSession implements CommandSender { public void connect(RemoteServer remoteServer) { startGame(); this.remoteServer = remoteServer; - if (connector.getAuthType() != AuthType.ONLINE) { - connector.getLogger().info( - "Attempting to login using " + connector.getAuthType().name().toLowerCase() + " mode... " + - (connector.getAuthType() == AuthType.OFFLINE ? - "authentication is disabled." : "authentication will be encrypted" - ) - ); - authenticate(authData.getName()); - } ChunkUtils.sendEmptyChunks(this, playerEntity.getPosition().toInt(), 0, false); @@ -174,6 +165,18 @@ public class GeyserSession implements CommandSender { upstream.sendPacket(playStatusPacket); } + public void login() { + if (connector.getAuthType() != AuthType.ONLINE) { + connector.getLogger().info( + "Attempting to login using " + connector.getAuthType().name().toLowerCase() + " mode... " + + (connector.getAuthType() == AuthType.OFFLINE ? + "authentication is disabled." : "authentication will be encrypted" + ) + ); + authenticate(authData.getName()); + } + } + public void authenticate(String username) { authenticate(username, ""); } @@ -184,7 +187,7 @@ public class GeyserSession implements CommandSender { return; } - loggedIn = true; + loggingIn = true; // new thread so clients don't timeout new Thread(() -> { try { diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java index 54a5112d..87da2d00 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java @@ -40,6 +40,7 @@ public class BedrockSetLocalPlayerAsInitializedTranslator extends PacketTranslat if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) { if (!session.getUpstream().isInitialized()) { session.getUpstream().setInitialized(true); + session.login(); for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) { if (!entity.isValid()) { diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java index 0d6caaed..34fe2271 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java @@ -29,7 +29,6 @@ import org.geysermc.connector.entity.PlayerEntity; import org.geysermc.connector.network.session.GeyserSession; import org.geysermc.connector.network.translators.PacketTranslator; import org.geysermc.connector.network.translators.Translator; -import org.geysermc.connector.utils.ChunkUtils; import org.geysermc.connector.utils.DimensionUtils; import com.github.steveice10.mc.protocol.packet.ingame.server.ServerJoinGamePacket; @@ -69,7 +68,6 @@ public class JavaJoinGameTranslator extends PacketTranslator<ServerJoinGamePacke session.setRenderDistance(packet.getViewDistance()); if (DimensionUtils.javaToBedrock(packet.getDimension()) != entity.getDimension()) { - ChunkUtils.sendEmptyChunks(session, entity.getPosition().toInt(), 3, true); DimensionUtils.switchDimension(session, packet.getDimension()); } }
      ['connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java', 'connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java', 'connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java', 'connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      762,725
      164,911
      19,418
      233
      1,454
      272
      29
      4
      983
      144
      224
      22
      2
      0
      1970-01-01T00:26:26
      4,071
      Java
      {'Java': 3890490, 'Kotlin': 27417}
      MIT License
      1,439
      geysermc/geyser/203/207
      geysermc
      geyser
      https://github.com/GeyserMC/Geyser/issues/207
      https://github.com/GeyserMC/Geyser/pull/203
      https://github.com/GeyserMC/Geyser/pull/203#issuecomment-598746853
      2
      fix
      Xbox cannot seem to join the server but other platforms can
      **Describe the bug** Ive attempted to get my xbox to join my Geyser server running the inventory branch and floodgate and i receive the error "We were unable to connect you." **To Reproduce** Steps to reproduce the behavior: 1. Attempt to join the Geyser Lan game on a xbox 4. See error **Expected behavior** To be able to join Add any other context about the problem here. I attempted to join with the Xbox Geyser branch but it didnt seem to work either
      105ce2b3b59a40c8438a88207c33d00dccd393a6
      9f36ba14cd32c7e1f9f0dac21602dfb2f711a658
      https://github.com/geysermc/geyser/compare/105ce2b3b59a40c8438a88207c33d00dccd393a6...9f36ba14cd32c7e1f9f0dac21602dfb2f711a658
      diff --git a/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java b/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java index ee14fc90..0705d169 100644 --- a/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java +++ b/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java @@ -42,7 +42,8 @@ public enum DeviceOS { DEDICATED, ORBIS, NX, - SWITCH; + SWITCH, + XBOX_ONE; private static final DeviceOS[] VALUES = values();
      ['common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      690,628
      148,188
      17,416
      215
      40
      11
      3
      1
      471
      83
      109
      14
      0
      0
      1970-01-01T00:26:23
      4,071
      Java
      {'Java': 3890490, 'Kotlin': 27417}
      MIT License
      1,440
      geysermc/geyser/347/333
      geysermc
      geyser
      https://github.com/GeyserMC/Geyser/issues/333
      https://github.com/GeyserMC/Geyser/pull/347
      https://github.com/GeyserMC/Geyser/pull/347
      2
      fixes
      Pistons disappear from inventory when getting them from creative tab
      **Description** Piston items dissapear from inventory after obtaining them via creative tab. (getting them from the ground works well both on creative and survival) **To Reproduce** 1. Make sure your gamemode is creative 2. Find piston or sticky piston in your creative tab 3. Try to put it to your inventory **Expected behavior** Pistons shouldn't disappear from your inventory. **Server Version** Paper 1.15.2 git-183 **Geyser Version** inventory #14 **Minecraft: Bedrock Edition Version** 1.14.30
      1cb2e658e02f60db32b280ec70d1132821d15de8
      d7b8f088990fcfdc9748eadbce47766b21fb6aaa
      https://github.com/geysermc/geyser/compare/1cb2e658e02f60db32b280ec70d1132821d15de8...d7b8f088990fcfdc9748eadbce47766b21fb6aaa
      diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java index 8ca95159..0bcbf4b7 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java @@ -118,6 +118,13 @@ public class ItemTranslator { return itemEntry; } } + // If item find was unsuccessful first time, we try again while ignoring damage + // Fixes piston, sticky pistons, dispensers and droppers turning into air from creative inventory + for (ItemEntry itemEntry : Toolbox.ITEM_ENTRIES.values()) { + if (itemEntry.getBedrockId() == data.getId()) { + return itemEntry; + } + } GeyserConnector.getInstance().getLogger().debug("Missing mapping for bedrock item " + data.getId() + ":" + data.getDamage()); return ItemEntry.AIR;
      ['connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      971,532
      209,382
      23,920
      281
      386
      76
      7
      1
      525
      73
      123
      21
      0
      0
      1970-01-01T00:26:26
      4,071
      Java
      {'Java': 3890490, 'Kotlin': 27417}
      MIT License
      1,444
      geysermc/geyser/170/157
      geysermc
      geyser
      https://github.com/GeyserMC/Geyser/issues/157
      https://github.com/GeyserMC/Geyser/pull/170
      https://github.com/GeyserMC/Geyser/pull/170
      2
      fixes
      Swimming Action Bugged
      **Describe the bug** Once you enter swimming mode, you can't exit it resulting in death by Drowning as you cannot reach land. **To Reproduce** Steps to reproduce the behavior: 1. Dive into an Ocean 2. Enter Swimming Mode 4. Try exiting Swimming Mode **Expected behavior** Enter and exit swimming mode based on Client Input. **Screenshots** If necessary, I will upload footage of the bug in action. **Server version** This server is running Paper version git-Paper-98 (MC: 1.15.2) (Implementing API version 1.15.2-R0.1-SNAPSHOT) **Geyser version** Jenkins Latest **Bedrock version** 1.14.2 **Additional context** currently nothing else to say.
      5913cb616419f5abd1e566d5eddaedc1acbfe6b5
      2d0a5841064e06b9d05cf85617b29c84b8dfc94b
      https://github.com/geysermc/geyser/compare/5913cb616419f5abd1e566d5eddaedc1acbfe6b5...2d0a5841064e06b9d05cf85617b29c84b8dfc94b
      diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java index 56e573c6..e5bec698 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java @@ -56,6 +56,14 @@ public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket // Don't put anything here as respawn is already handled // in BedrockRespawnTranslator break; + case START_SWIMMING: + ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING); + session.getDownstream().getSession().send(startSwimPacket); + break; + case STOP_SWIMMING: + ClientPlayerStatePacket stopSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SPRINTING); + session.getDownstream().getSession().send(stopSwimPacket); + break; case START_GLIDE: case STOP_GLIDE: ClientPlayerStatePacket glidePacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_ELYTRA_FLYING);
      ['connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java']
      {'.java': 1}
      1
      1
      0
      0
      1
      648,516
      139,188
      16,321
      205
      555
      107
      8
      1
      677
      95
      167
      26
      0
      0
      1970-01-01T00:26:21
      4,071
      Java
      {'Java': 3890490, 'Kotlin': 27417}
      MIT License
      1,442
      geysermc/geyser/305/218
      geysermc
      geyser
      https://github.com/GeyserMC/Geyser/issues/218
      https://github.com/GeyserMC/Geyser/pull/305
      https://github.com/GeyserMC/Geyser/pull/305
      1
      fixes
      Bricks slab and trap door can't be placed properly
      **Describe the bug** When player place a bricks slab or a trap door it just fall down. More information in the video [video](https://streamable.com/zptei) **To Reproduce** Steps to reproduce the behavior: 1. Setup server with geyser 2. Place a brick slab or a trap door 3. See error **Expected behavior** Brick slab and trap door can stay where they are and not falling down **Screenshots** See video above **Server version** paper 1.15 latest **Geyser version** Jenkins inventory branch latest **Bedrock version** latest
      27f4879f0a9db8f620c769bda347d672c83f463b
      23d98bb25f89919ff4f913f9bd7bf411cdec4d3b
      https://github.com/geysermc/geyser/compare/27f4879f0a9db8f620c769bda347d672c83f463b...23d98bb25f89919ff4f913f9bd7bf411cdec4d3b
      diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java index ebc45ff0..206f42d1 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java @@ -33,12 +33,10 @@ import org.geysermc.connector.network.translators.PacketTranslator; import org.geysermc.connector.network.translators.Translator; import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; -import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction; import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState; import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace; import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket; -import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket; import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket; import com.nukkitx.math.vector.Vector3i; import com.nukkitx.protocol.bedrock.packet.PlayStatusPacket; @@ -101,10 +99,7 @@ public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket session.getDownstream().getSession().send(stopSleepingPacket); break; case BLOCK_INTERACT: - ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(position, - BlockFace.values()[packet.getFace()], - Hand.MAIN_HAND, 0, 0, 0, false); - session.getDownstream().getSession().send(blockPacket); + // Handled in BedrockInventoryTransactionTranslator break; case START_BREAK: ClientPlayerActionPacket startBreakingPacket = new ClientPlayerActionPacket(PlayerAction.START_DIGGING, new Position(packet.getBlockPosition().getX(), diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java index c9547514..94903246 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java @@ -25,6 +25,7 @@ package org.geysermc.connector.network.translators.bedrock; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket; import org.geysermc.connector.entity.Entity; import org.geysermc.connector.network.session.GeyserSession; import org.geysermc.connector.network.translators.PacketTranslator; @@ -41,7 +42,6 @@ import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlaye import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket; import com.nukkitx.math.vector.Vector3f; import com.nukkitx.protocol.bedrock.packet.InventoryTransactionPacket; -import org.geysermc.connector.network.translators.block.BlockTranslator; @Translator(packet = InventoryTransactionPacket.class) public class BedrockInventoryTransactionTranslator extends PacketTranslator<InventoryTransactionPacket> { @@ -50,14 +50,26 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve public void translate(InventoryTransactionPacket packet, GeyserSession session) { switch (packet.getTransactionType()) { case ITEM_USE: - if (packet.getActionType() == 1) { - ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); - session.getDownstream().getSession().send(useItemPacket); - } else if (packet.getActionType() == 2) { - PlayerAction action = session.getGameMode() == GameMode.CREATIVE ? PlayerAction.START_DIGGING : PlayerAction.FINISH_DIGGING; - Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()); - ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getFace()]); - session.getDownstream().getSession().send(breakPacket); + switch (packet.getActionType()) { + case 0: + ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket( + new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), + BlockFace.values()[packet.getFace()], + Hand.MAIN_HAND, + packet.getClickPosition().getX(), packet.getClickPosition().getY(), packet.getClickPosition().getZ(), + false); + session.getDownstream().getSession().send(blockPacket); + break; + case 1: + ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); + session.getDownstream().getSession().send(useItemPacket); + break; + case 2: + PlayerAction action = session.getGameMode() == GameMode.CREATIVE ? PlayerAction.START_DIGGING : PlayerAction.FINISH_DIGGING; + Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()); + ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getFace()]); + session.getDownstream().getSession().send(breakPacket); + break; } break; case ITEM_RELEASE:
      ['connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java', 'connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      762,283
      164,888
      19,409
      233
      3,117
      546
      37
      2
      557
      81
      132
      28
      1
      0
      1970-01-01T00:26:26
      4,071
      Java
      {'Java': 3890490, 'Kotlin': 27417}
      MIT License
      1,443
      geysermc/geyser/274/253
      geysermc
      geyser
      https://github.com/GeyserMC/Geyser/issues/253
      https://github.com/GeyserMC/Geyser/pull/274
      https://github.com/GeyserMC/Geyser/pull/274
      1
      fixes
      Geyser does not shut down with /geyser shutdown, or Control-C after a player has joined
      **Describe the bug** `/geyser shutdown` does not fully shutdown Geyser after a player has joined through Geyser - in Linux, two Control-Cs are required to terminate the process. **To Reproduce** Steps to reproduce the behavior: 1. Run Geyser 2. Join Geyser 3. Try to shutdown Geyser **Expected behavior** Geyser cleanly shuts down. **Geyser version** Jenkins Inventory Latest
      ade40d5a8b34e848b9c71d16427317e429bc6f07
      8e1b5de4b0143ad980a0fc71f3bbc90b324289f3
      https://github.com/geysermc/geyser/compare/ade40d5a8b34e848b9c71d16427317e429bc6f07...8e1b5de4b0143ad980a0fc71f3bbc90b324289f3
      diff --git a/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java b/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java index 7df8a4ef..ac21215c 100644 --- a/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java +++ b/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java @@ -52,7 +52,7 @@ public class GeyserLogger extends SimpleTerminalConsole implements IGeyserLogger @Override protected void shutdown() { - GeyserConnector.getInstance().shutdown(); + GeyserConnector.getInstance().getBootstrap().onDisable(); } @Override diff --git a/connector/src/main/java/org/geysermc/connector/GeyserConnector.java b/connector/src/main/java/org/geysermc/connector/GeyserConnector.java index d33bda9a..714bd5ae 100644 --- a/connector/src/main/java/org/geysermc/connector/GeyserConnector.java +++ b/connector/src/main/java/org/geysermc/connector/GeyserConnector.java @@ -49,6 +49,7 @@ import java.net.InetSocketAddress; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -142,6 +143,40 @@ public class GeyserConnector { bootstrap.getGeyserLogger().info("Shutting down Geyser."); shuttingDown = true; + if (players.size() >= 1) { + bootstrap.getGeyserLogger().info("Kicking " + players.size() + " player(s)"); + + for (GeyserSession playerSession : players.values()) { + playerSession.disconnect("Geyser Proxy shutting down."); + } + + CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() { + @Override + public void run() { + // Simulate a long-running Job + try { + while (true) { + if (players.size() == 0) { + return; + } + + TimeUnit.MILLISECONDS.sleep(100); + } + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } + }); + + // Block and wait for the future to complete + try { + future.get(); + bootstrap.getGeyserLogger().info("Kicked all players"); + } catch (Exception e) { + // Quietly fail + } + } + generalThreadPool.shutdown(); bedrockServer.close(); players.clear(); @@ -149,6 +184,8 @@ public class GeyserConnector { authType = null; commandMap.getCommands().clear(); commandMap = null; + + bootstrap.getGeyserLogger().info("Geyser shutdown successfully."); } public void addPlayer(GeyserSession player) { diff --git a/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java b/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java index 4694d0fd..2222cdef 100644 --- a/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java +++ b/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java @@ -48,6 +48,11 @@ public class StopCommand extends GeyserCommand { if (!sender.isConsole() && connector.getPlatformType() == PlatformType.STANDALONE) { return; } + connector.shutdown(); + + if (connector.getPlatformType() == PlatformType.STANDALONE) { + System.exit(0); + } } }
      ['bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java', 'connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java', 'connector/src/main/java/org/geysermc/connector/GeyserConnector.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      738,490
      160,116
      18,755
      230
      1,594
      271
      44
      3
      393
      57
      98
      15
      0
      0
      1970-01-01T00:26:26
      4,071
      Java
      {'Java': 3890490, 'Kotlin': 27417}
      MIT License
      248
      killbill/killbill/1289/1288
      killbill
      killbill
      https://github.com/killbill/killbill/issues/1288
      https://github.com/killbill/killbill/pull/1289
      https://github.com/killbill/killbill/pull/1289
      1
      fixes
      NPE in /1.0/kb/invoices/:invoiceId/payments
      Aborted `payment_attempts` can have a corresponding row in `invoice_payments` with a `NULL` `payment_id` (note that the `payment_cookie_id` i.e. the `payment_attempts. transaction_external_key` won't be `NULL` though): ``` MySQL [killbill]> select * from invoice_payments order by record_id desc limit 1\\G *************************** 1. row *************************** record_id: 3 id: e7f6b1d0-3823-4c5b-9226-12327af64492 type: ATTEMPT invoice_id: 742a1a60-58f8-4ed2-b9db-b1816a741f44 payment_id: NULL payment_date: 2012-05-02 00:37:59 amount: 0.000000000 currency: USD processed_currency: USD payment_cookie_id: bac67833-ac7c-458d-8e2a-659c0cdfb0b6 linked_invoice_payment_id: NULL success: 0 created_by: PaymentRequestProcessor created_date: 2012-05-02 00:37:59 account_record_id: 1 tenant_record_id: 0 1 row in set (0.00 sec) ``` This can trigger a NPE here: https://github.com/killbill/killbill/blob/1be24a4a144e80abcf45a5982deb7c1f2e22aa3b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java#L623 ``` java.lang.NullPointerException: null at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:877) at com.google.common.collect.ImmutableSet$Builder.add(ImmutableSet.java:483) at com.google.common.collect.ImmutableSet.copyOf(ImmutableSet.java:248) at com.google.common.collect.ImmutableSet.copyOf(ImmutableSet.java:230) at org.killbill.billing.jaxrs.resources.InvoiceResource.getPaymentsForInvoice(InvoiceResource.java:620) ```
      1be24a4a144e80abcf45a5982deb7c1f2e22aa3b
      35e7720d186913255dab22053598ebfed436a7c7
      https://github.com/killbill/killbill/compare/1be24a4a144e80abcf45a5982deb7c1f2e22aa3b...35e7720d186913255dab22053598ebfed436a7c7
      diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java index 6d1def04a1..b917d4a740 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java @@ -25,6 +25,7 @@ import java.net.URI; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -83,6 +84,7 @@ import org.killbill.billing.payment.api.InvoicePaymentApi; import org.killbill.billing.payment.api.Payment; import org.killbill.billing.payment.api.PaymentApi; import org.killbill.billing.payment.api.PaymentApiException; +import org.killbill.billing.payment.api.PaymentOptions; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.tenant.api.TenantApiException; import org.killbill.billing.tenant.api.TenantKV.TenantKey; @@ -110,7 +112,6 @@ import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; @@ -617,12 +618,12 @@ public class InvoiceResource extends JaxRsResourceBase { final Invoice invoice = invoiceApi.getInvoice(invoiceId, tenantContext); // Extract unique set of paymentId for this invoice - final Set<UUID> invoicePaymentIds = ImmutableSet.copyOf(Iterables.transform(invoice.getPayments(), new Function<InvoicePayment, UUID>() { - @Override - public UUID apply(final InvoicePayment input) { - return input.getPaymentId(); + final Set<UUID> invoicePaymentIds = new HashSet<UUID>(); + for (final InvoicePayment invoicePayment : invoice.getPayments()) { + if (invoicePayment.getPaymentId() != null) { + invoicePaymentIds.add(invoicePayment.getPaymentId()); } - })); + } if (invoicePaymentIds.isEmpty()) { return Response.status(Status.OK).entity(ImmutableList.<InvoicePaymentJson>of()).build(); } @@ -655,6 +656,7 @@ public class InvoiceResource extends JaxRsResourceBase { public Response createInstantPayment(@PathParam("invoiceId") final UUID invoiceId, final InvoicePaymentJson payment, @QueryParam(QUERY_PAYMENT_EXTERNAL) @DefaultValue("false") final Boolean externalPayment, + @QueryParam(QUERY_PAYMENT_CONTROL_PLUGIN_NAME) final List<String> paymentControlPluginNames, @QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @@ -672,8 +674,9 @@ public class InvoiceResource extends JaxRsResourceBase { final UUID paymentMethodId = externalPayment ? null : (payment.getPaymentMethodId() != null ? payment.getPaymentMethodId() : account.getPaymentMethodId()); - final InvoicePayment result = createPurchaseForInvoice(account, invoiceId, payment.getPurchasedAmount(), paymentMethodId, externalPayment, - payment.getPaymentExternalKey(), null, pluginProperties, callContext); + final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(externalPayment, paymentControlPluginNames); + final InvoicePayment result = createPurchaseForInvoice(account, invoiceId, payment.getPurchasedAmount(), paymentMethodId, + payment.getPaymentExternalKey(), null, pluginProperties, paymentOptions, callContext); return result != null ? uriBuilder.buildResponse(uriInfo, InvoicePaymentResource.class, "getInvoicePayment", result.getPaymentId(), request) : Response.status(Status.NO_CONTENT).build(); diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java index 2f61bd1b57..4726ddc8ad 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java @@ -22,7 +22,6 @@ import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.net.URI; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -553,7 +552,35 @@ public abstract class JaxRsResourceBase implements JaxrsResource { return properties; } - protected InvoicePayment createPurchaseForInvoice(final Account account, final UUID invoiceId, final BigDecimal amountToPay, final UUID paymentMethodId, final Boolean externalPayment, final String paymentExternalKey, final String transactionExternalKey, final Iterable<PluginProperty> pluginProperties, final CallContext callContext) throws PaymentApiException { + protected InvoicePayment createPurchaseForInvoice(final Account account, + final UUID invoiceId, + final BigDecimal amountToPay, + final UUID paymentMethodId, + final Boolean externalPayment, + final String paymentExternalKey, + final String transactionExternalKey, + final Iterable<PluginProperty> pluginProperties, + final CallContext callContext) throws PaymentApiException { + return createPurchaseForInvoice(account, + invoiceId, + amountToPay, + paymentMethodId, + paymentExternalKey, + transactionExternalKey, + pluginProperties, + createInvoicePaymentControlPluginApiPaymentOptions(externalPayment), + callContext); + } + + protected InvoicePayment createPurchaseForInvoice(final Account account, + final UUID invoiceId, + final BigDecimal amountToPay, + final UUID paymentMethodId, + final String paymentExternalKey, + final String transactionExternalKey, + final Iterable<PluginProperty> pluginProperties, + final PaymentOptions paymentOptions, + final CallContext callContext) throws PaymentApiException { try { return invoicePaymentApi.createPurchaseForInvoicePayment(account, invoiceId, @@ -564,7 +591,7 @@ public abstract class JaxRsResourceBase implements JaxrsResource { paymentExternalKey, transactionExternalKey, pluginProperties, - createInvoicePaymentControlPluginApiPaymentOptions(externalPayment), + paymentOptions, callContext); } catch (final PaymentApiException e) { if (e.getCode() == ErrorCode.PAYMENT_PLUGIN_EXCEPTION.getCode() /* && diff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java index 4e8856125a..a0facd3ff9 100644 --- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java +++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java @@ -1,6 +1,6 @@ /* - * Copyright 2014-2015 Groupon, Inc - * Copyright 2014-2015 The Billing Project, LLC + * Copyright 2014-2020 Groupon, Inc + * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the @@ -19,14 +19,12 @@ package org.killbill.billing.jaxrs; import java.math.BigDecimal; import java.util.Arrays; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; -import javax.ws.rs.HEAD; import org.joda.time.DateTime; import org.killbill.billing.ObjectType; @@ -38,6 +36,8 @@ import org.killbill.billing.client.model.Tags; import org.killbill.billing.client.model.gen.Account; import org.killbill.billing.client.model.gen.AuditLog; import org.killbill.billing.client.model.gen.ComboPaymentTransaction; +import org.killbill.billing.client.model.gen.Invoice; +import org.killbill.billing.client.model.gen.InvoicePayment; import org.killbill.billing.client.model.gen.Payment; import org.killbill.billing.client.model.gen.PaymentMethod; import org.killbill.billing.client.model.gen.PaymentMethodPluginDetail; @@ -219,6 +219,50 @@ public class TestPayment extends TestJaxrsBase { } } + @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/1288") + public void testWithAbortedInvoicePayment() throws Exception { + mockPaymentProviderPlugin.makeNextPaymentFailWithError(); + final Account account = createAccountWithPMBundleAndSubscriptionAndWaitForFirstInvoice(false); + // Getting Invoice #2 (first after Trial period) + final Invoice failedInvoice = accountApi.getInvoicesForAccount(account.getAccountId(), null, null, RequestOptions.empty()).get(1); + + // Verify initial state + final Payments initialPayments = accountApi.getPaymentsForAccount(account.getAccountId(), true, false, ImmutableMap.<String, String>of(), AuditLevel.NONE, requestOptions); + Assert.assertEquals(initialPayments.size(), 1); + Assert.assertEquals(initialPayments.get(0).getTransactions().size(), 1); + Assert.assertEquals(initialPayments.get(0).getTransactions().get(0).getStatus(), TransactionStatus.PAYMENT_FAILURE); + Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().size(), 2); + Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().get(0).getStateName(), "RETRIED"); + Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().get(1).getStateName(), "SCHEDULED"); + final InvoicePayments initialInvoicePayments = invoiceApi.getPaymentsForInvoice(failedInvoice.getInvoiceId(), requestOptions); + Assert.assertEquals(initialInvoicePayments.size(), 1); + Assert.assertEquals(initialInvoicePayments.get(0).getPaymentId(), initialPayments.get(0).getPaymentId()); + + // Trigger manually an invoice payment but make the control plugin abort it + mockPaymentControlProviderPlugin.setAborted(true); + final HashMultimap<String, String> queryParams = HashMultimap.create(); + queryParams.putAll("controlPluginName", Arrays.<String>asList(MockPaymentControlProviderPlugin.PLUGIN_NAME)); + final RequestOptions inputOptions = RequestOptions.builder() + .withCreatedBy(createdBy) + .withReason(reason) + .withComment(comment) + .withQueryParams(queryParams).build(); + final InvoicePayment invoicePayment = new InvoicePayment(); + invoicePayment.setPurchasedAmount(failedInvoice.getBalance()); + invoicePayment.setAccountId(failedInvoice.getAccountId()); + invoicePayment.setTargetInvoiceId(failedInvoice.getInvoiceId()); + final InvoicePayment invoicePaymentNull = invoiceApi.createInstantPayment(failedInvoice.getInvoiceId(), invoicePayment, true, null, inputOptions); + Assert.assertNull(invoicePaymentNull); + + // Verify new state + final Payments updatedPayments = accountApi.getPaymentsForAccount(account.getAccountId(), true, false, ImmutableMap.<String, String>of(), AuditLevel.NONE, requestOptions); + Assert.assertEquals(updatedPayments.size(), 1); + Assert.assertEquals(updatedPayments.get(0).getPaymentId(), initialPayments.get(0).getPaymentId()); + final InvoicePayments updatedInvoicePayments = invoiceApi.getPaymentsForInvoice(failedInvoice.getInvoiceId(), requestOptions); + Assert.assertEquals(updatedInvoicePayments.size(), 1); + Assert.assertEquals(updatedInvoicePayments.get(0).getPaymentId(), updatedPayments.get(0).getPaymentId()); + } + @Test(groups = "slow") public void testWithFailedPaymentAndScheduledAttemptsGetInvoicePayment() throws Exception { mockPaymentProviderPlugin.makeNextPaymentFailWithError();
      ['profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java']
      {'.java': 3}
      3
      3
      0
      0
      3
      6,411,254
      1,198,901
      138,507
      1,026
      4,350
      551
      52
      2
      1,747
      104
      470
      34
      1
      2
      1970-01-01T00:26:25
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      247
      killbill/killbill/1371/1370
      killbill
      killbill
      https://github.com/killbill/killbill/issues/1370
      https://github.com/killbill/killbill/pull/1371
      https://github.com/killbill/killbill/pull/1371
      1
      fixes
      Sub-millisecond precision in catalog date can lead to duplicate invoice items
      If the catalog effective date is set to `2020-09-16T10:34:25.348646Z` for instance, the DDL must support sub-millisecond precision (by default, it doesn't).
      0b850e9bcf5b632c2422691d6f2c731d179f4f84
      2796799bb8a7e73acfde0dfd1d318852ade8ca8d
      https://github.com/killbill/killbill/compare/0b850e9bcf5b632c2422691d6f2c731d179f4f84...2796799bb8a7e73acfde0dfd1d318852ade8ca8d
      diff --git a/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java b/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java index 398f49bb61..65c0cd69cb 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java @@ -25,6 +25,7 @@ import javax.annotation.Nullable; import org.joda.time.DateTime; import org.joda.time.LocalDate; +import org.joda.time.Seconds; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.api.InvoiceItemType; @@ -127,7 +128,11 @@ public class InvoiceItemCatalogBase extends InvoiceItemBase implements InvoiceIt return false; } final InvoiceItemCatalogBase that = (InvoiceItemCatalogBase) o; - if (catalogEffectiveDate != null && that.catalogEffectiveDate != null && catalogEffectiveDate.compareTo(that.catalogEffectiveDate) != 0) { + if (catalogEffectiveDate != null && + that.catalogEffectiveDate != null && + catalogEffectiveDate.compareTo(that.catalogEffectiveDate) != 0 && + // https://github.com/killbill/killbill/issues/1370 + Math.abs(Seconds.secondsBetween(catalogEffectiveDate, that.catalogEffectiveDate).getSeconds()) != 0) { return false; } else if (catalogEffectiveDate == null || that.catalogEffectiveDate == null) { /* At least one such item has a 'null' catalogEffectiveDate, reflecting a prior 0.22 release item diff --git a/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java b/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java index 43e974cdd4..8c1bbd0698 100644 --- a/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java +++ b/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java @@ -22,6 +22,7 @@ import java.math.BigDecimal; import java.util.List; import java.util.UUID; +import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.killbill.billing.invoice.model.TaxInvoiceItem; import org.testng.Assert; @@ -243,6 +244,29 @@ public class TestInvoiceItemDao extends InvoiceTestSuiteWithEmbeddedDB { createAndVerifyExternalCharge(new BigDecimal("10.2"), Currency.MGA); } + @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/1370") + public void testFixedPriceWithSubMillisecondCatalogEffectiveDateInvoiceSqlDao() throws EntityPersistenceException { + final UUID invoiceId = UUID.randomUUID(); + final UUID accountId = account.getId(); + final LocalDate startDate = new LocalDate(2012, 4, 1); + + final InvoiceItem fixedPriceInvoiceItem = new FixedPriceInvoiceItem(invoiceId, + accountId, + UUID.randomUUID(), + UUID.randomUUID(), + "test product", + "test plan", + "test phase", + new DateTime("2020-09-16T10:34:25.348646Z"), + startDate, + TEN, + Currency.USD); + invoiceUtil.createInvoiceItem(fixedPriceInvoiceItem, context); + + final InvoiceItemModelDao savedItem = invoiceUtil.getInvoiceItemById(fixedPriceInvoiceItem.getId(), context); + assertSameInvoiceItem(fixedPriceInvoiceItem, savedItem); + } + private void createAndVerifyExternalCharge(final BigDecimal amount, final Currency currency) throws EntityPersistenceException { final InvoiceItem externalChargeInvoiceItem = new ExternalChargeInvoiceItem(UUID.randomUUID(), account.getId(), UUID.randomUUID(), UUID.randomUUID().toString(), new LocalDate(2012, 4, 1), new LocalDate(2012, 5, 1), amount, currency, null);
      ['invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      6,434,529
      1,203,210
      139,094
      1,027
      533
      113
      7
      1
      156
      21
      46
      1
      0
      0
      1970-01-01T00:26:42
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      246
      killbill/killbill/1427/1422
      killbill
      killbill
      https://github.com/killbill/killbill/issues/1422
      https://github.com/killbill/killbill/pull/1427
      https://github.com/killbill/killbill/pull/1427
      1
      fixes
      Search endpoint issue
      ``` GET http://127.0.0.1:8080/1.0/kb/accounts/search/john?offset=0&limit=1&accountWithBalance=true&accountWithBalanceAndCBA=false ``` Results in: ``` org.glassfish.jersey.server.internal.process.MappableException: java.lang.IllegalArgumentException: The template variable 'searchKey' has no value ``` It looks like we need to update `JaxrsUriBuilder` and pass the search key as such (instead of params): ``` uriBuilder.resolveTemplate("searchKey", "john") ``` This is likely a regression from https://github.com/killbill/killbill/issues/1384.
      535e3f5278786dae29bef6da40bd0ca1cff46426
      d7661c8d75f73248928f0e2b1e5c542f428e4b1f
      https://github.com/killbill/killbill/compare/535e3f5278786dae29bef6da40bd0ca1cff46426...d7661c8d75f73248928f0e2b1e5c542f428e4b1f
      diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java index 0d414e234a..f86d400bf5 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java @@ -230,9 +230,14 @@ public class AccountResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<Account> accounts = accountUserApi.getAccounts(offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, "getAccounts", accounts.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(), - QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, + "getAccounts", + accounts.getNextOffset(), + limit, + ImmutableMap.<String, String>of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(), + QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of()); return buildStreamingPaginationResponse(accounts, new Function<Account, AccountJson>() { @Override @@ -260,10 +265,14 @@ public class AccountResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<Account> accounts = accountUserApi.searchAccounts(searchKey, offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, "searchAccounts", accounts.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(), - QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, + "searchAccounts", + accounts.getNextOffset(), + limit, + ImmutableMap.<String, String>of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(), + QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of("searchKey", searchKey)); return buildStreamingPaginationResponse(accounts, new Function<Account, AccountJson>() { @Override diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java index 3f7afc8d8c..ed30c1b7bf 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java @@ -313,6 +313,7 @@ public class AdminResource extends JaxRsResourceBase { "triggerInvoiceGenerationForParkedAccounts", tags.getNextOffset(), limit, + ImmutableMap.<String, String>of(), ImmutableMap.<String, String>of()); return Response.status(Status.OK) .entity(json) diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java index ea2d0a1180..5a15ec0952 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java @@ -193,7 +193,7 @@ public class BundleResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<SubscriptionBundle> bundles = subscriptionApi.getSubscriptionBundles(offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, "getBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, "getBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of()); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); return buildStreamingPaginationResponse(bundles, new Function<SubscriptionBundle, BundleJson>() { @@ -228,8 +228,7 @@ public class BundleResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<SubscriptionBundle> bundles = subscriptionApi.searchSubscriptionBundles(searchKey, offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, "searchBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(BundleResource.class,"searchBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey)); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); return buildStreamingPaginationResponse(bundles, new Function<SubscriptionBundle, BundleJson>() { diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java index 271042051a..b273aa6091 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java @@ -98,7 +98,7 @@ public class CustomFieldResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<CustomField> customFields = customFieldUserApi.getCustomFields(offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "getCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "getCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of()); return buildStreamingPaginationResponse(customFields, new Function<CustomField, CustomFieldJson>() { @@ -135,10 +135,15 @@ public class CustomFieldResource extends JaxRsResourceBase { customFieldUserApi.searchCustomFields(fieldName, fieldValue, ObjectType.valueOf(objectType), offset, limit, tenantContext) : customFieldUserApi.searchCustomFields(fieldName, ObjectType.valueOf(objectType), offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "searchCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of("objectType", objectType, - "fieldName", fieldName, - "fieldValue", MoreObjects.firstNonNull(fieldValue, ""), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, + "searchCustomFields", + customFields.getNextOffset(), + limit, + ImmutableMap.<String, String>of("objectType", objectType, + "fieldName", fieldName, + "fieldValue", MoreObjects.firstNonNull(fieldValue, ""), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of()); return buildStreamingPaginationResponse(customFields, new Function<CustomField, CustomFieldJson>() { @Override @@ -166,8 +171,7 @@ public class CustomFieldResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<CustomField> customFields = customFieldUserApi.searchCustomFields(searchKey, offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "searchCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "searchCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey)); return buildStreamingPaginationResponse(customFields, new Function<CustomField, CustomFieldJson>() { @Override diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java index 451811c6f3..7053e9425b 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java @@ -270,7 +270,7 @@ public class InvoiceResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws InvoiceApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<Invoice> invoices = invoiceApi.getInvoices(offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "getInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "getInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of()); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); @@ -302,8 +302,7 @@ public class InvoiceResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<Invoice> invoices = invoiceApi.searchInvoices(searchKey, offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "searchInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "searchInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey)); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); return buildStreamingPaginationResponse(invoices, new Function<Invoice, InvoiceJson>() { diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java index 5402912ebe..605bc77310 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java @@ -168,8 +168,13 @@ public class PaymentMethodResource extends JaxRsResourceBase { paymentMethods = paymentApi.getPaymentMethods(offset, limit, pluginName, withPluginInfo, pluginProperties, tenantContext); } - final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, "getPaymentMethods", paymentMethods.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, + "getPaymentMethods", + paymentMethods.getNextOffset(), + limit, + ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of()); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); final Map<UUID, Account> accounts = new HashMap<UUID, Account>(); @@ -226,9 +231,13 @@ public class PaymentMethodResource extends JaxRsResourceBase { paymentMethods = paymentApi.searchPaymentMethods(searchKey, offset, limit, pluginName, withPluginInfo, pluginProperties, tenantContext); } - final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, "searchPaymentMethods", paymentMethods.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, + "searchPaymentMethods", + paymentMethods.getNextOffset(), + limit, + ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of("searchKey", searchKey)); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); final Map<UUID, Account> accounts = new HashMap<UUID, Account>(); diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java index bbe6e4aa62..99934df39e 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java @@ -178,8 +178,13 @@ public class PaymentResource extends ComboPaymentResource { payments = paymentApi.getPayments(offset, limit, pluginName, withPluginInfo, withAttempts, pluginProperties, tenantContext); } - final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, "getPayments", payments.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, + "getPayments", + payments.getNextOffset(), + limit, + ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of()); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); return buildStreamingPaginationResponse(payments, @@ -224,9 +229,13 @@ public class PaymentResource extends ComboPaymentResource { payments = paymentApi.searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, withAttempts, pluginProperties, tenantContext); } - final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, "searchPayments", payments.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, + "searchPayments", + payments.getNextOffset(), + limit, + ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName), + QUERY_AUDIT, auditMode.getLevel().toString()), + ImmutableMap.<String, String>of("searchKey", searchKey)); final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>()); return buildStreamingPaginationResponse(payments, diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java index 9762fb8c05..bb76391d56 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java @@ -98,7 +98,7 @@ public class TagResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<Tag> tags = tagUserApi.getTags(offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "getTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "getTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of()); final Map<UUID, TagDefinition> tagDefinitionsCache = new HashMap<UUID, TagDefinition>(); for (final TagDefinition tagDefinition : tagUserApi.getTagDefinitions(tenantContext)) { @@ -132,8 +132,7 @@ public class TagResource extends JaxRsResourceBase { @javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException { final TenantContext tenantContext = context.createTenantContextNoAccountId(request); final Pagination<Tag> tags = tagUserApi.searchTags(searchKey, offset, limit, tenantContext); - final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "searchTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey, - QUERY_AUDIT, auditMode.getLevel().toString())); + final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "searchTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey)); final Map<UUID, TagDefinition> tagDefinitionsCache = new HashMap<UUID, TagDefinition>(); for (final TagDefinition tagDefinition : tagUserApi.getTagDefinitions(tenantContext)) { tagDefinitionsCache.put(tagDefinition.getId(), tagDefinition); diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java index 6d9f9b666c..d57cb06701 100644 --- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java +++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java @@ -117,7 +117,12 @@ public class JaxrsUriBuilder { return objectId != null ? uriBuilder.build(objectId) : uriBuilder.build(); } - public URI nextPage(final Class<? extends JaxrsResource> theClass, final String getMethodName, final Long nextOffset, final Long limit, final Map<String, String> params) { + public URI nextPage(final Class<? extends JaxrsResource> theClass, + final String getMethodName, + final Long nextOffset, + final Long limit, + final Map<String, String> queryParams, + final Map<String, String> pathParams) { if (nextOffset == null || limit == null) { // End of pagination? return null; @@ -125,8 +130,11 @@ public class JaxrsUriBuilder { final UriBuilder uriBuilder = getUriBuilder(theClass, getMethodName).queryParam(JaxRsResourceBase.QUERY_SEARCH_OFFSET, nextOffset) .queryParam(JaxRsResourceBase.QUERY_SEARCH_LIMIT, limit); - for (final String key : params.keySet()) { - uriBuilder.queryParam(key, params.get(key)); + for (final String key : queryParams.keySet()) { + uriBuilder.queryParam(key, queryParams.get(key)); + } + for (final String key : pathParams.keySet()) { + uriBuilder.resolveTemplate(key, pathParams.get(key)); } return uriBuilder.build(); } diff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java index d6bbd1b5d6..46dc3cc8bb 100644 --- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java +++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java @@ -118,13 +118,27 @@ public class TestAccount extends TestJaxrsBase { public void testAccountOk() throws Exception { final Account input = createAccount(); + // Create a second account (https://github.com/killbill/killbill/issues/1422 regression testing) + final Account secondAccount = createAccount(); + final Account retrievedSecondAccount = accountApi.getAccountByKey(secondAccount.getExternalKey(), requestOptions); + Assert.assertEquals(secondAccount, retrievedSecondAccount); + // Retrieves by external key final Account retrievedAccount = accountApi.getAccountByKey(input.getExternalKey(), requestOptions); - Assert.assertTrue(retrievedAccount.equals(input)); + Assert.assertEquals(input, retrievedAccount); // Try search endpoint searchAccount(input, retrievedAccount); + // Force limit=1 (https://github.com/killbill/killbill/issues/1422 regression testing) + final Accounts allAccounts = accountApi.searchAccounts(input.getCompany(), 0L, 1L, false, false, AuditLevel.NONE, requestOptions); + // Company name is the same for both accounts + Assert.assertEquals(allAccounts.size(), 1); + Assert.assertEquals(allAccounts.get(0).getExternalKey(), retrievedAccount.getExternalKey()); + final Accounts secondPage = allAccounts.getNext(); + Assert.assertEquals(secondPage.size(), 1); + Assert.assertEquals(secondPage.get(0).getExternalKey(), retrievedSecondAccount.getExternalKey()); + // Update Account final Account newInput = new Account(input.getAccountId(), "zozo", 4, input.getExternalKey(), "[email protected]", 18, @@ -445,9 +459,6 @@ public class TestAccount extends TestJaxrsBase { // Search by email doSearchAccount(input.getEmail(), output); - // Search by company name - doSearchAccount(input.getCompany(), output); - // Search by external key. // Note: we will always find a match since we don't update it final List<Account> accountsByExternalKey = accountApi.searchAccounts(input.getExternalKey(), requestOptions);
      ['jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java', 'profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java']
      {'.java': 10}
      10
      10
      0
      0
      10
      6,492,754
      1,215,206
      140,489
      1,042
      15,066
      2,117
      109
      9
      563
      46
      148
      17
      2
      3
      1970-01-01T00:26:58
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      245
      killbill/killbill/1530/1528
      killbill
      killbill
      https://github.com/killbill/killbill/issues/1528
      https://github.com/killbill/killbill/pull/1530
      https://github.com/killbill/killbill/pull/1530#discussion_r751898548
      1
      close
      Pending subscription shows a `PENDING` state after being canceled
      Scenario: 1. Create a subscription with an future start (billing) date -> `PENDING` state 2. Cancel the subscription immediately -> This will default to the future start date 3. Fetch the subscription and check the state -> `CANCELLED` state It seems that in step 3. `state` is incorrectly showing `PENDING`
      2b80b0445c7baf1f613425bb236a8cb36f1f377a
      9890c11b6b4cdcdb5c3196f890fa672cb250da44
      https://github.com/killbill/killbill/compare/2b80b0445c7baf1f613425bb236a8cb36f1f377a...9890c11b6b4cdcdb5c3196f890fa672cb250da44
      diff --git a/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java b/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java index 1a9e0cfa83..157269856b 100644 --- a/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java +++ b/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java @@ -184,6 +184,7 @@ public class DefaultSubscriptionBase extends EntityBase implements SubscriptionB throw new IllegalStateException("Should return a valid EntitlementState"); } + @Override public EntitlementSourceType getSourceType() { if (transitions == null) { diff --git a/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java b/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java index aa74d92dc7..3d7680b140 100644 --- a/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java +++ b/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java @@ -509,17 +509,22 @@ public class TestUserApiCancel extends SubscriptionTestSuiteWithEmbeddedDB { assertEquals(subscription.getStartDate().compareTo(startDate.toDateTime(accountData.getReferenceTime())), 0); subscription.cancelWithPolicy(BillingActionPolicy.IMMEDIATE, callContext); + + final DefaultSubscriptionBase subscription2 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext); + assertEquals(subscription2.getStartDate().compareTo(subscription.getStartDate()), 0); + assertEquals(subscription2.getState(), Entitlement.EntitlementState.PENDING); testListener.pushExpectedEvents(NextEvent.CREATE, NextEvent.CANCEL); clock.addDays(5); assertListenerStatus(); - final DefaultSubscriptionBase subscription2 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext); - assertEquals(subscription2.getStartDate().compareTo(subscription.getStartDate()), 0); - assertEquals(subscription2.getState(), Entitlement.EntitlementState.CANCELLED); - assertNull(subscription2.getCurrentPlan()); + final DefaultSubscriptionBase subscription3 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext); + assertEquals(subscription3.getStartDate().compareTo(subscription.getStartDate()), 0); + assertEquals(subscription3.getState(), Entitlement.EntitlementState.CANCELLED); + assertNull(subscription3.getCurrentPlan()); } - + + @Test(groups = "slow", description="See https://github.com/killbill/killbill/issues/1207") public void testDoubleFutureLaterCancellation() throws SubscriptionBaseApiException {
      ['subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java', 'subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java']
      {'.java': 2}
      2
      2
      0
      0
      2
      6,580,195
      1,232,435
      142,320
      1,051
      1
      1
      1
      1
      313
      50
      72
      6
      0
      0
      1970-01-01T00:27:17
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      251
      killbill/killbill/1075/1074
      killbill
      killbill
      https://github.com/killbill/killbill/issues/1074
      https://github.com/killbill/killbill/pull/1075
      https://github.com/killbill/killbill/pull/1075
      1
      fixes
      Wrong computed invoice target date for non-UTC TZ
      See [mailing-list thread](https://groups.google.com/forum/#!msg/killbilling-users/ChJ7DeOQCzk/BQzCL5E0BAAJ).
      938aa3e7d3c8c980cfa3b9416927ca7ae69e2dd9
      b6860e565acc632e859e67ab72721f9a06d7aef1
      https://github.com/killbill/killbill/compare/938aa3e7d3c8c980cfa3b9416927ca7ae69e2dd9...b6860e565acc632e859e67ab72721f9a06d7aef1
      diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java index a7140c378f..0e8cd1a603 100644 --- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java +++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java @@ -426,15 +426,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen return (DefaultSubscriptionBase) sub; } - protected Account createAccountWithOsgiPaymentMethod(final AccountData accountData) throws Exception { - return createAccountWithPaymentMethod(accountData, BeatrixIntegrationModule.OSGI_PLUGIN_NAME); - } - protected Account createAccountWithNonOsgiPaymentMethod(final AccountData accountData) throws Exception { - return createAccountWithPaymentMethod(accountData, BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME); - } - - private Account createAccountWithPaymentMethod(final AccountData accountData, final String paymentPluginName) throws Exception { final Account account = accountUserApi.createAccount(accountData, callContext); assertNotNull(account); @@ -442,7 +434,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen final PaymentMethodPlugin info = createPaymentMethodPlugin(); - paymentApi.addPaymentMethod(account, UUID.randomUUID().toString(), paymentPluginName, true, info, PLUGIN_PROPERTIES, callContext); + paymentApi.addPaymentMethod(account, UUID.randomUUID().toString(), BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME, true, info, PLUGIN_PROPERTIES, callContext); return accountUserApi.getAccountById(account.getId(), callContext); } @@ -451,6 +443,10 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen } protected AccountData getAccountData(@Nullable final Integer billingDay) { + return getAccountData(billingDay, DateTimeZone.UTC); + } + + protected AccountData getAccountData(@Nullable final Integer billingDay, final DateTimeZone tz) { final MockAccountBuilder builder = new MockAccountBuilder() .name(UUID.randomUUID().toString().substring(1, 8)) .firstNameLength(6) @@ -460,7 +456,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen .externalKey(UUID.randomUUID().toString().substring(1, 8)) .currency(Currency.USD) .referenceTime(clock.getUTCNow()) - .timeZone(DateTimeZone.UTC); + .timeZone(tz); if (billingDay != null) { builder.billingCycleDayLocal(billingDay); } diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java index 3d5c66a248..455173d6ee 100644 --- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java +++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java @@ -1,7 +1,7 @@ /* * Copyright 2010-2013 Ning, Inc. - * Copyright 2014-2016 Groupon, Inc - * Copyright 2014-2016 The Billing Project, LLC + * Copyright 2014-2018 Groupon, Inc + * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the @@ -20,9 +20,10 @@ package org.killbill.billing.beatrix.integration; import java.util.Collection; import java.util.List; -import java.util.UUID; import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.LocalDate; import org.killbill.billing.ObjectType; import org.killbill.billing.account.api.Account; import org.killbill.billing.api.TestApiListener.NextEvent; @@ -30,13 +31,8 @@ import org.killbill.billing.catalog.api.BillingPeriod; import org.killbill.billing.catalog.api.ProductCategory; import org.killbill.billing.entitlement.api.DefaultEntitlement; import org.killbill.billing.invoice.api.Invoice; -import org.killbill.billing.invoice.api.InvoiceStatus; import org.killbill.billing.invoice.api.InvoiceUserApi; -import org.killbill.billing.util.api.TagApiException; -import org.killbill.billing.util.api.TagDefinitionApiException; import org.killbill.billing.util.api.TagUserApi; -import org.killbill.billing.util.tag.ControlTagType; -import org.killbill.billing.util.tag.Tag; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -102,4 +98,47 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase { assertEquals(invoices.size(), 1); } + @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/1074") + public void testAutoInvoiceOffWithTZ() throws Exception { + clock.setTime(new DateTime(2018, 12, 1, 0, 25, 0, 0)); + + account = createAccountWithNonOsgiPaymentMethod(getAccountData(null, DateTimeZone.forID("America/Los_Angeles"))); + assertEquals(account.getBillCycleDayLocal(), (Integer) 0); + + final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE); + assertNotNull(bpEntitlement); + assertEquals(accountUserApi.getAccountById(account.getId(), callContext).getBillCycleDayLocal(), (Integer) 30); + + List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext); + assertEquals(invoices.size(), 1); + assertEquals(invoices.get(0).getInvoiceItems().size(), 1); + assertEquals(invoices.get(0).getTargetDate(), new LocalDate(2018, 11, 30)); + assertEquals(invoices.get(0).getInvoiceItems().get(0).getStartDate(), new LocalDate(2018, 11, 30)); + + clock.setTime(new DateTime(2018, 12, 30, 0, 20, 0, 0)); + assertEquals(clock.getUTCToday(), new LocalDate(2018, 12, 30)); + assertEquals(clock.getUTCNow().toDateTime(account.getTimeZone()).toLocalDate(), new LocalDate(2018, 12, 29)); + // Still in trial + assertListenerStatus(); + assertEquals(entitlementApi.getEntitlementForId(bpEntitlement.getId(), callContext).getLastActivePhase().getName(), "shotgun-monthly-trial"); + assertEquals(invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext).size(), 1); + + // Adding / Removing AUTO_INVOICING_OFF shouldn't have any impact + add_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT); + remove_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.NULL_INVOICE); + + assertListenerStatus(); + assertEquals(entitlementApi.getEntitlementForId(bpEntitlement.getId(), callContext).getLastActivePhase().getName(), "shotgun-monthly-trial"); + assertEquals(invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext).size(), 1); + + busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); + clock.setTime(new DateTime(2018, 12, 31, 0, 25, 0, 0)); + assertListenerStatus(); + + invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext); + assertEquals(invoices.size(), 2); + assertEquals(invoices.get(1).getTargetDate(), new LocalDate(2018, 12, 30)); + assertEquals(invoices.get(1).getInvoiceItems().get(0).getStartDate(), new LocalDate(2018, 12, 30)); + assertEquals(invoices.get(1).getInvoiceItems().get(0).getEndDate(), new LocalDate(2019, 1, 30)); + } } diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java index f901875e05..4715f25131 100644 --- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java +++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java @@ -1,7 +1,7 @@ /* * Copyright 2010-2013 Ning, Inc. - * Copyright 2014-2017 Groupon, Inc - * Copyright 2014-2017 The Billing Project, LLC + * Copyright 2014-2018 Groupon, Inc + * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the @@ -22,21 +22,15 @@ import java.math.BigDecimal; import java.util.Collection; import org.joda.time.DateTime; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - import org.killbill.billing.ObjectType; import org.killbill.billing.account.api.Account; import org.killbill.billing.api.TestApiListener.NextEvent; import org.killbill.billing.catalog.api.BillingPeriod; -import org.killbill.billing.catalog.api.PriceListSet; import org.killbill.billing.catalog.api.ProductCategory; import org.killbill.billing.entitlement.api.DefaultEntitlement; import org.killbill.billing.invoice.api.Invoice; -import org.killbill.billing.subscription.api.user.SubscriptionBaseBundle; -import org.killbill.billing.util.config.definition.PaymentConfig; - -import com.google.inject.Inject; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -45,10 +39,8 @@ import static org.testng.Assert.assertTrue; public class TestIntegrationWithAutoPayOff extends TestIntegrationBase { private Account account; - private SubscriptionBaseBundle bundle; private String productName; private BillingPeriod term; - private String planSetName; @Override @BeforeMethod(groups = "slow") @@ -62,7 +54,6 @@ public class TestIntegrationWithAutoPayOff extends TestIntegrationBase { assertNotNull(account); productName = "Shotgun"; term = BillingPeriod.MONTHLY; - planSetName = PriceListSet.DEFAULT_PRICELIST_NAME; } @Test(groups = "slow") @@ -242,7 +233,6 @@ public class TestIntegrationWithAutoPayOff extends TestIntegrationBase { } - private void addDelayBceauseOfLackOfCorrectSynchro() { // TODO When removing the tag, the payment system will schedule retries for payments that are in non terminal state // The issue is that at this point we know the event went on the bus but we don't know if the listener in payment completed diff --git a/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java b/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java index 767cd30d00..2bc350b107 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java @@ -326,7 +326,7 @@ public class InvoiceDispatcher { LocalDate inputTargetDate = inputTargetDateMaybeNull; // A null inputTargetDate is only allowed in UPCOMING_INVOICE dryRun mode to have the system compute it if (inputTargetDate == null && !upcomingInvoiceDryRun) { - inputTargetDate = clock.getUTCToday(); + inputTargetDate = context.toLocalDate(clock.getUTCNow()); } Preconditions.checkArgument(inputTargetDate != null || upcomingInvoiceDryRun, "inputTargetDate is required in non dryRun mode");
      ['beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java', 'invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java', 'beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java', 'beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      6,223,188
      1,167,835
      135,115
      1,018
      122
      25
      2
      1
      108
      3
      39
      1
      1
      0
      1970-01-01T00:25:44
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      257
      killbill/killbill/405/118
      killbill
      killbill
      https://github.com/killbill/killbill/issues/118
      https://github.com/killbill/killbill/pull/405
      https://github.com/killbill/killbill/pull/405
      1
      fixed
      Invoice formatter display wrong currency symbol
      First of all, the code is using the locale to set the currency formatter. For instance in DefaultInvoiceFormatter: ``` public String getFormattedPaidAmount() { final NumberFormat number = NumberFormat.getCurrencyInstance(locale); return number.format(getPaidAmount().doubleValue()); } ``` The number format returned is based on the locale which is 'good' so it knows how to display the dots, comma, ... but wrong it comes to display the currency symbol.
      2eda0f052c5c04c53b18bf249c02ba489881349b
      43afb0759795e3ffdf748925e592b65738e00f25
      https://github.com/killbill/killbill/compare/2eda0f052c5c04c53b18bf249c02ba489881349b...43afb0759795e3ffdf748925e592b65738e00f25
      diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java index 8ae278acfc..a3fed268b4 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java @@ -17,24 +17,22 @@ package org.killbill.billing.invoice.template.formatters; import java.math.BigDecimal; -import java.text.NumberFormat; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.UUID; +import org.joda.money.CurrencyUnit; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.killbill.billing.callcontext.InternalTenantContext; -import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory; -import org.killbill.billing.tenant.api.TenantInternalApi; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.currency.api.CurrencyConversion; import org.killbill.billing.currency.api.CurrencyConversionApi; @@ -45,17 +43,18 @@ import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.api.InvoiceItemType; import org.killbill.billing.invoice.api.InvoicePayment; import org.killbill.billing.invoice.api.formatters.InvoiceFormatter; +import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory; import org.killbill.billing.invoice.model.CreditAdjInvoiceItem; import org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem; import org.killbill.billing.invoice.model.DefaultInvoice; import org.killbill.billing.util.template.translation.TranslatorConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; -import static org.killbill.billing.util.DefaultAmountFormatter.round; - /** * Format invoice fields */ @@ -70,8 +69,11 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter { private final CurrencyConversionApi currencyConversionApi; private final InternalTenantContext context; private final ResourceBundleFactory bundleFactory; + private Map<java.util.Currency, Locale> currencyLocaleMap; - public DefaultInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, final CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory, final InternalTenantContext context) { + public DefaultInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, + final CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory, + final InternalTenantContext context, Map<java.util.Currency, Locale> currencyLocaleMap) { this.config = config; this.invoice = invoice; this.dateFormatter = DateTimeFormat.mediumDate().withLocale(locale); @@ -79,6 +81,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter { this.currencyConversionApi = currencyConversionApi; this.bundleFactory = bundleFactory; this.context = context; + this.currencyLocaleMap = currencyLocaleMap; } @Override @@ -198,35 +201,56 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter { @Override public BigDecimal getChargedAmount() { - return round(Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO)); + return Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO); } @Override public BigDecimal getOriginalChargedAmount() { - return round(Objects.firstNonNull(invoice.getOriginalChargedAmount(), BigDecimal.ZERO)); + return Objects.firstNonNull(invoice.getOriginalChargedAmount(), BigDecimal.ZERO); } @Override public BigDecimal getBalance() { - return round(Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO)); + return Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO); } @Override public String getFormattedChargedAmount() { - final NumberFormat number = NumberFormat.getCurrencyInstance(locale); - return number.format(getChargedAmount().doubleValue()); + return getFormattedAmountByLocaleAndInvoiceCurrency(getChargedAmount()); } @Override public String getFormattedPaidAmount() { - final NumberFormat number = NumberFormat.getCurrencyInstance(locale); - return number.format(getPaidAmount().doubleValue()); + return getFormattedAmountByLocaleAndInvoiceCurrency(getPaidAmount()); } @Override public String getFormattedBalance() { - final NumberFormat number = NumberFormat.getCurrencyInstance(locale); - return number.format(getBalance().doubleValue()); + return getFormattedAmountByLocaleAndInvoiceCurrency(getBalance()); + } + + // Returns the formatted amount with the correct currency symbol that is get from the invoice currency. + private String getFormattedAmountByLocaleAndInvoiceCurrency(BigDecimal amount) { + + String invoiceCurrencyCode = invoice.getCurrency().toString(); + CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode); + + final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); + DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); + dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode()); + + try { + final java.util.Currency currency = java.util.Currency.getInstance(invoiceCurrencyCode); + dfs.setCurrencySymbol(currency.getSymbol(currencyLocaleMap.get(currency))); + } catch (Exception e) { + dfs.setCurrencySymbol(currencyUnit.getSymbol(locale)); + } + + numberFormatter.setDecimalFormatSymbols(dfs); + numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits()); + numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits()); + + return numberFormatter.format(amount.doubleValue()); } @Override @@ -288,7 +312,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter { @Override public BigDecimal getPaidAmount() { - return round(Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO)); + return Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO); } @Override @@ -337,13 +361,18 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter { return invoice; } + @SuppressWarnings("UnusedDeclaration") + protected Map<java.util.Currency, Locale> getCurrencyLocaleMap() { + return currencyLocaleMap; + } + @Override public BigDecimal getCreditedAmount() { - return round(Objects.firstNonNull(invoice.getCreditedAmount(), BigDecimal.ZERO)); + return Objects.firstNonNull(invoice.getCreditedAmount(), BigDecimal.ZERO); } @Override public BigDecimal getRefundedAmount() { - return round(Objects.firstNonNull(invoice.getRefundedAmount(), BigDecimal.ZERO)); + return Objects.firstNonNull(invoice.getRefundedAmount(), BigDecimal.ZERO); } } diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java index 890fb30338..6496df73f5 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java @@ -16,7 +16,10 @@ package org.killbill.billing.invoice.template.formatters; +import java.util.Currency; +import java.util.HashMap; import java.util.Locale; +import java.util.Map; import org.killbill.billing.callcontext.InternalTenantContext; import org.killbill.billing.currency.api.CurrencyConversionApi; @@ -24,7 +27,6 @@ import org.killbill.billing.invoice.api.Invoice; import org.killbill.billing.invoice.api.formatters.InvoiceFormatter; import org.killbill.billing.invoice.api.formatters.InvoiceFormatterFactory; import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory; -import org.killbill.billing.tenant.api.TenantInternalApi; import org.killbill.billing.util.template.translation.TranslatorConfig; public class DefaultInvoiceFormatterFactory implements InvoiceFormatterFactory { @@ -32,6 +34,17 @@ public class DefaultInvoiceFormatterFactory implements InvoiceFormatterFactory { @Override public InvoiceFormatter createInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory, final InternalTenantContext context) { - return new DefaultInvoiceFormatter(config, invoice, locale, currencyConversionApi, bundleFactory, context); + + // this initialization relies on System.currentTimeMillis() instead of the Kill Bill clock (it won't be accurate when moving the clock) + Map<Currency, Locale> currencyLocaleMap = new HashMap<Currency, Locale>(); + for (Locale localeItem : Locale.getAvailableLocales()) { + try { + java.util.Currency currency = java.util.Currency.getInstance(localeItem); + currencyLocaleMap.put(currency, localeItem); + }catch (Exception e){ + } + } + + return new DefaultInvoiceFormatter(config, invoice, locale, currencyConversionApi, bundleFactory, context, currencyLocaleMap); } } diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java index 51ddcc637a..5516c8ca90 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java @@ -36,14 +36,10 @@ import org.killbill.billing.util.LocaleUtils; import org.killbill.billing.util.template.translation.DefaultCatalogTranslator; import org.killbill.billing.util.template.translation.Translator; import org.killbill.billing.util.template.translation.TranslatorConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.google.common.base.Objects; import com.google.common.base.Strings; -import static org.killbill.billing.util.DefaultAmountFormatter.round; - /** * Format invoice item fields */ @@ -71,7 +67,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter { @Override public BigDecimal getAmount() { - return round(Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO)); + return Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO); } @Override @@ -168,7 +164,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter { @Override public BigDecimal getRate() { - return round(BigDecimal.ZERO); + return BigDecimal.ZERO; } @Override diff --git a/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java b/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java index df0a9d7a08..6d5cc0afb0 100644 --- a/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java +++ b/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java @@ -34,7 +34,6 @@ import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.api.InvoiceItemType; import org.killbill.billing.invoice.api.InvoicePaymentType; import org.killbill.billing.invoice.api.formatters.InvoiceFormatter; -import org.killbill.billing.invoice.api.formatters.InvoiceFormatterFactory; import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory.ResourceBundleType; import org.killbill.billing.invoice.model.CreditAdjInvoiceItem; import org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem; @@ -89,7 +88,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB { Assert.assertEquals(invoice.getCreditedAmount().doubleValue(), 0.00); // Verify the merge - final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext); + final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext, getAvailableLocales()); final List<InvoiceItem> invoiceItems = formatter.getInvoiceItems(); Assert.assertEquals(invoiceItems.size(), 1); Assert.assertEquals(invoiceItems.get(0).getInvoiceItemType(), InvoiceItemType.FIXED); @@ -143,7 +142,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB { Assert.assertEquals(invoice.getRefundedAmount().doubleValue(), -1.00); // Verify the merge - final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext); + final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext, getAvailableLocales()); final List<InvoiceItem> invoiceItems = formatter.getInvoiceItems(); Assert.assertEquals(invoiceItems.size(), 4); Assert.assertEquals(invoiceItems.get(0).getInvoiceItemType(), InvoiceItemType.FIXED); @@ -160,7 +159,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB { public void testFormattedAmount() throws Exception { final FixedPriceInvoiceItem fixedItemEUR = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), - new LocalDate(), new BigDecimal("1499.95"), Currency.EUR); + new LocalDate(), new BigDecimal("1499.952"), Currency.EUR); final Invoice invoiceEUR = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.EUR); invoiceEUR.addInvoiceItem(fixedItemEUR); @@ -186,6 +185,158 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB { Locale.FRANCE); } + @Test(groups = "fast") + public void testFormattedAmountFranceAndJPY() throws Exception { + + final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null, + UUID.randomUUID().toString(), UUID.randomUUID().toString(), + new LocalDate(), new BigDecimal("1500.00"), Currency.JPY); + final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.JPY); + invoice.addInvoiceItem(fixedItem); + + checkOutput(invoice, + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" + + "</tr>", + "<tr>\\n" + + " <td class=\\"amount\\"><strong>1 500 ¥</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>0 ¥</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>1 500 ¥</strong></td>\\n" + + "</tr>", + Locale.FRANCE); + } + + @Test(groups = "fast") + public void testFormattedAmountUSAndBTC() throws Exception { + + final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null, + UUID.randomUUID().toString(), UUID.randomUUID().toString(), + new LocalDate(), new BigDecimal("1105.28843439"), Currency.BTC); + final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.BTC); + invoice.addInvoiceItem(fixedItem); + + checkOutput(invoice, + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" + + "</tr>", + "<tr>\\n" + + " <td class=\\"amount\\"><strong>BTC1,105.28843439</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>BTC0.00000000</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>BTC1,105.28843439</strong></td>\\n" + + "</tr>", + Locale.US); + } + + @Test(groups = "fast") + public void testFormattedAmountUSAndEUR() throws Exception { + final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null, + UUID.randomUUID().toString(), UUID.randomUUID().toString(), + new LocalDate(), new BigDecimal("2635.14"), Currency.EUR); + final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.EUR); + invoice.addInvoiceItem(fixedItem); + + checkOutput(invoice, + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" + + "</tr>", + "<tr>\\n" + + " <td class=\\"amount\\"><strong>€2,635.14</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>€0.00</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>€2,635.14</strong></td>\\n" + + "</tr>", + Locale.US); + } + + @Test(groups = "fast") + public void testFormattedAmountUSAndBRL() throws Exception { + final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null, + UUID.randomUUID().toString(), UUID.randomUUID().toString(), + new LocalDate(), new BigDecimal("2635.14"), Currency.BRL); + final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.BRL); + invoice.addInvoiceItem(fixedItem); + + checkOutput(invoice, + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" + + "</tr>", + "<tr>\\n" + + " <td class=\\"amount\\"><strong>R$2,635.14</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>R$0.00</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>R$2,635.14</strong></td>\\n" + + "</tr>", + Locale.US); + } + + @Test(groups = "fast") + public void testFormattedAmountUSAndGBP() throws Exception { + final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null, + UUID.randomUUID().toString(), UUID.randomUUID().toString(), + new LocalDate(), new BigDecimal("1499.95"), Currency.GBP); + final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.GBP); + invoice.addInvoiceItem(fixedItem); + + checkOutput(invoice, + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" + + "</tr>", + "<tr>\\n" + + " <td class=\\"amount\\"><strong>£1,499.95</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>£0.00</strong></td>\\n" + + "</tr>\\n" + + "<tr>\\n" + + " <td class=\\"amount\\"><strong>£1,499.95</strong></td>\\n" + + "</tr>", + Locale.US); + } + @Test(groups = "fast") public void testProcessedCurrencyExists() throws Exception { final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), clock.getUTCNow(), UUID.randomUUID(), new Integer(234), new LocalDate(), new LocalDate(), Currency.BRL, Currency.USD, false); @@ -329,7 +480,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB { data.put("text", translator); - data.put("invoice", new DefaultInvoiceFormatter(config, invoice, Locale.US, currencyConversionApi, resourceBundleFactory, internalCallContext)); + data.put("invoice", new DefaultInvoiceFormatter(config, invoice, Locale.US, currencyConversionApi, resourceBundleFactory, internalCallContext, getAvailableLocales())); final String formattedText = templateEngine.executeTemplateText(template, data); @@ -338,9 +489,23 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB { private void checkOutput(final Invoice invoice, final String template, final String expected, final Locale locale) { final Map<String, Object> data = new HashMap<String, Object>(); - data.put("invoice", new DefaultInvoiceFormatter(config, invoice, locale, null, resourceBundleFactory, internalCallContext)); + data.put("invoice", new DefaultInvoiceFormatter(config, invoice, locale, null, resourceBundleFactory, internalCallContext, getAvailableLocales())); final String formattedText = templateEngine.executeTemplateText(template, data); Assert.assertEquals(formattedText, expected); } + + private Map<java.util.Currency, Locale> getAvailableLocales() { + Map<java.util.Currency, Locale> currencyLocaleMap = new HashMap<java.util.Currency, Locale>(); + + currencyLocaleMap.put(java.util.Currency.getInstance(Locale.US), Locale.US); + currencyLocaleMap.put(java.util.Currency.getInstance(Locale.FRANCE), Locale.FRANCE); + currencyLocaleMap.put(java.util.Currency.getInstance(Locale.JAPAN), Locale.JAPAN); + currencyLocaleMap.put(java.util.Currency.getInstance(Locale.UK), Locale.UK); + Locale brLocale = new Locale("pt", "BR"); + currencyLocaleMap.put(java.util.Currency.getInstance(brLocale), brLocale); + + return currencyLocaleMap; + } + }
      ['invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java', 'invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java', 'invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java', 'invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      4,510,922
      859,544
      101,923
      872
      5,674
      993
      96
      3
      475
      63
      96
      12
      0
      1
      1970-01-01T00:24:04
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      253
      killbill/killbill/1016/1015
      killbill
      killbill
      https://github.com/killbill/killbill/issues/1015
      https://github.com/killbill/killbill/pull/1016
      https://github.com/killbill/killbill/pull/1016
      1
      fixes
      Possible double payments with invoice payments in UNKNOWN state
      Scenario: 1. Invoice payment in `UNKNOWN` state 2. Trigger a new successful payment by calling `invoicePaymentApi.createPurchaseForInvoicePayment` 3. Fix the original payment (`UNKNOWN -> SUCCESS`) Result: the invoice ends up double payed and the invoice balance is negative (absolute value is the amount of the payment).
      08ffcbbd2cf366a9f26603248384fab50722da14
      29a6f930250b640dd511002a6a60597509e24a10
      https://github.com/killbill/killbill/compare/08ffcbbd2cf366a9f26603248384fab50722da14...29a6f930250b640dd511002a6a60597509e24a10
      diff --git a/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java b/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java index ffe6ad5e9a..e6534c81d5 100644 --- a/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java +++ b/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java @@ -84,5 +84,7 @@ public interface InvoiceInternalApi { public List<InvoicePayment> getInvoicePaymentsByAccount(UUID accountId, TenantContext context); + public List<InvoicePayment> getInvoicePaymentsByInvoice(UUID invoiceId, InternalTenantContext context); + public InvoicePayment getInvoicePaymentByCookieId(String cookieId, TenantContext context); } diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java index b00c5e308a..4eca162eba 100644 --- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java +++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java @@ -1095,4 +1095,139 @@ public class TestInvoicePayment extends TestIntegrationBase { Assert.assertEquals(payments.get(0).getTransactions().size(), 1); } + + @Test(groups = "slow") + public void testWithUNKNOWNPaymentFixedToSuccess() throws Exception { + // Verify integration with Overdue in that particular test + final String configXml = "<overdueConfig>" + + " <accountOverdueStates>" + + " <initialReevaluationInterval>" + + " <unit>DAYS</unit><number>1</number>" + + " </initialReevaluationInterval>" + + " <state name=\\"OD1\\">" + + " <condition>" + + " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + + " <unit>DAYS</unit><number>1</number>" + + " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + + " </condition>" + + " <externalMessage>Reached OD1</externalMessage>" + + " <blockChanges>true</blockChanges>" + + " <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>" + + " </state>" + + " </accountOverdueStates>" + + "</overdueConfig>"; + final InputStream is = new ByteArrayInputStream(configXml.getBytes()); + final DefaultOverdueConfig config = XMLLoader.getObjectFromStreamNoValidation(is, DefaultOverdueConfig.class); + overdueConfigCache.loadDefaultOverdueConfig(config); + + clock.setDay(new LocalDate(2012, 4, 1)); + + final AccountData accountData = getAccountData(1); + final Account account = createAccountWithNonOsgiPaymentMethod(accountData); + accountChecker.checkAccount(account.getId(), accountData, callContext); + + checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId()); + + paymentPlugin.makeNextPaymentUnknown(); + + final DefaultEntitlement baseEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE); + + addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_PLUGIN_ERROR, NextEvent.INVOICE_PAYMENT_ERROR); + + invoiceChecker.checkChargedThroughDate(baseEntitlement.getId(), new LocalDate(2012, 6, 1), callContext); + + final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext); + assertEquals(invoices.size(), 2); + + final Invoice invoice1 = invoices.get(0).getInvoiceItems().get(0).getInvoiceItemType() == InvoiceItemType.RECURRING ? + invoices.get(0) : invoices.get(1); + assertTrue(invoice1.getBalance().compareTo(new BigDecimal("249.95")) == 0); + assertTrue(invoice1.getPaidAmount().compareTo(BigDecimal.ZERO) == 0); + assertTrue(invoice1.getChargedAmount().compareTo(new BigDecimal("249.95")) == 0); + assertEquals(invoice1.getPayments().size(), 1); + assertEquals(invoice1.getPayments().get(0).getAmount().compareTo(BigDecimal.ZERO), 0); + assertEquals(invoice1.getPayments().get(0).getCurrency(), Currency.USD); + assertFalse(invoice1.getPayments().get(0).isSuccess()); + assertNotNull(invoice1.getPayments().get(0).getPaymentId()); + + final BigDecimal accountBalance1 = invoiceUserApi.getAccountBalance(account.getId(), callContext); + assertTrue(accountBalance1.compareTo(new BigDecimal("249.95")) == 0); + + final List<Payment> payments = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.<PluginProperty>of(), callContext); + assertEquals(payments.size(), 1); + assertEquals(payments.get(0).getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); + assertEquals(payments.get(0).getTransactions().size(), 1); + assertEquals(payments.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0); + assertEquals(payments.get(0).getTransactions().get(0).getCurrency(), Currency.USD); + assertEquals(payments.get(0).getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); + assertEquals(payments.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD); + assertEquals(payments.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.UNKNOWN); + assertEquals(payments.get(0).getPaymentAttempts().size(), 1); + assertEquals(payments.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME); + assertEquals(payments.get(0).getPaymentAttempts().get(0).getStateName(), "ABORTED"); + + // Verify account transitions to OD1 + addDaysAndCheckForCompletion(2, NextEvent.BLOCK); + checkODState("OD1", account.getId()); + + // Verify we cannot trigger double payments + try { + invoicePaymentApi.createPurchaseForInvoicePayment(account, + invoice1.getId(), + payments.get(0).getPaymentMethodId(), + null, + invoice1.getBalance(), + invoice1.getCurrency(), + clock.getUTCNow(), + null, + null, + ImmutableList.<PluginProperty>of(), + PAYMENT_OPTIONS, + callContext); + Assert.fail(); + } catch (final PaymentApiException e) { + Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode()); + assertListenerStatus(); + } + + // Transition the payment to success + final PaymentTransaction existingPaymentTransaction = payments.get(0).getTransactions().get(0); + final PaymentTransaction updatedPaymentTransaction = Mockito.mock(PaymentTransaction.class); + Mockito.when(updatedPaymentTransaction.getId()).thenReturn(existingPaymentTransaction.getId()); + Mockito.when(updatedPaymentTransaction.getExternalKey()).thenReturn(existingPaymentTransaction.getExternalKey()); + Mockito.when(updatedPaymentTransaction.getTransactionType()).thenReturn(existingPaymentTransaction.getTransactionType()); + Mockito.when(updatedPaymentTransaction.getProcessedAmount()).thenReturn(new BigDecimal("249.95")); + Mockito.when(updatedPaymentTransaction.getProcessedCurrency()).thenReturn(existingPaymentTransaction.getCurrency()); + busHandler.pushExpectedEvents(NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT, NextEvent.BLOCK); + adminPaymentApi.fixPaymentTransactionState(payments.get(0), updatedPaymentTransaction, TransactionStatus.SUCCESS, null, null, ImmutableList.<PluginProperty>of(), callContext); + assertListenerStatus(); + + checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId()); + + final Invoice invoice2 = invoiceUserApi.getInvoice(invoice1.getId(), callContext); + assertTrue(invoice2.getBalance().compareTo(BigDecimal.ZERO) == 0); + assertTrue(invoice2.getPaidAmount().compareTo(new BigDecimal("249.95")) == 0); + assertTrue(invoice2.getChargedAmount().compareTo(new BigDecimal("249.95")) == 0); + assertEquals(invoice2.getPayments().size(), 1); + assertEquals(invoice2.getPayments().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0); + assertEquals(invoice2.getPayments().get(0).getCurrency(), Currency.USD); + assertTrue(invoice2.getPayments().get(0).isSuccess()); + assertNotNull(invoice2.getPayments().get(0).getPaymentId()); + + final BigDecimal accountBalance2 = invoiceUserApi.getAccountBalance(account.getId(), callContext); + assertTrue(accountBalance2.compareTo(BigDecimal.ZERO) == 0); + + final List<Payment> payments2 = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.<PluginProperty>of(), callContext); + assertEquals(payments2.size(), 1); + assertEquals(payments2.get(0).getPurchasedAmount().compareTo(new BigDecimal("249.95")), 0); + assertEquals(payments2.get(0).getTransactions().size(), 1); + assertEquals(payments2.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0); + assertEquals(payments2.get(0).getTransactions().get(0).getCurrency(), Currency.USD); + assertEquals(payments2.get(0).getTransactions().get(0).getProcessedAmount().compareTo(new BigDecimal("249.95")), 0); + assertEquals(payments2.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD); + assertEquals(payments2.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); + assertEquals(payments2.get(0).getPaymentAttempts().size(), 1); + assertEquals(payments2.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME); + assertEquals(payments2.get(0).getPaymentAttempts().get(0).getStateName(), "SUCCESS"); + } } diff --git a/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java b/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java index 0f2cba226c..1b9e082849 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java @@ -217,6 +217,18 @@ public class DefaultInvoiceInternalApi implements InvoiceInternalApi { )); } + @Override + public List<InvoicePayment> getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) { + return ImmutableList.<InvoicePayment>copyOf(Collections2.transform(dao.getInvoicePaymentsByInvoice(invoiceId, context), + new Function<InvoicePaymentModelDao, InvoicePayment>() { + @Override + public InvoicePayment apply(final InvoicePaymentModelDao input) { + return new DefaultInvoicePayment(input); + } + } + )); + } + @Override public InvoicePayment getInvoicePaymentByCookieId(final String cookieId, final TenantContext context) { final InvoicePaymentModelDao invoicePaymentModelDao = dao.getInvoicePaymentByCookieId(cookieId, internalCallContextFactory.createInternalTenantContext(context.getAccountId(), ObjectType.ACCOUNT, context)); diff --git a/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java b/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java index 963e6c9cf4..cc48631f72 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java @@ -559,6 +559,16 @@ public class DefaultInvoiceDao extends EntityDaoBase<InvoiceModelDao, Invoice, I }); } + @Override + public List<InvoicePaymentModelDao> getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) { + return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<List<InvoicePaymentModelDao>>() { + @Override + public List<InvoicePaymentModelDao> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception { + return entitySqlDaoWrapperFactory.become(InvoicePaymentSqlDao.class).getAllPaymentsForInvoiceIncludedInit(invoiceId.toString(), context); + } + }); + } + @Override public InvoicePaymentModelDao getInvoicePaymentByCookieId(final String cookieId, final InternalTenantContext context) { return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<InvoicePaymentModelDao>() { diff --git a/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java b/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java index 8d4f871c8b..e7c77901b5 100644 --- a/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java +++ b/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java @@ -66,6 +66,8 @@ public interface InvoiceDao extends EntityDao<InvoiceModelDao, Invoice, InvoiceA List<InvoicePaymentModelDao> getInvoicePaymentsByAccount(InternalTenantContext context); + List<InvoicePaymentModelDao> getInvoicePaymentsByInvoice(final UUID invoiceId, InternalTenantContext context); + InvoicePaymentModelDao getInvoicePaymentByCookieId(String cookieId, InternalTenantContext internalTenantContext); BigDecimal getAccountBalance(UUID accountId, InternalTenantContext context); diff --git a/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java b/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java index b51ee616f0..32499dff55 100644 --- a/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java +++ b/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java @@ -233,6 +233,19 @@ public class MockInvoiceDao extends MockEntityDaoBase<InvoiceModelDao, Invoice, return result; } + @Override + public List<InvoicePaymentModelDao> getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) { + final List<InvoicePaymentModelDao> result = new LinkedList<InvoicePaymentModelDao>(); + synchronized (monitor) { + for (final InvoicePaymentModelDao payment : payments.values()) { + if (invoiceId.equals(payment.getInvoiceId())) { + result.add(payment); + } + } + } + return result; + } + @Override public List<InvoicePaymentModelDao> getInvoicePaymentsByAccount(final InternalTenantContext context) { diff --git a/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java b/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java index ecb7dd218c..01277a9b92 100644 --- a/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java +++ b/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java @@ -55,6 +55,7 @@ import org.killbill.billing.payment.api.PaymentApiException; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.payment.api.TransactionStatus; import org.killbill.billing.payment.api.TransactionType; +import org.killbill.billing.payment.core.janitor.IncompletePaymentTransactionTask; import org.killbill.billing.payment.dao.PaymentDao; import org.killbill.billing.payment.dao.PaymentModelDao; import org.killbill.billing.payment.dao.PaymentTransactionModelDao; @@ -321,7 +322,6 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi return new DefaultPriorPaymentControlResult(true); } - // Get account and check if it is child and payment is delegated to parent => abort final AccountData accountData = accountApi.getAccountById(invoice.getAccountId(), internalContext); @@ -340,7 +340,7 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi // Do we have a paymentMethod ? if (paymentControlPluginContext.getPaymentMethodId() == null) { - log.warn("Payment for invoiceId='{}' was not triggered, accountId='{}' doesn't have a default payment method", getInvoiceId(pluginProperties), paymentControlPluginContext.getAccountId()); + log.warn("Payment for invoiceId='{}' was not triggered, accountId='{}' doesn't have a default payment method", invoiceId, paymentControlPluginContext.getAccountId()); invoiceApi.recordPaymentAttemptCompletion(invoiceId, paymentControlPluginContext.getAmount(), paymentControlPluginContext.getCurrency(), @@ -359,6 +359,16 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi return new DefaultPriorPaymentControlResult(true); } + final List<InvoicePayment> existingInvoicePayments = invoiceApi.getInvoicePaymentsByInvoice(invoiceId, internalContext); + for (final InvoicePayment existingInvoicePayment : existingInvoicePayments) { + final List<PaymentTransactionModelDao> existingTransactions = paymentDao.getPaymentTransactionsByExternalKey(existingInvoicePayment.getPaymentCookieId(), internalContext); + for (final PaymentTransactionModelDao existingTransaction : existingTransactions) { + if (existingTransaction.getTransactionStatus() == TransactionStatus.UNKNOWN) { + log.warn("Existing paymentTransactionId='{}' for invoiceId='{}' in UNKNOWN state", existingTransaction.getId(), invoiceId); + return new DefaultPriorPaymentControlResult(true); + } + } + } // // Insert attempt row with a success = false status to implement a two-phase commit strategy and guard against scenario where payment would go through diff --git a/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java b/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java index 32bba1c8da..78004a59c5 100644 --- a/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java +++ b/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java @@ -1,7 +1,7 @@ /* * Copyright 2010-2013 Ning, Inc. - * Copyright 2014-2016 Groupon, Inc - * Copyright 2014-2016 The Billing Project, LLC + * Copyright 2014-2018 Groupon, Inc + * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the @@ -76,6 +76,7 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi { private final AtomicBoolean makeNextPaymentFailWithException = new AtomicBoolean(false); private final AtomicBoolean makeAllPaymentsFailWithError = new AtomicBoolean(false); private final AtomicBoolean makeNextPaymentPending = new AtomicBoolean(false); + private final AtomicBoolean makeNextPaymentUnknown = new AtomicBoolean(false); private final AtomicInteger makePluginWaitSomeMilliseconds = new AtomicInteger(0); private final AtomicReference<BigDecimal> overrideNextProcessedAmount = new AtomicReference<BigDecimal>(); private final AtomicReference<Currency> overrideNextProcessedCurrency = new AtomicReference<Currency>(); @@ -206,6 +207,7 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi { makeNextPaymentFailWithError.set(false); makeNextPaymentFailWithCancellation.set(false); makeNextPaymentPending.set(false); + makeNextPaymentUnknown.set(false); makePluginWaitSomeMilliseconds.set(0); overrideNextProcessedAmount.set(null); paymentMethods.clear(); @@ -222,6 +224,10 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi { makeNextPaymentPending.set(true); } + public void makeNextPaymentUnknown() { + makeNextPaymentUnknown.set(true); + } + public void makeNextPaymentFailWithCancellation() { makeNextPaymentFailWithCancellation.set(true); } @@ -465,6 +471,8 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi { status = PaymentPluginStatus.CANCELED; } else if (makeNextPaymentPending.getAndSet(false)) { status = PaymentPluginStatus.PENDING; + } else if (makeNextPaymentUnknown.getAndSet(false)) { + status = PaymentPluginStatus.UNDEFINED; } else { status = PaymentPluginStatus.PROCESSED; }
      ['beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java', 'invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java', 'api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java', 'invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java', 'payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java', 'payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java']
      {'.java': 8}
      8
      8
      0
      0
      8
      6,119,816
      1,147,700
      132,717
      1,008
      3,226
      500
      40
      5
      331
      45
      68
      8
      0
      0
      1970-01-01T00:25:30
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0
      256
      killbill/killbill/550/548
      killbill
      killbill
      https://github.com/killbill/killbill/issues/548
      https://github.com/killbill/killbill/pull/550
      https://github.com/killbill/killbill/pull/550
      1
      fixes
      DefaultPaymentGatewayApi doesn't respect isAborted flag
      We should make sure 422 is returned if the HPP payment is aborted by a control plugin.
      071796f5dcb8dd7c52fd8a0cd28aa0cf1a6a0120
      13fd4001d59e59868186e2a306146d572be750dc
      https://github.com/killbill/killbill/compare/071796f5dcb8dd7c52fd8a0cd28aa0cf1a6a0120...13fd4001d59e59868186e2a306146d572be750dc
      diff --git a/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java b/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java index ec17b19c60..09685fa60b 100644 --- a/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java +++ b/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java @@ -34,6 +34,7 @@ import org.killbill.billing.control.plugin.api.PriorPaymentControlResult; import org.killbill.billing.payment.core.PaymentExecutors; import org.killbill.billing.payment.core.PaymentGatewayProcessor; import org.killbill.billing.payment.core.sm.control.ControlPluginRunner; +import org.killbill.billing.payment.core.sm.control.PaymentControlApiAbortException; import org.killbill.billing.payment.dispatcher.PluginDispatcher; import org.killbill.billing.payment.dispatcher.PluginDispatcher.PluginDispatcherReturnType; import org.killbill.billing.payment.plugin.api.GatewayNotification; @@ -147,6 +148,8 @@ public class DefaultPaymentGatewayApi extends DefaultApiBase implements PaymentG PaymentApiType.HPP, null, HPPType.BUILD_FORM_DESCRIPTOR, null, null, true, paymentControlPluginNames, properties, callContext); + } catch (final PaymentControlApiAbortException e) { + throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_API_ABORTED, e.getPluginName()); } catch (final PaymentControlApiException e) { throw new PaymentApiException(e, ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e); } diff --git a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java index f2b1472cc3..1ee36fc04a 100644 --- a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java +++ b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java @@ -25,7 +25,6 @@ import javax.annotation.Nullable; import javax.inject.Inject; import org.joda.time.DateTime; -import org.killbill.billing.ErrorCode; import org.killbill.billing.account.api.Account; import org.killbill.billing.callcontext.DefaultCallContext; import org.killbill.billing.catalog.api.Currency; @@ -38,7 +37,6 @@ import org.killbill.billing.control.plugin.api.PaymentControlContext; import org.killbill.billing.control.plugin.api.PaymentControlPluginApi; import org.killbill.billing.control.plugin.api.PriorPaymentControlResult; import org.killbill.billing.osgi.api.OSGIServiceRegistration; -import org.killbill.billing.payment.api.PaymentApiException; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.payment.api.TransactionType; import org.killbill.billing.payment.retry.DefaultFailureCallResult; diff --git a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java index c3524e5bd6..33b4df4b54 100644 --- a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java +++ b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java @@ -22,7 +22,7 @@ import org.killbill.billing.control.plugin.api.PaymentControlApiException; /** * Created by arodrigues on 5/6/16. */ -class PaymentControlApiAbortException extends PaymentControlApiException { +public class PaymentControlApiAbortException extends PaymentControlApiException { private final String pluginName; public PaymentControlApiAbortException(final String pluginName) { diff --git a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java index 680221b084..3aa3554519 100644 --- a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java +++ b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import org.killbill.billing.ErrorCode; import org.killbill.billing.account.api.Account; import org.killbill.billing.control.plugin.api.OnFailurePaymentControlResult; import org.killbill.billing.control.plugin.api.OnSuccessPaymentControlResult; @@ -152,6 +153,20 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD } + @Test(groups = "fast") + public void testBuildFormDescriptorWithPaymentControlAbortedPayment() throws PaymentApiException { + plugin.setAborted(true); + + // Set a random UUID to verify the plugin will successfully override it + try { + paymentGatewayApi.buildFormDescriptorWithPaymentControl(account, UUID.randomUUID(), ImmutableList.<PluginProperty>of(), ImmutableList.<PluginProperty>of(), paymentOptions, callContext); + Assert.fail(); + } catch (PaymentApiException e) { + Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode()); + } + + } + public static class TestPaymentGatewayApiValidationPlugin implements PaymentControlPluginApi { public static final String VALIDATION_PLUGIN_NAME = "TestPaymentGatewayApiValidationPlugin"; @@ -216,13 +231,20 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD private Iterable<PluginProperty> newOnResultProperties; private Iterable<PluginProperty> removedOnResultProperties; + private boolean aborted; + public TestPaymentGatewayApiControlPlugin() { + this.aborted = false; this.newPriorCallProperties = ImmutableList.of(); this.removedPriorCallProperties = ImmutableList.of(); this.newOnResultProperties = ImmutableList.of(); this.removedOnResultProperties = ImmutableList.of(); } + public void setAborted(final boolean aborted) { + this.aborted = aborted; + } + public void setPriorCallProperties(final Iterable<PluginProperty> newPriorCallProperties, final Iterable<PluginProperty> removedPriorCallProperties) { this.newPriorCallProperties = newPriorCallProperties; this.removedPriorCallProperties = removedPriorCallProperties; @@ -235,7 +257,7 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD @Override public PriorPaymentControlResult priorCall(final PaymentControlContext paymentControlContext, final Iterable<PluginProperty> properties) throws PaymentControlApiException { - return new DefaultPriorPaymentControlResult(false, account.getPaymentMethodId(), null, null, getAdjustedProperties(properties, newPriorCallProperties, removedPriorCallProperties)); + return new DefaultPriorPaymentControlResult(aborted, account.getPaymentMethodId(), null, null, getAdjustedProperties(properties, newPriorCallProperties, removedPriorCallProperties)); } @Override
      ['payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java', 'payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java', 'payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java', 'payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java']
      {'.java': 4}
      4
      4
      0
      0
      4
      4,876,641
      926,318
      109,381
      927
      596
      95
      7
      3
      87
      17
      20
      2
      0
      0
      1970-01-01T00:24:23
      4,053
      Java
      {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593}
      Apache License 2.0