{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \");\n b.append(\"\");\n\n\n\n response.setContentType(\"text/html\");\n response.setCharacterEncoding(\"UTF-8\");\n response.setStatus(200);\n\n response.getWriter().print(b.toString());\n } catch (Exception e) {\n throw new IOSAutomationException(e);\n }\n\n }\n\n @Override\n public void render(HttpServletResponse response) throws Exception {\n try {\n StringBuilder b = new StringBuilder();\n b.append(\"\");\n b.append(\"\");\n\n b.append(\" \");\n b.append(\"\");\n b.append(\"\");\n\n\n /*\n * IPadDevicePositioning position = new IPadDevicePositioning(model.getDeviceOrientation(),\n * 25, 25); int degree = model.getDeviceOrientation().getRotationInDegree();\n */\n IOSDevice device = model.getCapabilities().getDevice();\n\n /*\n * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) {\n * b.append(\"\"); } else {\n * b.append(\"\"); b.append(\"\"); }\n */\n\n\n\n b.append(\"\");\n\n\n\n b.append(\"\");\n\n\n b.append(\"\");\n b.append(\"\");\n\n\n\n b.append(\"
\");\n\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n\n b.append(\"
\");\n b.append(\"\");\n b.append(\"
\");\n b.append(\" \");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n\n\n\n b.append(\"
\");\n b.append(\"
details
\");\n\n\n\n b.append(\"\");\n\n b.append(\"\");\n b.append(\"\");\n\n\n\n response.setContentType(\"text/html\");\n response.setCharacterEncoding(\"UTF-8\");\n response.setStatus(200);\n\n response.getWriter().print(b.toString());\n } catch (Exception e) {\n throw new IOSAutomationException(e);\n }\n\n }\n\n private String getScreen(IOSDevice device) {\n return getResource(\"session/\" + model.getSession().getSessionId() + \"/screenshot.png\");\n }\n\n\n\n private String getFrame(IOSDevice device) {\n if (device == IOSDevice.iPhoneSimulator) {\n return getResource(\"frameiphone.png\");\n } else {\n return getResource(\"frameipad.png\");\n }\n }\n\n\n\n private String getResource(String name) {\n String res = servletPath + \"/resources/\" + name;\n return res;\n }\n}\n"},"new_file":{"kind":"string","value":"ide/src/main/java/org/uiautomation/ios/ide/views/IDEMainView.java"},"old_contents":{"kind":"string","value":"package org.uiautomation.ios.ide.views;\n\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.uiautomation.ios.UIAModels.Orientation;\nimport org.uiautomation.ios.communication.IOSDevice;\nimport org.uiautomation.ios.exceptions.IOSAutomationException;\nimport org.uiautomation.ios.ide.model.IDESessionModel;\nimport org.uiautomation.ios.ide.views.positioning.IPadDevicePositioning;\n\npublic class IDEMainView implements View {\n\n private final IDESessionModel model;\n private final String servletPath;\n\n public IDEMainView(IDESessionModel model, String servletPath) {\n this.model = model;\n this.servletPath = servletPath;\n }\n\n\n\n public void render2(HttpServletResponse response) throws Exception {\n try {\n StringBuilder b = new StringBuilder();\n b.append(\"\");\n b.append(\"\");\n\n b.append(\" \");\n b.append(\"\");\n b.append(\"\");\n\n IPadDevicePositioning position =\n new IPadDevicePositioning(model.getDeviceOrientation(), 25, 25);\n int degree = model.getDeviceOrientation().getRotationInDegree();\n\n /*\n * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) {\n * b.append(\"\"); } else {\n * b.append(\"\"); b.append(\"\"); }\n */\n\n\n\n b.append(\"\");\n\n\n\n b.append(\"\");\n\n\n b.append(\"\");\n b.append(\"\");\n b.append(\"
\");\n\n String suffix = \"iPad\";\n if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) {\n suffix = \"iPhone\";\n }\n\n\n String rotate = \"-moz-transform:rotate(\" + degree + \"deg);\";\n b.append(\"
\" +\n\n \"
\");\n\n b.append(\"
\");\n b.append(\"
\" + \"
\");\n\n\n\n b.append(\"
\");\n\n b.append(\"
details
\");\n\n\n\n b.append(\"
actions\");\n b.append(\"
\");\n\n b.append(\"
\");\n\n b.append(\" \");\n b.append(\"
\");\n\n b.append(\"
\");\n\n b.append(\"X: \");\n b.append(\"Y: \");\n\n b.append(\"\");\n b.append(\"
\");\n b.append(\"
\");\n\n\n b.append(\"\");\n b.append(\"\");\n\n\n\n response.setContentType(\"text/html\");\n response.setCharacterEncoding(\"UTF-8\");\n response.setStatus(200);\n\n response.getWriter().print(b.toString());\n } catch (Exception e) {\n throw new IOSAutomationException(e);\n }\n\n }\n\n @Override\n public void render(HttpServletResponse response) throws Exception {\n try {\n StringBuilder b = new StringBuilder();\n b.append(\"\");\n b.append(\"\");\n\n b.append(\" \");\n b.append(\"\");\n b.append(\"\");\n\n\n /*\n * IPadDevicePositioning position = new IPadDevicePositioning(model.getDeviceOrientation(),\n * 25, 25); int degree = model.getDeviceOrientation().getRotationInDegree();\n */\n IOSDevice device = model.getCapabilities().getDevice();\n\n /*\n * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) {\n * b.append(\"\"); } else {\n * b.append(\"\"); b.append(\"\"); }\n */\n\n\n\n b.append(\"\");\n\n\n\n b.append(\"\");\n\n\n b.append(\"\");\n b.append(\"\");\n\n\n\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"\");\n b.append(\"
\");\n b.append(\" \");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n b.append(\"
\");\n\n\n\n b.append(\"
\");\n b.append(\"
details
\");\n\n\n\n b.append(\"\");\n\n b.append(\"\");\n b.append(\"\");\n\n\n\n response.setContentType(\"text/html\");\n response.setCharacterEncoding(\"UTF-8\");\n response.setStatus(200);\n\n response.getWriter().print(b.toString());\n } catch (Exception e) {\n throw new IOSAutomationException(e);\n }\n\n }\n\n private String getScreen(IOSDevice device) {\n return getResource(\"session/\" + model.getSession().getSessionId() + \"/screenshot.png\");\n }\n\n\n\n private String getFrame(IOSDevice device) {\n if (device == IOSDevice.iPhoneSimulator) {\n return getResource(\"frameiphone.png\");\n } else {\n return getResource(\"frameipad.png\");\n }\n }\n\n\n\n private String getResource(String name) {\n String res = servletPath + \"/resources/\" + name;\n return res;\n }\n}\n"},"message":{"kind":"string","value":"formatting\n"},"old_file":{"kind":"string","value":"ide/src/main/java/org/uiautomation/ios/ide/views/IDEMainView.java"},"subject":{"kind":"string","value":"formatting"}}},{"rowIdx":1237,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e09c80742ce3c42180513314eb63f178005f07ac"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"intruxxer/twitter4j,matsumo/twitter4j,eunamong/twitter4j,xfxf123444/twitter4j,qingsong-xu/twitter4j,kaosmos/twitter4j,savethejets/twitter4j,tylermac/twitter4j,takke/twitter4j,mumei/twitter4j,afeiluo/twitter4j,lamorin/Twitter4J,intruxxer/twitter4j,savethejets/twitter4j,osamuaoki/twitter4j,DellayHaroun/twitter4j,krallus/twitter4j,fabienfleureau/twitter4j,HubSpot/twitter4j,david8zhang/twitter4j,thedevd/twitter4j,ColinZang/twitter4j,u2i/twitter4j,fabianormatias/twitter4j,yusuke/twitter4j,mumei/twitter4j,matsumo/twitter4j,lithiumtech/twitter4j-pub,thedevd/twitter4j,eunamong/twitter4j,ColinZang/twitter4j,tylermac/twitter4j,osamuaoki/twitter4j,yusuke/twitter4j,lamorin/Twitter4J,fabianormatias/twitter4j,HasanAliKaraca/twitter4j,kaosmos/twitter4j,HubSpot/twitter4j,xfxf123444/twitter4j,fabienfleureau/twitter4j,qingsong-xu/twitter4j,u2i/twitter4j,takke/twitter4j,david8zhang/twitter4j,DellayHaroun/twitter4j,lithiumtech/twitter4j-pub,afeiluo/twitter4j,krallus/twitter4j,HasanAliKaraca/twitter4j"},"new_contents":{"kind":"string","value":"package twitter4j;\n\nimport twitter4j.http.HttpClient;\nimport twitter4j.http.PostParameter;\nimport twitter4j.http.Response;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.TimeZone;\n\n/**\n * A java reporesentation of the Twitter API\n */\npublic class Twitter implements java.io.Serializable {\n HttpClient http = null;\n private String baseURL = \"http://twitter.com/\";\n private String source = \"Twitter4J\";\n\n private boolean usePostForcibly = false;\n private static final long serialVersionUID = 4346156413282535531L;\n private static final int MAX_COUNT = 200;\n\n public Twitter() {\n http = new HttpClient();\n setRequestHeader(\"X-Twitter-Client\", \"Twitter4J\");\n setRequestHeader(\"X-Twitter-Client-Version\", \"1.1.3\");\n setRequestHeader(\"X-Twitter-Client-URL\",\n \"http://yusuke.homeip.net/twitter4j/en/twitter4j-1.1.3.xml\");\n format.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n }\n\n public Twitter(String baseURL) {\n this();\n this.baseURL = baseURL;\n }\n\n public Twitter(String id, String password) {\n this();\n setUserId(id);\n setPassword(password);\n }\n\n public Twitter(String id, String password, String baseURL) {\n this(id, password);\n this.baseURL = baseURL;\n }\n\n /**\n * Sets the base URL\n *\n * @param baseURL String the base URL\n */\n public void setBaseURL(String baseURL) {\n this.baseURL = baseURL;\n }\n\n /**\n * Returns the base URL\n *\n * @return the base URL\n */\n public String getBaseURL() {\n return this.baseURL;\n }\n\n /**\n * Sets the userid\n *\n * @param userId new userid\n */\n public void setUserId(String userId) {\n http.setUserId(userId);\n }\n\n /**\n * Returns authenticating userid\n *\n * @return userid\n */\n public String getUserId() {\n return http.getUserId();\n }\n\n /**\n * Sets the password\n *\n * @param password new password\n */\n public void setPassword(String password) {\n http.setPassword(password);\n }\n\n /**\n * Returns authenticating password\n *\n * @return password\n */\n public String getPassword() {\n return http.getPassword();\n }\n\n /**\n * Sets the source parameter that will be passed by updating methods\n * See below for details.\n * Twitter API Wiki > How do I get “from [my_application]” appended to updates sent from my API application?\n * http://apiwiki.twitter.com/REST+API+Documentation\n *\n * @param source the new source\n */\n public void setSource(String source) {\n this.source = source;\n }\n\n /**\n * Returns the source\n *\n * @return source\n */\n public String getSource() {\n return this.source;\n }\n\n /**\n * sets the request header name/value combination\n * see Twitter Fan Wiki for detail.\n * http://twitter.pbwiki.com/API-Docs#RequestHeaders\n *\n * @param name the name of the request header\n * @param value the value of the request header\n */\n public void setRequestHeader(String name, String value) {\n http.setRequestHeader(name, value);\n }\n\n /**\n * set true to force using POST method communicating to the server\n *\n * @param forceUsePost if true POST method will be used forcibly\n */\n public void forceUsePost(boolean forceUsePost) {\n this.usePostForcibly = forceUsePost;\n }\n\n /**\n * @return true if POST is used forcibly\n */\n public boolean isUsePostForced() {\n return this.usePostForcibly;\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, boolean authenticate) throws TwitterException {\n return get(url, null, authenticate);\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @param name1 the name of the first parameter\n * @param value1 the value of the first parameter\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, String name1, String value1, boolean authenticate) throws TwitterException {\n return get(url, new PostParameter[]{new PostParameter(name1, value1)}, authenticate);\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param name1 the name of the first parameter\n * @param value1 the value of the first parameter\n * @param name2 the name of the second parameter\n * @param value2 the value of the second parameter\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws TwitterException {\n return get(url, new PostParameter[]{new PostParameter(name1, value1), new PostParameter(name2, value2)}, authenticate);\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param params the request parameters\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, PostParameter[] params, boolean authenticate) throws TwitterException {\n if (usePostForcibly) {\n if (null == params) {\n return http.post(url, new PostParameter[0], authenticate);\n } else {\n return http.post(url, params, authenticate);\n }\n } else {\n if (null != params && params.length > 0) {\n url += \"?\" + HttpClient.encodeParameters(params);\n }\n return http.get(url, authenticate);\n }\n }\n\n /* Status Methods */\n\n /**\n * Returns the 20 most recent statuses from non-protected users who have set a custom user icon.\n *\n * @return list of statuses of the Public Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getPublicTimeline() throws\n TwitterException {\n return Status.constructStatuses(get(baseURL +\n \"statuses/public_timeline.xml\", false).\n asDocument(), this);\n }\n\n /**\n * Returns only public statuses with an ID greater than (that is, more recent than) the specified ID.\n *\n * @param sinceID returns only public statuses with an ID greater than (that is, more recent than) the specified ID\n * @return the 20 most recent statuses\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getPublicTimeline(int sinceID) throws\n TwitterException {\n return Status.constructStatuses(get(baseURL +\n \"statuses/public_timeline.xml\", \"since_id\", String.valueOf(sinceID), false).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends.\n * It's also possible to request another user's friends_timeline via the id parameter below.\n *\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getFriendsTimeline() throws\n TwitterException {\n return Status.constructStatuses(get(baseURL +\n \"statuses/friends_timeline.xml\", true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @param page the number of page\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriendsTimelineByPage(int page) throws\n TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline.xml\",\n \"page\", String.valueOf(page), true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the friends_timeline\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getFriendsTimeline(String id) throws\n TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline/\" + id + \".xml\",\n true).asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the friends_timeline\n * @param page the number of page\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getFriendsTimelineByPage(String id, int page) throws\n TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline/\" + id + \".xml\",\n \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriendsTimeline(Date since) throws\n TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline.xml\",\n \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the friends_timeline\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriendsTimeline(String id,\n Date since) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline/\" + id + \".xml\",\n \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return list of the user Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id, int count,\n Date since) throws TwitterException {\n if (MAX_COUNT < count) {\n throw new IllegalArgumentException(\"count may not be greater than \" + MAX_COUNT + \" for performance purposes.\");\n }\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\",\n \"since\", format.format(since), \"count\", String.valueOf(count), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id, Date since) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\",\n \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id, int count) throws\n TwitterException {\n if (MAX_COUNT < count) {\n throw new IllegalArgumentException(\"count may not be greater than \" + MAX_COUNT + \" for performance purposes.\");\n }\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\",\n \"count\", String.valueOf(count), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(int count, Date since) throws TwitterException {\n if (MAX_COUNT < count) {\n throw new IllegalArgumentException(\"count may not be greater than \" + MAX_COUNT + \" for performance purposes.\");\n }\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline.xml\",\n \"since\", format.format(since), \"count\", String.valueOf(count), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline() throws\n TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline.xml\", true).\n asDocument(), this);\n }\n\n /**\n * Returns a single status, specified by the id parameter. The status's author will be returned inline.\n *\n * @param id the numerical ID of the status you're trying to retrieve\n * @return a single status\n * @throws TwitterException when Twitter service or network is unavailable\n * @deprecated Use show(long id) instead.\n */\n\n public synchronized Status show(int id) throws TwitterException {\n return new Status(get(baseURL + \"statuses/show/\" + id + \".xml\", false).asDocument().getDocumentElement(), this);\n }\n /**\n * Returns a single status, specified by the id parameter. The status's author will be returned inline.\n *\n * @param id the numerical ID of the status you're trying to retrieve\n * @return a single status\n * @throws TwitterException when Twitter service or network is unavailable\n * @since 1.1.1\n */\n\n public synchronized Status show(long id) throws TwitterException {\n return new Status(get(baseURL + \"statuses/show/\" + id + \".xml\", false).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Updates the user's status.\n * The text will be trimed if the length of the text is exceeding 160 characters.\n *\n * @param status the text of your status update\n * @return the latest status\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public Status update(String status) throws TwitterException {\n if (status.length() > 160) {\n status = status.substring(0, 160);\n }\n return new Status(http.post(baseURL + \"statuses/update.xml\",\n new PostParameter[]{new PostParameter(\"status\", status), new PostParameter(\"source\", source)}, true).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns the 20 most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected.\n *\n * @return the 20 most recent replies\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getReplies() throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/replies.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected.\n *\n * @param page the number of page\n * @return the 20 most recent replies\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getRepliesByPage(int page) throws TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return Status.constructStatuses(get(baseURL + \"statuses/replies.xml\",\n \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.\n *\n * @param statusId The ID of the status to destroy.\n * @return the deleted status\n * @throws TwitterException when Twitter service or network is unavailable\n * @since 1.0.5\n */\n public Status destroyStatus(long statusId) throws TwitterException {\n return new Status(http.post(baseURL + \"statuses/destroy/\" + statusId + \".xml\",\n new PostParameter[0], true).asDocument().getDocumentElement(), this);\n }\n\n /* User Methods */\n\n /**\n * Returns the specified user's friends, each with current status inline.\n *\n * @return the list of friends\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends() throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the specified user's friends, each with current status inline.\n *\n * @param page number of page\n * @return the list of friends\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends(int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\", \"page\",\n String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the user's friends, each with current status inline.\n *\n * @param id the ID or screen name of the user for whom to request a list of friends\n * @return the list of friends\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends(String id) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\",\n \"id\", id, true).asDocument(), this);\n }\n\n /**\n * Returns the user's friends, each with current status inline.\n *\n * @param id the ID or screen name of the user for whom to request a list of friends\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends(String id, int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\",\n \"id\", id, \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFollowers() throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @param page Retrieves the next 100 followers.\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.0\n */\n public synchronized List getFollowers(int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers.xml\", \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @param id The ID or screen name of the user for whom to request a list of followers.\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.0\n */\n public synchronized List getFollowers(String id) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers/\" + id + \".xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @param id The ID or screen name of the user for whom to request a list of followers.\n * @param page Retrieves the next 100 followers.\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.0\n */\n public synchronized List getFollowers(String id, int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers/\" + id + \".xml\", \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the users currently featured on the site with their current statuses inline.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFeatured() throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/featured.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.\n *\n * @param id the ID or screen name of the user for whom to request the detail\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized UserWithStatus getUserDetail(String id) throws TwitterException {\n return new UserWithStatus(get(baseURL + \"users/show/\" + id + \".xml\", true).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessages() throws TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL + \"direct_messages.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessagesByPage(int page) throws TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return DirectMessage.constructDirectMessages(get(baseURL + \"direct_messages.xml\",\n \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @param sinceId int\n * @return list of direct messages\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessages(int sinceId) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages.xml\", \"since_id\", String.valueOf(sinceId), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date\n * @return list of direct messages\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessages(Date since) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages.xml\", \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent by the authenticating user.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getSentDirectMessages() throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages/sent.xml\", new PostParameter[0], true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent by the authenticating user.\n *\n * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getSentDirectMessages(Date since) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages/sent.xml\", \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent by the authenticating user.\n *\n * @param sinceId returns only sent direct messages with an ID greater than (that is, more recent than) the specified ID\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getSentDirectMessages(int sinceId) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages/sent.xml\", \"since_id\", String.valueOf(sinceId), true).asDocument(), this);\n }\n\n /**\n * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.\n * The text will be trimed if the length of the text is exceeding 140 characters.\n *\n * @param id the ID or screen name of the user to whom send the direct message\n * @param text String\n * @return DirectMessage\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized DirectMessage sendDirectMessage(String id,\n String text) throws TwitterException {\n if (text.length() > 160) {\n text = text.substring(0, 160);\n }\n return new DirectMessage(http.post(baseURL + \"direct_messages/new.xml\",\n new PostParameter[]{new PostParameter(\"user\", id),\n new PostParameter(\"text\", text)}, true).\n asDocument().getDocumentElement(), this);\n }\n\n\n /**\n * Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.\n *\n * @param id the ID of the direct message to destroy\n * @return the deleted direct message\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized DirectMessage deleteDirectMessage(int id) throws\n TwitterException {\n return new DirectMessage(http.post(baseURL +\n \"direct_messages/destroy/\" + id + \".xml\", new PostParameter[0], true).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.\n *\n * @param id the ID or screen name of the user to be befriended\n * @return the befriended user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized User create(String id) throws TwitterException {\n return new User(http.post(baseURL + \"friendships/create/\" + id + \".xml\", new PostParameter[0], true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.\n *\n * @param id the ID or screen name of the user for whom to request a list of friends\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized User destroy(String id) throws TwitterException {\n return new User(http.post(baseURL + \"friendships/destroy/\" + id + \".xml\", new PostParameter[0], true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns true if authentication was successful. Use this method to test if supplied user credentials are valid with minimal overhead.\n *\n * @return success\n */\n public synchronized boolean verifyCredentials() {\n try {\n return get(baseURL + \"account/verify_credentials.xml\", true).getStatusCode() == 200;\n } catch (TwitterException te) {\n return false;\n }\n }\n\n /**\n * Update the location\n *\n * @param location the current location of the user\n * @return the updated user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User updateLocation(String location) throws TwitterException {\n return new User(http.post(baseURL + \"account/update_location.xml\", new PostParameter[]{new PostParameter(\"location\", location)}, true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns the remaining number of API requests available to the requesting user before the API limit is reached for the current hour. Calls to rate_limit_status do not count against the rate limit. If authentication credentials are provided, the rate limit status for the authenticating user is returned. Otherwise, the rate limit status for the requester's IP address is returned.
\n * See Twitter REST API Documentation &gt; Account Methods &gt; rate_limit_status for detail.\n *\n * @return the rate limit status\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.4\n */\n public synchronized RateLimitStatus rateLimitStatus() throws TwitterException {\n return new RateLimitStatus(http.get(baseURL + \"account/rate_limit_status.xml\", null != getUserId() && null != getPassword()).\n asDocument().getDocumentElement());\n }\n\n public final static Device IM = new Device(\"im\");\n public final static Device SMS = new Device(\"sms\");\n public final static Device NONE = new Device(\"none\");\n\n static class Device {\n final String DEVICE;\n\n public Device(String device) {\n DEVICE = device;\n }\n }\n\n /**\n * Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable IM or SMS updates.\n *\n * @param device new Delivery device. Must be one of: IM, SMS, NONE.\n * @return the updated user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User updateDeliverlyDevice(Device device) throws TwitterException {\n return new User(http.post(baseURL + \"account/update_delivery_device.xml\", new PostParameter[]{new PostParameter(\"device\", device.DEVICE)}, true).\n asDocument().getDocumentElement(), this);\n }\n\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites() throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites.xml\", new PostParameter[0], true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites(int page) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites.xml\", \"page\", String.valueOf(page), true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @param id the ID or screen name of the user for whom to request a list of favorite statuses\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites(String id) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites/\" + id + \".xml\", new PostParameter[0], true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @param id the ID or screen name of the user for whom to request a list of favorite statuses\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites(String id, int page) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites/\" + id + \".xml\", \"page\", String.valueOf(page), true).\n asDocument(), this);\n }\n\n /**\n * Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.\n *\n * @param id the ID of the status to favorite\n * @return Status\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized Status createFavorite(long id) throws TwitterException {\n return new Status(http.post(baseURL + \"favorites/create/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.\n *\n * @param id the ID of the status to un-favorite\n * @return Status\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized Status destroyFavorite(long id) throws TwitterException {\n return new Status(http.post(baseURL + \"favorites/destroy/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.\n *\n * @param id String\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized User follow(String id) throws TwitterException {\n return new User(http.post(baseURL + \"notifications/follow/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.\n *\n * @param id String\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized User leave(String id) throws TwitterException {\n return new User(http.post(baseURL + \"notifications/leave/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /* Block Methods */\n\n /**\n * Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful.\n *\n * @param id the ID or screen_name of the user to block\n * @return the blocked user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User block(String id) throws TwitterException {\n return new User(http.post(baseURL + \"blocks/create/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n\n /**\n * Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful.\n *\n * @param id the ID or screen_name of the user to block\n * @return the unblocked user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User unblock(String id) throws TwitterException {\n return new User(http.post(baseURL + \"blocks/destroy/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /* Help Methods */\n/*\ntest New as of April 29th, 2008!\n\nReturns the string \"ok\" in the requested format with a 200 OK HTTP status code.\nURL:http://twitter.com/help/test.format\nFormats: xml, json\n*/\n\n /**\n * Returns the string \"ok\" in the requested format with a 200 OK HTTP status code.\n *\n * @return true if the API is working\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized boolean test() throws TwitterException {\n return -1 != get(baseURL + \"help/test.xml\", false).\n asString().indexOf(\"ok\");\n }\n\n /**\n * Returns extended information of the authenticated user. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.
\n * The call Twitter.getAuthenticatedUser() is equivalent to the call:
\n * twitter.getUserDetail(twitter.getUserId());\n *\n * @return UserWithStatus\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.3\n */\n public synchronized UserWithStatus getAuthenticatedUser() throws TwitterException {\n if(null == getUserId()){\n throw new IllegalStateException(\"User Id not specified.\");\n }\n return getUserDetail(getUserId());\n }\n\n/*\ndowntime_schedule New as of April 29th, 2008!\n\nReturns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format.\nURL:http://twitter.com/help/downtime_schedule.format\nFormats: xml, json\n*/\n\n /**\n * Returns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format.\n *\n * @return the schedule\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized String getDowntimeSchedule() throws TwitterException {\n return get(baseURL + \"help/downtime_schedule.xml\", false).asString();\n }\n \n\n private SimpleDateFormat format = new SimpleDateFormat(\n \"EEE, d MMM yyyy HH:mm:ss z\", Locale.ENGLISH);\n\n public void setRetryCount(int retryCount) {\n http.setRetryCount(retryCount);\n }\n\n public void setRetryIntervalSecs(int retryIntervalSecs) {\n http.setRetryIntervalSecs(retryIntervalSecs);\n }\n\n @Override\n public int hashCode() {\n return http.hashCode() + this.baseURL.hashCode() + http.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (null == obj) {\n return false;\n }\n if (this == obj) {\n return true;\n }\n if (obj instanceof Twitter) {\n Twitter that = (Twitter) obj;\n return this.http.equals(that.http)\n && this.baseURL.equals(that.baseURL)\n && this.http.equals(that.http);\n }\n return false;\n }\n\n @Override\n public String toString() {\n return \"Twitter{\" +\n \"http=\" + http +\n \", baseURL='\" + baseURL + '\\'' +\n \", source='\" + source + '\\'' +\n \", usePostForcibly=\" + usePostForcibly +\n \", format=\" + format +\n '}';\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/twitter4j/Twitter.java"},"old_contents":{"kind":"string","value":"package twitter4j;\n\nimport twitter4j.http.HttpClient;\nimport twitter4j.http.PostParameter;\nimport twitter4j.http.Response;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.TimeZone;\n\n/**\n * A java reporesentation of the Twitter API\n */\npublic class Twitter implements java.io.Serializable {\n HttpClient http = null;\n private String baseURL = \"http://twitter.com/\";\n private String source = \"Twitter4J\";\n\n private boolean usePostForcibly = false;\n private static final long serialVersionUID = 4346156413282535531L;\n private static final int MAX_COUNT = 200;\n\n public Twitter() {\n http = new HttpClient();\n setRequestHeader(\"X-Twitter-Client\", \"Twitter4J\");\n setRequestHeader(\"X-Twitter-Client-Version\", \"1.1.3\");\n setRequestHeader(\"X-Twitter-Client-URL\",\n \"http://yusuke.homeip.net/twitter4j/en/twitter4j-1.1.3.xml\");\n format.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n }\n\n public Twitter(String baseURL) {\n this();\n this.baseURL = baseURL;\n }\n\n public Twitter(String id, String password) {\n this();\n setUserId(id);\n setPassword(password);\n }\n\n public Twitter(String id, String password, String baseURL) {\n this(id, password);\n this.baseURL = baseURL;\n }\n\n /**\n * Sets the base URL\n *\n * @param baseURL String the base URL\n */\n public void setBaseURL(String baseURL) {\n this.baseURL = baseURL;\n }\n\n /**\n * Returns the base URL\n *\n * @return the base URL\n */\n public String getBaseURL() {\n return this.baseURL;\n }\n\n /**\n * Sets the userid\n *\n * @param userId new userid\n */\n public void setUserId(String userId) {\n http.setUserId(userId);\n }\n\n /**\n * Returns authenticating userid\n *\n * @return userid\n */\n public String getUserId() {\n return http.getUserId();\n }\n\n /**\n * Sets the password\n *\n * @param password new password\n */\n public void setPassword(String password) {\n http.setPassword(password);\n }\n\n /**\n * Returns authenticating password\n *\n * @return password\n */\n public String getPassword() {\n return http.getPassword();\n }\n\n /**\n * Sets the source parameter that will be passed by updating methods\n * See below for details.\n * Twitter API Wiki > How do I get “from [my_application]” appended to updates sent from my API application?\n * http://apiwiki.twitter.com/REST+API+Documentation\n *\n * @param source the new source\n */\n public void setSource(String source) {\n this.source = source;\n }\n\n /**\n * Returns the source\n *\n * @return source\n */\n public String getSource() {\n return this.source;\n }\n\n /**\n * sets the request header name/value combination\n * see Twitter Fan Wiki for detail.\n * http://twitter.pbwiki.com/API-Docs#RequestHeaders\n *\n * @param name the name of the request header\n * @param value the value of the request header\n */\n public void setRequestHeader(String name, String value) {\n http.setRequestHeader(name, value);\n }\n\n /**\n * set true to force using POST method communicating to the server\n *\n * @param forceUsePost if true POST method will be used forcibly\n */\n public void forceUsePost(boolean forceUsePost) {\n this.usePostForcibly = forceUsePost;\n }\n\n /**\n * @return true if POST is used forcibly\n */\n public boolean isUsePostForced() {\n return this.usePostForcibly;\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, boolean authenticate) throws TwitterException {\n return get(url, null, authenticate);\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @param name1 the name of the first parameter\n * @param value1 the value of the first parameter\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, String name1, String value1, boolean authenticate) throws TwitterException {\n return get(url, new PostParameter[]{new PostParameter(name1, value1)}, authenticate);\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param name1 the name of the first parameter\n * @param value1 the value of the first parameter\n * @param name2 the name of the second parameter\n * @param value2 the value of the second parameter\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws TwitterException {\n return get(url, new PostParameter[]{new PostParameter(name1, value1), new PostParameter(name2, value2)}, authenticate);\n }\n\n /**\n * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true.\n *\n * @param url the request url\n * @param params the request parameters\n * @param authenticate if true, the request will be sent with BASIC authentication header\n * @return the response\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n private Response get(String url, PostParameter[] params, boolean authenticate) throws TwitterException {\n if (usePostForcibly) {\n if (null == params) {\n return http.post(url, new PostParameter[0], authenticate);\n } else {\n return http.post(url, params, authenticate);\n }\n } else {\n if (null != params && params.length > 0) {\n url += \"?\" + HttpClient.encodeParameters(params);\n }\n return http.get(url, authenticate);\n }\n }\n\n /* Status Methods */\n\n /**\n * Returns the 20 most recent statuses from non-protected users who have set a custom user icon.\n *\n * @return list of statuses of the Public Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getPublicTimeline() throws\n TwitterException {\n return Status.constructStatuses(get(baseURL +\n \"statuses/public_timeline.xml\", false).\n asDocument(), this);\n }\n\n /**\n * Returns only public statuses with an ID greater than (that is, more recent than) the specified ID.\n *\n * @param sinceID returns only public statuses with an ID greater than (that is, more recent than) the specified ID\n * @return the 20 most recent statuses\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getPublicTimeline(int sinceID) throws\n TwitterException {\n return Status.constructStatuses(get(baseURL +\n \"statuses/public_timeline.xml\", \"since_id\", String.valueOf(sinceID), false).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends.\n * It's also possible to request another user's friends_timeline via the id parameter below.\n *\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getFriendsTimeline() throws\n TwitterException {\n return Status.constructStatuses(get(baseURL +\n \"statuses/friends_timeline.xml\", true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @param page the number of page\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriendsTimelineByPage(int page) throws\n TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline.xml\",\n \"page\", String.valueOf(page), true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the friends_timeline\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getFriendsTimeline(String id) throws\n TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline/\" + id + \".xml\",\n true).asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the friends_timeline\n * @param page the number of page\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized List getFriendsTimelineByPage(String id, int page) throws\n TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline/\" + id + \".xml\",\n \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriendsTimeline(Date since) throws\n TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline.xml\",\n \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the friends_timeline\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return list of the Friends Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriendsTimeline(String id,\n Date since) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/friends_timeline/\" + id + \".xml\",\n \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return list of the user Timeline\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id, int count,\n Date since) throws TwitterException {\n if (MAX_COUNT < count) {\n throw new IllegalArgumentException(\"count may not be greater than \" + MAX_COUNT + \" for performance purposes.\");\n }\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\",\n \"since\", format.format(since), \"count\", String.valueOf(count), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id, Date since) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\",\n \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id, int count) throws\n TwitterException {\n if (MAX_COUNT < count) {\n throw new IllegalArgumentException(\"count may not be greater than \" + MAX_COUNT + \" for performance purposes.\");\n }\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\",\n \"count\", String.valueOf(count), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes\n * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(int count, Date since) throws TwitterException {\n if (MAX_COUNT < count) {\n throw new IllegalArgumentException(\"count may not be greater than \" + MAX_COUNT + \" for performance purposes.\");\n }\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline.xml\",\n \"since\", format.format(since), \"count\", String.valueOf(count), true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the specified userid.\n *\n * @param id specifies the ID or screen name of the user for whom to return the user_timeline\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline(String id) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline/\" + id + \".xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the most recent statuses posted in the last 24 hours from the authenticating user.\n *\n * @return the 20 most recent statuses posted in the last 24 hours from the user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getUserTimeline() throws\n TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/user_timeline.xml\", true).\n asDocument(), this);\n }\n\n /**\n * Returns a single status, specified by the id parameter. The status's author will be returned inline.\n *\n * @param id the numerical ID of the status you're trying to retrieve\n * @return a single status\n * @throws TwitterException when Twitter service or network is unavailable\n * @deprecated Use show(long id) instead.\n */\n\n public synchronized Status show(int id) throws TwitterException {\n return new Status(get(baseURL + \"statuses/show/\" + id + \".xml\", false).asDocument().getDocumentElement(), this);\n }\n /**\n * Returns a single status, specified by the id parameter. The status's author will be returned inline.\n *\n * @param id the numerical ID of the status you're trying to retrieve\n * @return a single status\n * @throws TwitterException when Twitter service or network is unavailable\n * @since 1.1.1\n */\n\n public synchronized Status show(long id) throws TwitterException {\n return new Status(get(baseURL + \"statuses/show/\" + id + \".xml\", false).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Updates the user's status.\n * The text will be trimed if the length of the text is exceeding 160 characters.\n *\n * @param status the text of your status update\n * @return the latest status\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public Status update(String status) throws TwitterException {\n if (status.length() > 160) {\n status = status.substring(0, 160);\n }\n return new Status(http.post(baseURL + \"statuses/update.xml\",\n new PostParameter[]{new PostParameter(\"status\", status), new PostParameter(\"source\", source)}, true).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns the 20 most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected.\n *\n * @return the 20 most recent replies\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getReplies() throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"statuses/replies.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected.\n *\n * @param page the number of page\n * @return the 20 most recent replies\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getRepliesByPage(int page) throws TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return Status.constructStatuses(get(baseURL + \"statuses/replies.xml\",\n \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.\n *\n * @param statusId The ID of the status to destroy.\n * @return the deleted status\n * @throws TwitterException when Twitter service or network is unavailable\n * @since 1.0.5\n */\n public Status destroyStatus(long statusId) throws TwitterException {\n return new Status(http.post(baseURL + \"statuses/destroy/\" + statusId + \".xml\",\n new PostParameter[0], true).asDocument().getDocumentElement(), this);\n }\n\n /* User Methods */\n\n /**\n * Returns the specified user's friends, each with current status inline.\n *\n * @return the list of friends\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends() throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the specified user's friends, each with current status inline.\n *\n * @param page number of page\n * @return the list of friends\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends(int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\", \"page\",\n String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the user's friends, each with current status inline.\n *\n * @param id the ID or screen name of the user for whom to request a list of friends\n * @return the list of friends\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends(String id) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\",\n \"id\", id, true).asDocument(), this);\n }\n\n /**\n * Returns the user's friends, each with current status inline.\n *\n * @param id the ID or screen name of the user for whom to request a list of friends\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFriends(String id, int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/friends.xml\",\n \"id\", id, \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFollowers() throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @param page Retrieves the next 100 followers.\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.0\n */\n public synchronized List getFollowers(int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers.xml\", \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @param id The ID or screen name of the user for whom to request a list of followers.\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.0\n */\n public synchronized List getFollowers(String id) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers/\" + id + \".xml\", true).asDocument(), this);\n }\n\n /**\n * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed).\n *\n * @param id The ID or screen name of the user for whom to request a list of followers.\n * @param page Retrieves the next 100 followers.\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.0\n */\n public synchronized List getFollowers(String id, int page) throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/followers/\" + id + \".xml\", \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the users currently featured on the site with their current statuses inline.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getFeatured() throws TwitterException {\n return User.constructUsers(get(baseURL + \"statuses/featured.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.\n *\n * @param id the ID or screen name of the user for whom to request the detail\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized UserWithStatus getUserDetail(String id) throws TwitterException {\n return new UserWithStatus(get(baseURL + \"users/show/\" + id + \".xml\", true).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessages() throws TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL + \"direct_messages.xml\", true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessagesByPage(int page) throws TwitterException {\n if (page < 1) {\n throw new IllegalArgumentException(\"page should be positive integer. passed:\" + page);\n }\n return DirectMessage.constructDirectMessages(get(baseURL + \"direct_messages.xml\",\n \"page\", String.valueOf(page), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @param sinceId int\n * @return list of direct messages\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessages(int sinceId) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages.xml\", \"since_id\", String.valueOf(sinceId), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent to the authenticating user.\n *\n * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date\n * @return list of direct messages\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getDirectMessages(Date since) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages.xml\", \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent by the authenticating user.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getSentDirectMessages() throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages/sent.xml\", new PostParameter[0], true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent by the authenticating user.\n *\n * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getSentDirectMessages(Date since) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages/sent.xml\", \"since\", format.format(since), true).asDocument(), this);\n }\n\n /**\n * Returns a list of the direct messages sent by the authenticating user.\n *\n * @param sinceId returns only sent direct messages with an ID greater than (that is, more recent than) the specified ID\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List getSentDirectMessages(int sinceId) throws\n TwitterException {\n return DirectMessage.constructDirectMessages(get(baseURL +\n \"direct_messages/sent.xml\", \"since_id\", String.valueOf(sinceId), true).asDocument(), this);\n }\n\n /**\n * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.\n * The text will be trimed if the length of the text is exceeding 140 characters.\n *\n * @param id the ID or screen name of the user to whom send the direct message\n * @param text String\n * @return DirectMessage\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized DirectMessage sendDirectMessage(String id,\n String text) throws TwitterException {\n if (text.length() > 160) {\n text = text.substring(0, 160);\n }\n return new DirectMessage(http.post(baseURL + \"direct_messages/new.xml\",\n new PostParameter[]{new PostParameter(\"user\", id),\n new PostParameter(\"text\", text)}, true).\n asDocument().getDocumentElement(), this);\n }\n\n\n /**\n * Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.\n *\n * @param id the ID of the direct message to destroy\n * @return the deleted direct message\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized DirectMessage deleteDirectMessage(int id) throws\n TwitterException {\n return new DirectMessage(http.post(baseURL +\n \"direct_messages/destroy/\" + id + \".xml\", new PostParameter[0], true).asDocument().getDocumentElement(), this);\n }\n\n /**\n * Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.\n *\n * @param id the ID or screen name of the user to be befriended\n * @return the befriended user\n * @throws TwitterException when Twitter service or network is unavailable\n */\n\n public synchronized User create(String id) throws TwitterException {\n return new User(http.post(baseURL + \"friendships/create/\" + id + \".xml\", new PostParameter[0], true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.\n *\n * @param id the ID or screen name of the user for whom to request a list of friends\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized User destroy(String id) throws TwitterException {\n return new User(http.post(baseURL + \"friendships/destroy/\" + id + \".xml\", new PostParameter[0], true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns true if authentication was successful. Use this method to test if supplied user credentials are valid with minimal overhead.\n *\n * @return success\n */\n public synchronized boolean verifyCredentials() {\n try {\n return get(baseURL + \"account/verify_credentials.xml\", true).getStatusCode() == 200;\n } catch (TwitterException te) {\n return false;\n }\n }\n\n /**\n * Update the location\n *\n * @param location the current location of the user\n * @return the updated user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User updateLocation(String location) throws TwitterException {\n return new User(http.post(baseURL + \"account/update_location.xml\", new PostParameter[]{new PostParameter(\"location\", location)}, true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Returns the remaining number of API requests available to the requesting user before the API limit is reached for the current hour. Calls to rate_limit_status do not count against the rate limit. If authentication credentials are provided, the rate limit status for the authenticating user is returned. Otherwise, the rate limit status for the requester's IP address is returned.
\n * See Twitter REST API Documentation &gt; Account Methods &gt; rate_limit_status for detail.\n *\n * @return the rate limit status\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.4\n */\n public synchronized RateLimitStatus rateLimitStatus() throws TwitterException {\n return new RateLimitStatus(http.get(baseURL + \"account/rate_limit_status.xml\", null != getUserId() && null != getPassword()).\n asDocument().getDocumentElement());\n }\n\n public final static Device IM = new Device(\"im\");\n public final static Device SMS = new Device(\"sms\");\n public final static Device NONE = new Device(\"none\");\n\n static class Device {\n final String DEVICE;\n\n public Device(String device) {\n DEVICE = device;\n }\n }\n\n /**\n * Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable IM or SMS updates.\n *\n * @param device new Delivery device. Must be one of: IM, SMS, NONE.\n * @return the updated user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User updateDeliverlyDevice(Device device) throws TwitterException {\n return new User(http.post(baseURL + \"account/update_delivery_device\", new PostParameter[]{new PostParameter(\"device\", device.DEVICE)}, true).\n asDocument().getDocumentElement(), this);\n }\n\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites() throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites.xml\", new PostParameter[0], true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites(int page) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites.xml\", \"page\", String.valueOf(page), true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @param id the ID or screen name of the user for whom to request a list of favorite statuses\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites(String id) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites/\" + id + \".xml\", new PostParameter[0], true).\n asDocument(), this);\n }\n\n /**\n * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.\n *\n * @param id the ID or screen name of the user for whom to request a list of favorite statuses\n * @param page the number of page\n * @return List\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized List favorites(String id, int page) throws TwitterException {\n return Status.constructStatuses(get(baseURL + \"favorites/\" + id + \".xml\", \"page\", String.valueOf(page), true).\n asDocument(), this);\n }\n\n /**\n * Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.\n *\n * @param id the ID of the status to favorite\n * @return Status\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized Status createFavorite(long id) throws TwitterException {\n return new Status(http.post(baseURL + \"favorites/create/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.\n *\n * @param id the ID of the status to un-favorite\n * @return Status\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized Status destroyFavorite(long id) throws TwitterException {\n return new Status(http.post(baseURL + \"favorites/destroy/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.\n *\n * @param id String\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized User follow(String id) throws TwitterException {\n return new User(http.post(baseURL + \"notifications/follow/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /**\n * Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.\n *\n * @param id String\n * @return User\n * @throws TwitterException when Twitter service or network is unavailable\n */\n public synchronized User leave(String id) throws TwitterException {\n return new User(http.post(baseURL + \"notifications/leave/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /* Block Methods */\n\n /**\n * Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful.\n *\n * @param id the ID or screen_name of the user to block\n * @return the blocked user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User block(String id) throws TwitterException {\n return new User(http.post(baseURL + \"blocks/create/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n\n /**\n * Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful.\n *\n * @param id the ID or screen_name of the user to block\n * @return the unblocked user\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized User unblock(String id) throws TwitterException {\n return new User(http.post(baseURL + \"blocks/destroy/\" + id + \".xml\", true).\n asDocument().getDocumentElement(), this);\n }\n\n /* Help Methods */\n/*\ntest New as of April 29th, 2008!\n\nReturns the string \"ok\" in the requested format with a 200 OK HTTP status code.\nURL:http://twitter.com/help/test.format\nFormats: xml, json\n*/\n\n /**\n * Returns the string \"ok\" in the requested format with a 200 OK HTTP status code.\n *\n * @return true if the API is working\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized boolean test() throws TwitterException {\n return -1 != get(baseURL + \"help/test.xml\", false).\n asString().indexOf(\"ok\");\n }\n\n /**\n * Returns extended information of the authenticated user. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.
\n * The call Twitter.getAuthenticatedUser() is equivalent to the call:
\n * twitter.getUserDetail(twitter.getUserId());\n *\n * @return UserWithStatus\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.1.3\n */\n public synchronized UserWithStatus getAuthenticatedUser() throws TwitterException {\n if(null == getUserId()){\n throw new IllegalStateException(\"User Id not specified.\");\n }\n return getUserDetail(getUserId());\n }\n\n/*\ndowntime_schedule New as of April 29th, 2008!\n\nReturns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format.\nURL:http://twitter.com/help/downtime_schedule.format\nFormats: xml, json\n*/\n\n /**\n * Returns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format.\n *\n * @return the schedule\n * @throws TwitterException when Twitter service or network is unavailable\n * @since twitter4j 1.0.4\n */\n public synchronized String getDowntimeSchedule() throws TwitterException {\n return get(baseURL + \"help/downtime_schedule.xml\", false).asString();\n }\n \n\n private SimpleDateFormat format = new SimpleDateFormat(\n \"EEE, d MMM yyyy HH:mm:ss z\", Locale.ENGLISH);\n\n public void setRetryCount(int retryCount) {\n http.setRetryCount(retryCount);\n }\n\n public void setRetryIntervalSecs(int retryIntervalSecs) {\n http.setRetryIntervalSecs(retryIntervalSecs);\n }\n\n @Override\n public int hashCode() {\n return http.hashCode() + this.baseURL.hashCode() + http.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (null == obj) {\n return false;\n }\n if (this == obj) {\n return true;\n }\n if (obj instanceof Twitter) {\n Twitter that = (Twitter) obj;\n return this.http.equals(that.http)\n && this.baseURL.equals(that.baseURL)\n && this.http.equals(that.http);\n }\n return false;\n }\n\n @Override\n public String toString() {\n return \"Twitter{\" +\n \"http=\" + http +\n \", baseURL='\" + baseURL + '\\'' +\n \", source='\" + source + '\\'' +\n \", usePostForcibly=\" + usePostForcibly +\n \", format=\" + format +\n '}';\n }\n}\n"},"message":{"kind":"string","value":"TFJ-48 support update_delivery_device method\n\ngit-svn-id: 45a72d8ee61e5c3af5aa32c3525f4dded50a42aa@160 117b7e0d-5933-0410-9d29-ab41bb01d86b\n"},"old_file":{"kind":"string","value":"src/main/java/twitter4j/Twitter.java"},"subject":{"kind":"string","value":"TFJ-48 support update_delivery_device method"}}},{"rowIdx":1238,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"bd37677dbbf34f2b562927bc286bade3e1230a44"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,tmpgit/intellij-community,semonte/intellij-community,suncycheng/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,samthor/intellij-community,kdwink/intellij-community,caot/intellij-community,supersven/intellij-community,dslomov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,signed/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,izonder/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,joewalnes/idea-community,clumsy/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,consulo/consulo,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,consulo/consulo,consulo/consulo,dslomov/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,da1z/intellij-community,petteyg/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,consulo/consulo,vvv1559/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,signed/intellij-community,ahb0327/intellij-community,semonte/intellij-community,apixandru/intellij-community,slisson/intellij-community,xfournet/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,slisson/intellij-community,robovm/robovm-studio,samthor/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,signed/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,holmes/intellij-community,da1z/intellij-community,jagguli/intellij-community,kdwink/intellij-community,izonder/intellij-community,dslomov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,blademainer/intellij-community,hurricup/intellij-community,amith01994/intellij-community,allotria/intellij-community,holmes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,asedunov/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,amith01994/intellij-community,slisson/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,jagguli/intellij-community,diorcety/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,holmes/intellij-community,adedayo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,semonte/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ryano144/intellij-community,supersven/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,jagguli/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,izonder/intellij-community,fitermay/intellij-community,signed/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,blademainer/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ryano144/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,caot/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ernestp/consulo,diorcety/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,holmes/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,kool79/intellij-community,robovm/robovm-studio,blademainer/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,izonder/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,allotria/intellij-community,jagguli/intellij-community,allotria/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,joewalnes/idea-community,supersven/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,caot/intellij-community,kdwink/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,joewalnes/idea-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,allotria/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,dslomov/intellij-community,consulo/consulo,vvv1559/intellij-community,orekyuu/intellij-community,da1z/intellij-community,slisson/intellij-community,fnouama/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ernestp/consulo,pwoodworth/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,allotria/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,allotria/intellij-community,signed/intellij-community,amith01994/intellij-community,robovm/robovm-studio,semonte/intellij-community,diorcety/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,clumsy/intellij-community,allotria/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,ernestp/consulo,fitermay/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,supersven/intellij-community,holmes/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,xfournet/intellij-community,kool79/intellij-community,youdonghai/intellij-community,holmes/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ernestp/consulo,alphafoobar/intellij-community,xfournet/intellij-community,allotria/intellij-community,fnouama/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,dslomov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,supersven/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,supersven/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,hurricup/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,signed/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vladmm/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,samthor/intellij-community,suncycheng/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,hurricup/intellij-community,blademainer/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,caot/intellij-community,samthor/intellij-community,xfournet/intellij-community,caot/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,samthor/intellij-community,slisson/intellij-community,consulo/consulo,signed/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,adedayo/intellij-community,ernestp/consulo,ahb0327/intellij-community,allotria/intellij-community,vladmm/intellij-community,fitermay/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,petteyg/intellij-community,retomerz/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fitermay/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,retomerz/intellij-community,slisson/intellij-community,FHannes/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,caot/intellij-community,orekyuu/intellij-community,ernestp/consulo,tmpgit/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,da1z/intellij-community,adedayo/intellij-community,dslomov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,kool79/intellij-community,youdonghai/intellij-community,slisson/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,ibinti/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fnouama/intellij-community,joewalnes/idea-community,clumsy/intellij-community,youdonghai/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,hurricup/intellij-community,izonder/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,retomerz/intellij-community,supersven/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,blademainer/intellij-community,slisson/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,kool79/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,caot/intellij-community,caot/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,wreckJ/intellij-community,da1z/intellij-community,robovm/robovm-studio,kool79/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,tmpgit/intellij-community,izonder/intellij-community,fitermay/intellij-community,semonte/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,signed/intellij-community,fitermay/intellij-community,da1z/intellij-community,adedayo/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,adedayo/intellij-community,da1z/intellij-community,vladmm/intellij-community,caot/intellij-community,blademainer/intellij-community,semonte/intellij-community,ahb0327/intellij-community,kool79/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,petteyg/intellij-community,kool79/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,samthor/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,caot/intellij-community,vladmm/intellij-community,ibinti/intellij-community,apixandru/intellij-community"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2000-2009 JetBrains s.r.o.\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 */\npackage com.intellij.debugger.ui;\n\nimport com.intellij.debugger.DebuggerBundle;\nimport com.intellij.debugger.DebuggerInvocationUtil;\nimport com.intellij.debugger.actions.DebuggerActions;\nimport com.intellij.debugger.engine.DebugProcessImpl;\nimport com.intellij.debugger.engine.DebuggerManagerThreadImpl;\nimport com.intellij.debugger.engine.SuspendContextImpl;\nimport com.intellij.debugger.engine.SuspendManagerUtil;\nimport com.intellij.debugger.engine.evaluation.EvaluateException;\nimport com.intellij.debugger.engine.evaluation.EvaluationContextImpl;\nimport com.intellij.debugger.engine.events.DebuggerContextCommandImpl;\nimport com.intellij.debugger.engine.events.SuspendContextCommandImpl;\nimport com.intellij.debugger.engine.jdi.StackFrameProxy;\nimport com.intellij.debugger.impl.DebuggerContextImpl;\nimport com.intellij.debugger.impl.DebuggerContextUtil;\nimport com.intellij.debugger.impl.DebuggerSession;\nimport com.intellij.debugger.impl.DebuggerStateManager;\nimport com.intellij.debugger.jdi.StackFrameProxyImpl;\nimport com.intellij.debugger.jdi.ThreadReferenceProxyImpl;\nimport com.intellij.debugger.settings.DebuggerSettings;\nimport com.intellij.debugger.ui.impl.DebuggerComboBoxRenderer;\nimport com.intellij.debugger.ui.impl.FramesList;\nimport com.intellij.debugger.ui.impl.UpdatableDebuggerView;\nimport com.intellij.debugger.ui.impl.watch.MethodsTracker;\nimport com.intellij.debugger.ui.impl.watch.StackFrameDescriptorImpl;\nimport com.intellij.debugger.ui.impl.watch.ThreadDescriptorImpl;\nimport com.intellij.debugger.ui.tree.render.DescriptorLabelListener;\nimport com.intellij.ide.OccurenceNavigator;\nimport com.intellij.openapi.Disposable;\nimport com.intellij.openapi.actionSystem.ActionManager;\nimport com.intellij.openapi.actionSystem.ActionPopupMenu;\nimport com.intellij.openapi.actionSystem.DefaultActionGroup;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.ui.ComboBoxWithWidePopup;\nimport com.intellij.ui.PopupHandler;\nimport com.intellij.ui.ScrollPaneFactory;\nimport com.sun.jdi.ObjectCollectedException;\n\nimport javax.swing.*;\nimport javax.swing.event.ListSelectionEvent;\nimport javax.swing.event.ListSelectionListener;\nimport java.awt.*;\nimport java.awt.event.ItemEvent;\nimport java.awt.event.ItemListener;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class FramesPanel extends UpdatableDebuggerView {\n private final JComboBox myThreadsCombo;\n private final FramesList myFramesList;\n private final ThreadsListener myThreadsListener;\n private final FramesListener myFramesListener;\n private final DebuggerStateManager myStateManager;\n private boolean myShowLibraryFrames = DebuggerSettings.getInstance().SHOW_LIBRARY_STACKFRAMES;\n \n public FramesPanel(Project project, DebuggerStateManager stateManager) {\n super(project, stateManager);\n myStateManager = stateManager;\n\n setLayout(new BorderLayout());\n\n myThreadsCombo = new ComboBoxWithWidePopup();\n myThreadsCombo.setRenderer(new DebuggerComboBoxRenderer());\n myThreadsListener = new ThreadsListener();\n myThreadsCombo.addItemListener(myThreadsListener);\n\n myFramesList = new FramesList(project);\n myFramesListener = new FramesListener();\n myFramesList.addListSelectionListener(myFramesListener);\n\n myFramesList.addMouseListener(new MouseAdapter() {\n public void mousePressed(final MouseEvent e) {\n int index = myFramesList.locationToIndex(e.getPoint());\n if (index >= 0 && myFramesList.isSelectedIndex(index)) {\n processListValue(myFramesList.getModel().getElementAt(index));\n }\n }\n });\n\n registerThreadsPopupMenu(myFramesList);\n\n setBorder(null);\n add(myThreadsCombo, BorderLayout.NORTH);\n add(ScrollPaneFactory.createScrollPane(myFramesList), BorderLayout.CENTER);\n }\n\n public DebuggerStateManager getContextManager() {\n return myStateManager;\n }\n\n private class FramesListener implements ListSelectionListener {\n boolean myIsEnabled = true;\n\n public void setEnabled(boolean enabled) {\n myIsEnabled = enabled;\n }\n\n public void valueChanged(ListSelectionEvent e) {\n if (!myIsEnabled || e.getValueIsAdjusting()) {\n return;\n }\n final JList list = (JList)e.getSource();\n processListValue(list.getSelectedValue());\n }\n\n }\n private void processListValue(final Object selected) {\n if (selected instanceof StackFrameDescriptorImpl) {\n DebuggerContextUtil.setStackFrame(getContextManager(), ((StackFrameDescriptorImpl)selected).getFrameProxy());\n }\n }\n\n\n private void registerThreadsPopupMenu(final JList framesList) {\n final PopupHandler popupHandler = new PopupHandler() {\n public void invokePopup(Component comp, int x, int y) {\n DefaultActionGroup group = (DefaultActionGroup)ActionManager.getInstance().getAction(DebuggerActions.THREADS_PANEL_POPUP);\n ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(DebuggerActions.THREADS_PANEL_POPUP, group);\n popupMenu.getComponent().show(comp, x, y);\n }\n };\n framesList.addMouseListener(popupHandler);\n registerDisposable(new Disposable() {\n public void dispose() {\n myThreadsCombo.removeItemListener(myThreadsListener);\n framesList.removeMouseListener(popupHandler);\n }\n });\n }\n\n private class ThreadsListener implements ItemListener {\n boolean myIsEnabled = true;\n\n public void setEnabled(boolean enabled) {\n myIsEnabled = enabled;\n }\n\n public void itemStateChanged(ItemEvent e) {\n if (!myIsEnabled) return;\n if (e.getStateChange() == ItemEvent.SELECTED) {\n ThreadDescriptorImpl item = (ThreadDescriptorImpl)e.getItem();\n DebuggerContextUtil.setThread(getContextManager(), item);\n }\n }\n }\n\n /*invoked in swing thread*/\n protected void rebuild(int event) {\n final DebuggerContextImpl context = getContext();\n final boolean paused = context.getDebuggerSession().isPaused();\n final boolean isRefresh = event == DebuggerSession.EVENT_REFRESH ||\n event == DebuggerSession.EVENT_REFRESH_VIEWS_ONLY ||\n event == DebuggerSession.EVENT_THREADS_REFRESH;\n if (!paused || !isRefresh) {\n myThreadsCombo.removeAllItems();\n synchronized (myFramesList) {\n myFramesList.clear();\n }\n }\n\n if (paused) {\n final DebugProcessImpl process = context.getDebugProcess();\n if (process != null) {\n process.getManagerThread().schedule(new RefreshFramePanelCommand(isRefresh && myThreadsCombo.getItemCount() != 0));\n }\n }\n }\n\n public boolean isShowLibraryFrames() {\n return myShowLibraryFrames;\n }\n\n public void setShowLibraryFrames(boolean showLibraryFrames) {\n if (myShowLibraryFrames != showLibraryFrames) {\n myShowLibraryFrames = showLibraryFrames;\n rebuild(DebuggerSession.EVENT_CONTEXT);\n }\n\n }\n\n public long getFramesLastUpdateTime() {\n return myFramesLastUpdateTime;\n }\n\n public void setFramesLastUpdateTime(long framesLastUpdateTime) {\n myFramesLastUpdateTime = framesLastUpdateTime;\n }\n\n private class RefreshFramePanelCommand extends DebuggerContextCommandImpl {\n private final boolean myRefreshOnly;\n private final ThreadDescriptorImpl[] myThreadDescriptorsToUpdate;\n\n public RefreshFramePanelCommand(final boolean refreshOnly) {\n super(getContext());\n myRefreshOnly = refreshOnly;\n if (refreshOnly) {\n final int size = myThreadsCombo.getItemCount();\n myThreadDescriptorsToUpdate = new ThreadDescriptorImpl[size];\n for (int idx = 0; idx < size; idx++) {\n myThreadDescriptorsToUpdate[idx] = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx);\n }\n }\n else {\n myThreadDescriptorsToUpdate = null;\n }\n }\n\n private List createThreadDescriptorsList() {\n final List threads = new ArrayList(getSuspendContext().getDebugProcess().getVirtualMachineProxy().allThreads());\n Collections.sort(threads, ThreadReferenceProxyImpl.ourComparator);\n\n final List descriptors = new ArrayList(threads.size());\n EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext();\n\n for (ThreadReferenceProxyImpl thread : threads) {\n ThreadDescriptorImpl threadDescriptor = new ThreadDescriptorImpl(thread);\n threadDescriptor.setContext(evaluationContext);\n threadDescriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n descriptors.add(threadDescriptor);\n }\n return descriptors;\n }\n\n public void threadAction() {\n if (myRefreshOnly && myThreadDescriptorsToUpdate.length != myThreadsCombo.getItemCount()) {\n // there is no sense in refreshing combobox if thread list has changed since creation of this command\n return;\n }\n \n final DebuggerContextImpl context = getDebuggerContext();\n\n final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy();\n if(threadToSelect == null) {\n return;\n }\n\n final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), threadToSelect);\n final ThreadDescriptorImpl currentThreadDescriptor = (ThreadDescriptorImpl)myThreadsCombo.getSelectedItem();\n final ThreadReferenceProxyImpl currentThread = currentThreadDescriptor != null? currentThreadDescriptor.getThreadReference() : null;\n\n if (myRefreshOnly && threadToSelect.equals(currentThread)) {\n context.getDebugProcess().getManagerThread().schedule(new UpdateFramesListCommand(context, threadContext));\n }\n else {\n context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext));\n }\n\n if (myRefreshOnly) {\n final EvaluationContextImpl evaluationContext = context.createEvaluationContext();\n for (ThreadDescriptorImpl descriptor : myThreadDescriptorsToUpdate) {\n descriptor.setContext(evaluationContext);\n descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n }\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myThreadsListener.setEnabled(false);\n selectThread(threadToSelect);\n myFramesList.repaint();\n }\n finally {\n myThreadsListener.setEnabled(true);\n }\n }\n });\n }\n else { // full rebuild\n refillThreadsCombo(threadToSelect);\n }\n }\n\n protected void commandCancelled() {\n if (!DebuggerManagerThreadImpl.isManagerThread()) {\n return;\n }\n // context thread is not suspended\n final DebuggerContextImpl context = getDebuggerContext();\n\n final SuspendContextImpl suspendContext = context.getSuspendContext();\n if (suspendContext == null) {\n return;\n }\n final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy();\n if(threadToSelect == null) {\n return;\n }\n\n if (!suspendContext.isResumed()) {\n final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(suspendContext, threadToSelect);\n context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext));\n refillThreadsCombo(threadToSelect);\n }\n }\n\n private void refillThreadsCombo(final ThreadReferenceProxyImpl threadToSelect) {\n final List threadItems = createThreadDescriptorsList();\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myThreadsListener.setEnabled(false);\n\n myThreadsCombo.removeAllItems();\n for (final ThreadDescriptorImpl threadItem : threadItems) {\n myThreadsCombo.addItem(threadItem);\n }\n\n selectThread(threadToSelect);\n }\n finally {\n myThreadsListener.setEnabled(true);\n }\n }\n });\n }\n\n }\n\n private class UpdateFramesListCommand extends SuspendContextCommandImpl {\n private final DebuggerContextImpl myDebuggerContext;\n\n public UpdateFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) {\n super(suspendContext);\n myDebuggerContext = debuggerContext;\n }\n\n public void contextAction() throws Exception {\n updateFrameList(myDebuggerContext.getThreadProxy());\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myFramesListener.setEnabled(false);\n final StackFrameProxyImpl contextFrame = getDebuggerContext().getFrameProxy();\n if(contextFrame != null) {\n selectFrame(contextFrame);\n }\n }\n finally {\n myFramesListener.setEnabled(true);\n }\n }\n });\n\n }\n\n private void updateFrameList(ThreadReferenceProxyImpl thread) {\n try {\n if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) {\n return;\n }\n }\n catch (ObjectCollectedException e) {\n return;\n }\n \n final EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext();\n final List descriptors = new ArrayList();\n\n synchronized (myFramesList) {\n final DefaultListModel model = myFramesList.getModel();\n final int size = model.getSize();\n for (int i = 0; i < size; i++) {\n final Object elem = model.getElementAt(i);\n if (elem instanceof StackFrameDescriptorImpl) {\n descriptors.add((StackFrameDescriptorImpl)elem);\n }\n }\n }\n\n for (StackFrameDescriptorImpl descriptor : descriptors) {\n descriptor.setContext(evaluationContext);\n descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n }\n }\n\n public DebuggerContextImpl getDebuggerContext() {\n return myDebuggerContext;\n }\n }\n\n private class RebuildFramesListCommand extends SuspendContextCommandImpl {\n private final DebuggerContextImpl myDebuggerContext;\n\n public RebuildFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) {\n super(suspendContext);\n myDebuggerContext = debuggerContext;\n }\n\n public void contextAction() throws Exception {\n final ThreadReferenceProxyImpl thread = myDebuggerContext.getThreadProxy();\n try {\n if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) {\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myFramesListener.setEnabled(false);\n synchronized (myFramesList) {\n final DefaultListModel model = myFramesList.getModel();\n model.clear();\n model.addElement(new Object() {\n public String toString() {\n return DebuggerBundle.message(\"frame.panel.frames.not.available\");\n }\n });\n myFramesList.setSelectedIndex(0);\n }\n }\n finally {\n myFramesListener.setEnabled(true);\n }\n }\n });\n \n return;\n }\n }\n catch (ObjectCollectedException e) {\n return;\n }\n\n List frames;\n try {\n frames = thread.frames();\n }\n catch (EvaluateException e) {\n frames = Collections.emptyList();\n }\n\n final StackFrameProxyImpl contextFrame = myDebuggerContext.getFrameProxy();\n final EvaluationContextImpl evaluationContext = myDebuggerContext.createEvaluationContext();\n final DebuggerManagerThreadImpl managerThread = myDebuggerContext.getDebugProcess().getManagerThread();\n final MethodsTracker tracker = new MethodsTracker();\n final int totalFramesCount = frames.size();\n int index = 0;\n final IndexCounter indexCounter = new IndexCounter(totalFramesCount);\n final long timestamp = Math.abs(System.nanoTime());\n for (StackFrameProxyImpl stackFrameProxy : frames) {\n managerThread.schedule(\n new AppendFrameCommand(\n getSuspendContext(), \n stackFrameProxy, \n evaluationContext, \n tracker, \n index++, \n stackFrameProxy.equals(contextFrame),\n timestamp, \n indexCounter\n )\n );\n }\n }\n }\n\n private void selectThread(ThreadReferenceProxyImpl toSelect) {\n int count = myThreadsCombo.getItemCount();\n for (int idx = 0; idx < count; idx++) {\n ThreadDescriptorImpl item = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx);\n if (toSelect.equals(item.getThreadReference())) {\n if (!item.equals(myThreadsCombo.getSelectedItem())) {\n myThreadsCombo.setSelectedIndex(idx);\n }\n return;\n }\n }\n }\n\n /*invoked in swing thread*/\n private void selectFrame(StackFrameProxy frame) {\n synchronized (myFramesList) {\n final int count = myFramesList.getElementCount();\n final Object selectedValue = myFramesList.getSelectedValue();\n final DefaultListModel model = myFramesList.getModel();\n for (int idx = 0; idx < count; idx++) {\n final Object elem = model.getElementAt(idx);\n if (elem instanceof StackFrameDescriptorImpl) {\n final StackFrameDescriptorImpl item = (StackFrameDescriptorImpl)elem;\n if (frame.equals(item.getFrameProxy())) {\n if (!item.equals(selectedValue)) {\n myFramesList.setSelectedIndex(idx);\n }\n return;\n }\n }\n }\n }\n }\n\n private static class IndexCounter {\n private final int[] myData;\n\n private IndexCounter(int totalSize) {\n myData = new int[totalSize];\n for (int idx = 0; idx < totalSize; idx++) {\n myData[idx] = 0;\n }\n }\n \n public void markCalculated(int idx){\n myData[idx] = 1;\n }\n \n public int getActualIndex(final int index) {\n int result = 0;\n for (int idx = 0; idx < index; idx++) {\n result += myData[idx];\n }\n return result;\n }\n }\n \n private volatile long myFramesLastUpdateTime = 0L;\n private class AppendFrameCommand extends SuspendContextCommandImpl {\n private final StackFrameProxyImpl myFrame;\n private final EvaluationContextImpl myEvaluationContext;\n private final MethodsTracker myTracker;\n private final int myIndexToInsert;\n private final boolean myIsContextFrame;\n private final long myTimestamp;\n private final IndexCounter myCounter;\n\n public AppendFrameCommand(SuspendContextImpl suspendContext, StackFrameProxyImpl frame, EvaluationContextImpl evaluationContext,\n MethodsTracker tracker, int indexToInsert, final boolean isContextFrame, final long timestamp, IndexCounter counter) {\n super(suspendContext);\n myFrame = frame;\n myEvaluationContext = evaluationContext;\n myTracker = tracker;\n myIndexToInsert = indexToInsert;\n myIsContextFrame = isContextFrame;\n myTimestamp = timestamp;\n myCounter = counter;\n }\n\n public void contextAction() throws Exception {\n final StackFrameDescriptorImpl descriptor = new StackFrameDescriptorImpl(myFrame, myTracker);\n descriptor.setContext(myEvaluationContext);\n descriptor.updateRepresentation(myEvaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n final Project project = getProject();\n DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() {\n public void run() {\n try {\n myFramesListener.setEnabled(false);\n synchronized (myFramesList) {\n final DefaultListModel model = myFramesList.getModel();\n if (model.isEmpty() || myFramesLastUpdateTime < myTimestamp) {\n myFramesLastUpdateTime = myTimestamp;\n model.clear();\n }\n if (myTimestamp != myFramesLastUpdateTime) {\n return; // the command has expired\n }\n final boolean shouldHide = !myShowLibraryFrames && !myIsContextFrame && myIndexToInsert != 0 && (descriptor.isSynthetic() || descriptor.isInLibraryContent());\n if (!shouldHide) {\n myCounter.markCalculated(myIndexToInsert);\n final int actualIndex = myCounter.getActualIndex(myIndexToInsert);\n model.insertElementAt(descriptor, actualIndex);\n if (myIsContextFrame) {\n myFramesList.setSelectedIndex(actualIndex);\n }\n }\n }\n }\n finally {\n myFramesListener.setEnabled(true);\n }\n }\n });\n }\n }\n\n public void requestFocus() {\n myThreadsCombo.requestFocus();\n }\n\n public OccurenceNavigator getOccurenceNavigator() {\n return myFramesList;\n }\n\n public FramesList getFramesList() {\n return myFramesList;\n }\n}\n"},"new_file":{"kind":"string","value":"java/debugger/impl/src/com/intellij/debugger/ui/FramesPanel.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2000-2009 JetBrains s.r.o.\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 */\npackage com.intellij.debugger.ui;\n\nimport com.intellij.debugger.DebuggerBundle;\nimport com.intellij.debugger.DebuggerInvocationUtil;\nimport com.intellij.debugger.actions.DebuggerActions;\nimport com.intellij.debugger.engine.DebugProcessImpl;\nimport com.intellij.debugger.engine.DebuggerManagerThreadImpl;\nimport com.intellij.debugger.engine.SuspendContextImpl;\nimport com.intellij.debugger.engine.SuspendManagerUtil;\nimport com.intellij.debugger.engine.evaluation.EvaluateException;\nimport com.intellij.debugger.engine.evaluation.EvaluationContextImpl;\nimport com.intellij.debugger.engine.events.DebuggerContextCommandImpl;\nimport com.intellij.debugger.engine.events.SuspendContextCommandImpl;\nimport com.intellij.debugger.engine.jdi.StackFrameProxy;\nimport com.intellij.debugger.impl.DebuggerContextImpl;\nimport com.intellij.debugger.impl.DebuggerContextUtil;\nimport com.intellij.debugger.impl.DebuggerSession;\nimport com.intellij.debugger.impl.DebuggerStateManager;\nimport com.intellij.debugger.jdi.StackFrameProxyImpl;\nimport com.intellij.debugger.jdi.ThreadReferenceProxyImpl;\nimport com.intellij.debugger.settings.DebuggerSettings;\nimport com.intellij.debugger.ui.impl.DebuggerComboBoxRenderer;\nimport com.intellij.debugger.ui.impl.FramesList;\nimport com.intellij.debugger.ui.impl.UpdatableDebuggerView;\nimport com.intellij.debugger.ui.impl.watch.MethodsTracker;\nimport com.intellij.debugger.ui.impl.watch.StackFrameDescriptorImpl;\nimport com.intellij.debugger.ui.impl.watch.ThreadDescriptorImpl;\nimport com.intellij.debugger.ui.tree.render.DescriptorLabelListener;\nimport com.intellij.ide.OccurenceNavigator;\nimport com.intellij.openapi.Disposable;\nimport com.intellij.openapi.actionSystem.ActionManager;\nimport com.intellij.openapi.actionSystem.ActionPopupMenu;\nimport com.intellij.openapi.actionSystem.DefaultActionGroup;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.ui.ComboBoxWithWidePopup;\nimport com.intellij.ui.PopupHandler;\nimport com.intellij.ui.ScrollPaneFactory;\nimport com.sun.jdi.ObjectCollectedException;\n\nimport javax.swing.*;\nimport javax.swing.event.ListSelectionEvent;\nimport javax.swing.event.ListSelectionListener;\nimport java.awt.*;\nimport java.awt.event.ItemEvent;\nimport java.awt.event.ItemListener;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class FramesPanel extends UpdatableDebuggerView {\n private final JComboBox myThreadsCombo;\n private final FramesList myFramesList;\n private final ThreadsListener myThreadsListener;\n private final FramesListener myFramesListener;\n private final DebuggerStateManager myStateManager;\n private boolean myShowLibraryFrames = DebuggerSettings.getInstance().SHOW_LIBRARY_STACKFRAMES;\n \n public FramesPanel(Project project, DebuggerStateManager stateManager) {\n super(project, stateManager);\n myStateManager = stateManager;\n\n setLayout(new BorderLayout());\n\n myThreadsCombo = new ComboBoxWithWidePopup();\n myThreadsCombo.setRenderer(new DebuggerComboBoxRenderer());\n myThreadsListener = new ThreadsListener();\n myThreadsCombo.addItemListener(myThreadsListener);\n\n myFramesList = new FramesList(project);\n myFramesListener = new FramesListener();\n myFramesList.addListSelectionListener(myFramesListener);\n\n myFramesList.addMouseListener(new MouseAdapter() {\n public void mousePressed(final MouseEvent e) {\n int index = myFramesList.locationToIndex(e.getPoint());\n if (index >= 0 && myFramesList.isSelectedIndex(index)) {\n processListValue(myFramesList.getModel().getElementAt(index));\n }\n }\n });\n\n registerThreadsPopupMenu(myFramesList);\n\n setBorder(null);\n add(myThreadsCombo, BorderLayout.NORTH);\n add(ScrollPaneFactory.createScrollPane(myFramesList), BorderLayout.CENTER);\n }\n\n public DebuggerStateManager getContextManager() {\n return myStateManager;\n }\n\n private class FramesListener implements ListSelectionListener {\n boolean myIsEnabled = true;\n\n public void setEnabled(boolean enabled) {\n myIsEnabled = enabled;\n }\n\n public void valueChanged(ListSelectionEvent e) {\n if (!myIsEnabled || e.getValueIsAdjusting()) {\n return;\n }\n final JList list = (JList)e.getSource();\n processListValue(list.getSelectedValue());\n }\n\n }\n private void processListValue(final Object selected) {\n if (selected instanceof StackFrameDescriptorImpl) {\n DebuggerContextUtil.setStackFrame(getContextManager(), ((StackFrameDescriptorImpl)selected).getFrameProxy());\n }\n }\n\n\n private void registerThreadsPopupMenu(final JList framesList) {\n final PopupHandler popupHandler = new PopupHandler() {\n public void invokePopup(Component comp, int x, int y) {\n DefaultActionGroup group = (DefaultActionGroup)ActionManager.getInstance().getAction(DebuggerActions.THREADS_PANEL_POPUP);\n ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(DebuggerActions.THREADS_PANEL_POPUP, group);\n popupMenu.getComponent().show(comp, x, y);\n }\n };\n framesList.addMouseListener(popupHandler);\n registerDisposable(new Disposable() {\n public void dispose() {\n myThreadsCombo.removeItemListener(myThreadsListener);\n framesList.removeMouseListener(popupHandler);\n }\n });\n }\n\n private class ThreadsListener implements ItemListener {\n boolean myIsEnabled = true;\n\n public void setEnabled(boolean enabled) {\n myIsEnabled = enabled;\n }\n\n public void itemStateChanged(ItemEvent e) {\n if (!myIsEnabled) return;\n if (e.getStateChange() == ItemEvent.SELECTED) {\n ThreadDescriptorImpl item = (ThreadDescriptorImpl)e.getItem();\n DebuggerContextUtil.setThread(getContextManager(), item);\n }\n }\n }\n\n /*invoked in swing thread*/\n protected void rebuild(int event) {\n final DebuggerContextImpl context = getContext();\n final boolean paused = context.getDebuggerSession().isPaused();\n final boolean isRefresh = event == DebuggerSession.EVENT_REFRESH ||\n event == DebuggerSession.EVENT_REFRESH_VIEWS_ONLY ||\n event == DebuggerSession.EVENT_THREADS_REFRESH;\n if (!paused || !isRefresh) {\n myThreadsCombo.removeAllItems();\n synchronized (myFramesList) {\n myFramesList.clear();\n }\n }\n\n if (paused) {\n final DebugProcessImpl process = context.getDebugProcess();\n if (process != null) {\n process.getManagerThread().schedule(new RefreshFramePanelCommand(isRefresh && myThreadsCombo.getItemCount() != 0));\n }\n }\n }\n\n public boolean isShowLibraryFrames() {\n return myShowLibraryFrames;\n }\n\n public void setShowLibraryFrames(boolean showLibraryFrames) {\n if (myShowLibraryFrames != showLibraryFrames) {\n myShowLibraryFrames = showLibraryFrames;\n rebuild(DebuggerSession.EVENT_CONTEXT);\n }\n\n }\n\n public long getFramesLastUpdateTime() {\n return myFramesLastUpdateTime;\n }\n\n public void setFramesLastUpdateTime(long framesLastUpdateTime) {\n myFramesLastUpdateTime = framesLastUpdateTime;\n }\n\n private class RefreshFramePanelCommand extends DebuggerContextCommandImpl {\n private final boolean myRefreshOnly;\n private final ThreadDescriptorImpl[] myThreadDescriptorsToUpdate;\n\n public RefreshFramePanelCommand(final boolean refreshOnly) {\n super(getContext());\n myRefreshOnly = refreshOnly;\n if (refreshOnly) {\n final int size = myThreadsCombo.getItemCount();\n myThreadDescriptorsToUpdate = new ThreadDescriptorImpl[size];\n for (int idx = 0; idx < size; idx++) {\n myThreadDescriptorsToUpdate[idx] = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx);\n }\n }\n else {\n myThreadDescriptorsToUpdate = null;\n }\n }\n\n private List createThreadDescriptorsList() {\n final List threads = new ArrayList(getSuspendContext().getDebugProcess().getVirtualMachineProxy().allThreads());\n Collections.sort(threads, ThreadReferenceProxyImpl.ourComparator);\n\n final List descriptors = new ArrayList(threads.size());\n EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext();\n\n for (ThreadReferenceProxyImpl thread : threads) {\n ThreadDescriptorImpl threadDescriptor = new ThreadDescriptorImpl(thread);\n threadDescriptor.setContext(evaluationContext);\n threadDescriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n descriptors.add(threadDescriptor);\n }\n return descriptors;\n }\n\n public void threadAction() {\n if (myRefreshOnly && myThreadDescriptorsToUpdate.length != myThreadsCombo.getItemCount()) {\n // there is no sense in refreshing combobox if thread list has changed since creation of this command\n return;\n }\n \n final DebuggerContextImpl context = getDebuggerContext();\n\n final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy();\n if(threadToSelect == null) {\n return;\n }\n\n final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), threadToSelect);\n final ThreadDescriptorImpl currentThreadDescriptor = (ThreadDescriptorImpl)myThreadsCombo.getSelectedItem();\n final ThreadReferenceProxyImpl currentThread = currentThreadDescriptor != null? currentThreadDescriptor.getThreadReference() : null;\n\n if (myRefreshOnly && threadToSelect.equals(currentThread)) {\n context.getDebugProcess().getManagerThread().schedule(new UpdateFramesListCommand(context, threadContext));\n }\n else {\n context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext));\n }\n\n if (myRefreshOnly) {\n final EvaluationContextImpl evaluationContext = context.createEvaluationContext();\n for (ThreadDescriptorImpl descriptor : myThreadDescriptorsToUpdate) {\n descriptor.setContext(evaluationContext);\n descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n }\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myThreadsListener.setEnabled(false);\n selectThread(threadToSelect);\n myFramesList.repaint();\n }\n finally {\n myThreadsListener.setEnabled(true);\n }\n }\n });\n }\n else { // full rebuild\n refillThreadsCombo(threadToSelect);\n }\n }\n\n protected void commandCancelled() {\n if (!DebuggerManagerThreadImpl.isManagerThread()) {\n return;\n }\n // context thread is not suspended\n final DebuggerContextImpl context = getDebuggerContext();\n\n final SuspendContextImpl suspendContext = context.getSuspendContext();\n if (suspendContext == null) {\n return;\n }\n final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy();\n if(threadToSelect == null) {\n return;\n }\n\n if (!suspendContext.isResumed()) {\n final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(suspendContext, threadToSelect);\n context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext));\n refillThreadsCombo(threadToSelect);\n }\n }\n\n private void refillThreadsCombo(final ThreadReferenceProxyImpl threadToSelect) {\n final List threadItems = createThreadDescriptorsList();\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myThreadsListener.setEnabled(false);\n\n myThreadsCombo.removeAllItems();\n for (final ThreadDescriptorImpl threadItem : threadItems) {\n myThreadsCombo.addItem(threadItem);\n }\n\n selectThread(threadToSelect);\n }\n finally {\n myThreadsListener.setEnabled(true);\n }\n }\n });\n }\n\n }\n\n private class UpdateFramesListCommand extends SuspendContextCommandImpl {\n private final DebuggerContextImpl myDebuggerContext;\n\n public UpdateFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) {\n super(suspendContext);\n myDebuggerContext = debuggerContext;\n }\n\n public void contextAction() throws Exception {\n updateFrameList(myDebuggerContext.getThreadProxy());\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myFramesListener.setEnabled(false);\n final StackFrameProxyImpl contextFrame = getDebuggerContext().getFrameProxy();\n if(contextFrame != null) {\n selectFrame(contextFrame);\n }\n }\n finally {\n myFramesListener.setEnabled(true);\n }\n }\n });\n\n }\n\n private void updateFrameList(ThreadReferenceProxyImpl thread) {\n try {\n if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) {\n return;\n }\n }\n catch (ObjectCollectedException e) {\n return;\n }\n \n final EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext();\n final List descriptors = new ArrayList();\n\n synchronized (myFramesList) {\n final DefaultListModel model = myFramesList.getModel();\n final int size = model.getSize();\n for (int i = 0; i < size; i++) {\n final Object elem = model.getElementAt(i);\n if (elem instanceof StackFrameDescriptorImpl) {\n descriptors.add((StackFrameDescriptorImpl)elem);\n }\n }\n }\n\n for (StackFrameDescriptorImpl descriptor : descriptors) {\n descriptor.setContext(evaluationContext);\n descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n }\n }\n\n public DebuggerContextImpl getDebuggerContext() {\n return myDebuggerContext;\n }\n }\n\n private class RebuildFramesListCommand extends SuspendContextCommandImpl {\n private final DebuggerContextImpl myDebuggerContext;\n\n public RebuildFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) {\n super(suspendContext);\n myDebuggerContext = debuggerContext;\n }\n\n public void contextAction() throws Exception {\n final ThreadReferenceProxyImpl thread = myDebuggerContext.getThreadProxy();\n try {\n if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) {\n DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() {\n public void run() {\n try {\n myFramesListener.setEnabled(false);\n synchronized (myFramesList) {\n final DefaultListModel model = myFramesList.getModel();\n model.clear();\n model.addElement(new Object() {\n public String toString() {\n return DebuggerBundle.message(\"frame.panel.frames.not.available\");\n }\n });\n myFramesList.setSelectedIndex(0);\n }\n }\n finally {\n myFramesListener.setEnabled(true);\n }\n }\n });\n \n return;\n }\n }\n catch (ObjectCollectedException e) {\n return;\n }\n\n List frames;\n try {\n frames = thread.frames();\n }\n catch (EvaluateException e) {\n frames = Collections.emptyList();\n }\n\n final StackFrameProxyImpl contextFrame = myDebuggerContext.getFrameProxy();\n final EvaluationContextImpl evaluationContext = myDebuggerContext.createEvaluationContext();\n final DebuggerManagerThreadImpl managerThread = myDebuggerContext.getDebugProcess().getManagerThread();\n final MethodsTracker tracker = new MethodsTracker();\n final int totalFramesCount = frames.size();\n int index = 0;\n final IndexCounter indexCounter = new IndexCounter(totalFramesCount);\n final long timestamp = Math.abs(System.nanoTime());\n for (StackFrameProxyImpl stackFrameProxy : frames) {\n managerThread.schedule(\n new AppendFrameCommand(\n getSuspendContext(), \n stackFrameProxy, \n evaluationContext, \n tracker, \n index++, \n stackFrameProxy.equals(contextFrame), \n totalFramesCount, \n timestamp, \n indexCounter\n )\n );\n }\n }\n }\n\n private void selectThread(ThreadReferenceProxyImpl toSelect) {\n int count = myThreadsCombo.getItemCount();\n for (int idx = 0; idx < count; idx++) {\n ThreadDescriptorImpl item = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx);\n if (toSelect.equals(item.getThreadReference())) {\n if (!item.equals(myThreadsCombo.getSelectedItem())) {\n myThreadsCombo.setSelectedIndex(idx);\n }\n return;\n }\n }\n }\n\n /*invoked in swing thread*/\n private void selectFrame(StackFrameProxy frame) {\n synchronized (myFramesList) {\n final int count = myFramesList.getElementCount();\n final Object selectedValue = myFramesList.getSelectedValue();\n final DefaultListModel model = myFramesList.getModel();\n for (int idx = 0; idx < count; idx++) {\n final Object elem = model.getElementAt(idx);\n if (elem instanceof StackFrameDescriptorImpl) {\n final StackFrameDescriptorImpl item = (StackFrameDescriptorImpl)elem;\n if (frame.equals(item.getFrameProxy())) {\n if (!item.equals(selectedValue)) {\n myFramesList.setSelectedIndex(idx);\n }\n return;\n }\n }\n }\n }\n }\n\n private static class IndexCounter {\n private final int[] myData;\n\n private IndexCounter(int totalSize) {\n myData = new int[totalSize];\n for (int idx = 0; idx < totalSize; idx++) {\n myData[idx] = 1;\n }\n }\n \n public void markHidden(int idx){\n myData[idx] = 0;\n }\n \n public int getActualIndex(final int index) {\n int result = 0;\n for (int idx = 0; idx < index; idx++) {\n result += myData[idx];\n }\n return result;\n }\n }\n \n private volatile long myFramesLastUpdateTime = 0L;\n private class AppendFrameCommand extends SuspendContextCommandImpl {\n private final StackFrameProxyImpl myFrame;\n private final EvaluationContextImpl myEvaluationContext;\n private final MethodsTracker myTracker;\n private final int myIndexToInsert;\n private final boolean myIsContextFrame;\n private final int myTotalFramesCount;\n private final long myTimestamp;\n private final IndexCounter myCounter;\n\n public AppendFrameCommand(SuspendContextImpl suspendContext, StackFrameProxyImpl frame, EvaluationContextImpl evaluationContext,\n MethodsTracker tracker, int indexToInsert, final boolean isContextFrame, final int totalFramesCount,\n final long timestamp, IndexCounter counter) {\n super(suspendContext);\n myFrame = frame;\n myEvaluationContext = evaluationContext;\n myTracker = tracker;\n myIndexToInsert = indexToInsert;\n myIsContextFrame = isContextFrame;\n myTotalFramesCount = totalFramesCount;\n myTimestamp = timestamp;\n myCounter = counter;\n }\n\n public void contextAction() throws Exception {\n final StackFrameDescriptorImpl descriptor = new StackFrameDescriptorImpl(myFrame, myTracker);\n descriptor.setContext(myEvaluationContext);\n descriptor.updateRepresentation(myEvaluationContext, DescriptorLabelListener.DUMMY_LISTENER);\n final Project project = getProject();\n DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() {\n public void run() {\n try {\n myFramesListener.setEnabled(false);\n synchronized (myFramesList) {\n final DefaultListModel model = myFramesList.getModel();\n if (model.isEmpty() || myFramesLastUpdateTime < myTimestamp) {\n myFramesLastUpdateTime = myTimestamp;\n model.clear();\n for (int idx = 0; idx < myTotalFramesCount; idx++) {\n final String label = \"\";\n model.addElement(new Object() {\n public String toString() {\n return label;\n }\n });\n }\n }\n if (myTimestamp != myFramesLastUpdateTime) {\n return; // the command has expired\n }\n final int actualIndex = myCounter.getActualIndex(myIndexToInsert);\n model.removeElementAt(actualIndex); // remove placeholder\n boolean shouldHide = !myShowLibraryFrames && !myIsContextFrame && myIndexToInsert != 0 && (descriptor.isSynthetic() || descriptor.isInLibraryContent());\n if (shouldHide) {\n myCounter.markHidden(myIndexToInsert);\n }\n else {\n model.insertElementAt(descriptor, actualIndex);\n if (myIsContextFrame) {\n myFramesList.setSelectedIndex(actualIndex);\n }\n }\n }\n }\n finally {\n myFramesListener.setEnabled(true);\n }\n }\n });\n }\n }\n\n public void requestFocus() {\n myThreadsCombo.requestFocus();\n }\n\n public OccurenceNavigator getOccurenceNavigator() {\n return myFramesList;\n }\n\n public FramesList getFramesList() {\n return myFramesList;\n }\n}\n"},"message":{"kind":"string","value":"rollback incorrect change\n"},"old_file":{"kind":"string","value":"java/debugger/impl/src/com/intellij/debugger/ui/FramesPanel.java"},"subject":{"kind":"string","value":"rollback incorrect change"}}},{"rowIdx":1239,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"04f87b84b87bcfd3d2652179318b579c2d528333"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse"},"new_contents":{"kind":"string","value":"package edu.harvard.iq.dataverse;\n\nimport edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;\nimport edu.harvard.iq.dataverse.authorization.DataverseRole;\nimport edu.harvard.iq.dataverse.authorization.DataverseRolePermissionHelper;\nimport edu.harvard.iq.dataverse.authorization.Permission;\nimport edu.harvard.iq.dataverse.authorization.RoleAssignee;\nimport edu.harvard.iq.dataverse.authorization.RoleAssigneeDisplayInfo;\nimport edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean;\nimport edu.harvard.iq.dataverse.authorization.groups.impl.builtin.AuthenticatedUsers;\nimport edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroup;\nimport edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupServiceBean;\nimport edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;\nimport edu.harvard.iq.dataverse.engine.command.exception.CommandException;\nimport edu.harvard.iq.dataverse.engine.command.exception.PermissionException;\nimport edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand;\nimport edu.harvard.iq.dataverse.engine.command.impl.CreateRoleCommand;\nimport edu.harvard.iq.dataverse.engine.command.impl.RevokeRoleCommand;\nimport edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseDefaultContributorRoleCommand;\nimport edu.harvard.iq.dataverse.util.JsfHelper;\nimport static edu.harvard.iq.dataverse.util.JsfHelper.JH;\nimport edu.harvard.iq.dataverse.util.StringUtil;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.ResourceBundle;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.ejb.EJB;\nimport javax.faces.application.FacesMessage;\nimport javax.faces.event.ActionEvent;\nimport javax.faces.view.ViewScoped;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\nimport org.apache.commons.lang.StringEscapeUtils;\n\n/**\n *\n * @author gdurand\n */\n@ViewScoped\n@Named\npublic class ManagePermissionsPage implements java.io.Serializable {\n\n private static final Logger logger = Logger.getLogger(ManagePermissionsPage.class.getCanonicalName());\n\n @EJB\n DvObjectServiceBean dvObjectService;\n @EJB\n DataverseRoleServiceBean roleService;\n @EJB\n RoleAssigneeServiceBean roleAssigneeService;\n @EJB\n PermissionServiceBean permissionService;\n @EJB\n AuthenticationServiceBean authenticationService;\n @EJB\n ExplicitGroupServiceBean explicitGroupService;\n @EJB \n GroupServiceBean groupService;\n @EJB\n EjbDataverseEngine commandEngine;\n @EJB\n UserNotificationServiceBean userNotificationService;\n @Inject\n DataverseRequestServiceBean dvRequestService;\n @Inject\n PermissionsWrapper permissionsWrapper;\n\n\n @PersistenceContext(unitName = \"VDCNet-ejbPU\")\n EntityManager em;\n\n @Inject\n DataverseSession session;\n \n private DataverseRolePermissionHelper dataverseRolePermissionHelper;\n private List roleList;\n\n DvObject dvObject = new Dataverse(); // by default we use a Dataverse, but this will be overridden in init by the findById\n \n public DvObject getDvObject() {\n return dvObject;\n }\n\n public void setDvObject(DvObject dvObject) {\n this.dvObject = dvObject;\n /*\n SEK 09/15/2016 - may need to do something here if permissions are transmitted/inherited from dataverse to dataverse\n */\n \n /*if (dvObject instanceof DvObjectContainer) {\n inheritAssignments = !((DvObjectContainer) dvObject).isPermissionRoot();\n }*/\n }\n\n public String init() {\n //@todo deal with any kind of dvObject\n if (dvObject.getId() != null) {\n dvObject = dvObjectService.findDvObject(dvObject.getId());\n }\n\n // check if dvObject exists and user has permission\n if (dvObject == null) {\n return permissionsWrapper.notFound();\n }\n\n // for dataFiles, check the perms on its owning dataset\n DvObject checkPermissionsdvObject = dvObject instanceof DataFile ? dvObject.getOwner() : dvObject;\n if (!permissionService.on(checkPermissionsdvObject).has(checkPermissionsdvObject instanceof Dataverse ? Permission.ManageDataversePermissions : Permission.ManageDatasetPermissions)) {\n return permissionsWrapper.notAuthorized();\n }\n\n // initialize the configure settings\n if (dvObject instanceof Dataverse) {\n initAccessSettings();\n }\n roleList = roleService.findAll();\n roleAssignments = initRoleAssignments();\n dataverseRolePermissionHelper = new DataverseRolePermissionHelper(roleList); \n return \"\";\n }\n\n /* \n main page - role assignment table\n */\n \n // used by remove Role Assignment\n private RoleAssignment selectedRoleAssignment;\n\n public RoleAssignment getSelectedRoleAssignment() {\n return selectedRoleAssignment;\n }\n\n public void setSelectedRoleAssignment(RoleAssignment selectedRoleAssignment) {\n this.selectedRoleAssignment = selectedRoleAssignment;\n } \n \n private List roleAssignments;\n\n public List getRoleAssignments() {\n return roleAssignments;\n }\n\n public void setRoleAssignments(List roleAssignments) {\n this.roleAssignments = roleAssignments;\n }\n \n public List initRoleAssignments() {\n List raList = null;\n if (dvObject != null && dvObject.getId() != null) {\n Set ras = roleService.rolesAssignments(dvObject);\n raList = new ArrayList<>(ras.size());\n for (RoleAssignment roleAssignment : ras) {\n // for files, only show role assignments which can download\n if (!(dvObject instanceof DataFile) || roleAssignment.getRole().permissions().contains(Permission.DownloadFile)) {\n RoleAssignee roleAssignee = roleAssigneeService.getRoleAssignee(roleAssignment.getAssigneeIdentifier());\n if (roleAssignee != null) {\n raList.add(new RoleAssignmentRow(roleAssignment, roleAssignee.getDisplayInfo()));\n } else {\n logger.info(\"Could not find role assignee based on role assignment id \" + roleAssignment.getId());\n }\n }\n }\n }\n return raList;\n }\n \n public void removeRoleAssignment() {\n revokeRole(selectedRoleAssignment);\n\n if (dvObject instanceof Dataverse) {\n initAccessSettings(); // in case the revoke was for the AuthenticatedUsers group\n } \n roleAssignments = initRoleAssignments();\n showAssignmentMessages(); \n }\n \n // internal method used by removeRoleAssignment and saveConfiguration\n private void revokeRole(RoleAssignment ra) {\n try {\n commandEngine.submit(new RevokeRoleCommand(ra, dvRequestService.getDataverseRequest()));\n JsfHelper.addSuccessMessage(ra.getRole().getName() + \" role for \" + roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier()).getDisplayInfo().getTitle() + \" was removed.\");\n RoleAssignee assignee = roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier());\n notifyRoleChange(assignee, UserNotification.Type.REVOKEROLE);\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"The role assignment was not able to be removed.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"The role assignment could not be removed.\");\n logger.log(Level.SEVERE, \"Error removing role assignment: \" + ex.getMessage(), ex);\n }\n }\n \n /* \n main page - roles table\n */ \n\n public List getRoles() {\n if (dvObject != null && dvObject.getId() != null) {\n return roleService.findByOwnerId(dvObject.getId());\n }\n return new ArrayList<>();\n }\n\n public void createNewRole(ActionEvent e) {\n setRole(new DataverseRole());\n role.setOwner(dvObject);\n }\n\n public void cloneRole(String roleId) {\n DataverseRole clonedRole = new DataverseRole();\n clonedRole.setOwner(dvObject);\n\n DataverseRole originalRole = roleService.find(Long.parseLong(roleId));\n clonedRole.addPermissions(originalRole.permissions());\n setRole(clonedRole);\n }\n\n public void editRole(String roleId) {\n setRole(roleService.find(Long.parseLong(roleId)));\n }\n \n /*\n ============================================================================\n edit configuration dialog // only for dataverse version of page\n ============================================================================\n */\n \n private String authenticatedUsersContributorRoleAlias = null;\n private String defaultContributorRoleAlias = DataverseRole.EDITOR;\n\n public String getAuthenticatedUsersContributorRoleAlias() {\n return authenticatedUsersContributorRoleAlias;\n }\n\n public void setAuthenticatedUsersContributorRoleAlias(String authenticatedUsersContributorRoleAlias) {\n this.authenticatedUsersContributorRoleAlias = authenticatedUsersContributorRoleAlias;\n }\n\n public String getDefaultContributorRoleAlias() {\n return defaultContributorRoleAlias;\n }\n\n public void setDefaultContributorRoleAlias(String defaultContributorRoleAlias) {\n this.defaultContributorRoleAlias = defaultContributorRoleAlias;\n } \n \n public void initAccessSettings() {\n if (dvObject instanceof Dataverse) {\n authenticatedUsersContributorRoleAlias = \"\";\n\n List aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject);\n for (RoleAssignment roleAssignment : aUsersRoleAssignments) {\n String roleAlias = roleAssignment.getRole().getAlias();\n authenticatedUsersContributorRoleAlias = roleAlias;\n break;\n // @todo handle case where more than one role has been assigned to the AutenticatedUsers group!\n }\n\n defaultContributorRoleAlias = ((Dataverse) dvObject).getDefaultContributorRole().getAlias(); \n }\n }\n \n \n public void saveConfiguration(ActionEvent e) {\n // Set role (if any) for authenticatedUsers\n DataverseRole roleToAssign = null;\n List contributorRoles = Arrays.asList(DataverseRole.FULL_CONTRIBUTOR, DataverseRole.DV_CONTRIBUTOR, DataverseRole.DS_CONTRIBUTOR);\n\n if (!StringUtil.isEmpty(authenticatedUsersContributorRoleAlias)) {\n roleToAssign = roleService.findBuiltinRoleByAlias(authenticatedUsersContributorRoleAlias);\n }\n\n // then, check current contributor role\n List aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject);\n for (RoleAssignment roleAssignment : aUsersRoleAssignments) {\n DataverseRole currentRole = roleAssignment.getRole();\n if (contributorRoles.contains(currentRole.getAlias())) {\n if (currentRole.equals(roleToAssign)) {\n roleToAssign = null; // found the role, so no need to assign\n } else {\n revokeRole(roleAssignment);\n }\n }\n }\n // finally, assign role, if new\n if (roleToAssign != null) {\n assignRole(AuthenticatedUsers.get(), roleToAssign);\n }\n\n // set dataverse default contributor role\n if (dvObject instanceof Dataverse) {\n Dataverse dv = (Dataverse) dvObject;\n DataverseRole defaultRole = roleService.findBuiltinRoleByAlias(defaultContributorRoleAlias);\n if (!defaultRole.equals(dv.getDefaultContributorRole())) {\n try {\n commandEngine.submit(new UpdateDataverseDefaultContributorRoleCommand(defaultRole, dvRequestService.getDataverseRequest(), dv));\n JsfHelper.addSuccessMessage(\"The default permissions for this dataverse have been updated.\");\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"Cannot assign default permissions.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"Cannot assign default permissions.\");\n logger.log(Level.SEVERE, \"Error assigning default permissions: \" + ex.getMessage(), ex);\n }\n }\n }\n roleAssignments = initRoleAssignments();\n showConfigureMessages();\n } \n\n /*\n ============================================================================\n assign roles dialog\n ============================================================================\n */\n private List roleAssignSelectedRoleAssignees;\n private Long selectedRoleId;\n\n public List getRoleAssignSelectedRoleAssignees() {\n return roleAssignSelectedRoleAssignees;\n }\n\n public void setRoleAssignSelectedRoleAssignees(List selectedRoleAssignees) {\n this.roleAssignSelectedRoleAssignees = selectedRoleAssignees;\n }\n\n public Long getSelectedRoleId() {\n return selectedRoleId;\n }\n\n public void setSelectedRoleId(Long selectedRoleId) {\n this.selectedRoleId = selectedRoleId;\n }\n\n public void initAssigneeDialog(ActionEvent ae) {\n roleAssignSelectedRoleAssignees = new LinkedList<>();\n selectedRoleId = null;\n showNoMessages();\n }\n \n public List completeRoleAssignee( String query ) {\n return roleAssigneeService.filterRoleAssignees(query, dvObject, roleAssignSelectedRoleAssignees); \n }\n \n public List getAvailableRoles() {\n List roles = new LinkedList<>();\n if (dvObject != null && dvObject.getId() != null) {\n\n if (dvObject instanceof Dataverse) {\n roles.addAll(roleService.availableRoles(dvObject.getId()));\n \n } else if (dvObject instanceof Dataset) {\n // don't show roles that only have Dataverse level permissions\n // current the available roles for a dataset are gotten from its parent\n for (DataverseRole role : roleService.availableRoles(dvObject.getOwner().getId())) {\n for (Permission permission : role.permissions()) {\n if (permission.appliesTo(Dataset.class) || permission.appliesTo(DataFile.class)) {\n roles.add(role);\n break;\n }\n }\n }\n \n } else if (dvObject instanceof DataFile) {\n roles.add(roleService.findBuiltinRoleByAlias(DataverseRole.FILE_DOWNLOADER));\n }\n \n Collections.sort(roles, DataverseRole.CMP_BY_NAME);\n }\n return roles;\n }\n\n public DataverseRole getAssignedRole() {\n if (selectedRoleId != null) {\n return roleService.find(selectedRoleId);\n }\n return null;\n }\n \n public String getAssignedRoleObjectTypes(){\n String retString = \"\";\n if (selectedRoleId != null) {\n /* SEK 09/15/2016 SEK commenting out for now \n because permissions are not inherited\n \n if (dataverseRolePermissionHelper.hasDataversePermissions(selectedRoleId) && dvObject instanceof Dataverse){\n String dvLabel = ResourceBundle.getBundle(\"Bundle\").getString(\"dataverses\");\n retString = dvLabel;\n }\n */\n if (dataverseRolePermissionHelper.hasDatasetPermissions(selectedRoleId) && dvObject instanceof Dataverse){\n String dsLabel = ResourceBundle.getBundle(\"Bundle\").getString(\"datasets\");\n if(!retString.isEmpty()) {\n retString +=\", \" + dsLabel;\n } else {\n retString = dsLabel; \n }\n \n }\n if (dataverseRolePermissionHelper.hasFilePermissions(selectedRoleId)){\n String filesLabel = ResourceBundle.getBundle(\"Bundle\").getString(\"files\");\n if(!retString.isEmpty()) {\n retString +=\", \" + filesLabel;\n } else {\n retString = filesLabel; \n } \n }\n return retString;\n }\n return null; \n }\n \n public String getDefinitionLevelString(){\n if (dvObject != null){\n if (dvObject instanceof Dataverse) return ResourceBundle.getBundle(\"Bundle\").getString(\"dataverse\");\n if (dvObject instanceof Dataset) return ResourceBundle.getBundle(\"Bundle\").getString(\"dataset\");\n }\n return null;\n }\n\n public void assignRole(ActionEvent evt) { \n logger.info(\"Got to assignRole\");\n List selectedRoleAssigneesList = getRoleAssignSelectedRoleAssignees();\n if ( selectedRoleAssigneesList == null ) {\n logger.info(\"** SELECTED role asignees is null\");\n selectedRoleAssigneesList = new LinkedList<>();\n }\n for (RoleAssignee roleAssignee : selectedRoleAssigneesList) {\n assignRole(roleAssignee, roleService.find(selectedRoleId));\n }\n roleAssignments = initRoleAssignments(); \n }\n\n /**\n * Notify a {@code RoleAssignee} that a role was either assigned or revoked.\n * Will notify all members of a group.\n * @param ra The {@code RoleAssignee} to be notified.\n * @param type The type of notification.\n */\n private void notifyRoleChange(RoleAssignee ra, UserNotification.Type type) {\n if (ra instanceof AuthenticatedUser) {\n userNotificationService.sendNotification((AuthenticatedUser) ra, new Timestamp(new Date().getTime()), type, dvObject.getId());\n } else if (ra instanceof ExplicitGroup) {\n ExplicitGroup eg = (ExplicitGroup) ra;\n Set explicitGroupMembers = eg.getContainedRoleAssgineeIdentifiers();\n for (String id : explicitGroupMembers) {\n RoleAssignee explicitGroupMember = roleAssigneeService.getRoleAssignee(id);\n if (explicitGroupMember instanceof AuthenticatedUser) {\n userNotificationService.sendNotification((AuthenticatedUser) explicitGroupMember, new Timestamp(new Date().getTime()), type, dvObject.getId());\n }\n }\n }\n }\n\n private void assignRole(RoleAssignee ra, DataverseRole r) {\n try {\n String privateUrlToken = null;\n commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(), privateUrlToken));\n JsfHelper.addSuccessMessage(r.getName() + \" role assigned to \" + ra.getDisplayInfo().getTitle() + \" for \" + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()) + \".\");\n // don't notify if role = file downloader and object is not released\n if (!(r.getAlias().equals(DataverseRole.FILE_DOWNLOADER) && !dvObject.isReleased()) ){\n notifyRoleChange(ra, UserNotification.Type.ASSIGNROLE);\n }\n\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"The role was not able to be assigned.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"The role was not able to be assigned.\");\n logger.log(Level.SEVERE, \"Error assiging role: \" + ex.getMessage(), ex);\n }\n \n showAssignmentMessages();\n }\n\n /*\n ============================================================================\n edit role dialog\n ============================================================================\n */\n private DataverseRole role = new DataverseRole();\n private List selectedPermissions;\n\n public DataverseRole getRole() {\n return role;\n }\n\n public void setRole(DataverseRole role) {\n this.role = role;\n selectedPermissions = new LinkedList<>();\n if (role != null) {\n for (Permission p : role.permissions()) {\n selectedPermissions.add(p.name());\n }\n }\n }\n\n public List getSelectedPermissions() {\n return selectedPermissions;\n }\n\n public void setSelectedPermissions(List selectedPermissions) {\n this.selectedPermissions = selectedPermissions;\n }\n\n public List getPermissions() {\n return Arrays.asList(Permission.values());\n }\n\n public void updateRole(ActionEvent e) {\n // @todo currently only works for Dataverse since CreateRoleCommand only takes a dataverse\n // we need to decide if we want roles at the dataset level or not\n if (dvObject instanceof Dataverse) {\n role.clearPermissions();\n for (String pmsnStr : getSelectedPermissions()) {\n role.addPermission(Permission.valueOf(pmsnStr));\n }\n try {\n String roleState = role.getId() != null ? \"updated\" : \"created\";\n setRole(commandEngine.submit(new CreateRoleCommand(role, dvRequestService.getDataverseRequest(), (Dataverse) role.getOwner())));\n JsfHelper.addSuccessMessage(\"The role was \" + roleState + \". To assign it to a user and/or group, click on the Assign Roles to Users/Groups button in the Users/Groups section of this page.\");\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"The role was not able to be saved.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"The role was not able to be saved.\");\n logger.log(Level.SEVERE, \"Error saving role: \" + ex.getMessage(), ex);\n }\n }\n showRoleMessages();\n }\n \n \n public DataverseRolePermissionHelper getDataverseRolePermissionHelper() {\n return dataverseRolePermissionHelper;\n }\n\n public void setDataverseRolePermissionHelper(DataverseRolePermissionHelper dataverseRolePermissionHelper) {\n this.dataverseRolePermissionHelper = dataverseRolePermissionHelper;\n }\n\n /* \n ============================================================================\n Internal methods\n ============================================================================\n */\n \n boolean renderConfigureMessages = false;\n boolean renderAssignmentMessages = false;\n boolean renderRoleMessages = false; \n \n private void showNoMessages() {\n renderConfigureMessages = false;\n renderAssignmentMessages = false;\n renderRoleMessages = false;\n } \n \n private void showConfigureMessages() {\n renderConfigureMessages = true;\n renderAssignmentMessages = false;\n renderRoleMessages = false;\n }\n \n private void showAssignmentMessages() {\n renderConfigureMessages = false;\n renderAssignmentMessages = true;\n renderRoleMessages = false;\n }\n \n private void showRoleMessages() {\n renderConfigureMessages = false;\n renderAssignmentMessages = false;\n renderRoleMessages = true;\n } \n\n public Boolean getRenderConfigureMessages() {\n return renderConfigureMessages;\n }\n\n public void setRenderConfigureMessages(Boolean renderConfigureMessages) {\n this.renderConfigureMessages = renderConfigureMessages;\n }\n\n public Boolean getRenderAssignmentMessages() {\n return renderAssignmentMessages;\n }\n\n public void setRenderAssignmentMessages(Boolean renderAssignmentMessages) {\n this.renderAssignmentMessages = renderAssignmentMessages;\n }\n\n public Boolean getRenderRoleMessages() {\n return renderRoleMessages;\n }\n\n public void setRenderRoleMessages(Boolean renderRoleMessages) {\n this.renderRoleMessages = renderRoleMessages;\n }\n\n // inner class used for display of role assignments\n public static class RoleAssignmentRow {\n\n private final RoleAssigneeDisplayInfo assigneeDisplayInfo;\n private final RoleAssignment ra;\n\n public RoleAssignmentRow(RoleAssignment anRa, RoleAssigneeDisplayInfo disInf) {\n ra = anRa;\n assigneeDisplayInfo = disInf;\n }\n \n public RoleAssignment getRoleAssignment() {\n return ra;\n } \n\n public RoleAssigneeDisplayInfo getAssigneeDisplayInfo() {\n return assigneeDisplayInfo;\n }\n\n public DataverseRole getRole() {\n return ra.getRole();\n }\n\n public String getRoleName() {\n return getRole().getName();\n }\n \n\n public DvObject getDefinitionPoint() {\n return ra.getDefinitionPoint();\n }\n\n public String getAssignedDvName() {\n return ra.getDefinitionPoint().getDisplayName();\n }\n\n public Long getId() {\n return ra.getId();\n }\n\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/edu/harvard/iq/dataverse/ManagePermissionsPage.java"},"old_contents":{"kind":"string","value":"package edu.harvard.iq.dataverse;\n\nimport edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;\nimport edu.harvard.iq.dataverse.authorization.DataverseRole;\nimport edu.harvard.iq.dataverse.authorization.DataverseRolePermissionHelper;\nimport edu.harvard.iq.dataverse.authorization.Permission;\nimport edu.harvard.iq.dataverse.authorization.RoleAssignee;\nimport edu.harvard.iq.dataverse.authorization.RoleAssigneeDisplayInfo;\nimport edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean;\nimport edu.harvard.iq.dataverse.authorization.groups.impl.builtin.AuthenticatedUsers;\nimport edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroup;\nimport edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupServiceBean;\nimport edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;\nimport edu.harvard.iq.dataverse.engine.command.exception.CommandException;\nimport edu.harvard.iq.dataverse.engine.command.exception.PermissionException;\nimport edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand;\nimport edu.harvard.iq.dataverse.engine.command.impl.CreateRoleCommand;\nimport edu.harvard.iq.dataverse.engine.command.impl.RevokeRoleCommand;\nimport edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseDefaultContributorRoleCommand;\nimport edu.harvard.iq.dataverse.util.JsfHelper;\nimport static edu.harvard.iq.dataverse.util.JsfHelper.JH;\nimport edu.harvard.iq.dataverse.util.StringUtil;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.ResourceBundle;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.ejb.EJB;\nimport javax.faces.application.FacesMessage;\nimport javax.faces.event.ActionEvent;\nimport javax.faces.view.ViewScoped;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\nimport org.apache.commons.lang.StringEscapeUtils;\n\n/**\n *\n * @author gdurand\n */\n@ViewScoped\n@Named\npublic class ManagePermissionsPage implements java.io.Serializable {\n\n private static final Logger logger = Logger.getLogger(ManagePermissionsPage.class.getCanonicalName());\n\n @EJB\n DvObjectServiceBean dvObjectService;\n @EJB\n DataverseRoleServiceBean roleService;\n @EJB\n RoleAssigneeServiceBean roleAssigneeService;\n @EJB\n PermissionServiceBean permissionService;\n @EJB\n AuthenticationServiceBean authenticationService;\n @EJB\n ExplicitGroupServiceBean explicitGroupService;\n @EJB \n GroupServiceBean groupService;\n @EJB\n EjbDataverseEngine commandEngine;\n @EJB\n UserNotificationServiceBean userNotificationService;\n @Inject\n DataverseRequestServiceBean dvRequestService;\n @Inject\n PermissionsWrapper permissionsWrapper;\n\n\n @PersistenceContext(unitName = \"VDCNet-ejbPU\")\n EntityManager em;\n\n @Inject\n DataverseSession session;\n \n private DataverseRolePermissionHelper dataverseRolePermissionHelper;\n private List roleList;\n\n DvObject dvObject = new Dataverse(); // by default we use a Dataverse, but this will be overridden in init by the findById\n \n public DvObject getDvObject() {\n return dvObject;\n }\n\n public void setDvObject(DvObject dvObject) {\n this.dvObject = dvObject;\n /*if (dvObject instanceof DvObjectContainer) {\n inheritAssignments = !((DvObjectContainer) dvObject).isPermissionRoot();\n }*/\n }\n\n public String init() {\n //@todo deal with any kind of dvObject\n if (dvObject.getId() != null) {\n dvObject = dvObjectService.findDvObject(dvObject.getId());\n }\n\n // check if dvObject exists and user has permission\n if (dvObject == null) {\n return permissionsWrapper.notFound();\n }\n\n // for dataFiles, check the perms on its owning dataset\n DvObject checkPermissionsdvObject = dvObject instanceof DataFile ? dvObject.getOwner() : dvObject;\n if (!permissionService.on(checkPermissionsdvObject).has(checkPermissionsdvObject instanceof Dataverse ? Permission.ManageDataversePermissions : Permission.ManageDatasetPermissions)) {\n return permissionsWrapper.notAuthorized();\n }\n\n // initialize the configure settings\n if (dvObject instanceof Dataverse) {\n initAccessSettings();\n }\n roleList = roleService.findAll();\n roleAssignments = initRoleAssignments();\n dataverseRolePermissionHelper = new DataverseRolePermissionHelper(roleList); \n return \"\";\n }\n\n /* \n main page - role assignment table\n */\n \n // used by remove Role Assignment\n private RoleAssignment selectedRoleAssignment;\n\n public RoleAssignment getSelectedRoleAssignment() {\n return selectedRoleAssignment;\n }\n\n public void setSelectedRoleAssignment(RoleAssignment selectedRoleAssignment) {\n this.selectedRoleAssignment = selectedRoleAssignment;\n } \n \n private List roleAssignments;\n\n public List getRoleAssignments() {\n return roleAssignments;\n }\n\n public void setRoleAssignments(List roleAssignments) {\n this.roleAssignments = roleAssignments;\n }\n \n public List initRoleAssignments() {\n List raList = null;\n if (dvObject != null && dvObject.getId() != null) {\n Set ras = roleService.rolesAssignments(dvObject);\n raList = new ArrayList<>(ras.size());\n for (RoleAssignment roleAssignment : ras) {\n // for files, only show role assignments which can download\n if (!(dvObject instanceof DataFile) || roleAssignment.getRole().permissions().contains(Permission.DownloadFile)) {\n RoleAssignee roleAssignee = roleAssigneeService.getRoleAssignee(roleAssignment.getAssigneeIdentifier());\n if (roleAssignee != null) {\n raList.add(new RoleAssignmentRow(roleAssignment, roleAssignee.getDisplayInfo()));\n } else {\n logger.info(\"Could not find role assignee based on role assignment id \" + roleAssignment.getId());\n }\n }\n }\n }\n return raList;\n }\n \n public void removeRoleAssignment() {\n revokeRole(selectedRoleAssignment);\n\n if (dvObject instanceof Dataverse) {\n initAccessSettings(); // in case the revoke was for the AuthenticatedUsers group\n } \n roleAssignments = initRoleAssignments();\n showAssignmentMessages(); \n }\n \n // internal method used by removeRoleAssignment and saveConfiguration\n private void revokeRole(RoleAssignment ra) {\n try {\n commandEngine.submit(new RevokeRoleCommand(ra, dvRequestService.getDataverseRequest()));\n JsfHelper.addSuccessMessage(ra.getRole().getName() + \" role for \" + roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier()).getDisplayInfo().getTitle() + \" was removed.\");\n RoleAssignee assignee = roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier());\n notifyRoleChange(assignee, UserNotification.Type.REVOKEROLE);\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"The role assignment was not able to be removed.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"The role assignment could not be removed.\");\n logger.log(Level.SEVERE, \"Error removing role assignment: \" + ex.getMessage(), ex);\n }\n }\n \n /* \n main page - roles table\n */ \n\n public List getRoles() {\n if (dvObject != null && dvObject.getId() != null) {\n return roleService.findByOwnerId(dvObject.getId());\n }\n return new ArrayList<>();\n }\n\n public void createNewRole(ActionEvent e) {\n setRole(new DataverseRole());\n role.setOwner(dvObject);\n }\n\n public void cloneRole(String roleId) {\n DataverseRole clonedRole = new DataverseRole();\n clonedRole.setOwner(dvObject);\n\n DataverseRole originalRole = roleService.find(Long.parseLong(roleId));\n clonedRole.addPermissions(originalRole.permissions());\n setRole(clonedRole);\n }\n\n public void editRole(String roleId) {\n setRole(roleService.find(Long.parseLong(roleId)));\n }\n \n /*\n ============================================================================\n edit configuration dialog // only for dataverse version of page\n ============================================================================\n */\n \n private String authenticatedUsersContributorRoleAlias = null;\n private String defaultContributorRoleAlias = DataverseRole.EDITOR;\n\n public String getAuthenticatedUsersContributorRoleAlias() {\n return authenticatedUsersContributorRoleAlias;\n }\n\n public void setAuthenticatedUsersContributorRoleAlias(String authenticatedUsersContributorRoleAlias) {\n this.authenticatedUsersContributorRoleAlias = authenticatedUsersContributorRoleAlias;\n }\n\n public String getDefaultContributorRoleAlias() {\n return defaultContributorRoleAlias;\n }\n\n public void setDefaultContributorRoleAlias(String defaultContributorRoleAlias) {\n this.defaultContributorRoleAlias = defaultContributorRoleAlias;\n } \n \n public void initAccessSettings() {\n if (dvObject instanceof Dataverse) {\n authenticatedUsersContributorRoleAlias = \"\";\n\n List aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject);\n for (RoleAssignment roleAssignment : aUsersRoleAssignments) {\n String roleAlias = roleAssignment.getRole().getAlias();\n authenticatedUsersContributorRoleAlias = roleAlias;\n break;\n // @todo handle case where more than one role has been assigned to the AutenticatedUsers group!\n }\n\n defaultContributorRoleAlias = ((Dataverse) dvObject).getDefaultContributorRole().getAlias(); \n }\n }\n \n \n public void saveConfiguration(ActionEvent e) {\n // Set role (if any) for authenticatedUsers\n DataverseRole roleToAssign = null;\n List contributorRoles = Arrays.asList(DataverseRole.FULL_CONTRIBUTOR, DataverseRole.DV_CONTRIBUTOR, DataverseRole.DS_CONTRIBUTOR);\n\n if (!StringUtil.isEmpty(authenticatedUsersContributorRoleAlias)) {\n roleToAssign = roleService.findBuiltinRoleByAlias(authenticatedUsersContributorRoleAlias);\n }\n\n // then, check current contributor role\n List aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject);\n for (RoleAssignment roleAssignment : aUsersRoleAssignments) {\n DataverseRole currentRole = roleAssignment.getRole();\n if (contributorRoles.contains(currentRole.getAlias())) {\n if (currentRole.equals(roleToAssign)) {\n roleToAssign = null; // found the role, so no need to assign\n } else {\n revokeRole(roleAssignment);\n }\n }\n }\n // finally, assign role, if new\n if (roleToAssign != null) {\n assignRole(AuthenticatedUsers.get(), roleToAssign);\n }\n\n // set dataverse default contributor role\n if (dvObject instanceof Dataverse) {\n Dataverse dv = (Dataverse) dvObject;\n DataverseRole defaultRole = roleService.findBuiltinRoleByAlias(defaultContributorRoleAlias);\n if (!defaultRole.equals(dv.getDefaultContributorRole())) {\n try {\n commandEngine.submit(new UpdateDataverseDefaultContributorRoleCommand(defaultRole, dvRequestService.getDataverseRequest(), dv));\n JsfHelper.addSuccessMessage(\"The default permissions for this dataverse have been updated.\");\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"Cannot assign default permissions.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"Cannot assign default permissions.\");\n logger.log(Level.SEVERE, \"Error assigning default permissions: \" + ex.getMessage(), ex);\n }\n }\n }\n roleAssignments = initRoleAssignments();\n showConfigureMessages();\n } \n\n /*\n ============================================================================\n assign roles dialog\n ============================================================================\n */\n private List roleAssignSelectedRoleAssignees;\n private Long selectedRoleId;\n\n public List getRoleAssignSelectedRoleAssignees() {\n return roleAssignSelectedRoleAssignees;\n }\n\n public void setRoleAssignSelectedRoleAssignees(List selectedRoleAssignees) {\n this.roleAssignSelectedRoleAssignees = selectedRoleAssignees;\n }\n\n public Long getSelectedRoleId() {\n return selectedRoleId;\n }\n\n public void setSelectedRoleId(Long selectedRoleId) {\n this.selectedRoleId = selectedRoleId;\n }\n\n public void initAssigneeDialog(ActionEvent ae) {\n roleAssignSelectedRoleAssignees = new LinkedList<>();\n selectedRoleId = null;\n showNoMessages();\n }\n \n public List completeRoleAssignee( String query ) {\n return roleAssigneeService.filterRoleAssignees(query, dvObject, roleAssignSelectedRoleAssignees); \n }\n \n public List getAvailableRoles() {\n List roles = new LinkedList<>();\n if (dvObject != null && dvObject.getId() != null) {\n\n if (dvObject instanceof Dataverse) {\n roles.addAll(roleService.availableRoles(dvObject.getId()));\n \n } else if (dvObject instanceof Dataset) {\n // don't show roles that only have Dataverse level permissions\n // current the available roles for a dataset are gotten from its parent\n for (DataverseRole role : roleService.availableRoles(dvObject.getOwner().getId())) {\n for (Permission permission : role.permissions()) {\n if (permission.appliesTo(Dataset.class) || permission.appliesTo(DataFile.class)) {\n roles.add(role);\n break;\n }\n }\n }\n \n } else if (dvObject instanceof DataFile) {\n roles.add(roleService.findBuiltinRoleByAlias(DataverseRole.FILE_DOWNLOADER));\n }\n \n Collections.sort(roles, DataverseRole.CMP_BY_NAME);\n }\n return roles;\n }\n\n public DataverseRole getAssignedRole() {\n if (selectedRoleId != null) {\n return roleService.find(selectedRoleId);\n }\n return null;\n }\n \n public String getAssignedRoleObjectTypes(){\n String retString = \"\";\n if (selectedRoleId != null) {\n if (dataverseRolePermissionHelper.hasDataversePermissions(selectedRoleId) && dvObject instanceof Dataverse){\n String dvLabel = ResourceBundle.getBundle(\"Bundle\").getString(\"dataverses\");\n retString = dvLabel;\n }\n if (dataverseRolePermissionHelper.hasDatasetPermissions(selectedRoleId) && dvObject instanceof Dataverse){\n String dsLabel = ResourceBundle.getBundle(\"Bundle\").getString(\"datasets\");\n if(!retString.isEmpty()) {\n retString +=\", \" + dsLabel;\n } else {\n retString = dsLabel; \n }\n \n }\n if (dataverseRolePermissionHelper.hasFilePermissions(selectedRoleId)){\n String filesLabel = ResourceBundle.getBundle(\"Bundle\").getString(\"files\");\n if(!retString.isEmpty()) {\n retString +=\", \" + filesLabel;\n } else {\n retString = filesLabel; \n } \n }\n return retString;\n }\n return null; \n }\n \n public String getDefinitionLevelString(){\n if (dvObject != null){\n if (dvObject instanceof Dataverse) return ResourceBundle.getBundle(\"Bundle\").getString(\"dataverse\");\n if (dvObject instanceof Dataset) return ResourceBundle.getBundle(\"Bundle\").getString(\"dataset\");\n }\n return null;\n }\n\n public void assignRole(ActionEvent evt) { \n logger.info(\"Got to assignRole\");\n List selectedRoleAssigneesList = getRoleAssignSelectedRoleAssignees();\n if ( selectedRoleAssigneesList == null ) {\n logger.info(\"** SELECTED role asignees is null\");\n selectedRoleAssigneesList = new LinkedList<>();\n }\n for (RoleAssignee roleAssignee : selectedRoleAssigneesList) {\n assignRole(roleAssignee, roleService.find(selectedRoleId));\n }\n roleAssignments = initRoleAssignments(); \n }\n\n /**\n * Notify a {@code RoleAssignee} that a role was either assigned or revoked.\n * Will notify all members of a group.\n * @param ra The {@code RoleAssignee} to be notified.\n * @param type The type of notification.\n */\n private void notifyRoleChange(RoleAssignee ra, UserNotification.Type type) {\n if (ra instanceof AuthenticatedUser) {\n userNotificationService.sendNotification((AuthenticatedUser) ra, new Timestamp(new Date().getTime()), type, dvObject.getId());\n } else if (ra instanceof ExplicitGroup) {\n ExplicitGroup eg = (ExplicitGroup) ra;\n Set explicitGroupMembers = eg.getContainedRoleAssgineeIdentifiers();\n for (String id : explicitGroupMembers) {\n RoleAssignee explicitGroupMember = roleAssigneeService.getRoleAssignee(id);\n if (explicitGroupMember instanceof AuthenticatedUser) {\n userNotificationService.sendNotification((AuthenticatedUser) explicitGroupMember, new Timestamp(new Date().getTime()), type, dvObject.getId());\n }\n }\n }\n }\n\n private void assignRole(RoleAssignee ra, DataverseRole r) {\n try {\n String privateUrlToken = null;\n commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(), privateUrlToken));\n JsfHelper.addSuccessMessage(r.getName() + \" role assigned to \" + ra.getDisplayInfo().getTitle() + \" for \" + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()) + \".\");\n // don't notify if role = file downloader and object is not released\n if (!(r.getAlias().equals(DataverseRole.FILE_DOWNLOADER) && !dvObject.isReleased()) ){\n notifyRoleChange(ra, UserNotification.Type.ASSIGNROLE);\n }\n\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"The role was not able to be assigned.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"The role was not able to be assigned.\");\n logger.log(Level.SEVERE, \"Error assiging role: \" + ex.getMessage(), ex);\n }\n \n showAssignmentMessages();\n }\n\n /*\n ============================================================================\n edit role dialog\n ============================================================================\n */\n private DataverseRole role = new DataverseRole();\n private List selectedPermissions;\n\n public DataverseRole getRole() {\n return role;\n }\n\n public void setRole(DataverseRole role) {\n this.role = role;\n selectedPermissions = new LinkedList<>();\n if (role != null) {\n for (Permission p : role.permissions()) {\n selectedPermissions.add(p.name());\n }\n }\n }\n\n public List getSelectedPermissions() {\n return selectedPermissions;\n }\n\n public void setSelectedPermissions(List selectedPermissions) {\n this.selectedPermissions = selectedPermissions;\n }\n\n public List getPermissions() {\n return Arrays.asList(Permission.values());\n }\n\n public void updateRole(ActionEvent e) {\n // @todo currently only works for Dataverse since CreateRoleCommand only takes a dataverse\n // we need to decide if we want roles at the dataset level or not\n if (dvObject instanceof Dataverse) {\n role.clearPermissions();\n for (String pmsnStr : getSelectedPermissions()) {\n role.addPermission(Permission.valueOf(pmsnStr));\n }\n try {\n String roleState = role.getId() != null ? \"updated\" : \"created\";\n setRole(commandEngine.submit(new CreateRoleCommand(role, dvRequestService.getDataverseRequest(), (Dataverse) role.getOwner())));\n JsfHelper.addSuccessMessage(\"The role was \" + roleState + \". To assign it to a user and/or group, click on the Assign Roles to Users/Groups button in the Users/Groups section of this page.\");\n } catch (PermissionException ex) {\n JH.addMessage(FacesMessage.SEVERITY_ERROR, \"The role was not able to be saved.\", \"Permissions \" + ex.getRequiredPermissions().toString() + \" missing.\");\n } catch (CommandException ex) {\n JH.addMessage(FacesMessage.SEVERITY_FATAL, \"The role was not able to be saved.\");\n logger.log(Level.SEVERE, \"Error saving role: \" + ex.getMessage(), ex);\n }\n }\n showRoleMessages();\n }\n \n \n public DataverseRolePermissionHelper getDataverseRolePermissionHelper() {\n return dataverseRolePermissionHelper;\n }\n\n public void setDataverseRolePermissionHelper(DataverseRolePermissionHelper dataverseRolePermissionHelper) {\n this.dataverseRolePermissionHelper = dataverseRolePermissionHelper;\n }\n\n /* \n ============================================================================\n Internal methods\n ============================================================================\n */\n \n boolean renderConfigureMessages = false;\n boolean renderAssignmentMessages = false;\n boolean renderRoleMessages = false; \n \n private void showNoMessages() {\n renderConfigureMessages = false;\n renderAssignmentMessages = false;\n renderRoleMessages = false;\n } \n \n private void showConfigureMessages() {\n renderConfigureMessages = true;\n renderAssignmentMessages = false;\n renderRoleMessages = false;\n }\n \n private void showAssignmentMessages() {\n renderConfigureMessages = false;\n renderAssignmentMessages = true;\n renderRoleMessages = false;\n }\n \n private void showRoleMessages() {\n renderConfigureMessages = false;\n renderAssignmentMessages = false;\n renderRoleMessages = true;\n } \n\n public Boolean getRenderConfigureMessages() {\n return renderConfigureMessages;\n }\n\n public void setRenderConfigureMessages(Boolean renderConfigureMessages) {\n this.renderConfigureMessages = renderConfigureMessages;\n }\n\n public Boolean getRenderAssignmentMessages() {\n return renderAssignmentMessages;\n }\n\n public void setRenderAssignmentMessages(Boolean renderAssignmentMessages) {\n this.renderAssignmentMessages = renderAssignmentMessages;\n }\n\n public Boolean getRenderRoleMessages() {\n return renderRoleMessages;\n }\n\n public void setRenderRoleMessages(Boolean renderRoleMessages) {\n this.renderRoleMessages = renderRoleMessages;\n }\n\n // inner class used for display of role assignments\n public static class RoleAssignmentRow {\n\n private final RoleAssigneeDisplayInfo assigneeDisplayInfo;\n private final RoleAssignment ra;\n\n public RoleAssignmentRow(RoleAssignment anRa, RoleAssigneeDisplayInfo disInf) {\n ra = anRa;\n assigneeDisplayInfo = disInf;\n }\n \n public RoleAssignment getRoleAssignment() {\n return ra;\n } \n\n public RoleAssigneeDisplayInfo getAssigneeDisplayInfo() {\n return assigneeDisplayInfo;\n }\n\n public DataverseRole getRole() {\n return ra.getRole();\n }\n\n public String getRoleName() {\n return getRole().getName();\n }\n \n\n public DvObject getDefinitionPoint() {\n return ra.getDefinitionPoint();\n }\n\n public String getAssignedDvName() {\n return ra.getDefinitionPoint().getDisplayName();\n }\n\n public Long getId() {\n return ra.getId();\n }\n\n }\n}\n"},"message":{"kind":"string","value":"#2657 Remove DV from permissions caveat\n"},"old_file":{"kind":"string","value":"src/main/java/edu/harvard/iq/dataverse/ManagePermissionsPage.java"},"subject":{"kind":"string","value":"#2657 Remove DV from permissions caveat"}}},{"rowIdx":1240,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-2-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f04413bcb6fdf6bfa1b19f3c8d5fce99597185db"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"alpha-asp/Alpha,AntoniusW/Alpha,alpha-asp/Alpha"},"new_contents":{"kind":"string","value":"/**\n * Copyright (c) 2016-2019, the Alpha Team.\n * All rights reserved.\n * \n * Additional changes made by Siemens.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1) Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * 2) Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage at.ac.tuwien.kr.alpha.grounder;\n\nimport at.ac.tuwien.kr.alpha.common.*;\nimport at.ac.tuwien.kr.alpha.common.NoGood.Type;\nimport at.ac.tuwien.kr.alpha.common.atoms.*;\nimport at.ac.tuwien.kr.alpha.common.terms.VariableTerm;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.ChoiceAtom;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.EnumerationAtom;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.IntervalLiteral;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.RuleAtom;\nimport at.ac.tuwien.kr.alpha.grounder.bridges.Bridge;\nimport at.ac.tuwien.kr.alpha.grounder.heuristics.GrounderHeuristicsConfiguration;\nimport at.ac.tuwien.kr.alpha.grounder.structure.AnalyzeUnjustified;\nimport at.ac.tuwien.kr.alpha.grounder.structure.ProgramAnalysis;\nimport at.ac.tuwien.kr.alpha.grounder.transformation.*;\nimport at.ac.tuwien.kr.alpha.solver.ThriceTruth;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.util.*;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport static at.ac.tuwien.kr.alpha.Util.oops;\nimport static at.ac.tuwien.kr.alpha.common.Literals.atomOf;\nimport static java.util.Collections.singletonList;\n\n/**\n * A semi-naive grounder.\n * Copyright (c) 2016-2019, the Alpha Team.\n */\npublic class NaiveGrounder extends BridgedGrounder implements ProgramAnalyzingGrounder {\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(NaiveGrounder.class);\n\n\tprivate final WorkingMemory workingMemory = new WorkingMemory();\n\tprivate final AtomStore atomStore;\n\tprivate final NogoodRegistry registry = new NogoodRegistry();\n\tfinal NoGoodGenerator noGoodGenerator;\n\tprivate final ChoiceRecorder choiceRecorder;\n\tprivate final ProgramAnalysis programAnalysis;\n\tprivate final AnalyzeUnjustified analyzeUnjustified;\n\n\tprivate final Map> factsFromProgram = new LinkedHashMap<>();\n\tprivate final Map> rulesUsingPredicateWorkingMemory = new HashMap<>();\n\tprivate final Map> knownGroundingSubstitutions = new HashMap<>();\n\tprivate final Map knownNonGroundRules = new HashMap<>();\n\n\tprivate ArrayList fixedRules = new ArrayList<>();\n\tprivate LinkedHashSet removeAfterObtainingNewNoGoods = new LinkedHashSet<>();\n\tprivate boolean disableInstanceRemoval;\n\tprivate final boolean useCountingGridNormalization;\n\tprivate final boolean debugInternalChecks;\n\t\n\tprivate final GrounderHeuristicsConfiguration heuristicsConfiguration;\n\n\tpublic NaiveGrounder(Program program, AtomStore atomStore, boolean debugInternalChecks, Bridge... bridges) {\n\t\tthis(program, atomStore, new GrounderHeuristicsConfiguration(), debugInternalChecks, bridges);\n\t}\n\n\tprivate NaiveGrounder(Program program, AtomStore atomStore, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean debugInternalChecks, Bridge... bridges) {\n\t\tthis(program, atomStore, p -> true, heuristicsConfiguration, false, debugInternalChecks, bridges);\n\t}\n\n\tNaiveGrounder(Program program, AtomStore atomStore, java.util.function.Predicate filter, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean useCountingGrid, boolean debugInternalChecks, Bridge... bridges) {\n\t\tsuper(filter, bridges);\n\t\tthis.atomStore = atomStore;\n\t\tthis.heuristicsConfiguration = heuristicsConfiguration;\n\t\tLOGGER.debug(\"Grounder configuration: \" + heuristicsConfiguration);\n\n\t\tprogramAnalysis = new ProgramAnalysis(program);\n\t\tanalyzeUnjustified = new AnalyzeUnjustified(programAnalysis, atomStore, factsFromProgram);\n\n\t\t// Apply program transformations/rewritings.\n\t\tuseCountingGridNormalization = useCountingGrid;\n\t\tapplyProgramTransformations(program);\n\t\tLOGGER.debug(\"Transformed input program is:\\n\" + program);\n\n\t\tinitializeFactsAndRules(program);\n\n\t\tfinal Set uniqueGroundRulePerGroundHead = getRulesWithUniqueHead();\n\t\tchoiceRecorder = new ChoiceRecorder(atomStore);\n\t\tnoGoodGenerator = new NoGoodGenerator(atomStore, choiceRecorder, factsFromProgram, programAnalysis, uniqueGroundRulePerGroundHead);\n\t\t\n\t\tthis.debugInternalChecks = debugInternalChecks;\n\t}\n\n\tprivate void initializeFactsAndRules(Program program) {\n\t\t// initialize all facts\n\t\tfor (Atom fact : program.getFacts()) {\n\t\t\tfinal Predicate predicate = fact.getPredicate();\n\n\t\t\t// Record predicate\n\t\t\tworkingMemory.initialize(predicate);\n\n\t\t\t// Construct fact instance(s).\n\t\t\tList instances = FactIntervalEvaluator.constructFactInstances(fact);\n\n\t\t\t// Add instances to corresponding list of facts.\n\t\t\tfactsFromProgram.putIfAbsent(predicate, new LinkedHashSet<>());\n\t\t\tHashSet internalPredicateInstances = factsFromProgram.get(predicate);\n\t\t\tinternalPredicateInstances.addAll(instances);\n\t\t}\n\n\t\t// Register internal atoms.\n\t\tworkingMemory.initialize(RuleAtom.PREDICATE);\n\t\tworkingMemory.initialize(ChoiceAtom.OFF);\n\t\tworkingMemory.initialize(ChoiceAtom.ON);\n\n\t\t// Initialize rules and constraints.\n\t\tfor (Rule rule : program.getRules()) {\n\t\t\t// Record the rule for later use\n\t\t\tNonGroundRule nonGroundRule = NonGroundRule.constructNonGroundRule(rule);\n\t\t\tknownNonGroundRules.put(nonGroundRule.getRuleId(), nonGroundRule);\n\t\t\tLOGGER.debug(\"NonGroundRule #\" + nonGroundRule.getRuleId() + \": \" + nonGroundRule);\n\n\t\t\t// Record defining rules for each predicate.\n\t\t\tAtom headAtom = nonGroundRule.getHeadAtom();\n\t\t\tif (headAtom != null) {\n\t\t\t\tPredicate headPredicate = headAtom.getPredicate();\n\t\t\t\tprogramAnalysis.recordDefiningRule(headPredicate, nonGroundRule);\n\t\t\t}\n\n\t\t\t// Create working memories for all predicates occurring in the rule\n\t\t\tfor (Predicate predicate : nonGroundRule.getOccurringPredicates()) {\n\t\t\t\t// FIXME: this also contains interval/builtin predicates that are not needed.\n\t\t\t\tworkingMemory.initialize(predicate);\n\t\t\t}\n\n\t\t\t// If the rule has fixed ground instantiations, it is not registered but grounded once like facts.\n\t\t\tif (nonGroundRule.groundingOrder.fixedInstantiation()) {\n\t\t\t\tfixedRules.add(nonGroundRule);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Register each starting literal at the corresponding working memory.\n\t\t\tfor (Literal literal : nonGroundRule.groundingOrder.getStartingLiterals()) {\n\t\t\t\tregisterLiteralAtWorkingMemory(literal, nonGroundRule);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Set getRulesWithUniqueHead() {\n\t\t// FIXME: below optimisation (adding support nogoods if there is only one rule instantiation per unique atom over the interpretation) could be done as a transformation (adding a non-ground constraint corresponding to the nogood that is generated by the grounder).\n\t\t// Record all unique rule heads.\n\t\tfinal Set uniqueGroundRulePerGroundHead = new HashSet<>();\n\n\t\tfor (Map.Entry> headDefiningRules : programAnalysis.getPredicateDefiningRules().entrySet()) {\n\t\t\tif (headDefiningRules.getValue().size() != 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tNonGroundRule nonGroundRule = headDefiningRules.getValue().iterator().next();\n\t\t\t// Check that all variables of the body also occur in the head (otherwise grounding is not unique).\n\t\t\tAtom headAtom = nonGroundRule.getHeadAtom();\n\n\t\t\t// Rule is not guaranteed unique if there are facts for it.\n\t\t\tHashSet potentialFacts = factsFromProgram.get(headAtom.getPredicate());\n\t\t\tif (potentialFacts != null && !potentialFacts.isEmpty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Collect head and body variables.\n\t\t\tHashSet occurringVariablesHead = new HashSet<>(headAtom.toLiteral().getBindingVariables());\n\t\t\tHashSet occurringVariablesBody = new HashSet<>();\n\t\t\tfor (Atom atom : nonGroundRule.getBodyAtomsPositive()) {\n\t\t\t\toccurringVariablesBody.addAll(atom.toLiteral().getBindingVariables());\n\t\t\t}\n\t\t\toccurringVariablesBody.removeAll(occurringVariablesHead);\n\n\t\t\t// Check if ever body variables occurs in the head.\n\t\t\tif (occurringVariablesBody.isEmpty()) {\n\t\t\t\tuniqueGroundRulePerGroundHead.add(nonGroundRule);\n\t\t\t}\n\t\t}\n\t\treturn uniqueGroundRulePerGroundHead;\n\t}\n\n\tprivate void applyProgramTransformations(Program program) {\n\t\t// Transform choice rules.\n\t\tnew ChoiceHeadToNormal().transform(program);\n\t\t// Transform cardinality aggregates.\n\t\tnew CardinalityNormalization(!useCountingGridNormalization).transform(program);\n\t\t// Transform sum aggregates.\n\t\tnew SumNormalization().transform(program);\n\t\t// Transform intervals.\n\t\tnew IntervalTermToIntervalAtom().transform(program);\n\t\t// Remove variable equalities.\n\t\tnew VariableEqualityRemoval().transform(program);\n\t\t// Transform enumeration atoms.\n\t\tnew EnumerationRewriting().transform(program);\n\t\tEnumerationAtom.resetEnumerations();\n\t}\n\n\t/**\n\t * Registers a starting literal of a NonGroundRule at its corresponding working memory.\n\t * @param nonGroundRule the rule in which the literal occurs.\n\t */\n\tprivate void registerLiteralAtWorkingMemory(Literal literal, NonGroundRule nonGroundRule) {\n\t\tif (literal.isNegated()) {\n\t\t\tthrow new RuntimeException(\"Literal to register is negated. Should not happen.\");\n\t\t}\n\t\tIndexedInstanceStorage workingMemory = this.workingMemory.get(literal.getPredicate(), true);\n\t\trulesUsingPredicateWorkingMemory.putIfAbsent(workingMemory, new ArrayList<>());\n\t\trulesUsingPredicateWorkingMemory.get(workingMemory).add(new FirstBindingAtom(nonGroundRule, literal));\n\t}\n\n\t@Override\n\tpublic AnswerSet assignmentToAnswerSet(Iterable trueAtoms) {\n\t\tMap> predicateInstances = new LinkedHashMap<>();\n\t\tSortedSet knownPredicates = new TreeSet<>();\n\n\t\t// Iterate over all true atomIds, computeNextAnswerSet instances from atomStore and add them if not filtered.\n\t\tfor (int trueAtom : trueAtoms) {\n\t\t\tfinal Atom atom = atomStore.get(trueAtom);\n\t\t\tPredicate predicate = atom.getPredicate();\n\n\t\t\t// Skip atoms over internal predicates.\n\t\t\tif (predicate.isInternal()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip filtered predicates.\n\t\t\tif (!filter.test(predicate)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tknownPredicates.add(predicate);\n\t\t\tpredicateInstances.putIfAbsent(predicate, new TreeSet<>());\n\t\t\tSet instances = predicateInstances.get(predicate);\n\t\t\tinstances.add(atom);\n\t\t}\n\n\t\t// Add true atoms from facts.\n\t\tfor (Map.Entry> facts : factsFromProgram.entrySet()) {\n\t\t\tPredicate factPredicate = facts.getKey();\n\t\t\t// Skip atoms over internal predicates.\n\t\t\tif (factPredicate.isInternal()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Skip filtered predicates.\n\t\t\tif (!filter.test(factPredicate)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Skip predicates without any instances.\n\t\t\tif (facts.getValue().isEmpty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tknownPredicates.add(factPredicate);\n\t\t\tpredicateInstances.putIfAbsent(factPredicate, new TreeSet<>());\n\t\t\tfor (Instance factInstance : facts.getValue()) {\n\t\t\t\tSortedSet instances = predicateInstances.get(factPredicate);\n\t\t\t\tinstances.add(new BasicAtom(factPredicate, factInstance.terms));\n\t\t\t}\n\t\t}\n\n\t\tif (knownPredicates.isEmpty()) {\n\t\t\treturn BasicAnswerSet.EMPTY;\n\t\t}\n\n\t\treturn new BasicAnswerSet(knownPredicates, predicateInstances);\n\t}\n\n\t/**\n\t * Prepares facts of the input program for joining and derives all NoGoods representing ground rules. May only be called once.\n\t * @return\n\t */\n\tprivate HashMap bootstrap() {\n\t\tfinal HashMap groundNogoods = new LinkedHashMap<>();\n\n\t\tfor (Predicate predicate : factsFromProgram.keySet()) {\n\t\t\t// Instead of generating NoGoods, add instance to working memories directly.\n\t\t\tworkingMemory.addInstances(predicate, true, factsFromProgram.get(predicate));\n\t\t}\n\n\t\tfor (NonGroundRule nonGroundRule : fixedRules) {\n\t\t\t// Generate NoGoods for all rules that have a fixed grounding.\n\t\t\tRuleGroundingOrder groundingOrder = nonGroundRule.groundingOrder.getFixedGroundingOrder();\n\t\t\tBindingResult bindingResult = bindNextAtomInRule(nonGroundRule, groundingOrder, new Substitution(), null);\n\t\t\tgroundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, groundNogoods);\n\t\t}\n\n\t\tfixedRules = null;\n\n\t\treturn groundNogoods;\n\t}\n\n\t@Override\n\tpublic Map getNoGoods(Assignment currentAssignment) {\n\t\t// In first call, prepare facts and ground rules.\n\t\tfinal Map newNoGoods = fixedRules != null ? bootstrap() : new LinkedHashMap<>();\n\n\t\t// Compute new ground rule (evaluate joins with newly changed atoms)\n\t\tfor (IndexedInstanceStorage modifiedWorkingMemory : workingMemory.modified()) {\n\t\t\t// Skip predicates solely used in the solver which do not occur in rules.\n\t\t\tPredicate workingMemoryPredicate = modifiedWorkingMemory.getPredicate();\n\t\t\tif (workingMemoryPredicate.isSolverInternal()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Iterate over all rules whose body contains the interpretation corresponding to the current workingMemory.\n\t\t\tfinal ArrayList firstBindingAtoms = rulesUsingPredicateWorkingMemory.get(modifiedWorkingMemory);\n\n\t\t\t// Skip working memories that are not used by any rule.\n\t\t\tif (firstBindingAtoms == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (FirstBindingAtom firstBindingAtom : firstBindingAtoms) {\n\t\t\t\t// Use the recently added instances from the modified working memory to construct an initial substitution\n\t\t\t\tNonGroundRule nonGroundRule = firstBindingAtom.rule;\n\n\t\t\t\t// Generate substitutions from each recent instance.\n\t\t\t\tfor (Instance instance : modifiedWorkingMemory.getRecentlyAddedInstances()) {\n\t\t\t\t\t// Check instance if it matches with the atom.\n\n\t\t\t\t\tfinal Substitution unifier = Substitution.unify(firstBindingAtom.startingLiteral, instance, new Substitution());\n\n\t\t\t\t\tif (unifier == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal BindingResult bindingResult = bindNextAtomInRule(\n\t\t\t\t\t\tnonGroundRule,\n\t\t\t\t\t\tnonGroundRule.groundingOrder.orderStartingFrom(firstBindingAtom.startingLiteral),\n\t\t\t\t\t\tunifier,\n\t\t\t\t\t\tcurrentAssignment\n\t\t\t\t\t);\n\n\t\t\t\t\tgroundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, newNoGoods);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Mark instances added by updateAssignment as done\n\t\t\tmodifiedWorkingMemory.markRecentlyAddedInstancesDone();\n\t\t}\n\n\t\tworkingMemory.reset();\n\t\tfor (Atom removeAtom : removeAfterObtainingNewNoGoods) {\n\t\t\tfinal IndexedInstanceStorage storage = this.workingMemory.get(removeAtom, true);\n\t\t\tInstance instance = new Instance(removeAtom.getTerms());\n\t\t\tif (storage.containsInstance(instance)) {\n\t\t\t\t// lax grounder heuristics may attempt to remove instances that are not yet in the working memory\n\t\t\t\tstorage.removeInstance(instance);\n\t\t\t}\n\t\t}\n\n\t\tremoveAfterObtainingNewNoGoods = new LinkedHashSet<>();\n\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\tLOGGER.debug(\"Grounded NoGoods are:\");\n\t\t\tfor (Map.Entry noGoodEntry : newNoGoods.entrySet()) {\n\t\t\t\tLOGGER.debug(\"{} == {}\", noGoodEntry.getValue(), atomStore.noGoodToString(noGoodEntry.getValue()));\n\t\t\t}\n\t\t\tLOGGER.debug(\"{}\", choiceRecorder);\n\t\t}\n\t\t\n\t\tif (debugInternalChecks) {\n\t\t\tcheckTypesOfNoGoods(newNoGoods.values());\n\t\t}\n\t\t\n\t\treturn newNoGoods;\n\t}\n\n\t/**\n\t * Grounds the given {@code nonGroundRule} by applying the given {@code substitutions} and registers the nogoods generated during that process.\n\t * \n\t * @param nonGroundRule\n\t * the rule to be grounded\n\t * @param substitutions\n\t * the substitutions to be applied\n\t * @param newNoGoods\n\t * a set of nogoods to which newly generated nogoods will be added\n\t */\n\tprivate void groundAndRegister(final NonGroundRule nonGroundRule, final List substitutions, final Map newNoGoods) {\n\t\tfor (Substitution substitution : substitutions) {\n\t\t\tList generatedNoGoods = noGoodGenerator.generateNoGoodsFromGroundSubstitution(nonGroundRule, substitution);\n\t\t\tregistry.register(generatedNoGoods, newNoGoods);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int register(NoGood noGood) {\n\t\treturn registry.register(noGood);\n\t}\n\n\tprivate BindingResult bindNextAtomInRule(NonGroundRule rule, RuleGroundingOrder groundingOrder, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tint tolerance = heuristicsConfiguration.getTolerance(rule.isConstraint());\n\t\tif (tolerance < 0) {\n\t\t\ttolerance = Integer.MAX_VALUE;\n\t\t}\n\t\tBindingResult bindingResult = bindNextAtomInRule(groundingOrder, 0, tolerance, tolerance, partialSubstitution, currentAssignment);\n\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\tfor (int i = 0; i < bindingResult.size(); i++) {\n\t\t\t\tInteger numberOfUnassignedPositiveBodyAtoms = bindingResult.numbersOfUnassignedPositiveBodyAtoms.get(i);\n\t\t\t\tif (numberOfUnassignedPositiveBodyAtoms > 0) {\n\t\t\t\t\tLOGGER.debug(\"Grounded rule in which \" + numberOfUnassignedPositiveBodyAtoms + \" positive atoms are still unassigned: \" + rule + \" (substitution: \" + bindingResult.generatedSubstitutions.get(i) + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn bindingResult;\n\t}\n\n\tprivate BindingResult advanceAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tgroundingOrder.considerUntilCurrentEnd();\n\t\treturn bindNextAtomInRule(groundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t}\n\t\n\tprivate BindingResult pushBackAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tRuleGroundingOrder modifiedGroundingOrder = groundingOrder.pushBack(orderPosition);\n\t\tif (modifiedGroundingOrder == null) {\n\t\t\treturn BindingResult.empty();\n\t\t}\n\t\treturn bindNextAtomInRule(modifiedGroundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t}\n\t\n\tprivate BindingResult bindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tboolean laxGrounderHeuristic = originalTolerance > 0;\n\t\t\n\t\tLiteral currentLiteral = groundingOrder.getLiteralAtOrderPosition(orderPosition);\n\t\tif (currentLiteral == null) {\n\t\t\treturn BindingResult.singleton(partialSubstitution, originalTolerance - remainingTolerance);\n\t\t}\n\t\t\n\t\tAtom currentAtom = currentLiteral.getAtom();\n\t\tif (currentLiteral instanceof FixedInterpretationLiteral) {\n\t\t\t// Generate all substitutions for the builtin/external/interval atom.\n\t\t\tFixedInterpretationLiteral substitutedLiteral = (FixedInterpretationLiteral)currentLiteral.substitute(partialSubstitution);\n\t\t\t// TODO: this has to be improved before merging into master:\n\t\t\tif (!substitutedLiteral.isGround() &&\n\t\t\t\t\t!(substitutedLiteral instanceof ComparisonLiteral && ((ComparisonLiteral)substitutedLiteral).isLeftOrRightAssigning()) &&\n\t\t\t\t\t!(substitutedLiteral instanceof IntervalLiteral && substitutedLiteral.getTerms().get(0).isGround()) &&\n\t\t\t\t\t!(substitutedLiteral instanceof ExternalLiteral)\n\t\t\t\t\t) {\n\t\t\t\treturn pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t}\n\t\t\tfinal List substitutions = substitutedLiteral.getSubstitutions(partialSubstitution);\n\t\t\t\n\t\t\tif (substitutions.isEmpty()) {\n\t\t\t\t// if FixedInterpretationLiteral cannot be satisfied now, it will never be\n\t\t\t\treturn BindingResult.empty();\n\t\t\t}\n\t\t\t\n\t\t\tfinal BindingResult bindingResult = new BindingResult();\n\t\t\tfor (Substitution substitution : substitutions) {\n\t\t\t\t// Continue grounding with each of the generated values.\n\t\t\t\tbindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, substitution, currentAssignment));\n\t\t\t}\n\t\t\treturn bindingResult;\n\t\t}\n\t\tif (currentAtom instanceof EnumerationAtom) {\n\t\t\t// Get the enumeration value and add it to the current partialSubstitution.\n\t\t\t((EnumerationAtom) currentAtom).addEnumerationToSubstitution(partialSubstitution);\n\t\t\treturn advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t}\n\n\t\tCollection instances = null;\n\n\t\t// check if partialVariableSubstitution already yields a ground atom\n\t\tfinal Atom substitute = currentAtom.substitute(partialSubstitution);\n\t\tif (substitute.isGround()) {\n\t\t\t// Substituted atom is ground, in case it is positive, only ground if it also holds true\n\t\t\tif (currentLiteral.isNegated()) {\n\t\t\t\t// Atom occurs negated in the rule: continue grounding\n\t\t\t\treturn advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t}\n\n\t\t\tif (!groundingOrder.isGround() && remainingTolerance <= 0\n\t\t\t\t\t&& !workingMemory.get(currentAtom.getPredicate(), true).containsInstance(new Instance(substitute.getTerms()))) {\n\t\t\t\t// Generate no variable substitution.\n\t\t\t\treturn BindingResult.empty();\n\t\t\t}\n\n\t\t\t// Check if atom is also assigned true.\n\t\t\tfinal LinkedHashSet factInstances = factsFromProgram.get(substitute.getPredicate());\n\t\t\tif (factInstances != null && factInstances.contains(new Instance(substitute.getTerms()))) {\n\t\t\t\t// Ground literal holds, continue finding a variable substitution.\n\t\t\t\treturn advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t}\n\n\t\t\t// Atom is not a fact already.\n\t\t\tinstances = singletonList(new Instance(substitute.getTerms()));\n\t\t}\n\t\t\n\t\t// substituted atom contains variables\n\t\tif (currentLiteral.isNegated()) {\n\t\t\tif (laxGrounderHeuristic) {\n\t\t\t\treturn pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t} else {\n\t\t\t\tthrow oops(\"Current atom should be positive at this point but is not\");\n\t\t\t}\n\t\t}\n\n\t\tif (instances == null) {\n\t\t\tinstances = getInstancesForSubstitute(substitute, partialSubstitution);\n\t\t}\n\t\t\n\t\tif (laxGrounderHeuristic && instances.isEmpty()) {\n\t\t\t// we have reached a point where we have to terminate binding,\n\t\t\t// but it might be possible that a different grounding order would allow us to continue binding\n\t\t\t// under the presence of a lax grounder heuristic\n\t\t\treturn pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t}\n\n\t\treturn createBindings(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment, instances, substitute);\n\t}\n\n\tprivate Collection getInstancesForSubstitute(Atom substitute, Substitution partialSubstitution) {\n\t\tCollection instances;\n\t\tIndexedInstanceStorage storage = workingMemory.get(substitute.getPredicate(), true);\n\t\tif (partialSubstitution.isEmpty()) {\n\t\t\t// No variables are bound, but first atom in the body became recently true, consider all instances now.\n\t\t\tinstances = storage.getAllInstances();\n\t\t} else {\n\t\t\tinstances = storage.getInstancesFromPartiallyGroundAtom(substitute);\n\t\t}\n\t\treturn instances;\n\t}\n\n\tprivate BindingResult createBindings(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment, Collection instances, Atom substitute) {\n\t\tBindingResult bindingResult = new BindingResult();\n\t\tfor (Instance instance : instances) {\n\t\t\t// Check each instance if it matches with the atom.\n\t\t\tSubstitution unified = Substitution.unify(substitute, instance, new Substitution(partialSubstitution));\n\t\t\tif (unified == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Check if atom is also assigned true.\n\t\t\tAtom substituteClone = new BasicAtom(substitute.getPredicate(), substitute.getTerms());\n\t\t\tAtom substitutedAtom = substituteClone.substitute(unified);\n\t\t\tif (!substitutedAtom.isGround()) {\n\t\t\t\tthrow oops(\"Grounded atom should be ground but is not\");\n\t\t\t}\n\n\t\t\tAtomicInteger atomicRemainingTolerance = new AtomicInteger(remainingTolerance);\t// TODO: done this way for call-by-reference, should be refactored\n\t\t\tif (factsFromProgram.get(substitutedAtom.getPredicate()) == null || !factsFromProgram.get(substitutedAtom.getPredicate()).contains(new Instance(substitutedAtom.getTerms()))) {\n\t\t\t\tif (storeAtomAndTerminateIfAtomDoesNotHold(substitutedAtom, currentAssignment, atomicRemainingTolerance)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, atomicRemainingTolerance.get(), unified, currentAssignment));\n\t\t}\n\n\t\treturn bindingResult;\n\t}\n\n\tprivate boolean storeAtomAndTerminateIfAtomDoesNotHold(final Atom substitute, Assignment currentAssignment, AtomicInteger remainingTolerance) {\n\t\tfinal int atomId = atomStore.putIfAbsent(substitute);\n\n\t\tif (currentAssignment != null) {\n\t\t\tThriceTruth truth = currentAssignment.isAssigned(atomId) ? currentAssignment.getTruth(atomId) : null;\n\t\t\tif (truth == null || !truth.toBoolean()) {\n\t\t\t\t// Atom currently does not hold\n\t\t\t\tif (!disableInstanceRemoval) {\n\t\t\t\t\tremoveAfterObtainingNewNoGoods.add(substitute);\n\t\t\t\t}\n\t\t\t\tif (truth == null && remainingTolerance.decrementAndGet() < 0) {\n\t\t\t\t\t// terminate if more positive atoms are unsatisfied as tolerated by the heuristic\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t// terminate if positive body atom is assigned false\n\t\t\t\treturn truth != null && !truth.toBoolean();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Pair, Map> getChoiceAtoms() {\n\t\treturn choiceRecorder.getAndResetChoices();\n\t}\n\t\n\t@Override\n\tpublic Map> getHeadsToBodies() {\n\t\treturn choiceRecorder.getAndResetHeadsToBodies();\n\t}\n\n\t@Override\n\tpublic void updateAssignment(Iterator it) {\n\t\twhile (it.hasNext()) {\n\t\t\tworkingMemory.addInstance(atomStore.get(it.next()), true);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void forgetAssignment(int[] atomIds) {\n\t\tthrow new UnsupportedOperationException(\"Forgetting assignments is not implemented\");\n\t}\n\n\tpublic static String groundAndPrintRule(NonGroundRule rule, Substitution substitution) {\n\t\tStringBuilder ret = new StringBuilder();\n\t\tif (!rule.isConstraint()) {\n\t\t\tAtom groundHead = rule.getHeadAtom().substitute(substitution);\n\t\t\tret.append(groundHead.toString());\n\t\t}\n\t\tret.append(\" :- \");\n\t\tboolean isFirst = true;\n\t\tfor (Atom bodyAtom : rule.getBodyAtomsPositive()) {\n\t\t\tret.append(groundLiteralToString(bodyAtom.toLiteral(), substitution, isFirst));\n\t\t\tisFirst = false;\n\t\t}\n\t\tfor (Atom bodyAtom : rule.getBodyAtomsNegative()) {\n\t\t\tret.append(groundLiteralToString(bodyAtom.toLiteral(false), substitution, isFirst));\n\t\t\tisFirst = false;\n\t\t}\n\t\tret.append(\".\");\n\t\treturn ret.toString();\n\t}\n\n\tstatic String groundLiteralToString(Literal literal, Substitution substitution, boolean isFirst) {\n\t\tLiteral groundLiteral = literal.substitute(substitution);\n\t\treturn (isFirst ? \"\" : \", \") + groundLiteral.toString();\n\t}\n\n\t@Override\n\tpublic NonGroundRule getNonGroundRule(Integer ruleId) {\n\t\treturn knownNonGroundRules.get(ruleId);\n\t}\n\n\t@Override\n\tpublic boolean isFact(Atom atom) {\n\t\tLinkedHashSet instances = factsFromProgram.get(atom.getPredicate());\n\t\tif (instances == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn instances.contains(new Instance(atom.getTerms()));\n\t}\n\n\t@Override\n\tpublic Set justifyAtom(int atomToJustify, Assignment currentAssignment) {\n\t\tSet literals = analyzeUnjustified.analyze(atomToJustify, currentAssignment);\n\t\t// Remove facts from justification before handing it over to the solver.\n\t\tfor (Iterator iterator = literals.iterator(); iterator.hasNext();) {\n\t\t\tLiteral literal = iterator.next();\n\t\t\tif (literal.isNegated()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tLinkedHashSet factsOverPredicate = factsFromProgram.get(literal.getPredicate());\n\t\t\tif (factsOverPredicate != null && factsOverPredicate.contains(new Instance(literal.getAtom().getTerms()))) {\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\t\treturn literals;\n\t}\n\n\t/**\n\t * Checks that every nogood not marked as {@link NoGood.Type#INTERNAL} contains only\n\t * atoms which are not {@link Predicate#isSolverInternal()} (except {@link RuleAtom}s, which are allowed).\n\t * @param newNoGoods\n\t */\n\tprivate void checkTypesOfNoGoods(Collection newNoGoods) {\n\t\tfor (NoGood noGood : newNoGoods) {\n\t\t\tif (noGood.getType() != Type.INTERNAL) {\n\t\t\t\tfor (int literal : noGood) {\n\t\t\t\t\tAtom atom = atomStore.get(atomOf(literal));\n\t\t\t\t\tif (atom.getPredicate().isSolverInternal() && !(atom instanceof RuleAtom)) {\n\t\t\t\t\t\tthrow oops(\"NoGood containing atom of internal predicate \" + atom + \" is \" + noGood.getType() + \" instead of INTERNAL\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static class FirstBindingAtom {\n\t\tfinal NonGroundRule rule;\n\t\tfinal Literal startingLiteral;\n\n\t\tFirstBindingAtom(NonGroundRule rule, Literal startingLiteral) {\n\t\t\tthis.rule = rule;\n\t\t\tthis.startingLiteral = startingLiteral;\n\t\t}\n\t}\n\t\n\tprivate static class BindingResult {\n\t\tfinal List generatedSubstitutions = new ArrayList<>();\n\t\tfinal List numbersOfUnassignedPositiveBodyAtoms = new ArrayList<>();\n\t\t\n\t\tvoid add(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) {\n\t\t\tthis.generatedSubstitutions.add(generatedSubstitution);\n\t\t\tthis.numbersOfUnassignedPositiveBodyAtoms.add(numberOfUnassignedPositiveBodyAtoms);\n\t\t}\n\n\t\tvoid add(BindingResult otherBindingResult) {\n\t\t\tthis.generatedSubstitutions.addAll(otherBindingResult.generatedSubstitutions);\n\t\t\tthis.numbersOfUnassignedPositiveBodyAtoms.addAll(otherBindingResult.numbersOfUnassignedPositiveBodyAtoms);\n\t\t}\n\n\t\tint size() {\n\t\t\treturn generatedSubstitutions.size();\n\t\t}\n\t\t\n\t\tstatic BindingResult empty() {\n\t\t\treturn new BindingResult();\n\t\t}\n\t\t\n\t\tstatic BindingResult singleton(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) {\n\t\t\tBindingResult bindingResult = new BindingResult();\n\t\t\tbindingResult.add(generatedSubstitution, numberOfUnassignedPositiveBodyAtoms);\n\t\t\treturn bindingResult;\n\t\t}\n\t\t\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/main/java/at/ac/tuwien/kr/alpha/grounder/NaiveGrounder.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (c) 2016-2019, the Alpha Team.\n * All rights reserved.\n * \n * Additional changes made by Siemens.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1) Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * 2) Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage at.ac.tuwien.kr.alpha.grounder;\n\nimport at.ac.tuwien.kr.alpha.common.*;\nimport at.ac.tuwien.kr.alpha.common.NoGood.Type;\nimport at.ac.tuwien.kr.alpha.common.atoms.*;\nimport at.ac.tuwien.kr.alpha.common.terms.VariableTerm;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.ChoiceAtom;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.EnumerationAtom;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.IntervalLiteral;\nimport at.ac.tuwien.kr.alpha.grounder.atoms.RuleAtom;\nimport at.ac.tuwien.kr.alpha.grounder.bridges.Bridge;\nimport at.ac.tuwien.kr.alpha.grounder.heuristics.GrounderHeuristicsConfiguration;\nimport at.ac.tuwien.kr.alpha.grounder.structure.AnalyzeUnjustified;\nimport at.ac.tuwien.kr.alpha.grounder.structure.ProgramAnalysis;\nimport at.ac.tuwien.kr.alpha.grounder.transformation.*;\nimport at.ac.tuwien.kr.alpha.solver.ThriceTruth;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.util.*;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport static at.ac.tuwien.kr.alpha.Util.oops;\nimport static at.ac.tuwien.kr.alpha.common.Literals.atomOf;\nimport static java.util.Collections.singletonList;\n\n/**\n * A semi-naive grounder.\n * Copyright (c) 2016-2019, the Alpha Team.\n */\npublic class NaiveGrounder extends BridgedGrounder implements ProgramAnalyzingGrounder {\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(NaiveGrounder.class);\n\n\tprivate final WorkingMemory workingMemory = new WorkingMemory();\n\tprivate final AtomStore atomStore;\n\tprivate final NogoodRegistry registry = new NogoodRegistry();\n\tfinal NoGoodGenerator noGoodGenerator;\n\tprivate final ChoiceRecorder choiceRecorder;\n\tprivate final ProgramAnalysis programAnalysis;\n\tprivate final AnalyzeUnjustified analyzeUnjustified;\n\n\tprivate final Map> factsFromProgram = new LinkedHashMap<>();\n\tprivate final Map> rulesUsingPredicateWorkingMemory = new HashMap<>();\n\tprivate final Map> knownGroundingSubstitutions = new HashMap<>();\n\tprivate final Map knownNonGroundRules = new HashMap<>();\n\n\tprivate ArrayList fixedRules = new ArrayList<>();\n\tprivate LinkedHashSet removeAfterObtainingNewNoGoods = new LinkedHashSet<>();\n\tprivate boolean disableInstanceRemoval;\n\tprivate final boolean useCountingGridNormalization;\n\tprivate final boolean debugInternalChecks;\n\t\n\tprivate final GrounderHeuristicsConfiguration heuristicsConfiguration;\n\n\tpublic NaiveGrounder(Program program, AtomStore atomStore, boolean debugInternalChecks, Bridge... bridges) {\n\t\tthis(program, atomStore, new GrounderHeuristicsConfiguration(), debugInternalChecks, bridges);\n\t}\n\n\tprivate NaiveGrounder(Program program, AtomStore atomStore, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean debugInternalChecks, Bridge... bridges) {\n\t\tthis(program, atomStore, p -> true, heuristicsConfiguration, false, debugInternalChecks, bridges);\n\t}\n\n\tNaiveGrounder(Program program, AtomStore atomStore, java.util.function.Predicate filter, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean useCountingGrid, boolean debugInternalChecks, Bridge... bridges) {\n\t\tsuper(filter, bridges);\n\t\tthis.atomStore = atomStore;\n\t\tthis.heuristicsConfiguration = heuristicsConfiguration;\n\t\tLOGGER.debug(\"Grounder configuration: \" + heuristicsConfiguration);\n\n\t\tprogramAnalysis = new ProgramAnalysis(program);\n\t\tanalyzeUnjustified = new AnalyzeUnjustified(programAnalysis, atomStore, factsFromProgram);\n\n\t\t// Apply program transformations/rewritings.\n\t\tuseCountingGridNormalization = useCountingGrid;\n\t\tapplyProgramTransformations(program);\n\t\tLOGGER.debug(\"Transformed input program is:\\n\" + program);\n\n\t\tinitializeFactsAndRules(program);\n\n\t\tfinal Set uniqueGroundRulePerGroundHead = getRulesWithUniqueHead();\n\t\tchoiceRecorder = new ChoiceRecorder(atomStore);\n\t\tnoGoodGenerator = new NoGoodGenerator(atomStore, choiceRecorder, factsFromProgram, programAnalysis, uniqueGroundRulePerGroundHead);\n\t\t\n\t\tthis.debugInternalChecks = debugInternalChecks;\n\t}\n\n\tprivate void initializeFactsAndRules(Program program) {\n\t\t// initialize all facts\n\t\tfor (Atom fact : program.getFacts()) {\n\t\t\tfinal Predicate predicate = fact.getPredicate();\n\n\t\t\t// Record predicate\n\t\t\tworkingMemory.initialize(predicate);\n\n\t\t\t// Construct fact instance(s).\n\t\t\tList instances = FactIntervalEvaluator.constructFactInstances(fact);\n\n\t\t\t// Add instances to corresponding list of facts.\n\t\t\tfactsFromProgram.putIfAbsent(predicate, new LinkedHashSet<>());\n\t\t\tHashSet internalPredicateInstances = factsFromProgram.get(predicate);\n\t\t\tinternalPredicateInstances.addAll(instances);\n\t\t}\n\n\t\t// Register internal atoms.\n\t\tworkingMemory.initialize(RuleAtom.PREDICATE);\n\t\tworkingMemory.initialize(ChoiceAtom.OFF);\n\t\tworkingMemory.initialize(ChoiceAtom.ON);\n\n\t\t// Initialize rules and constraints.\n\t\tfor (Rule rule : program.getRules()) {\n\t\t\t// Record the rule for later use\n\t\t\tNonGroundRule nonGroundRule = NonGroundRule.constructNonGroundRule(rule);\n\t\t\tknownNonGroundRules.put(nonGroundRule.getRuleId(), nonGroundRule);\n\t\t\tLOGGER.debug(\"NonGroundRule #\" + nonGroundRule.getRuleId() + \": \" + nonGroundRule);\n\n\t\t\t// Record defining rules for each predicate.\n\t\t\tAtom headAtom = nonGroundRule.getHeadAtom();\n\t\t\tif (headAtom != null) {\n\t\t\t\tPredicate headPredicate = headAtom.getPredicate();\n\t\t\t\tprogramAnalysis.recordDefiningRule(headPredicate, nonGroundRule);\n\t\t\t}\n\n\t\t\t// Create working memories for all predicates occurring in the rule\n\t\t\tfor (Predicate predicate : nonGroundRule.getOccurringPredicates()) {\n\t\t\t\t// FIXME: this also contains interval/builtin predicates that are not needed.\n\t\t\t\tworkingMemory.initialize(predicate);\n\t\t\t}\n\n\t\t\t// If the rule has fixed ground instantiations, it is not registered but grounded once like facts.\n\t\t\tif (nonGroundRule.groundingOrder.fixedInstantiation()) {\n\t\t\t\tfixedRules.add(nonGroundRule);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Register each starting literal at the corresponding working memory.\n\t\t\tfor (Literal literal : nonGroundRule.groundingOrder.getStartingLiterals()) {\n\t\t\t\tregisterLiteralAtWorkingMemory(literal, nonGroundRule);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Set getRulesWithUniqueHead() {\n\t\t// FIXME: below optimisation (adding support nogoods if there is only one rule instantiation per unique atom over the interpretation) could be done as a transformation (adding a non-ground constraint corresponding to the nogood that is generated by the grounder).\n\t\t// Record all unique rule heads.\n\t\tfinal Set uniqueGroundRulePerGroundHead = new HashSet<>();\n\n\t\tfor (Map.Entry> headDefiningRules : programAnalysis.getPredicateDefiningRules().entrySet()) {\n\t\t\tif (headDefiningRules.getValue().size() != 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tNonGroundRule nonGroundRule = headDefiningRules.getValue().iterator().next();\n\t\t\t// Check that all variables of the body also occur in the head (otherwise grounding is not unique).\n\t\t\tAtom headAtom = nonGroundRule.getHeadAtom();\n\n\t\t\t// Rule is not guaranteed unique if there are facts for it.\n\t\t\tHashSet potentialFacts = factsFromProgram.get(headAtom.getPredicate());\n\t\t\tif (potentialFacts != null && !potentialFacts.isEmpty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Collect head and body variables.\n\t\t\tHashSet occurringVariablesHead = new HashSet<>(headAtom.toLiteral().getBindingVariables());\n\t\t\tHashSet occurringVariablesBody = new HashSet<>();\n\t\t\tfor (Atom atom : nonGroundRule.getBodyAtomsPositive()) {\n\t\t\t\toccurringVariablesBody.addAll(atom.toLiteral().getBindingVariables());\n\t\t\t}\n\t\t\toccurringVariablesBody.removeAll(occurringVariablesHead);\n\n\t\t\t// Check if ever body variables occurs in the head.\n\t\t\tif (occurringVariablesBody.isEmpty()) {\n\t\t\t\tuniqueGroundRulePerGroundHead.add(nonGroundRule);\n\t\t\t}\n\t\t}\n\t\treturn uniqueGroundRulePerGroundHead;\n\t}\n\n\tprivate void applyProgramTransformations(Program program) {\n\t\t// Transform choice rules.\n\t\tnew ChoiceHeadToNormal().transform(program);\n\t\t// Transform cardinality aggregates.\n\t\tnew CardinalityNormalization(!useCountingGridNormalization).transform(program);\n\t\t// Transform sum aggregates.\n\t\tnew SumNormalization().transform(program);\n\t\t// Transform intervals.\n\t\tnew IntervalTermToIntervalAtom().transform(program);\n\t\t// Remove variable equalities.\n\t\tnew VariableEqualityRemoval().transform(program);\n\t\t// Transform enumeration atoms.\n\t\tnew EnumerationRewriting().transform(program);\n\t\tEnumerationAtom.resetEnumerations();\n\t}\n\n\t/**\n\t * Registers a starting literal of a NonGroundRule at its corresponding working memory.\n\t * @param nonGroundRule the rule in which the literal occurs.\n\t */\n\tprivate void registerLiteralAtWorkingMemory(Literal literal, NonGroundRule nonGroundRule) {\n\t\tif (literal.isNegated()) {\n\t\t\tthrow new RuntimeException(\"Literal to register is negated. Should not happen.\");\n\t\t}\n\t\tIndexedInstanceStorage workingMemory = this.workingMemory.get(literal.getPredicate(), true);\n\t\trulesUsingPredicateWorkingMemory.putIfAbsent(workingMemory, new ArrayList<>());\n\t\trulesUsingPredicateWorkingMemory.get(workingMemory).add(new FirstBindingAtom(nonGroundRule, literal));\n\t}\n\n\t@Override\n\tpublic AnswerSet assignmentToAnswerSet(Iterable trueAtoms) {\n\t\tMap> predicateInstances = new LinkedHashMap<>();\n\t\tSortedSet knownPredicates = new TreeSet<>();\n\n\t\t// Iterate over all true atomIds, computeNextAnswerSet instances from atomStore and add them if not filtered.\n\t\tfor (int trueAtom : trueAtoms) {\n\t\t\tfinal Atom atom = atomStore.get(trueAtom);\n\t\t\tPredicate predicate = atom.getPredicate();\n\n\t\t\t// Skip atoms over internal predicates.\n\t\t\tif (predicate.isInternal()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip filtered predicates.\n\t\t\tif (!filter.test(predicate)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tknownPredicates.add(predicate);\n\t\t\tpredicateInstances.putIfAbsent(predicate, new TreeSet<>());\n\t\t\tSet instances = predicateInstances.get(predicate);\n\t\t\tinstances.add(atom);\n\t\t}\n\n\t\t// Add true atoms from facts.\n\t\tfor (Map.Entry> facts : factsFromProgram.entrySet()) {\n\t\t\tPredicate factPredicate = facts.getKey();\n\t\t\t// Skip atoms over internal predicates.\n\t\t\tif (factPredicate.isInternal()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Skip filtered predicates.\n\t\t\tif (!filter.test(factPredicate)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Skip predicates without any instances.\n\t\t\tif (facts.getValue().isEmpty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tknownPredicates.add(factPredicate);\n\t\t\tpredicateInstances.putIfAbsent(factPredicate, new TreeSet<>());\n\t\t\tfor (Instance factInstance : facts.getValue()) {\n\t\t\t\tSortedSet instances = predicateInstances.get(factPredicate);\n\t\t\t\tinstances.add(new BasicAtom(factPredicate, factInstance.terms));\n\t\t\t}\n\t\t}\n\n\t\tif (knownPredicates.isEmpty()) {\n\t\t\treturn BasicAnswerSet.EMPTY;\n\t\t}\n\n\t\treturn new BasicAnswerSet(knownPredicates, predicateInstances);\n\t}\n\n\t/**\n\t * Prepares facts of the input program for joining and derives all NoGoods representing ground rules. May only be called once.\n\t * @return\n\t */\n\tprivate HashMap bootstrap() {\n\t\tfinal HashMap groundNogoods = new LinkedHashMap<>();\n\n\t\tfor (Predicate predicate : factsFromProgram.keySet()) {\n\t\t\t// Instead of generating NoGoods, add instance to working memories directly.\n\t\t\tworkingMemory.addInstances(predicate, true, factsFromProgram.get(predicate));\n\t\t}\n\n\t\tfor (NonGroundRule nonGroundRule : fixedRules) {\n\t\t\t// Generate NoGoods for all rules that have a fixed grounding.\n\t\t\tRuleGroundingOrder groundingOrder = nonGroundRule.groundingOrder.getFixedGroundingOrder();\n\t\t\tBindingResult bindingResult = bindNextAtomInRule(nonGroundRule, groundingOrder, new Substitution(), null);\n\t\t\tgroundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, groundNogoods);\n\t\t}\n\n\t\tfixedRules = null;\n\n\t\treturn groundNogoods;\n\t}\n\n\t@Override\n\tpublic Map getNoGoods(Assignment currentAssignment) {\n\t\t// In first call, prepare facts and ground rules.\n\t\tfinal Map newNoGoods = fixedRules != null ? bootstrap() : new LinkedHashMap<>();\n\n\t\t// Compute new ground rule (evaluate joins with newly changed atoms)\n\t\tfor (IndexedInstanceStorage modifiedWorkingMemory : workingMemory.modified()) {\n\t\t\t// Skip predicates solely used in the solver which do not occur in rules.\n\t\t\tPredicate workingMemoryPredicate = modifiedWorkingMemory.getPredicate();\n\t\t\tif (workingMemoryPredicate.isSolverInternal()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Iterate over all rules whose body contains the interpretation corresponding to the current workingMemory.\n\t\t\tfinal ArrayList firstBindingAtoms = rulesUsingPredicateWorkingMemory.get(modifiedWorkingMemory);\n\n\t\t\t// Skip working memories that are not used by any rule.\n\t\t\tif (firstBindingAtoms == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (FirstBindingAtom firstBindingAtom : firstBindingAtoms) {\n\t\t\t\t// Use the recently added instances from the modified working memory to construct an initial substitution\n\t\t\t\tNonGroundRule nonGroundRule = firstBindingAtom.rule;\n\n\t\t\t\t// Generate substitutions from each recent instance.\n\t\t\t\tfor (Instance instance : modifiedWorkingMemory.getRecentlyAddedInstances()) {\n\t\t\t\t\t// Check instance if it matches with the atom.\n\n\t\t\t\t\tfinal Substitution unifier = Substitution.unify(firstBindingAtom.startingLiteral, instance, new Substitution());\n\n\t\t\t\t\tif (unifier == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal BindingResult bindingResult = bindNextAtomInRule(\n\t\t\t\t\t\tnonGroundRule,\n\t\t\t\t\t\tnonGroundRule.groundingOrder.orderStartingFrom(firstBindingAtom.startingLiteral),\n\t\t\t\t\t\tunifier,\n\t\t\t\t\t\tcurrentAssignment\n\t\t\t\t\t);\n\n\t\t\t\t\tgroundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, newNoGoods);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Mark instances added by updateAssignment as done\n\t\t\tmodifiedWorkingMemory.markRecentlyAddedInstancesDone();\n\t\t}\n\n\t\tworkingMemory.reset();\n\t\tfor (Atom removeAtom : removeAfterObtainingNewNoGoods) {\n\t\t\tfinal IndexedInstanceStorage storage = this.workingMemory.get(removeAtom, true);\n\t\t\tInstance instance = new Instance(removeAtom.getTerms());\n\t\t\tif (storage.containsInstance(instance)) {\n\t\t\t\t// lax grounder heuristics may attempt to remove instances that are not yet in the working memory\n\t\t\t\tstorage.removeInstance(instance);\n\t\t\t}\n\t\t}\n\n\t\tremoveAfterObtainingNewNoGoods = new LinkedHashSet<>();\n\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\tLOGGER.debug(\"Grounded NoGoods are:\");\n\t\t\tfor (Map.Entry noGoodEntry : newNoGoods.entrySet()) {\n\t\t\t\tLOGGER.debug(\"{} == {}\", noGoodEntry.getValue(), atomStore.noGoodToString(noGoodEntry.getValue()));\n\t\t\t}\n\t\t\tLOGGER.debug(\"{}\", choiceRecorder);\n\t\t}\n\t\t\n\t\tif (debugInternalChecks) {\n\t\t\tcheckTypesOfNoGoods(newNoGoods.values());\n\t\t}\n\t\t\n\t\treturn newNoGoods;\n\t}\n\n\t/**\n\t * Grounds the given {@code nonGroundRule} by applying the given {@code substitutions} and registers the nogoods generated during that process.\n\t * \n\t * @param nonGroundRule\n\t * the rule to be grounded\n\t * @param substitutions\n\t * the substitutions to be applied\n\t * @param newNoGoods\n\t * a set of nogoods to which newly generated nogoods will be added\n\t */\n\tprivate void groundAndRegister(final NonGroundRule nonGroundRule, final List substitutions, final Map newNoGoods) {\n\t\tfor (Substitution substitution : substitutions) {\n\t\t\tList generatedNoGoods = noGoodGenerator.generateNoGoodsFromGroundSubstitution(nonGroundRule, substitution);\n\t\t\tregistry.register(generatedNoGoods, newNoGoods);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int register(NoGood noGood) {\n\t\treturn registry.register(noGood);\n\t}\n\n\tprivate BindingResult bindNextAtomInRule(NonGroundRule rule, RuleGroundingOrder groundingOrder, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tint tolerance = heuristicsConfiguration.getTolerance(rule.isConstraint());\n\t\tif (tolerance < 0) {\n\t\t\ttolerance = Integer.MAX_VALUE;\n\t\t}\n\t\tBindingResult bindingResult = bindNextAtomInRule(groundingOrder, 0, tolerance, tolerance, partialSubstitution, currentAssignment);\n\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\tfor (int i = 0; i < bindingResult.size(); i++) {\n\t\t\t\tInteger numberOfUnassignedPositiveBodyAtoms = bindingResult.numbersOfUnassignedPositiveBodyAtoms.get(i);\n\t\t\t\tif (numberOfUnassignedPositiveBodyAtoms > 0) {\n\t\t\t\t\tLOGGER.debug(\"Grounded rule in which \" + numberOfUnassignedPositiveBodyAtoms + \" positive atoms are still unassigned: \" + rule + \" (substitution: \" + bindingResult.generatedSubstitutions.get(i) + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn bindingResult;\n\t}\n\n\tprivate BindingResult advanceAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tgroundingOrder.considerUntilCurrentEnd();\n\t\treturn bindNextAtomInRule(groundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t}\n\t\n\tprivate BindingResult pushBackAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tRuleGroundingOrder modifiedGroundingOrder = groundingOrder.pushBack(orderPosition);\n\t\tif (modifiedGroundingOrder == null) {\n\t\t\treturn BindingResult.empty();\n\t\t}\n\t\treturn bindNextAtomInRule(modifiedGroundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t}\n\t\n\tprivate BindingResult bindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {\n\t\tboolean laxGrounderHeuristic = originalTolerance > 0;\n\t\t\n\t\tLiteral currentLiteral = groundingOrder.getLiteralAtOrderPosition(orderPosition);\n\t\tif (currentLiteral == null) {\n\t\t\treturn BindingResult.singleton(partialSubstitution, originalTolerance - remainingTolerance);\n\t\t}\n\t\t\n\t\tAtom currentAtom = currentLiteral.getAtom();\n\t\tif (currentLiteral instanceof FixedInterpretationLiteral) {\n\t\t\t// Generate all substitutions for the builtin/external/interval atom.\n\t\t\tFixedInterpretationLiteral substitutedLiteral = (FixedInterpretationLiteral)currentLiteral.substitute(partialSubstitution);\n\t\t\t// TODO: this has to be improved before merging into master:\n\t\t\tif (!substitutedLiteral.isGround() &&\n\t\t\t\t\t!(substitutedLiteral instanceof ComparisonLiteral && ((ComparisonLiteral)substitutedLiteral).isLeftOrRightAssigning()) &&\n\t\t\t\t\t!(substitutedLiteral instanceof IntervalLiteral && substitutedLiteral.getTerms().get(0).isGround()) &&\n\t\t\t\t\t!(substitutedLiteral instanceof ExternalLiteral)\n\t\t\t\t\t) {\n\t\t\t\treturn pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t}\n\t\t\tfinal List substitutions = substitutedLiteral.getSubstitutions(partialSubstitution);\n\t\t\t\n\t\t\tif (substitutions.isEmpty()) {\n\t\t\t\t// if FixedInterpretationLiteral cannot be satisfied now, it will never be\n\t\t\t\treturn BindingResult.empty();\n\t\t\t}\n\t\t\t\n\t\t\tfinal BindingResult bindingResult = new BindingResult();\n\t\t\tfor (Substitution substitution : substitutions) {\n\t\t\t\t// Continue grounding with each of the generated values.\n\t\t\t\tbindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, substitution, currentAssignment));\n\t\t\t}\n\t\t\treturn bindingResult;\n\t\t}\n\t\tif (currentAtom instanceof EnumerationAtom) {\n\t\t\t// Get the enumeration value and add it to the current partialSubstitution.\n\t\t\t((EnumerationAtom) currentAtom).addEnumerationToSubstitution(partialSubstitution);\n\t\t\treturn advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t}\n\n\t\tCollection instances = null;\n\n\t\t// check if partialVariableSubstitution already yields a ground atom\n\t\tfinal Atom substitute = currentAtom.substitute(partialSubstitution);\n\t\tif (substitute.isGround()) {\n\t\t\t// Substituted atom is ground, in case it is positive, only ground if it also holds true\n\t\t\tif (currentLiteral.isNegated()) {\n\t\t\t\t// Atom occurs negated in the rule: continue grounding\n\t\t\t\treturn advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t}\n\n\t\t\tif (!groundingOrder.isGround() && remainingTolerance <= 0\n\t\t\t\t\t&& !workingMemory.get(currentAtom.getPredicate(), true).containsInstance(new Instance(substitute.getTerms()))) {\n\t\t\t\t// Generate no variable substitution.\n\t\t\t\treturn BindingResult.empty();\n\t\t\t}\n\n\t\t\t// Check if atom is also assigned true.\n\t\t\tfinal LinkedHashSet factInstances = factsFromProgram.get(substitute.getPredicate());\n\t\t\tif (factInstances != null && factInstances.contains(new Instance(substitute.getTerms()))) {\n\t\t\t\t// Ground literal holds, continue finding a variable substitution.\n\t\t\t\treturn advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t}\n\n\t\t\t// Atom is not a fact already.\n\t\t\tinstances = singletonList(new Instance(substitute.getTerms()));\n\t\t}\n\t\t\n\t\t// substituted atom contains variables\n\t\tif (currentLiteral.isNegated()) {\n\t\t\tif (laxGrounderHeuristic) {\n\t\t\t\treturn pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t\t} else {\n\t\t\t\tthrow oops(\"Current atom should be positive at this point but is not\");\n\t\t\t}\n\t\t}\n\n\t\tif (instances == null) {\n\t\t\tIndexedInstanceStorage storage = workingMemory.get(currentAtom.getPredicate(), true);\n\t\t\tif (partialSubstitution.isEmpty()) {\n\t\t\t\t// No variables are bound, but first atom in the body became recently true, consider all instances now.\n\t\t\t\tinstances = storage.getAllInstances();\n\t\t\t} else {\n\t\t\t\tinstances = storage.getInstancesFromPartiallyGroundAtom(substitute);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (laxGrounderHeuristic && instances.isEmpty()) {\n\t\t\t// we have reached a point where we have to terminate binding,\n\t\t\t// but it might be possible that a different grounding order would allow us to continue binding\n\t\t\t// under the presence of a lax grounder heuristic\n\t\t\treturn pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);\n\t\t}\n\n\t\tBindingResult bindingResult = new BindingResult();\n\t\tfor (Instance instance : instances) {\n\t\t\t// Check each instance if it matches with the atom.\n\t\t\tSubstitution unified = Substitution.unify(substitute, instance, new Substitution(partialSubstitution));\n\t\t\tif (unified == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Check if atom is also assigned true.\n\t\t\tAtom substituteClone = new BasicAtom(substitute.getPredicate(), substitute.getTerms());\n\t\t\tAtom substitutedAtom = substituteClone.substitute(unified);\n\t\t\tif (!substitutedAtom.isGround()) {\n\t\t\t\tthrow oops(\"Grounded atom should be ground but is not\");\n\t\t\t}\n\n\t\t\tAtomicInteger atomicRemainingTolerance = new AtomicInteger(remainingTolerance);\t// TODO: done this way for call-by-reference, should be refactored\n\t\t\tif (factsFromProgram.get(substitutedAtom.getPredicate()) == null || !factsFromProgram.get(substitutedAtom.getPredicate()).contains(new Instance(substitutedAtom.getTerms()))) {\n\t\t\t\tif (storeAtomAndTerminateIfAtomDoesNotHold(substitutedAtom, currentAssignment, atomicRemainingTolerance)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, atomicRemainingTolerance.get(), unified, currentAssignment));\n\t\t}\n\n\t\treturn bindingResult;\n\t}\n\n\tprivate boolean storeAtomAndTerminateIfAtomDoesNotHold(final Atom substitute, Assignment currentAssignment, AtomicInteger remainingTolerance) {\n\t\tfinal int atomId = atomStore.putIfAbsent(substitute);\n\n\t\tif (currentAssignment != null) {\n\t\t\tThriceTruth truth = currentAssignment.isAssigned(atomId) ? currentAssignment.getTruth(atomId) : null;\n\t\t\tif (truth == null || !truth.toBoolean()) {\n\t\t\t\t// Atom currently does not hold\n\t\t\t\tif (!disableInstanceRemoval) {\n\t\t\t\t\tremoveAfterObtainingNewNoGoods.add(substitute);\n\t\t\t\t}\n\t\t\t\tif (truth == null && remainingTolerance.decrementAndGet() < 0) {\n\t\t\t\t\t// terminate if more positive atoms are unsatisfied as tolerated by the heuristic\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t// terminate if positive body atom is assigned false\n\t\t\t\treturn truth != null && !truth.toBoolean();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Pair, Map> getChoiceAtoms() {\n\t\treturn choiceRecorder.getAndResetChoices();\n\t}\n\t\n\t@Override\n\tpublic Map> getHeadsToBodies() {\n\t\treturn choiceRecorder.getAndResetHeadsToBodies();\n\t}\n\n\t@Override\n\tpublic void updateAssignment(Iterator it) {\n\t\twhile (it.hasNext()) {\n\t\t\tworkingMemory.addInstance(atomStore.get(it.next()), true);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void forgetAssignment(int[] atomIds) {\n\t\tthrow new UnsupportedOperationException(\"Forgetting assignments is not implemented\");\n\t}\n\n\tpublic static String groundAndPrintRule(NonGroundRule rule, Substitution substitution) {\n\t\tStringBuilder ret = new StringBuilder();\n\t\tif (!rule.isConstraint()) {\n\t\t\tAtom groundHead = rule.getHeadAtom().substitute(substitution);\n\t\t\tret.append(groundHead.toString());\n\t\t}\n\t\tret.append(\" :- \");\n\t\tboolean isFirst = true;\n\t\tfor (Atom bodyAtom : rule.getBodyAtomsPositive()) {\n\t\t\tret.append(groundLiteralToString(bodyAtom.toLiteral(), substitution, isFirst));\n\t\t\tisFirst = false;\n\t\t}\n\t\tfor (Atom bodyAtom : rule.getBodyAtomsNegative()) {\n\t\t\tret.append(groundLiteralToString(bodyAtom.toLiteral(false), substitution, isFirst));\n\t\t\tisFirst = false;\n\t\t}\n\t\tret.append(\".\");\n\t\treturn ret.toString();\n\t}\n\n\tstatic String groundLiteralToString(Literal literal, Substitution substitution, boolean isFirst) {\n\t\tLiteral groundLiteral = literal.substitute(substitution);\n\t\treturn (isFirst ? \"\" : \", \") + groundLiteral.toString();\n\t}\n\n\t@Override\n\tpublic NonGroundRule getNonGroundRule(Integer ruleId) {\n\t\treturn knownNonGroundRules.get(ruleId);\n\t}\n\n\t@Override\n\tpublic boolean isFact(Atom atom) {\n\t\tLinkedHashSet instances = factsFromProgram.get(atom.getPredicate());\n\t\tif (instances == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn instances.contains(new Instance(atom.getTerms()));\n\t}\n\n\t@Override\n\tpublic Set justifyAtom(int atomToJustify, Assignment currentAssignment) {\n\t\tSet literals = analyzeUnjustified.analyze(atomToJustify, currentAssignment);\n\t\t// Remove facts from justification before handing it over to the solver.\n\t\tfor (Iterator iterator = literals.iterator(); iterator.hasNext();) {\n\t\t\tLiteral literal = iterator.next();\n\t\t\tif (literal.isNegated()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tLinkedHashSet factsOverPredicate = factsFromProgram.get(literal.getPredicate());\n\t\t\tif (factsOverPredicate != null && factsOverPredicate.contains(new Instance(literal.getAtom().getTerms()))) {\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\t\treturn literals;\n\t}\n\n\t/**\n\t * Checks that every nogood not marked as {@link NoGood.Type#INTERNAL} contains only\n\t * atoms which are not {@link Predicate#isSolverInternal()} (except {@link RuleAtom}s, which are allowed).\n\t * @param newNoGoods\n\t */\n\tprivate void checkTypesOfNoGoods(Collection newNoGoods) {\n\t\tfor (NoGood noGood : newNoGoods) {\n\t\t\tif (noGood.getType() != Type.INTERNAL) {\n\t\t\t\tfor (int literal : noGood) {\n\t\t\t\t\tAtom atom = atomStore.get(atomOf(literal));\n\t\t\t\t\tif (atom.getPredicate().isSolverInternal() && !(atom instanceof RuleAtom)) {\n\t\t\t\t\t\tthrow oops(\"NoGood containing atom of internal predicate \" + atom + \" is \" + noGood.getType() + \" instead of INTERNAL\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static class FirstBindingAtom {\n\t\tfinal NonGroundRule rule;\n\t\tfinal Literal startingLiteral;\n\n\t\tFirstBindingAtom(NonGroundRule rule, Literal startingLiteral) {\n\t\t\tthis.rule = rule;\n\t\t\tthis.startingLiteral = startingLiteral;\n\t\t}\n\t}\n\t\n\tprivate static class BindingResult {\n\t\tfinal List generatedSubstitutions = new ArrayList<>();\n\t\tfinal List numbersOfUnassignedPositiveBodyAtoms = new ArrayList<>();\n\t\t\n\t\tvoid add(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) {\n\t\t\tthis.generatedSubstitutions.add(generatedSubstitution);\n\t\t\tthis.numbersOfUnassignedPositiveBodyAtoms.add(numberOfUnassignedPositiveBodyAtoms);\n\t\t}\n\n\t\tvoid add(BindingResult otherBindingResult) {\n\t\t\tthis.generatedSubstitutions.addAll(otherBindingResult.generatedSubstitutions);\n\t\t\tthis.numbersOfUnassignedPositiveBodyAtoms.addAll(otherBindingResult.numbersOfUnassignedPositiveBodyAtoms);\n\t\t}\n\n\t\tint size() {\n\t\t\treturn generatedSubstitutions.size();\n\t\t}\n\t\t\n\t\tstatic BindingResult empty() {\n\t\t\treturn new BindingResult();\n\t\t}\n\t\t\n\t\tstatic BindingResult singleton(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) {\n\t\t\tBindingResult bindingResult = new BindingResult();\n\t\t\tbindingResult.add(generatedSubstitution, numberOfUnassignedPositiveBodyAtoms);\n\t\t\treturn bindingResult;\n\t\t}\n\t\t\n\t}\n}\n"},"message":{"kind":"string","value":"Refactoring NaiveGrounder\n"},"old_file":{"kind":"string","value":"src/main/java/at/ac/tuwien/kr/alpha/grounder/NaiveGrounder.java"},"subject":{"kind":"string","value":"Refactoring NaiveGrounder"}}},{"rowIdx":1241,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"15b5ae619cc5dd9c72a2454f1fb3e18323418420"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"intuit/karate,intuit/karate,intuit/karate,intuit/karate"},"new_contents":{"kind":"string","value":"/*\n * The MIT License\n *\n * Copyright 2020 Intuit Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.intuit.karate.core;\n\nimport com.intuit.karate.EventContext;\nimport com.intuit.karate.FileUtils;\nimport com.intuit.karate.Json;\nimport com.intuit.karate.JsonUtils;\nimport com.intuit.karate.KarateException;\nimport com.intuit.karate.Logger;\nimport com.intuit.karate.Match;\nimport com.intuit.karate.MatchStep;\nimport com.intuit.karate.PerfContext;\nimport com.intuit.karate.StringUtils;\nimport com.intuit.karate.XmlUtils;\nimport com.intuit.karate.graal.JsEngine;\nimport com.intuit.karate.graal.JsLambda;\nimport com.intuit.karate.graal.JsList;\nimport com.intuit.karate.graal.JsMap;\nimport com.intuit.karate.graal.JsValue;\nimport com.intuit.karate.http.HttpClient;\nimport com.intuit.karate.http.HttpRequest;\nimport com.intuit.karate.http.HttpRequestBuilder;\nimport com.intuit.karate.http.ResourceType;\nimport com.intuit.karate.http.WebSocketClient;\nimport com.intuit.karate.http.WebSocketOptions;\nimport com.intuit.karate.shell.Command;\nimport java.io.File;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\nimport java.util.function.Function;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.graalvm.polyglot.Value;\n\n/**\n *\n * @author pthomas3\n */\npublic class ScenarioBridge implements PerfContext, EventContext {\n\n private final ScenarioEngine ENGINE;\n\n protected ScenarioBridge(ScenarioEngine engine) {\n ENGINE = engine;\n }\n\n public void abort() {\n getEngine().setAborted(true);\n }\n\n public Object append(Value... vals) {\n List list = new ArrayList();\n JsList jsList = new JsList(list);\n if (vals.length == 0) {\n return jsList;\n }\n Value val = vals[0];\n if (val.hasArrayElements()) {\n list.addAll(val.as(List.class));\n } else {\n list.add(val.as(Object.class));\n }\n if (vals.length == 1) {\n return jsList;\n }\n for (int i = 1; i < vals.length; i++) {\n Value v = vals[i];\n if (v.hasArrayElements()) {\n list.addAll(v.as(List.class));\n } else {\n list.add(v.as(Object.class));\n }\n }\n return jsList;\n }\n\n private Object appendToInternal(String varName, Value... vals) {\n ScenarioEngine engine = getEngine();\n Variable var = engine.vars.get(varName);\n if (!var.isList()) {\n return null;\n }\n List list = var.getValue();\n for (Value v : vals) {\n if (v.hasArrayElements()) {\n list.addAll(v.as(List.class));\n } else {\n Object temp = v.as(Object.class);\n list.add(temp);\n }\n }\n engine.setVariable(varName, list);\n return new JsList(list);\n }\n\n public Object appendTo(Value ref, Value... vals) {\n if (ref.isString()) {\n return appendToInternal(ref.asString(), vals);\n }\n List list;\n if (ref.hasArrayElements()) {\n list = new JsValue(ref).getAsList(); // make sure we unwrap the \"original\" list\n } else {\n list = new ArrayList();\n }\n for (Value v : vals) {\n if (v.hasArrayElements()) {\n list.addAll(v.as(List.class));\n } else {\n Object temp = v.as(Object.class);\n list.add(temp);\n }\n }\n return new JsList(list);\n }\n\n public Object call(String fileName) {\n return call(false, fileName, null);\n }\n\n public Object call(String fileName, Value arg) {\n return call(false, fileName, arg);\n }\n\n public Object call(boolean sharedScope, String fileName) {\n return call(sharedScope, fileName, null);\n }\n\n public Object call(boolean sharedScope, String fileName, Value arg) {\n ScenarioEngine engine = getEngine();\n Variable called = new Variable(engine.fileReader.readFile(fileName));\n Variable result = engine.call(called, arg == null ? null : new Variable(arg), sharedScope);\n return JsValue.fromJava(result.getValue());\n }\n\n private static Object callSingleResult(ScenarioEngine engine, Object o) throws Exception {\n if (o instanceof Exception) {\n engine.logger.warn(\"callSingle() cached result is an exception\");\n throw (Exception) o;\n }\n // if we don't clone, an attach operation would update the tree within the cached value\n // causing future cache hit + attach attempts to fail !\n o = engine.recurseAndAttachAndShallowClone(o);\n return JsValue.fromJava(o);\n }\n\n public Object callSingle(String fileName) throws Exception {\n return callSingle(fileName, null);\n }\n\n public Object callSingle(String fileName, Value arg) throws Exception {\n ScenarioEngine engine = getEngine();\n final Map CACHE = engine.runtime.featureRuntime.suite.callSingleCache;\n if (CACHE.containsKey(fileName)) {\n engine.logger.trace(\"callSingle cache hit: {}\", fileName);\n return callSingleResult(engine, CACHE.get(fileName));\n }\n long startTime = System.currentTimeMillis();\n engine.logger.trace(\"callSingle waiting for lock: {}\", fileName);\n synchronized (CACHE) { // lock\n if (CACHE.containsKey(fileName)) { // retry\n long endTime = System.currentTimeMillis() - startTime;\n engine.logger.warn(\"this thread waited {} milliseconds for callSingle lock: {}\", endTime, fileName);\n return callSingleResult(engine, CACHE.get(fileName));\n }\n // this thread is the 'winner'\n engine.logger.info(\">> lock acquired, begin callSingle: {}\", fileName);\n int minutes = engine.getConfig().getCallSingleCacheMinutes();\n Object result = null;\n File cacheFile = null;\n if (minutes > 0) {\n String cleanedName = StringUtils.toIdString(fileName);\n String cacheFileName = engine.getConfig().getCallSingleCacheDir() + File.separator + cleanedName + \".txt\";\n cacheFile = new File(cacheFileName);\n long since = System.currentTimeMillis() - minutes * 60 * 1000;\n if (cacheFile.exists()) {\n long lastModified = cacheFile.lastModified();\n if (lastModified > since) {\n String json = FileUtils.toString(cacheFile);\n result = JsonUtils.fromJson(json);\n engine.logger.info(\"callSingleCache hit: {}\", cacheFile);\n } else {\n engine.logger.info(\"callSingleCache stale, last modified {} - is before {} (minutes: {})\",\n lastModified, since, minutes);\n }\n } else {\n engine.logger.info(\"callSingleCache file does not exist, will create: {}\", cacheFile);\n }\n }\n if (result == null) {\n Variable called = new Variable(read(fileName));\n Variable argVar;\n if (arg == null || arg.isNull()) {\n argVar = null;\n } else {\n argVar = new Variable(arg);\n }\n Variable resultVar;\n try {\n resultVar = engine.call(called, argVar, false);\n } catch (Exception e) {\n // don't retain any vestiges of graal-js \n RuntimeException re = new RuntimeException(e.getMessage());\n // we do this so that an exception is also \"cached\"\n resultVar = new Variable(re); // will be thrown at end\n engine.logger.warn(\"callSingle() will cache an exception\");\n }\n if (minutes > 0) { // cacheFile will be not null\n if (resultVar.isMapOrList()) {\n String json = resultVar.getAsString();\n FileUtils.writeToFile(cacheFile, json);\n engine.logger.info(\"callSingleCache write: {}\", cacheFile);\n } else {\n engine.logger.warn(\"callSingleCache write failed, not json-like: {}\", resultVar);\n }\n }\n // functions have to be detached so that they can be re-hydrated in another js context\n result = engine.recurseAndDetachAndShallowClone(resultVar.getValue());\n }\n CACHE.put(fileName, result);\n engine.logger.info(\"<< lock released, cached callSingle: {}\", fileName);\n return callSingleResult(engine, result);\n }\n }\n\n public Object callonce(String path) {\n return callonce(false, path);\n }\n\n public Object callonce(boolean sharedScope, String path) {\n String exp = \"read('\" + path + \"')\";\n Variable v = getEngine().call(true, exp, sharedScope);\n return JsValue.fromJava(v.getValue());\n }\n\n @Override\n public void capturePerfEvent(String name, long startTime, long endTime) {\n PerfEvent event = new PerfEvent(startTime, endTime, name, 200);\n getEngine().capturePerfEvent(event);\n }\n\n public void configure(String key, Value value) {\n getEngine().configure(key, new Variable(value));\n }\n\n public Object distinct(Value o) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n long count = o.getArraySize();\n Set set = new LinkedHashSet();\n for (int i = 0; i < count; i++) {\n Object value = JsValue.toJava(o.getArrayElement(i));\n set.add(value);\n }\n return JsValue.fromJava(new ArrayList(set));\n }\n\n public String doc(Value v) {\n Map arg;\n if (v.isString()) {\n arg = Collections.singletonMap(\"read\", v.asString());\n } else if (v.hasMembers()) {\n arg = new JsValue(v).getAsMap();\n } else {\n getEngine().logger.warn(\"doc - unexpected argument: {}\", v);\n return null;\n }\n return getEngine().docInternal(arg);\n }\n\n public void embed(Object o, String contentType) {\n ResourceType resourceType;\n if (contentType == null) {\n resourceType = ResourceType.fromObject(o, ResourceType.BINARY);\n } else {\n resourceType = ResourceType.fromContentType(contentType);\n }\n getEngine().runtime.embed(JsValue.toBytes(o), resourceType);\n }\n\n public Object eval(String exp) {\n Variable result = getEngine().evalJs(exp);\n return JsValue.fromJava(result.getValue());\n }\n\n public String exec(Value value) {\n if (value.isString()) {\n return execInternal(Collections.singletonMap(\"line\", value.asString()));\n } else if (value.hasArrayElements()) {\n List args = new JsValue(value).getAsList();\n return execInternal(Collections.singletonMap(\"args\", args));\n } else {\n return execInternal(new JsValue(value).getAsMap());\n }\n }\n\n private String execInternal(Map options) {\n Command command = getEngine().fork(false, options);\n command.waitSync();\n return command.getAppender().collect();\n }\n\n public String extract(String text, String regex, int group) {\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n if (!matcher.find()) {\n getEngine().logger.warn(\"failed to find pattern: {}\", regex);\n return null;\n }\n return matcher.group(group);\n }\n\n public List extractAll(String text, String regex, int group) {\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n List list = new ArrayList();\n while (matcher.find()) {\n list.add(matcher.group(group));\n }\n return list;\n }\n\n public void fail(String reason) {\n getEngine().setFailedReason(new KarateException(reason));\n }\n\n public Object filter(Value o, Value f) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n assertIfJsFunction(f);\n long count = o.getArraySize();\n List list = new ArrayList();\n for (int i = 0; i < count; i++) {\n Value v = o.getArrayElement(i);\n Value res = JsEngine.execute(f, v, i);\n if (res.isBoolean() && res.asBoolean()) {\n list.add(new JsValue(v).getValue());\n }\n }\n return new JsList(list);\n }\n\n public Object filterKeys(Value o, Value... args) {\n if (!o.hasMembers() || args.length == 0) {\n return JsMap.EMPTY;\n }\n List keys = new ArrayList();\n if (args.length == 1) {\n if (args[0].isString()) {\n keys.add(args[0].asString());\n } else if (args[0].hasArrayElements()) {\n long count = args[0].getArraySize();\n for (int i = 0; i < count; i++) {\n keys.add(args[0].getArrayElement(i).toString());\n }\n } else if (args[0].hasMembers()) {\n for (String s : args[0].getMemberKeys()) {\n keys.add(s);\n }\n }\n } else {\n for (Value v : args) {\n keys.add(v.toString());\n }\n }\n Map map = new LinkedHashMap(keys.size());\n for (String key : keys) {\n if (key == null) {\n continue;\n }\n Value v = o.getMember(key);\n if (v != null) {\n map.put(key, v.as(Object.class));\n }\n }\n return new JsMap(map);\n }\n\n public void forEach(Value o, Value f) {\n assertIfJsFunction(f);\n if (o.hasArrayElements()) {\n long count = o.getArraySize();\n for (int i = 0; i < count; i++) {\n Value v = o.getArrayElement(i);\n f.executeVoid(v, i);\n }\n } else if (o.hasMembers()) { //map\n int i = 0;\n for (String k : o.getMemberKeys()) {\n Value v = o.getMember(k);\n f.executeVoid(k, v, i++);\n }\n } else {\n throw new RuntimeException(\"not an array or object: \" + o);\n }\n }\n\n public Command fork(Value value) {\n if (value.isString()) {\n return getEngine().fork(true, value.asString());\n } else if (value.hasArrayElements()) {\n List args = new JsValue(value).getAsList();\n return getEngine().fork(true, args);\n } else {\n return getEngine().fork(true, new JsValue(value).getAsMap());\n }\n }\n\n // TODO breaking returns actual object not wrapper\n // and fromObject() has been removed\n // use new typeOf() method to find type\n public Object fromString(String exp) {\n ScenarioEngine engine = getEngine();\n try {\n Variable result = engine.evalKarateExpression(exp);\n return JsValue.fromJava(result.getValue());\n } catch (Exception e) {\n engine.setFailedReason(null); // special case\n engine.logger.warn(\"auto evaluation failed: {}\", e.getMessage());\n return exp;\n }\n }\n\n public Object get(String exp) {\n ScenarioEngine engine = getEngine();\n Variable v;\n try {\n v = engine.evalKarateExpression(exp); // even json path expressions will work\n } catch (Exception e) {\n engine.logger.trace(\"karate.get failed for expression: '{}': {}\", exp, e.getMessage());\n engine.setFailedReason(null); // special case !\n return null;\n }\n if (v != null) {\n return JsValue.fromJava(v.getValue());\n } else {\n return null;\n }\n }\n\n public Object get(String exp, Object defaultValue) {\n Object result = get(exp);\n return result == null ? defaultValue : result;\n }\n\n // getters =================================================================\n // TODO migrate these to functions not properties\n //\n public ScenarioEngine getEngine() {\n ScenarioEngine engine = ScenarioEngine.get();\n return engine == null ? ENGINE : engine;\n }\n\n public String getEnv() {\n return getEngine().runtime.featureRuntime.suite.env;\n }\n\n public Object getFeature() {\n return new JsMap(getEngine().runtime.featureRuntime.result.toInfoJson());\n }\n\n public Object getInfo() { // TODO deprecate\n return new JsMap(getEngine().runtime.getScenarioInfo());\n }\n\n private LogFacade logFacade;\n\n public Object getLogger() {\n if (logFacade == null) {\n logFacade = new LogFacade();\n }\n return logFacade;\n }\n\n public Object getOs() {\n String name = FileUtils.getOsName();\n String type = FileUtils.getOsType(name).toString().toLowerCase();\n Map map = new HashMap(2);\n map.put(\"name\", name);\n map.put(\"type\", type);\n return new JsMap(map);\n }\n\n // TODO breaking uri has been renamed to url\n public Object getPrevRequest() {\n HttpRequest hr = getEngine().getRequest();\n if (hr == null) {\n return null;\n }\n Map map = new HashMap();\n map.put(\"method\", hr.getMethod());\n map.put(\"url\", hr.getUrl());\n map.put(\"headers\", hr.getHeaders());\n map.put(\"body\", hr.getBody());\n return JsValue.fromJava(map);\n }\n\n public Object getProperties() {\n return new JsMap(getEngine().runtime.featureRuntime.suite.systemProperties);\n }\n\n public Object getScenario() {\n return new JsMap(getEngine().runtime.result.toKarateJson());\n }\n\n public Object getTags() {\n return JsValue.fromJava(getEngine().runtime.tags.getTags());\n }\n\n public Object getTagValues() {\n return JsValue.fromJava(getEngine().runtime.tags.getTagValues());\n }\n\n //==========================================================================\n //\n public HttpRequestBuilder http(String url) {\n ScenarioEngine engine = getEngine();\n HttpClient client = engine.runtime.featureRuntime.suite.clientFactory.create(engine);\n return new HttpRequestBuilder(client).url(url);\n }\n\n public Object jsonPath(Object o, String exp) {\n Json json = Json.of(o);\n return JsValue.fromJava(json.get(exp));\n }\n\n public Object keysOf(Value o) {\n return new JsList(o.getMemberKeys());\n }\n\n public void log(Value... values) {\n ScenarioEngine engine = getEngine();\n if (engine.getConfig().isPrintEnabled()) {\n engine.logger.info(\"{}\", new LogWrapper(values));\n }\n }\n\n public Object lowerCase(Object o) {\n Variable var = new Variable(o);\n return JsValue.fromJava(var.toLowerCase().getValue());\n }\n\n public Object map(Value o, Value f) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n assertIfJsFunction(f);\n long count = o.getArraySize();\n List list = new ArrayList();\n for (int i = 0; i < count; i++) {\n Value v = o.getArrayElement(i);\n Value res = JsEngine.execute(f, v, i);\n list.add(new JsValue(res).getValue());\n }\n return new JsList(list);\n }\n\n public Object mapWithKey(Value v, String key) {\n if (!v.hasArrayElements()) {\n return JsList.EMPTY;\n }\n long count = v.getArraySize();\n List list = new ArrayList();\n for (int i = 0; i < count; i++) {\n Map map = new LinkedHashMap();\n Value res = v.getArrayElement(i);\n map.put(key, res.as(Object.class));\n list.add(map);\n }\n return new JsList(list);\n }\n\n public Object match(Object actual, Object expected) {\n Match.Result mr = getEngine().match(Match.Type.EQUALS, actual, expected);\n return JsValue.fromJava(mr.toMap());\n }\n\n public Object match(String exp) {\n MatchStep ms = new MatchStep(exp);\n Match.Result mr = getEngine().match(ms.type, ms.name, ms.path, ms.expected);\n return JsValue.fromJava(mr.toMap());\n }\n\n public Object merge(Value... vals) {\n if (vals.length == 0) {\n return null;\n }\n if (vals.length == 1) {\n return vals[0];\n }\n Map map = new HashMap(vals[0].as(Map.class));\n for (int i = 1; i < vals.length; i++) {\n map.putAll(vals[i].as(Map.class));\n }\n return new JsMap(map);\n }\n\n public void pause(Value value) {\n ScenarioEngine engine = getEngine();\n if (!value.isNumber()) {\n engine.logger.warn(\"pause argument is not a number:\", value);\n return;\n }\n if (engine.runtime.perfMode) {\n engine.runtime.featureRuntime.perfHook.pause(value.asInt());\n } else if (engine.getConfig().isPauseIfNotPerf()) {\n try {\n Thread.sleep(value.asInt());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n public String pretty(Object o) {\n Variable v = new Variable(o);\n return v.getAsPrettyString();\n }\n\n public String prettyXml(Object o) {\n Variable v = new Variable(o);\n return v.getAsPrettyXmlString();\n }\n\n public void proceed() {\n proceed(null);\n }\n\n public void proceed(String requestUrlBase) {\n getEngine().mockProceed(requestUrlBase);\n }\n\n public Object range(int start, int end) {\n return range(start, end, 1);\n }\n\n public Object range(int start, int end, int interval) {\n if (interval <= 0) {\n throw new RuntimeException(\"interval must be a positive integer\");\n }\n List list = new ArrayList();\n if (start <= end) {\n for (int i = start; i <= end; i += interval) {\n list.add(i);\n }\n } else {\n for (int i = start; i >= end; i -= interval) {\n list.add(i);\n }\n }\n return JsValue.fromJava(list);\n }\n\n public Object read(String name) {\n Object result = getEngine().fileReader.readFile(name);\n return JsValue.fromJava(result);\n }\n\n public String readAsString(String fileName) {\n return getEngine().fileReader.readFileAsString(fileName);\n }\n\n public void remove(String name, String path) {\n getEngine().remove(name, path);\n }\n\n public Object repeat(int n, Value f) {\n assertIfJsFunction(f);\n List list = new ArrayList(n);\n for (int i = 0; i < n; i++) {\n Value v = JsEngine.execute(f, i);\n list.add(new JsValue(v).getValue());\n }\n return new JsList(list);\n }\n\n // set multiple variables in one shot\n public void set(Map map) {\n getEngine().setVariables(map);\n }\n\n public void set(String name, Value value) {\n getEngine().setVariable(name, new Variable(value));\n }\n\n // this makes sense mainly for xpath manipulation from within js\n public void set(String name, String path, Object value) {\n getEngine().set(name, path, new Variable(value));\n }\n\n public void setXml(String name, String xml) {\n getEngine().setVariable(name, XmlUtils.toXmlDoc(xml));\n }\n\n // this makes sense mainly for xpath manipulation from within js\n public void setXml(String name, String path, String xml) {\n getEngine().set(name, path, new Variable(XmlUtils.toXmlDoc(xml)));\n }\n\n @Override\n public void signal(Object o) {\n Value v = Value.asValue(o);\n getEngine().signal(JsValue.toJava(v));\n }\n\n public Object sizeOf(Value v) {\n if (v.hasArrayElements()) {\n return v.getArraySize();\n } else if (v.hasMembers()) {\n return v.getMemberKeys().size();\n } else {\n return -1;\n }\n }\n\n public Object sort(Value o) {\n return sort(o, getEngine().JS.evalForValue(\"x => x\"));\n }\n\n public Object sort(Value o, Value f) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n assertIfJsFunction(f);\n long count = o.getArraySize();\n Map map = new TreeMap();\n for (int i = 0; i < count; i++) {\n Object item = JsValue.toJava(o.getArrayElement(i));\n Value key = JsEngine.execute(f, item, i);\n if (key.isNumber()) {\n map.put(key.as(Number.class), item);\n } else {\n map.put(key.asString(), item);\n }\n }\n return JsValue.fromJava(new ArrayList(map.values()));\n }\n\n public MockServer start(Value value) {\n if (value.isString()) {\n return startInternal(Collections.singletonMap(\"mock\", value.asString()));\n } else {\n return startInternal(new JsValue(value).getAsMap());\n }\n }\n\n private MockServer startInternal(Map config) {\n String mock = (String) config.get(\"mock\");\n if (mock == null) {\n throw new RuntimeException(\"'mock' is missing: \" + config);\n }\n File feature = toJavaFile(mock);\n MockServer.Builder builder = MockServer.feature(feature);\n String certFile = (String) config.get(\"cert\");\n if (certFile != null) {\n builder.certFile(toJavaFile(certFile));\n }\n String keyFile = (String) config.get(\"key\");\n if (keyFile != null) {\n builder.keyFile(toJavaFile(keyFile));\n }\n Boolean ssl = (Boolean) config.get(\"ssl\");\n if (ssl == null) {\n ssl = false;\n }\n Integer port = (Integer) config.get(\"port\");\n if (port == null) {\n port = 0;\n }\n Map arg = (Map) config.get(\"arg\");\n builder.args(arg);\n if (ssl) {\n builder.https(port);\n } else {\n builder.http(port);\n }\n return builder.build();\n }\n\n public void stop(int port) {\n Command.waitForSocket(port);\n }\n\n public String toAbsolutePath(String relativePath) {\n return getEngine().fileReader.toAbsolutePath(relativePath);\n }\n\n public Object toBean(Object o, String className) {\n Json json = Json.of(o);\n Object bean = JsonUtils.fromJson(json.toString(), className);\n return JsValue.fromJava(bean);\n }\n\n public String toCsv(Object o) {\n Variable v = new Variable(o);\n if (!v.isList()) {\n throw new RuntimeException(\"not a json array: \" + v);\n }\n List> list = v.getValue();\n return JsonUtils.toCsv(list);\n }\n\n public Object toJava(Value value) {\n if (value.canExecute()) {\n JsEngine copy = getEngine().JS.copy();\n return new JsLambda(copy.attach(value));\n } else {\n return new JsValue(value).getValue();\n }\n }\n\n private File toJavaFile(String path) {\n return getEngine().fileReader.toResource(path).getFile();\n }\n\n public Object toJson(Value value) {\n return toJson(value, false);\n }\n\n public Object toJson(Value value, boolean removeNulls) {\n JsValue jv = new JsValue(value);\n String json = JsonUtils.toJson(jv.getValue());\n Object result = Json.of(json).value();\n if (removeNulls) {\n JsonUtils.removeKeysWithNullValues(result);\n }\n return JsValue.fromJava(result);\n }\n\n // TODO deprecate\n public Object toList(Value value) {\n return new JsValue(value).getValue();\n }\n\n // TODO deprecate\n public Object toMap(Value value) {\n return new JsValue(value).getValue();\n }\n\n public String toString(Object o) {\n Variable v = new Variable(o);\n return v.getAsString();\n }\n\n public String trim(String s) {\n return s == null ? null : s.trim();\n }\n\n public String typeOf(Value value) {\n Variable v = new Variable(value);\n return v.getTypeString();\n }\n\n public String urlEncode(String s) {\n try {\n return URLEncoder.encode(s, \"UTF-8\");\n } catch (Exception e) {\n getEngine().logger.warn(\"url encode failed: {}\", e.getMessage());\n return s;\n }\n }\n\n public String urlDecode(String s) {\n try {\n return URLDecoder.decode(s, \"UTF-8\");\n } catch (Exception e) {\n getEngine().logger.warn(\"url encode failed: {}\", e.getMessage());\n return s;\n }\n }\n\n public Object valuesOf(Value v) {\n if (v.hasArrayElements()) {\n return v;\n } else if (v.hasMembers()) {\n List list = new ArrayList();\n for (String k : v.getMemberKeys()) {\n Value res = v.getMember(k);\n list.add(res.as(Object.class));\n }\n return new JsList(list);\n } else {\n return null;\n }\n }\n\n public boolean waitForHttp(String url) {\n return Command.waitForHttp(url);\n }\n\n public boolean waitForPort(String host, int port) {\n return new Command().waitForPort(host, port);\n }\n\n public WebSocketClient webSocket(String url) {\n return webSocket(url, null, null);\n }\n\n public WebSocketClient webSocket(String url, Value value) {\n return webSocket(url, value, null);\n }\n\n public WebSocketClient webSocket(String url, Value listener, Value value) {\n Function handler;\n ScenarioEngine engine = getEngine();\n if (listener == null || !listener.canExecute()) {\n handler = m -> true;\n } else {\n JsEngine copy = engine.JS.copy();\n handler = new JsLambda(copy.attach(listener));\n }\n WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue());\n options.setTextHandler(handler);\n return engine.webSocket(options);\n }\n\n public WebSocketClient webSocketBinary(String url) {\n return webSocketBinary(url, null, null);\n }\n\n public WebSocketClient webSocketBinary(String url, Value value) {\n return webSocketBinary(url, value, null);\n }\n\n public WebSocketClient webSocketBinary(String url, Value listener, Value value) {\n Function handler;\n ScenarioEngine engine = getEngine();\n if (listener == null || !listener.canExecute()) {\n handler = m -> true;\n } else {\n JsEngine copy = engine.JS.copy();\n handler = new JsLambda(copy.attach(listener));\n }\n WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue());\n options.setBinaryHandler(handler);\n return engine.webSocket(options);\n }\n\n public File write(Object o, String path) {\n ScenarioEngine engine = getEngine();\n path = engine.runtime.featureRuntime.suite.buildDir + File.separator + path;\n File file = new File(path);\n FileUtils.writeToFile(file, JsValue.toBytes(o));\n engine.logger.debug(\"write to file: {}\", file);\n return file;\n }\n\n public Object xmlPath(Object o, String path) {\n Variable var = new Variable(o);\n Variable res = ScenarioEngine.evalXmlPath(var, path);\n return JsValue.fromJava(res.getValue());\n }\n\n // helpers =================================================================\n //\n private static void assertIfJsFunction(Value f) {\n if (!f.canExecute()) {\n throw new RuntimeException(\"not a js function: \" + f);\n }\n }\n\n // make sure log() toString() is lazy\n static class LogWrapper {\n\n final Value[] values;\n\n LogWrapper(Value... values) {\n // sometimes a null array gets passed in, graal weirdness\n this.values = values == null ? new Value[0] : values;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (Value v : values) {\n Variable var = new Variable(v);\n sb.append(var.getAsPrettyString()).append(' ');\n }\n return sb.toString();\n }\n\n }\n\n public static class LogFacade {\n\n private static Logger getLogger() {\n return ScenarioEngine.get().logger;\n }\n\n private static String wrap(Value... values) {\n return new LogWrapper(values).toString();\n }\n\n public void debug(Value... values) {\n getLogger().debug(wrap(values));\n }\n\n public void info(Value... values) {\n getLogger().info(wrap(values));\n }\n\n public void trace(Value... values) {\n getLogger().trace(wrap(values));\n }\n\n public void warn(Value... values) {\n getLogger().warn(wrap(values));\n }\n\n public void error(Value... values) {\n getLogger().error(wrap(values));\n }\n\n }\n\n}\n"},"new_file":{"kind":"string","value":"karate-core/src/main/java/com/intuit/karate/core/ScenarioBridge.java"},"old_contents":{"kind":"string","value":"/*\n * The MIT License\n *\n * Copyright 2020 Intuit Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.intuit.karate.core;\n\nimport com.intuit.karate.EventContext;\nimport com.intuit.karate.FileUtils;\nimport com.intuit.karate.Json;\nimport com.intuit.karate.JsonUtils;\nimport com.intuit.karate.KarateException;\nimport com.intuit.karate.Logger;\nimport com.intuit.karate.Match;\nimport com.intuit.karate.MatchStep;\nimport com.intuit.karate.PerfContext;\nimport com.intuit.karate.StringUtils;\nimport com.intuit.karate.XmlUtils;\nimport com.intuit.karate.graal.JsEngine;\nimport com.intuit.karate.graal.JsLambda;\nimport com.intuit.karate.graal.JsList;\nimport com.intuit.karate.graal.JsMap;\nimport com.intuit.karate.graal.JsValue;\nimport com.intuit.karate.http.HttpClient;\nimport com.intuit.karate.http.HttpRequest;\nimport com.intuit.karate.http.HttpRequestBuilder;\nimport com.intuit.karate.http.ResourceType;\nimport com.intuit.karate.http.WebSocketClient;\nimport com.intuit.karate.http.WebSocketOptions;\nimport com.intuit.karate.shell.Command;\nimport java.io.File;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\nimport java.util.function.Function;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.graalvm.polyglot.Value;\n\n/**\n *\n * @author pthomas3\n */\npublic class ScenarioBridge implements PerfContext, EventContext {\n\n private final ScenarioEngine ENGINE;\n\n protected ScenarioBridge(ScenarioEngine engine) {\n ENGINE = engine;\n }\n\n public void abort() {\n getEngine().setAborted(true);\n }\n\n public Object append(Value... vals) {\n List list = new ArrayList();\n JsList jsList = new JsList(list);\n if (vals.length == 0) {\n return jsList;\n }\n Value val = vals[0];\n if (val.hasArrayElements()) {\n list.addAll(val.as(List.class));\n } else {\n list.add(val.as(Object.class));\n }\n if (vals.length == 1) {\n return jsList;\n }\n for (int i = 1; i < vals.length; i++) {\n Value v = vals[i];\n if (v.hasArrayElements()) {\n list.addAll(v.as(List.class));\n } else {\n list.add(v.as(Object.class));\n }\n }\n return jsList;\n }\n\n private Object appendToInternal(String varName, Value... vals) {\n ScenarioEngine engine = getEngine();\n Variable var = engine.vars.get(varName);\n if (!var.isList()) {\n return null;\n }\n List list = var.getValue();\n for (Value v : vals) {\n if (v.hasArrayElements()) {\n list.addAll(v.as(List.class));\n } else {\n Object temp = v.as(Object.class);\n list.add(temp);\n }\n }\n engine.setVariable(varName, list);\n return new JsList(list);\n }\n\n public Object appendTo(Value ref, Value... vals) {\n if (ref.isString()) {\n return appendToInternal(ref.asString(), vals);\n }\n List list;\n if (ref.hasArrayElements()) {\n list = new JsValue(ref).getAsList(); // make sure we unwrap the \"original\" list\n } else {\n list = new ArrayList();\n }\n for (Value v : vals) {\n if (v.hasArrayElements()) {\n list.addAll(v.as(List.class));\n } else {\n Object temp = v.as(Object.class);\n list.add(temp);\n }\n }\n return new JsList(list);\n }\n\n public Object call(String fileName) {\n return call(false, fileName, null);\n }\n\n public Object call(String fileName, Value arg) {\n return call(false, fileName, arg);\n }\n\n public Object call(boolean sharedScope, String fileName) {\n return call(sharedScope, fileName, null);\n }\n\n public Object call(boolean sharedScope, String fileName, Value arg) {\n ScenarioEngine engine = getEngine();\n Variable called = new Variable(engine.fileReader.readFile(fileName));\n Variable result = engine.call(called, arg == null ? null : new Variable(arg), sharedScope);\n return JsValue.fromJava(result.getValue());\n }\n\n private static Object callSingleResult(ScenarioEngine engine, Object o) throws Exception {\n if (o instanceof Exception) {\n engine.logger.warn(\"callSingle() cached result is an exception\");\n throw (Exception) o;\n }\n // if we don't clone, an attach operation would update the tree within the cached value\n // causing future cache hit + attach attempts to fail !\n o = engine.recurseAndAttachAndShallowClone(o);\n return JsValue.fromJava(o);\n }\n\n public Object callSingle(String fileName) throws Exception {\n return callSingle(fileName, null);\n }\n\n public Object callSingle(String fileName, Value arg) throws Exception {\n ScenarioEngine engine = getEngine();\n final Map CACHE = engine.runtime.featureRuntime.suite.callSingleCache;\n if (CACHE.containsKey(fileName)) {\n engine.logger.trace(\"callSingle cache hit: {}\", fileName);\n return callSingleResult(engine, CACHE.get(fileName));\n }\n long startTime = System.currentTimeMillis();\n engine.logger.trace(\"callSingle waiting for lock: {}\", fileName);\n synchronized (CACHE) { // lock\n if (CACHE.containsKey(fileName)) { // retry\n long endTime = System.currentTimeMillis() - startTime;\n engine.logger.warn(\"this thread waited {} milliseconds for callSingle lock: {}\", endTime, fileName);\n return callSingleResult(engine, CACHE.get(fileName));\n }\n // this thread is the 'winner'\n engine.logger.info(\">> lock acquired, begin callSingle: {}\", fileName);\n int minutes = engine.getConfig().getCallSingleCacheMinutes();\n Object result = null;\n File cacheFile = null;\n if (minutes > 0) {\n String cleanedName = StringUtils.toIdString(fileName);\n String cacheFileName = engine.getConfig().getCallSingleCacheDir() + File.separator + cleanedName + \".txt\";\n cacheFile = new File(cacheFileName);\n long since = System.currentTimeMillis() - minutes * 60 * 1000;\n if (cacheFile.exists()) {\n long lastModified = cacheFile.lastModified();\n if (lastModified > since) {\n String json = FileUtils.toString(cacheFile);\n result = JsonUtils.fromJson(json);\n engine.logger.info(\"callSingleCache hit: {}\", cacheFile);\n } else {\n engine.logger.info(\"callSingleCache stale, last modified {} - is before {} (minutes: {})\",\n lastModified, since, minutes);\n }\n } else {\n engine.logger.info(\"callSingleCache file does not exist, will create: {}\", cacheFile);\n }\n }\n if (result == null) {\n Variable called = new Variable(read(fileName));\n Variable argVar;\n if (arg == null || arg.isNull()) {\n argVar = null;\n } else {\n argVar = new Variable(arg);\n }\n Variable resultVar;\n try {\n resultVar = engine.call(called, argVar, false);\n } catch (Exception e) {\n // don't retain any vestiges of graal-js \n RuntimeException re = new RuntimeException(e.getMessage());\n // we do this so that an exception is also \"cached\"\n resultVar = new Variable(re); // will be thrown at end\n engine.logger.warn(\"callSingle() will cache an exception\");\n }\n if (minutes > 0) { // cacheFile will be not null\n if (resultVar.isMapOrList()) {\n String json = resultVar.getAsString();\n FileUtils.writeToFile(cacheFile, json);\n engine.logger.info(\"callSingleCache write: {}\", cacheFile);\n } else {\n engine.logger.warn(\"callSingleCache write failed, not json-like: {}\", resultVar);\n }\n }\n // functions have to be detached so that they can be re-hydrated in another js context\n result = engine.recurseAndDetachAndShallowClone(resultVar.getValue());\n }\n CACHE.put(fileName, result);\n engine.logger.info(\"<< lock released, cached callSingle: {}\", fileName);\n return callSingleResult(engine, result);\n }\n }\n\n public Object callonce(String path) {\n return callonce(false, path);\n }\n\n public Object callonce(boolean sharedScope, String path) {\n String exp = \"read('\" + path + \"')\";\n Variable v = getEngine().call(true, exp, sharedScope);\n return JsValue.fromJava(v.getValue());\n }\n\n @Override\n public void capturePerfEvent(String name, long startTime, long endTime) {\n PerfEvent event = new PerfEvent(startTime, endTime, name, 200);\n getEngine().capturePerfEvent(event);\n }\n\n public void configure(String key, Value value) {\n getEngine().configure(key, new Variable(value));\n }\n\n public Object distinct(Value o) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n long count = o.getArraySize();\n Set set = new LinkedHashSet();\n for (int i = 0; i < count; i++) {\n Object value = JsValue.toJava(o.getArrayElement(i));\n set.add(value);\n }\n return JsValue.fromJava(new ArrayList(set));\n }\n\n public String doc(Value v) {\n Map arg;\n if (v.isString()) {\n arg = Collections.singletonMap(\"read\", v.asString());\n } else if (v.hasMembers()) {\n arg = new JsValue(v).getAsMap();\n } else {\n getEngine().logger.warn(\"doc - unexpected argument: {}\", v);\n return null;\n }\n return getEngine().docInternal(arg);\n }\n\n public void embed(Object o, String contentType) {\n ResourceType resourceType;\n if (contentType == null) {\n resourceType = ResourceType.fromObject(o, ResourceType.BINARY);\n } else {\n resourceType = ResourceType.fromContentType(contentType);\n }\n getEngine().runtime.embed(JsValue.toBytes(o), resourceType);\n }\n\n public Object eval(String exp) {\n Variable result = getEngine().evalJs(exp);\n return JsValue.fromJava(result.getValue());\n }\n\n public String exec(Value value) {\n if (value.isString()) {\n return execInternal(Collections.singletonMap(\"line\", value.asString()));\n } else if (value.hasArrayElements()) {\n List args = new JsValue(value).getAsList();\n return execInternal(Collections.singletonMap(\"args\", args));\n } else {\n return execInternal(new JsValue(value).getAsMap());\n }\n }\n\n private String execInternal(Map options) {\n Command command = getEngine().fork(false, options);\n command.waitSync();\n return command.getAppender().collect();\n }\n\n public String extract(String text, String regex, int group) {\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n if (!matcher.find()) {\n getEngine().logger.warn(\"failed to find pattern: {}\", regex);\n return null;\n }\n return matcher.group(group);\n }\n\n public List extractAll(String text, String regex, int group) {\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n List list = new ArrayList();\n while (matcher.find()) {\n list.add(matcher.group(group));\n }\n return list;\n }\n\n public void fail(String reason) {\n getEngine().setFailedReason(new KarateException(reason));\n }\n\n public Object filter(Value o, Value f) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n assertIfJsFunction(f);\n long count = o.getArraySize();\n List list = new ArrayList();\n for (int i = 0; i < count; i++) {\n Value v = o.getArrayElement(i);\n Value res = JsEngine.execute(f, v, i);\n if (res.isBoolean() && res.asBoolean()) {\n list.add(new JsValue(v).getValue());\n }\n }\n return new JsList(list);\n }\n\n public Object filterKeys(Value o, Value... args) {\n if (!o.hasMembers() || args.length == 0) {\n return JsMap.EMPTY;\n }\n List keys = new ArrayList();\n if (args.length == 1) {\n if (args[0].isString()) {\n keys.add(args[0].asString());\n } else if (args[0].hasArrayElements()) {\n long count = args[0].getArraySize();\n for (int i = 0; i < count; i++) {\n keys.add(args[0].getArrayElement(i).toString());\n }\n } else if (args[0].hasMembers()) {\n for (String s : args[0].getMemberKeys()) {\n keys.add(s);\n }\n }\n } else {\n for (Value v : args) {\n keys.add(v.toString());\n }\n }\n Map map = new LinkedHashMap(keys.size());\n for (String key : keys) {\n if (key == null) {\n continue;\n }\n Value v = o.getMember(key);\n if (v != null) {\n map.put(key, v.as(Object.class));\n }\n }\n return new JsMap(map);\n }\n\n public void forEach(Value o, Value f) {\n assertIfJsFunction(f);\n if (o.hasArrayElements()) {\n long count = o.getArraySize();\n for (int i = 0; i < count; i++) {\n Value v = o.getArrayElement(i);\n f.executeVoid(v, i);\n }\n } else if (o.hasMembers()) { //map\n int i = 0;\n for (String k : o.getMemberKeys()) {\n Value v = o.getMember(k);\n f.executeVoid(k, v, i++);\n }\n } else {\n throw new RuntimeException(\"not an array or object: \" + o);\n }\n }\n\n public Command fork(Value value) {\n if (value.isString()) {\n return getEngine().fork(true, value.asString());\n } else if (value.hasArrayElements()) {\n List args = new JsValue(value).getAsList();\n return getEngine().fork(true, args);\n } else {\n return getEngine().fork(true, new JsValue(value).getAsMap());\n }\n }\n\n // TODO breaking returns actual object not wrapper\n // and fromObject() has been removed\n // use new typeOf() method to find type\n public Object fromString(String exp) {\n ScenarioEngine engine = getEngine();\n try {\n Variable result = engine.evalKarateExpression(exp);\n return JsValue.fromJava(result.getValue());\n } catch (Exception e) {\n engine.setFailedReason(null); // special case\n engine.logger.warn(\"auto evaluation failed: {}\", e.getMessage());\n return exp;\n }\n }\n\n public Object get(String exp) {\n ScenarioEngine engine = getEngine();\n Variable v;\n try {\n v = engine.evalKarateExpression(exp); // even json path expressions will work\n } catch (Exception e) {\n engine.logger.trace(\"karate.get failed for expression: '{}': {}\", exp, e.getMessage());\n engine.setFailedReason(null); // special case !\n return null;\n }\n if (v != null) {\n return JsValue.fromJava(v.getValue());\n } else {\n return null;\n }\n }\n\n public Object get(String exp, Object defaultValue) {\n Object result = get(exp);\n return result == null ? defaultValue : result;\n }\n\n // getters =================================================================\n // TODO migrate these to functions not properties\n //\n public ScenarioEngine getEngine() {\n ScenarioEngine engine = ScenarioEngine.get();\n return engine == null ? ENGINE : engine;\n }\n\n public String getEnv() {\n return getEngine().runtime.featureRuntime.suite.env;\n }\n\n public Object getFeature() {\n return new JsMap(getEngine().runtime.featureRuntime.result.toInfoJson());\n }\n\n public Object getInfo() { // TODO deprecate\n return new JsMap(getEngine().runtime.getScenarioInfo());\n }\n\n private LogFacade logFacade;\n\n public Object getLogger() {\n if (logFacade == null) {\n logFacade = new LogFacade();\n }\n return logFacade;\n }\n\n public Object getOs() {\n String name = FileUtils.getOsName();\n String type = FileUtils.getOsType(name).toString().toLowerCase();\n Map map = new HashMap(2);\n map.put(\"name\", name);\n map.put(\"type\", type);\n return new JsMap(map);\n }\n\n // TODO breaking uri has been renamed to url\n public Object getPrevRequest() {\n HttpRequest hr = getEngine().getRequest();\n if (hr == null) {\n return null;\n }\n Map map = new HashMap();\n map.put(\"method\", hr.getMethod());\n map.put(\"url\", hr.getUrl());\n map.put(\"headers\", hr.getHeaders());\n map.put(\"body\", hr.getBody());\n return JsValue.fromJava(map);\n }\n\n public Object getProperties() {\n return new JsMap(getEngine().runtime.featureRuntime.suite.systemProperties);\n }\n\n public Object getScenario() {\n return new JsMap(getEngine().runtime.result.toKarateJson());\n }\n\n public Object getTags() {\n return JsValue.fromJava(getEngine().runtime.tags.getTags());\n }\n\n public Object getTagValues() {\n return JsValue.fromJava(getEngine().runtime.tags.getTagValues());\n }\n\n //==========================================================================\n //\n public HttpRequestBuilder http(String url) {\n ScenarioEngine engine = getEngine();\n HttpClient client = engine.runtime.featureRuntime.suite.clientFactory.create(engine);\n return new HttpRequestBuilder(client).url(url);\n }\n\n public Object jsonPath(Object o, String exp) {\n Json json = Json.of(o);\n return JsValue.fromJava(json.get(exp));\n }\n\n public Object keysOf(Value o) {\n return new JsList(o.getMemberKeys());\n }\n\n public void log(Value... values) {\n ScenarioEngine engine = getEngine();\n if (engine.getConfig().isPrintEnabled()) {\n engine.logger.info(\"{}\", new LogWrapper(values));\n }\n }\n\n public Object lowerCase(Object o) {\n Variable var = new Variable(o);\n return JsValue.fromJava(var.toLowerCase().getValue());\n }\n\n public Object map(Value o, Value f) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n assertIfJsFunction(f);\n long count = o.getArraySize();\n List list = new ArrayList();\n for (int i = 0; i < count; i++) {\n Value v = o.getArrayElement(i);\n Value res = JsEngine.execute(f, v, i);\n list.add(new JsValue(res).getValue());\n }\n return new JsList(list);\n }\n\n public Object mapWithKey(Value v, String key) {\n if (!v.hasArrayElements()) {\n return JsList.EMPTY;\n }\n long count = v.getArraySize();\n List list = new ArrayList();\n for (int i = 0; i < count; i++) {\n Map map = new LinkedHashMap();\n Value res = v.getArrayElement(i);\n map.put(key, res.as(Object.class));\n list.add(map);\n }\n return new JsList(list);\n }\n\n public Object match(Object actual, Object expected) {\n Match.Result mr = getEngine().match(Match.Type.EQUALS, actual, expected);\n return JsValue.fromJava(mr.toMap());\n }\n\n public Object match(String exp) {\n MatchStep ms = new MatchStep(exp);\n Match.Result mr = getEngine().match(ms.type, ms.name, ms.path, ms.expected);\n return JsValue.fromJava(mr.toMap());\n }\n\n public Object merge(Value... vals) {\n if (vals.length == 0) {\n return null;\n }\n if (vals.length == 1) {\n return vals[0];\n }\n Map map = new HashMap(vals[0].as(Map.class));\n for (int i = 1; i < vals.length; i++) {\n map.putAll(vals[i].as(Map.class));\n }\n return new JsMap(map);\n }\n\n public void pause(Value value) {\n ScenarioEngine engine = getEngine();\n if (!value.isNumber()) {\n engine.logger.warn(\"pause argument is not a number:\", value);\n return;\n }\n if (engine.runtime.perfMode) {\n engine.runtime.featureRuntime.perfHook.pause(value.asInt());\n } else if (engine.getConfig().isPauseIfNotPerf()) {\n try {\n Thread.sleep(value.asInt());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n public String pretty(Object o) {\n Variable v = new Variable(o);\n return v.getAsPrettyString();\n }\n\n public String prettyXml(Object o) {\n Variable v = new Variable(o);\n return v.getAsPrettyXmlString();\n }\n\n public void proceed() {\n proceed(null);\n }\n\n public void proceed(String requestUrlBase) {\n getEngine().mockProceed(requestUrlBase);\n }\n\n public Object range(int start, int end) {\n return range(start, end, 1);\n }\n\n public Object range(int start, int end, int interval) {\n if (interval <= 0) {\n throw new RuntimeException(\"interval must be a positive integer\");\n }\n List list = new ArrayList();\n if (start <= end) {\n for (int i = start; i <= end; i += interval) {\n list.add(i);\n }\n } else {\n for (int i = start; i >= end; i -= interval) {\n list.add(i);\n }\n }\n return JsValue.fromJava(list);\n }\n\n public Object read(String name) {\n Object result = getEngine().fileReader.readFile(name);\n return JsValue.fromJava(result);\n }\n\n public String readAsString(String fileName) {\n return getEngine().fileReader.readFileAsString(fileName);\n }\n\n public void remove(String name, String path) {\n getEngine().remove(name, path);\n }\n\n public Object repeat(int n, Value f) {\n assertIfJsFunction(f);\n List list = new ArrayList(n);\n for (int i = 0; i < n; i++) {\n Value v = JsEngine.execute(f, i);\n list.add(new JsValue(v).getValue());\n }\n return new JsList(list);\n }\n\n // set multiple variables in one shot\n public void set(Map map) {\n getEngine().setVariables(map);\n }\n\n public void set(String name, Value value) {\n getEngine().setVariable(name, new Variable(value));\n }\n\n // this makes sense mainly for xpath manipulation from within js\n public void set(String name, String path, Object value) {\n getEngine().set(name, path, new Variable(value));\n }\n\n public void setXml(String name, String xml) {\n getEngine().setVariable(name, XmlUtils.toXmlDoc(xml));\n }\n\n // this makes sense mainly for xpath manipulation from within js\n public void setXml(String name, String path, String xml) {\n getEngine().set(name, path, new Variable(XmlUtils.toXmlDoc(xml)));\n }\n\n @Override\n public void signal(Object o) {\n Value v = Value.asValue(o);\n getEngine().signal(JsValue.toJava(v));\n }\n\n public Object sizeOf(Value v) {\n if (v.hasArrayElements()) {\n return v.getArraySize();\n } else if (v.hasMembers()) {\n return v.getMemberKeys().size();\n } else {\n return -1;\n }\n }\n\n public Object sort(Value o) {\n return sort(o, getEngine().JS.evalForValue(\"x => x\"));\n }\n\n public Object sort(Value o, Value f) {\n if (!o.hasArrayElements()) {\n return JsList.EMPTY;\n }\n assertIfJsFunction(f);\n long count = o.getArraySize();\n Map map = new TreeMap();\n for (int i = 0; i < count; i++) {\n Object item = JsValue.toJava(o.getArrayElement(i));\n Value key = JsEngine.execute(f, item, i);\n if (key.isNumber()) {\n map.put(key.as(Number.class), item);\n } else {\n map.put(key.asString(), item);\n }\n }\n return JsValue.fromJava(new ArrayList(map.values()));\n }\n\n public MockServer start(Value value) {\n if (value.isString()) {\n return startInternal(Collections.singletonMap(\"mock\", value.asString()));\n } else {\n return startInternal(new JsValue(value).getAsMap());\n }\n }\n\n private MockServer startInternal(Map config) {\n String mock = (String) config.get(\"mock\");\n if (mock == null) {\n throw new RuntimeException(\"'mock' is missing: \" + config);\n }\n File feature = toJavaFile(mock);\n MockServer.Builder builder = MockServer.feature(feature);\n String certFile = (String) config.get(\"cert\");\n if (certFile != null) {\n builder.certFile(toJavaFile(certFile));\n }\n String keyFile = (String) config.get(\"key\");\n if (keyFile != null) {\n builder.keyFile(toJavaFile(keyFile));\n }\n Boolean ssl = (Boolean) config.get(\"ssl\");\n if (ssl == null) {\n ssl = false;\n }\n Integer port = (Integer) config.get(\"port\");\n if (port == null) {\n port = 0;\n }\n Map arg = (Map) config.get(\"arg\");\n builder.args(arg);\n if (ssl) {\n builder.https(port);\n } else {\n builder.http(port);\n }\n return builder.build();\n }\n\n public void stop(int port) {\n Command.waitForSocket(port);\n }\n\n public String toAbsolutePath(String relativePath) {\n return getEngine().fileReader.toAbsolutePath(relativePath);\n }\n\n public Object toBean(Object o, String className) {\n Json json = Json.of(o);\n Object bean = JsonUtils.fromJson(json.toString(), className);\n return JsValue.fromJava(bean);\n }\n\n public String toCsv(Object o) {\n Variable v = new Variable(o);\n if (!v.isList()) {\n throw new RuntimeException(\"not a json array: \" + v);\n }\n List> list = v.getValue();\n return JsonUtils.toCsv(list);\n }\n\n public Object toJava(Value value) {\n if (value.canExecute()) {\n JsEngine copy = getEngine().JS.copy();\n return new JsLambda(copy.attach(value));\n } else {\n return new JsValue(value).getValue();\n }\n }\n\n private File toJavaFile(String path) {\n return getEngine().fileReader.toResource(path).getFile();\n }\n\n public Object toJson(Value value) {\n return toJson(value, false);\n }\n\n public Object toJson(Value value, boolean removeNulls) {\n JsValue jv = new JsValue(value);\n String json = JsonUtils.toJson(jv.getValue());\n Object result = Json.of(json).value();\n if (removeNulls) {\n JsonUtils.removeKeysWithNullValues(result);\n }\n return JsValue.fromJava(result);\n }\n\n // TODO deprecate\n public Object toList(Value value) {\n return new JsValue(value).getValue();\n }\n\n // TODO deprecate\n public Object toMap(Value value) {\n return new JsValue(value).getValue();\n }\n\n public String toString(Object o) {\n Variable v = new Variable(o);\n return v.getAsString();\n }\n\n public String trim(String s) {\n return s == null ? null : s.trim();\n }\n\n public String typeOf(Value value) {\n Variable v = new Variable(value);\n return v.getTypeString();\n }\n\n public String urlEncode(String s) {\n try {\n return URLEncoder.encode(s, \"UTF-8\");\n } catch (Exception e) {\n getEngine().logger.warn(\"url encode failed: {}\", e.getMessage());\n return s;\n }\n }\n\n public String urlDecode(String s) {\n try {\n return URLDecoder.decode(s, \"UTF-8\");\n } catch (Exception e) {\n getEngine().logger.warn(\"url encode failed: {}\", e.getMessage());\n return s;\n }\n }\n\n public Object valuesOf(Value v) {\n if (v.hasArrayElements()) {\n return v;\n } else if (v.hasMembers()) {\n List list = new ArrayList();\n for (String k : v.getMemberKeys()) {\n Value res = v.getMember(k);\n list.add(res.as(Object.class));\n }\n return new JsList(list);\n } else {\n return null;\n }\n }\n\n public boolean waitForHttp(String url) {\n return Command.waitForHttp(url);\n }\n\n public boolean waitForPort(String host, int port) {\n return new Command().waitForPort(host, port);\n }\n\n public WebSocketClient webSocket(String url) {\n return webSocket(url, null, null);\n }\n\n public WebSocketClient webSocket(String url, Value value) {\n return webSocket(url, value, null);\n }\n\n public WebSocketClient webSocket(String url, Value listener, Value value) {\n Function handler;\n ScenarioEngine engine = getEngine();\n if (listener == null || !listener.canExecute()) {\n handler = m -> true;\n } else {\n JsEngine copy = engine.JS.copy();\n handler = new JsLambda(copy.attach(listener));\n }\n WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue());\n options.setTextHandler(handler);\n return engine.webSocket(options);\n }\n\n public WebSocketClient webSocketBinary(String url) {\n return webSocketBinary(url, null, null);\n }\n\n public WebSocketClient webSocketBinary(String url, Value value) {\n return webSocketBinary(url, value, null);\n }\n\n public WebSocketClient webSocketBinary(String url, Value listener, Value value) {\n Function handler;\n ScenarioEngine engine = getEngine();\n if (listener == null || !listener.canExecute()) {\n handler = m -> true;\n } else {\n JsEngine copy = engine.JS.copy();\n handler = new JsLambda(copy.attach(listener));\n }\n WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue());\n options.setBinaryHandler(handler);\n return engine.webSocket(options);\n }\n\n public File write(Object o, String path) {\n ScenarioEngine engine = getEngine();\n path = engine.runtime.featureRuntime.suite.buildDir + File.separator + path;\n File file = new File(path);\n FileUtils.writeToFile(file, JsValue.toBytes(o));\n engine.logger.debug(\"write to file: {}\", file);\n return file;\n }\n\n public Object xmlPath(Object o, String path) {\n Variable var = new Variable(o);\n Variable res = ScenarioEngine.evalXmlPath(var, path);\n return JsValue.fromJava(res.getValue());\n }\n\n // helpers =================================================================\n //\n private static void assertIfJsFunction(Value f) {\n if (!f.canExecute()) {\n throw new RuntimeException(\"not a js function: \" + f);\n }\n }\n\n // make sure log() toString() is lazy\n static class LogWrapper {\n\n final Value[] values;\n\n LogWrapper(Value... values) {\n this.values = values;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (Value v : values) {\n Variable var = new Variable(v);\n sb.append(var.getAsPrettyString()).append(' ');\n }\n return sb.toString();\n }\n\n }\n\n public static class LogFacade {\n\n private static Logger getLogger() {\n return ScenarioEngine.get().logger;\n }\n\n private static String wrap(Value... values) {\n return new LogWrapper(values).toString();\n }\n\n public void debug(Value... values) {\n getLogger().debug(wrap(values));\n }\n\n public void info(Value... values) {\n getLogger().info(wrap(values));\n }\n\n public void trace(Value... values) {\n getLogger().trace(wrap(values));\n }\n\n public void warn(Value... values) {\n getLogger().warn(wrap(values));\n }\n\n public void error(Value... values) {\n getLogger().error(wrap(values));\n }\n\n }\n\n}\n"},"message":{"kind":"string","value":"defensive coding based on a problem someone reported\n"},"old_file":{"kind":"string","value":"karate-core/src/main/java/com/intuit/karate/core/ScenarioBridge.java"},"subject":{"kind":"string","value":"defensive coding based on a problem someone reported"}}},{"rowIdx":1242,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"5edefb0bf943852dc720342b668e0daa695419da"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg"},"new_contents":{"kind":"string","value":"package ua.com.fielden.platform.sample.domain;\n\nimport static java.lang.String.format;\n\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.joda.time.DateTime;\n\nimport com.google.inject.Inject;\n\nimport ua.com.fielden.platform.continuation.NeedMoreData;\nimport ua.com.fielden.platform.dao.CommonEntityDao;\nimport ua.com.fielden.platform.dao.annotations.SessionRequired;\nimport ua.com.fielden.platform.entity.annotation.EntityType;\nimport ua.com.fielden.platform.entity.fetch.IFetchProvider;\nimport ua.com.fielden.platform.entity.query.IFilter;\nimport ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;\nimport ua.com.fielden.platform.error.Result;\nimport ua.com.fielden.platform.sample.domain.observables.TgPersistentEntityWithPropertiesChangeSubject;\n\n/**\n * DAO implementation for companion object {@link ITgPersistentEntityWithProperties}.\n * It demos the use of {@link TgPersistentEntityWithPropertiesChangeSubject} for publishing change events to be propagated to the subscribed clients.\n *\n * @author Developers\n *\n */\n@EntityType(TgPersistentEntityWithProperties.class)\npublic class TgPersistentEntityWithPropertiesDao extends CommonEntityDao implements ITgPersistentEntityWithProperties {\n\n private final TgPersistentEntityWithPropertiesChangeSubject changeSubject;\n\n @Inject\n public TgPersistentEntityWithPropertiesDao(final TgPersistentEntityWithPropertiesChangeSubject changeSubject, final IFilter filter) {\n super(filter);\n\n this.changeSubject = changeSubject;\n }\n\n /**\n * Overridden to publish entity change events to an application wide observable.\n */\n @Override\n @SessionRequired\n public TgPersistentEntityWithProperties save(final TgPersistentEntityWithProperties entity) {\n if (!entity.isPersisted()) {\n final Date dateValue = entity.getDateProp();\n if (dateValue != null && new DateTime(2003, 2, 1, 6, 20).equals(new DateTime(dateValue))) {\n throw new IllegalArgumentException(format(\"Creation failed: [1/2/3 6:20] date is not permitted.\"));\n }\n if (dateValue != null && new DateTime(2003, 2, 1, 6, 21).equals(new DateTime(dateValue))) {\n entity.getProperty(\"dateProp\").setDomainValidationResult(Result.warning(dateValue, \"[1/2/3 6:21] is acceptable, but with warning.\"));\n }\n } else {\n final Result res = entity.isValid();\n if (!res.isSuccessful()) { // throw precise exception about the validation error\n throw new IllegalArgumentException(format(\"Modification failed: %s\", res.getMessage()));\n }\n }\n \n \n // let's demonstrate a simple approach to implementing user's warning acknowledgement\n // this example, albeit artificially, also demonstrates not just one but two sequential requests for additional user input in a form of acknowledgement \n if (entity.hasWarnings()) {\n if (!moreData(\"acknowledgedForTheFirstTime\").isPresent()) {\n throw new NeedMoreData(\"Warnings need acknowledgement (first time)\", TgAcknowledgeWarnings.class, \"acknowledgedForTheFirstTime\");\n } else {\n final TgAcknowledgeWarnings continuation = this. moreData(\"acknowledgedForTheFirstTime\").get();\n System.out.println(\"Acknowledged (first)? = \" + continuation.getAcknowledged());\n\n if (!moreData(\"acknowledgedForTheSecondTime\").isPresent()) {\n throw new NeedMoreData(\"Warnings need acknowledgement (second time)\", TgAcknowledgeWarnings.class, \"acknowledgedForTheSecondTime\");\n } else {\n final TgAcknowledgeWarnings secondContinuation = this. moreData(\"acknowledgedForTheSecondTime\").get();\n System.out.println(\"Acknowledged (second)? = \" + secondContinuation.getAcknowledged());\n }\n }\n }\n \n \n final boolean wasNew = false; // !entity.isPersisted();\n final TgPersistentEntityWithProperties saved = super.save(entity);\n changeSubject.publish(saved);\n\n // if the entity was new and just successfully saved then let's return a new entity to mimic \"continuous\" entry\n // otherwise simply return the same entity\n if (wasNew && saved.isValid().isSuccessful()) {\n final TgPersistentEntityWithProperties newEntity = saved.getEntityFactory().newEntity(TgPersistentEntityWithProperties.class);\n // the following two lines can be uncommented to simulate the situation of an invalid new entity returned from save\n //newEntity.setRequiredValidatedProp(1);\n //newEntity.setRequiredValidatedProp(null);\n return newEntity;\n }\n \n return saved;\n }\n\n @Override\n public int batchDelete(final Collection entitiesIds) {\n return defaultBatchDelete(entitiesIds);\n }\n\n @Override\n @SessionRequired\n public void delete(final TgPersistentEntityWithProperties entity) {\n defaultDelete(entity);\n }\n\n @Override\n @SessionRequired\n public void delete(final EntityResultQueryModel model, final Map paramValues) {\n defaultDelete(model, paramValues);\n }\n\n @Override\n public IFetchProvider createFetchProvider() {\n return super.createFetchProvider()\n .with(\"key\") // this property is \"required\" (necessary during saving) -- should be declared as fetching property\n .with(\"desc\")\n .with(\"integerProp\", \"moneyProp\", \"bigDecimalProp\", \"stringProp\", \"booleanProp\", \"dateProp\", \"requiredValidatedProp\")\n .with(\"domainInitProp\", \"nonConflictingProp\", \"conflictingProp\")\n // .with(\"entityProp\", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with(\"key\"))\n .with(\"userParam\", \"userParam.basedOnUser\")\n .with(\"entityProp\", \"entityProp.entityProp\", \"entityProp.compositeProp\", \"entityProp.compositeProp.desc\", \"entityProp.booleanProp\")\n // .with(\"status\")\n .with(\"critOnlyEntityProp\")\n .with(\"compositeProp\", \"compositeProp.desc\")\n // .with(\"producerInitProp\", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with(\"key\")\n .with(\"producerInitProp\", \"status.key\", \"status.desc\")\n .with(\"colourProp\"); //\n }\n}"},"new_file":{"kind":"string","value":"platform-dao/src/main/java/ua/com/fielden/platform/sample/domain/TgPersistentEntityWithPropertiesDao.java"},"old_contents":{"kind":"string","value":"package ua.com.fielden.platform.sample.domain;\n\nimport static java.lang.String.format;\n\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.joda.time.DateTime;\n\nimport com.google.inject.Inject;\n\nimport ua.com.fielden.platform.continuation.NeedMoreData;\nimport ua.com.fielden.platform.dao.CommonEntityDao;\nimport ua.com.fielden.platform.dao.annotations.SessionRequired;\nimport ua.com.fielden.platform.entity.annotation.EntityType;\nimport ua.com.fielden.platform.entity.fetch.IFetchProvider;\nimport ua.com.fielden.platform.entity.query.IFilter;\nimport ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;\nimport ua.com.fielden.platform.error.Result;\nimport ua.com.fielden.platform.sample.domain.observables.TgPersistentEntityWithPropertiesChangeSubject;\n\n/**\n * DAO implementation for companion object {@link ITgPersistentEntityWithProperties}.\n * It demos the use of {@link TgPersistentEntityWithPropertiesChangeSubject} for publishing change events to be propagated to the subscribed clients.\n *\n * @author Developers\n *\n */\n@EntityType(TgPersistentEntityWithProperties.class)\npublic class TgPersistentEntityWithPropertiesDao extends CommonEntityDao implements ITgPersistentEntityWithProperties {\n\n private final TgPersistentEntityWithPropertiesChangeSubject changeSubject;\n\n @Inject\n public TgPersistentEntityWithPropertiesDao(final TgPersistentEntityWithPropertiesChangeSubject changeSubject, final IFilter filter) {\n super(filter);\n\n this.changeSubject = changeSubject;\n }\n\n /**\n * Overridden to publish entity change events to an application wide observable.\n */\n @Override\n @SessionRequired\n public TgPersistentEntityWithProperties save(final TgPersistentEntityWithProperties entity) {\n if (!entity.isPersisted()) {\n final Date dateValue = entity.getDateProp();\n if (dateValue != null && new DateTime(2003, 2, 1, 6, 20).equals(new DateTime(dateValue))) {\n throw new IllegalArgumentException(format(\"Creation failed: [1/2/3 6:20] date is not permitted.\"));\n }\n if (dateValue != null && new DateTime(2003, 2, 1, 6, 21).equals(new DateTime(dateValue))) {\n entity.getProperty(\"dateProp\").setDomainValidationResult(Result.warning(dateValue, \"[1/2/3 6:21] is acceptable, but with warning.\"));\n }\n } else {\n final Result res = entity.isValid();\n if (!res.isSuccessful()) { // throw precise exception about the validation error\n throw new IllegalArgumentException(format(\"Modification failed: %s\", res.getMessage()));\n }\n }\n \n \n // let's demonstrate a simple approach to implementing user's warning acknowledgement\n // this example, albeit artificially, also demonstrates not just one but two sequential requests for additional user input in a form of acknowledgement \n if (entity.hasWarnings()) {\n if (moreData(\"acknowledgedForTheFirstTime\").isPresent()) {\n final TgAcknowledgeWarnings continuation = this. moreData(\"acknowledgedForTheFirstTime\").get();\n System.out.println(\"Acknowledged (first)? = \" + continuation.getAcknowledged());\n\n if (moreData(\"acknowledgedForTheSecondTime\").isPresent()) {\n final TgAcknowledgeWarnings secondContinuation = this. moreData(\"acknowledgedForTheSecondTime\").get();\n System.out.println(\"Acknowledged (second)? = \" + secondContinuation.getAcknowledged());\n } else {\n throw new NeedMoreData(\"Warnings need acknowledgement (second time)\", TgAcknowledgeWarnings.class, \"acknowledgedForTheSecondTime\");\n }\n } else {\n throw new NeedMoreData(\"Warnings need acknowledgement (first time)\", TgAcknowledgeWarnings.class, \"acknowledgedForTheFirstTime\");\n }\n }\n \n \n final boolean wasNew = false; // !entity.isPersisted();\n final TgPersistentEntityWithProperties saved = super.save(entity);\n changeSubject.publish(saved);\n\n // if the entity was new and just successfully saved then let's return a new entity to mimic \"continuous\" entry\n // otherwise simply return the same entity\n if (wasNew && saved.isValid().isSuccessful()) {\n final TgPersistentEntityWithProperties newEntity = saved.getEntityFactory().newEntity(TgPersistentEntityWithProperties.class);\n // the following two lines can be uncommented to simulate the situation of an invalid new entity returned from save\n //newEntity.setRequiredValidatedProp(1);\n //newEntity.setRequiredValidatedProp(null);\n return newEntity;\n }\n \n return saved;\n }\n\n @Override\n public int batchDelete(final Collection entitiesIds) {\n return defaultBatchDelete(entitiesIds);\n }\n\n @Override\n @SessionRequired\n public void delete(final TgPersistentEntityWithProperties entity) {\n defaultDelete(entity);\n }\n\n @Override\n @SessionRequired\n public void delete(final EntityResultQueryModel model, final Map paramValues) {\n defaultDelete(model, paramValues);\n }\n\n @Override\n public IFetchProvider createFetchProvider() {\n return super.createFetchProvider()\n .with(\"key\") // this property is \"required\" (necessary during saving) -- should be declared as fetching property\n .with(\"desc\")\n .with(\"integerProp\", \"moneyProp\", \"bigDecimalProp\", \"stringProp\", \"booleanProp\", \"dateProp\", \"requiredValidatedProp\")\n .with(\"domainInitProp\", \"nonConflictingProp\", \"conflictingProp\")\n // .with(\"entityProp\", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with(\"key\"))\n .with(\"userParam\", \"userParam.basedOnUser\")\n .with(\"entityProp\", \"entityProp.entityProp\", \"entityProp.compositeProp\", \"entityProp.compositeProp.desc\", \"entityProp.booleanProp\")\n // .with(\"status\")\n .with(\"critOnlyEntityProp\")\n .with(\"compositeProp\", \"compositeProp.desc\")\n // .with(\"producerInitProp\", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with(\"key\")\n .with(\"producerInitProp\", \"status.key\", \"status.desc\")\n .with(\"colourProp\"); //\n }\n}"},"message":{"kind":"string","value":"#602 Made the continuation related example a bit more readable.\n"},"old_file":{"kind":"string","value":"platform-dao/src/main/java/ua/com/fielden/platform/sample/domain/TgPersistentEntityWithPropertiesDao.java"},"subject":{"kind":"string","value":"#602 Made the continuation related example a bit more readable."}}},{"rowIdx":1243,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"epl-1.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"06db9c84a7ec6284f0851da29b0dec3c89fb853a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse"},"new_contents":{"kind":"string","value":"package com.redhat.ceylon.eclipse.code.complete;\n\nimport static com.redhat.ceylon.compiler.typechecker.tree.TreeUtil.formatPath;\nimport static com.redhat.ceylon.eclipse.code.complete.ParameterContextValidator.findCharCount;\nimport static com.redhat.ceylon.eclipse.util.Escaping.escapeName;\nimport static com.redhat.ceylon.eclipse.util.Nodes.getReferencedNode;\nimport static com.redhat.ceylon.model.typechecker.model.ModelUtil.isNameMatching;\nimport static java.util.Collections.singletonList;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.antlr.runtime.CommonToken;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.ITextViewer;\nimport org.eclipse.jface.text.Region;\n\nimport com.redhat.ceylon.compiler.typechecker.tree.Node;\nimport com.redhat.ceylon.compiler.typechecker.tree.Tree;\nimport com.redhat.ceylon.compiler.typechecker.tree.Visitor;\nimport com.redhat.ceylon.eclipse.code.parse.CeylonParseController;\nimport com.redhat.ceylon.eclipse.util.Nodes;\nimport com.redhat.ceylon.model.typechecker.model.Class;\nimport com.redhat.ceylon.model.typechecker.model.Constructor;\nimport com.redhat.ceylon.model.typechecker.model.Declaration;\nimport com.redhat.ceylon.model.typechecker.model.DeclarationWithProximity;\nimport com.redhat.ceylon.model.typechecker.model.Function;\nimport com.redhat.ceylon.model.typechecker.model.FunctionOrValue;\nimport com.redhat.ceylon.model.typechecker.model.Functional;\nimport com.redhat.ceylon.model.typechecker.model.Interface;\nimport com.redhat.ceylon.model.typechecker.model.Parameter;\nimport com.redhat.ceylon.model.typechecker.model.ParameterList;\nimport com.redhat.ceylon.model.typechecker.model.Scope;\nimport com.redhat.ceylon.model.typechecker.model.Type;\nimport com.redhat.ceylon.model.typechecker.model.TypeDeclaration;\nimport com.redhat.ceylon.model.typechecker.model.Unit;\nimport com.redhat.ceylon.model.typechecker.model.Value;\n\npublic class CompletionUtil {\n\n public static List overloads(Declaration dec) {\n return dec.isAbstraction() ? \n dec.getOverloads() : \n singletonList(dec);\n }\n\n static List getParameters(ParameterList pl,\n boolean includeDefaults, boolean namedInvocation) {\n List ps = pl.getParameters();\n if (includeDefaults) {\n return ps;\n }\n else {\n List list = \n new ArrayList();\n for (Parameter p: ps) {\n if (!p.isDefaulted() || \n (namedInvocation && \n spreadable(p, ps))) {\n list.add(p);\n }\n }\n return list;\n }\n }\n\n private static boolean spreadable(Parameter param, \n List list) {\n Parameter lastParam = \n list.get(list.size()-1);\n if (param==lastParam &&\n param.getModel() instanceof Value) {\n Type type = param.getType();\n Unit unit = param.getDeclaration().getUnit();\n return type!=null &&\n unit.isIterableParameterType(type);\n }\n else {\n return false;\n }\n }\n\n static String fullPath(int offset, String prefix,\n Tree.ImportPath path) {\n StringBuilder fullPath = new StringBuilder();\n if (path!=null) {\n String pathString = \n formatPath(path.getIdentifiers());\n fullPath.append(pathString)\n .append('.');\n int len = \n offset\n -path.getStartIndex()\n -prefix.length();\n fullPath.setLength(len);\n }\n return fullPath.toString();\n }\n\n static boolean isPackageDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return lcu != null && \n lcu.getUnit() != null &&\n lcu.getUnit()\n .getFilename()\n .equals(\"package.ceylon\"); \n }\n\n static boolean isModuleDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return lcu != null && \n lcu.getUnit() != null &&\n lcu.getUnit()\n .getFilename()\n .equals(\"module.ceylon\"); \n }\n\n static boolean isEmptyModuleDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return isModuleDescriptor(cpc) && \n lcu != null && \n lcu.getModuleDescriptors()\n .isEmpty(); \n }\n\n static boolean isEmptyPackageDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return lcu != null &&\n lcu.getUnit() != null &&\n lcu.getUnit()\n .getFilename()\n .equals(\"package.ceylon\") && \n lcu.getPackageDescriptors()\n .isEmpty();\n }\n\n static int nextTokenType(CeylonParseController cpc,\n CommonToken token) {\n for (int i=token.getTokenIndex()+1; \n i upperBounds, Type t) {\n boolean ok = true;\n for (Type ub: upperBounds) {\n if (!t.isSubtypeOf(ub) &&\n !(ub.involvesTypeParameters() &&\n t.getDeclaration()\n .inherits(ub.getDeclaration()))) {\n ok = false;\n break;\n }\n }\n return ok;\n }\n \n public static List \n getSortedProposedValues(Scope scope, Unit unit) {\n return getSortedProposedValues(scope, unit, null);\n }\n \n public static List \n getSortedProposedValues(Scope scope, Unit unit, \n final String exactName) {\n Map map = \n scope.getMatchingDeclarations(unit, \"\", 0);\n if (exactName!=null) {\n for (DeclarationWithProximity dwp: \n new ArrayList\n (map.values())) {\n if (!dwp.isUnimported() && \n !dwp.isAlias() &&\n isNameMatching(dwp.getName(), \n exactName)) {\n map.put(dwp.getName(), \n new DeclarationWithProximity(\n dwp.getDeclaration(), -5));\n }\n }\n }\n List results = \n new ArrayList(\n map.values());\n Collections.sort(results, \n new ArgumentProposalComparator(exactName));\n return results;\n }\n\n public static boolean isIgnoredLanguageModuleClass(Class clazz) {\n return clazz.isString() ||\n clazz.isInteger() ||\n clazz.isFloat() ||\n clazz.isCharacter() ||\n clazz.isAnnotation();\n }\n\n public static boolean isIgnoredLanguageModuleValue(Value value) {\n String name = value.getName();\n return name.equals(\"process\") ||\n name.equals(\"runtime\") ||\n name.equals(\"system\") ||\n name.equals(\"operatingSystem\") ||\n name.equals(\"language\") ||\n name.equals(\"emptyIterator\") ||\n name.equals(\"infinity\") ||\n name.endsWith(\"IntegerValue\") ||\n name.equals(\"finished\");\n }\n\n public static boolean isIgnoredLanguageModuleMethod(Function method) {\n String name = method.getName();\n return name.equals(\"className\") || \n name.equals(\"flatten\") || \n name.equals(\"unflatten\")|| \n name.equals(\"curry\") || \n name.equals(\"uncurry\") ||\n name.equals(\"compose\") ||\n method.isAnnotation();\n }\n\n static boolean isIgnoredLanguageModuleType(TypeDeclaration td) {\n return !td.isObject() && \n !td.isAnything() &&\n !td.isString() &&\n !td.isInteger() &&\n !td.isCharacter() &&\n !td.isFloat() &&\n !td.isBoolean();\n }\n\n public static String getInitialValueDescription(\n final Declaration dec, \n CeylonParseController cpc) {\n if (cpc!=null) {\n Node refnode = getReferencedNode(dec);\n Tree.SpecifierOrInitializerExpression sie = null;\n String arrow = null;\n if (refnode instanceof Tree.AttributeDeclaration) {\n Tree.AttributeDeclaration ad = \n (Tree.AttributeDeclaration) \n refnode;\n sie = ad.getSpecifierOrInitializerExpression();\n arrow = \" = \";\n }\n else if (refnode instanceof Tree.MethodDeclaration) {\n Tree.MethodDeclaration md =\n (Tree.MethodDeclaration) \n refnode;\n sie = md.getSpecifierExpression();\n arrow = \" => \";\n }\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n if (sie==null) {\n class FindInitializerVisitor extends Visitor {\n Tree.SpecifierOrInitializerExpression result;\n @Override\n public void visit(\n Tree.InitializerParameter that) {\n super.visit(that);\n Declaration d = \n that.getParameterModel()\n .getModel();\n if (d!=null && d.equals(dec)) {\n result = that.getSpecifierExpression();\n }\n }\n }\n FindInitializerVisitor fiv = \n new FindInitializerVisitor();\n fiv.visit(lcu);\n sie = fiv.result;\n }\n if (sie!=null) {\n Tree.Expression e = sie.getExpression();\n if (e!=null) {\n Tree.Term term = e.getTerm();\n if (term instanceof Tree.Literal) {\n String text = \n term.getToken()\n .getText();\n if (text.length()<20) {\n return arrow + text;\n }\n }\n else if (term instanceof Tree.BaseMemberOrTypeExpression) {\n Tree.BaseMemberOrTypeExpression bme = \n (Tree.BaseMemberOrTypeExpression) \n term;\n Tree.Identifier id = bme.getIdentifier();\n if (id!=null && \n bme.getTypeArguments()==null) {\n return arrow + id.getText();\n }\n }\n else if (term!=null) {\n Unit unit = lcu.getUnit();\n if (term.getUnit().equals(unit)) {\n String impl = \n Nodes.toString(term, \n cpc.getTokens());\n if (impl.length()<10) {\n return arrow + impl;\n }\n }\n }\n //don't have the token stream :-/\n //TODO: figure out where to get it from!\n return arrow + \"...\";\n }\n }\n }\n return \"\";\n }\n\n public static String getDefaultValueDescription(\n Parameter param, CeylonParseController cpc) {\n if (param.isDefaulted()) {\n FunctionOrValue model = param.getModel();\n if (model instanceof Functional) {\n return \" => ...\";\n }\n else {\n return getInitialValueDescription(model, cpc);\n }\n }\n else {\n return \"\";\n }\n }\n\n static String anonFunctionHeader(\n Type requiredType, Unit unit) {\n StringBuilder text = new StringBuilder();\n text.append(\"(\");\n boolean first = true;\n char c = 'a';\n List argTypes = \n unit.getCallableArgumentTypes(requiredType);\n for (Type paramType: argTypes) {\n if (first) {\n first = false;\n }\n else {\n text.append(\", \");\n }\n text.append(paramType.asSourceCodeString(unit))\n .append(\" \")\n .append(c++);\n }\n text.append(\")\");\n return text.toString();\n }\n\n public static IRegion getCurrentSpecifierRegion(\n IDocument document, int offset) \n throws BadLocationException {\n int start = offset;\n int length = 0;\n for (int i=offset;\n i0 && document.getChar(offset)==' ') {\n offset++;\n }\n int nextOffset = \n findCharCount(index+1, document, \n loc+startOfArgs, endOfLine, \n \",;\", \"\", true);\n int middleOffset = \n findCharCount(1, document, \n offset, nextOffset, \n \"=\", \"\", true)+1;\n if (middleOffset>0 &&\n document.getChar(middleOffset)=='>') {\n middleOffset++;\n }\n while (middleOffset>0 &&\n document.getChar(middleOffset)==' ') {\n middleOffset++;\n }\n if (middleOffset>offset &&\n middleOffset overloads(Declaration dec) {\n return dec.isAbstraction() ? \n dec.getOverloads() : \n singletonList(dec);\n }\n\n static List getParameters(ParameterList pl,\n boolean includeDefaults, boolean namedInvocation) {\n List ps = pl.getParameters();\n if (includeDefaults) {\n return ps;\n }\n else {\n List list = \n new ArrayList();\n for (Parameter p: ps) {\n if (!p.isDefaulted() || \n (namedInvocation && \n spreadable(p, ps))) {\n list.add(p);\n }\n }\n return list;\n }\n }\n\n private static boolean spreadable(Parameter param, \n List list) {\n Parameter lastParam = \n list.get(list.size()-1);\n if (param==lastParam &&\n param.getModel() instanceof Value) {\n Type type = param.getType();\n Unit unit = param.getDeclaration().getUnit();\n return type!=null &&\n unit.isIterableParameterType(type);\n }\n else {\n return false;\n }\n }\n\n static String fullPath(int offset, String prefix,\n Tree.ImportPath path) {\n StringBuilder fullPath = new StringBuilder();\n if (path!=null) {\n String pathString = \n formatPath(path.getIdentifiers());\n fullPath.append(pathString)\n .append('.');\n int len = \n offset\n -path.getStartIndex()\n -prefix.length();\n fullPath.setLength(len);\n }\n return fullPath.toString();\n }\n\n static boolean isPackageDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return lcu != null && \n lcu.getUnit() != null &&\n lcu.getUnit()\n .getFilename()\n .equals(\"package.ceylon\"); \n }\n\n static boolean isModuleDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return lcu != null && \n lcu.getUnit() != null &&\n lcu.getUnit()\n .getFilename()\n .equals(\"module.ceylon\"); \n }\n\n static boolean isEmptyModuleDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return isModuleDescriptor(cpc) && \n lcu != null && \n lcu.getModuleDescriptors()\n .isEmpty(); \n }\n\n static boolean isEmptyPackageDescriptor(CeylonParseController cpc) {\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n return lcu != null &&\n lcu.getUnit() != null &&\n lcu.getUnit()\n .getFilename()\n .equals(\"package.ceylon\") && \n lcu.getPackageDescriptors()\n .isEmpty();\n }\n\n static int nextTokenType(CeylonParseController cpc,\n CommonToken token) {\n for (int i=token.getTokenIndex()+1; \n i upperBounds, Type t) {\n boolean ok = true;\n for (Type ub: upperBounds) {\n if (!t.isSubtypeOf(ub) &&\n !(ub.involvesTypeParameters() &&\n t.getDeclaration()\n .inherits(ub.getDeclaration()))) {\n ok = false;\n break;\n }\n }\n return ok;\n }\n \n public static List \n getSortedProposedValues(Scope scope, Unit unit) {\n return getSortedProposedValues(scope, unit, null);\n }\n \n public static List \n getSortedProposedValues(Scope scope, Unit unit, \n final String exactName) {\n Map map = \n scope.getMatchingDeclarations(unit, \"\", 0);\n if (exactName!=null) {\n for (DeclarationWithProximity dwp: \n new ArrayList\n (map.values())) {\n if (!dwp.isUnimported() && \n !dwp.isAlias() &&\n isNameMatching(dwp.getName(), \n exactName)) {\n map.put(dwp.getName(), \n new DeclarationWithProximity(\n dwp.getDeclaration(), -5));\n }\n }\n }\n List results = \n new ArrayList(\n map.values());\n Collections.sort(results, \n new ArgumentProposalComparator(exactName));\n return results;\n }\n\n public static boolean isIgnoredLanguageModuleClass(Class clazz) {\n return clazz.isString() ||\n clazz.isInteger() ||\n clazz.isFloat() ||\n clazz.isCharacter() ||\n clazz.isAnnotation();\n }\n\n public static boolean isIgnoredLanguageModuleValue(Value value) {\n String name = value.getName();\n return name.equals(\"process\") ||\n name.equals(\"runtime\") ||\n name.equals(\"system\") ||\n name.equals(\"operatingSystem\") ||\n name.equals(\"language\") ||\n name.equals(\"emptyIterator\") ||\n name.equals(\"infinity\") ||\n name.endsWith(\"IntegerValue\") ||\n name.equals(\"finished\");\n }\n\n public static boolean isIgnoredLanguageModuleMethod(Function method) {\n String name = method.getName();\n return name.equals(\"className\") || \n name.equals(\"flatten\") || \n name.equals(\"unflatten\")|| \n name.equals(\"curry\") || \n name.equals(\"uncurry\") ||\n name.equals(\"compose\") ||\n method.isAnnotation();\n }\n\n static boolean isIgnoredLanguageModuleType(TypeDeclaration td) {\n return !td.isObject() && \n !td.isAnything() &&\n !td.isString() &&\n !td.isInteger() &&\n !td.isCharacter() &&\n !td.isFloat() &&\n !td.isBoolean();\n }\n\n public static String getInitialValueDescription(\n final Declaration dec, \n CeylonParseController cpc) {\n if (cpc!=null) {\n Node refnode = getReferencedNode(dec);\n Tree.SpecifierOrInitializerExpression sie = null;\n String arrow = null;\n if (refnode instanceof Tree.AttributeDeclaration) {\n Tree.AttributeDeclaration ad = \n (Tree.AttributeDeclaration) \n refnode;\n sie = ad.getSpecifierOrInitializerExpression();\n arrow = \" = \";\n }\n else if (refnode instanceof Tree.MethodDeclaration) {\n Tree.MethodDeclaration md =\n (Tree.MethodDeclaration) \n refnode;\n sie = md.getSpecifierExpression();\n arrow = \" => \";\n }\n Tree.CompilationUnit lcu = \n cpc.getLastCompilationUnit();\n if (sie==null) {\n class FindInitializerVisitor extends Visitor {\n Tree.SpecifierOrInitializerExpression result;\n @Override\n public void visit(\n Tree.InitializerParameter that) {\n super.visit(that);\n Declaration d = \n that.getParameterModel()\n .getModel();\n if (d!=null && d.equals(dec)) {\n result = that.getSpecifierExpression();\n }\n }\n }\n FindInitializerVisitor fiv = \n new FindInitializerVisitor();\n fiv.visit(lcu);\n sie = fiv.result;\n }\n if (sie!=null) {\n Tree.Expression e = sie.getExpression();\n if (e!=null) {\n Tree.Term term = e.getTerm();\n if (term instanceof Tree.Literal) {\n String text = \n term.getToken()\n .getText();\n if (text.length()<20) {\n return arrow + text;\n }\n }\n else if (term instanceof Tree.BaseMemberOrTypeExpression) {\n Tree.BaseMemberOrTypeExpression bme = \n (Tree.BaseMemberOrTypeExpression) \n term;\n Tree.Identifier id = bme.getIdentifier();\n if (id!=null && \n bme.getTypeArguments()==null) {\n return arrow + id.getText();\n }\n }\n else if (term.getUnit()\n .equals(lcu.getUnit())) {\n String impl = \n Nodes.toString(term, \n cpc.getTokens());\n if (impl.length()<10) {\n return arrow + impl;\n }\n }\n //don't have the token stream :-/\n //TODO: figure out where to get it from!\n return arrow + \"...\";\n }\n }\n }\n return \"\";\n }\n\n public static String getDefaultValueDescription(\n Parameter param, CeylonParseController cpc) {\n if (param.isDefaulted()) {\n FunctionOrValue model = param.getModel();\n if (model instanceof Functional) {\n return \" => ...\";\n }\n else {\n return getInitialValueDescription(model, cpc);\n }\n }\n else {\n return \"\";\n }\n }\n\n static String anonFunctionHeader(\n Type requiredType, Unit unit) {\n StringBuilder text = new StringBuilder();\n text.append(\"(\");\n boolean first = true;\n char c = 'a';\n List argTypes = \n unit.getCallableArgumentTypes(requiredType);\n for (Type paramType: argTypes) {\n if (first) {\n first = false;\n }\n else {\n text.append(\", \");\n }\n text.append(paramType.asSourceCodeString(unit))\n .append(\" \")\n .append(c++);\n }\n text.append(\")\");\n return text.toString();\n }\n\n public static IRegion getCurrentSpecifierRegion(\n IDocument document, int offset) \n throws BadLocationException {\n int start = offset;\n int length = 0;\n for (int i=offset;\n i0 && document.getChar(offset)==' ') {\n offset++;\n }\n int nextOffset = \n findCharCount(index+1, document, \n loc+startOfArgs, endOfLine, \n \",;\", \"\", true);\n int middleOffset = \n findCharCount(1, document, \n offset, nextOffset, \n \"=\", \"\", true)+1;\n if (middleOffset>0 &&\n document.getChar(middleOffset)=='>') {\n middleOffset++;\n }\n while (middleOffset>0 &&\n document.getChar(middleOffset)==' ') {\n middleOffset++;\n }\n if (middleOffset>offset &&\n middleOffsettransparent property.\n */\n public static final String PROP_TRANSPARENT = \"transparent\";\n /**\n * The ID of the double type property.\n */\n public static final int TYPE_DOUBLE = 1;\n\n /**\n * Standard constructor.\n */\n public TextInputModel() {\n setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);\n setCursorId(CursorStyleEnum.IBEAM.name());\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getTypeID() {\n return ID;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void configureProperties() {\n // Display\n addStringProperty(PROP_INPUT_TEXT, \"Input Text\", WidgetPropertyCategory.DISPLAY, \"\", true,PROP_TOOLTIP); //$NON-NLS-1$\n addArrayOptionProperty(PROP_TEXT_TYPE,\n \"Value Type\",\n WidgetPropertyCategory.DISPLAY,\n TextTypeEnum.getDisplayNames(),\n TextTypeEnum.DOUBLE.getIndex(), false, PROP_INPUT_TEXT);\n addIntegerProperty(PROP_PRECISION,\n \"Decimal places\",\n WidgetPropertyCategory.DISPLAY,\n 2,\n 0,\n 10, false,PROP_TEXT_TYPE);\n // Format\n addFontProperty(PROP_FONT,\n \"Font\", WidgetPropertyCategory.FORMAT, ColorAndFontUtil.toFontString(\"Arial\", 8), false, PROP_COLOR_FOREGROUND); //$NON-NLS-1$\n addArrayOptionProperty(PROP_TEXT_ALIGNMENT,\n \"Text Alignment\",\n WidgetPropertyCategory.FORMAT,\n TextAlignmentEnum.getDisplayNames(),\n TextAlignmentEnum.CENTER.getIndex(), false, PROP_FONT );\n addBooleanProperty(PROP_TRANSPARENT,\n \"Transparent Background\",\n WidgetPropertyCategory.FORMAT,\n true,\n true, AbstractWidgetModel.PROP_COLOR_BACKGROUND);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected String getDefaultToolTip() {\n StringBuffer buffer = new StringBuffer();\n buffer.append(createTooltipParameter(PROP_ALIASES) + \"\\n\");\n buffer.append(\"Text:\\t\");\n buffer.append(createTooltipParameter(PROP_INPUT_TEXT));\n return buffer.toString();\n }\n\n /**\n * Gets the input text.\n *\n * @return the input text\n */\n public String getInputText() {\n return getStringProperty(PROP_INPUT_TEXT);\n }\n\n /**\n * Gets, if the marks should be shown or not.\n *\n * @return int 0 = Center, 1 = Top, 2 = Bottom, 3 = Left, 4 = Right\n */\n public int getTextAlignment() {\n return getArrayOptionProperty(PROP_TEXT_ALIGNMENT);\n }\n\n /**\n * Returns, if this widget should have a transparent background.\n *\n * @return boolean True, if it should have a transparent background, false otherwise\n */\n public boolean getTransparent() {\n return getBooleanProperty(PROP_TRANSPARENT);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getStringValueID() {\n return PROP_INPUT_TEXT;\n }\n\n}\n"},"new_file":{"kind":"string","value":"applications/plugins/org.csstudio.sds.components/src/org/csstudio/sds/components/model/TextInputModel.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2006 Stiftung Deutsches Elektronen-Synchroton, Member of the Helmholtz Association,\n * (DESY), HAMBURG, GERMANY. THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN \"../AS IS\" BASIS.\n * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR\n * THE USE OR OTHER DEALINGS IN THE SOFTWARE. SHOULD THE SOFTWARE PROVE DEFECTIVE IN ANY RESPECT,\n * THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF\n * WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY SOFTWARE IS AUTHORIZED\n * HEREUNDER EXCEPT UNDER THIS DISCLAIMER. DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,\n * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE\n * REDISTRIBUTION, MODIFICATION, USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE\n * DISTRIBUTION OF THIS PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY\n * FIND A COPY AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM\n */\npackage org.csstudio.sds.components.model;\n\nimport org.csstudio.sds.model.AbstractTextTypeWidgetModel;\nimport org.csstudio.sds.model.AbstractWidgetModel;\nimport org.csstudio.sds.model.CursorStyleEnum;\nimport org.csstudio.sds.model.TextAlignmentEnum;\nimport org.csstudio.sds.model.TextTypeEnum;\nimport org.csstudio.sds.model.WidgetPropertyCategory;\nimport org.csstudio.sds.util.ColorAndFontUtil;\n\n/**\n * A widget model for text inputs.\n *\n * @author Alexander Will, Kai Meyer\n * @version $Revision$\n */\npublic final class TextInputModel extends AbstractTextTypeWidgetModel {\n /**\n * The ID of the text input.\n */\n public static final String PROP_INPUT_TEXT = \"inputText\"; //$NON-NLS-1$\n\n /**\n * The ID of the font property.\n */\n public static final String PROP_FONT = \"font\"; //$NON-NLS-1$\n\n /**\n * The ID of the text alignment property.\n */\n public static final String PROP_TEXT_ALIGNMENT = \"textAlignment\"; //$NON-NLS-1$\n\n /**\n * The ID of this widget model.\n */\n public static final String ID = \"org.csstudio.sds.components.Textinput\"; //$NON-NLS-1$\n\n /**\n * The default value of the height property.\n */\n private static final int DEFAULT_HEIGHT = 20;\n\n /**\n * The default value of the width property.\n */\n private static final int DEFAULT_WIDTH = 80;\n /**\n * The ID of the transparent property.\n */\n public static final String PROP_TRANSPARENT = \"transparent\";\n /**\n * The ID of the double type property.\n */\n public static final int TYPE_DOUBLE = 1;\n\n /**\n * Standard constructor.\n */\n public TextInputModel() {\n setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);\n setCursorId(CursorStyleEnum.IBEAM.name());\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getTypeID() {\n return ID;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void configureProperties() {\n // Display\n addStringProperty(PROP_INPUT_TEXT, \"Input Text\", WidgetPropertyCategory.DISPLAY, \"\", true,PROP_TOOLTIP); //$NON-NLS-1$\n addArrayOptionProperty(PROP_TEXT_ALIGNMENT,\n \"Text Alignment\",\n WidgetPropertyCategory.DISPLAY,\n TextAlignmentEnum.getDisplayNames(),\n TextAlignmentEnum.CENTER.getIndex(), false, PROP_INPUT_TEXT );\n addArrayOptionProperty(PROP_TEXT_TYPE,\n \"Value Type\",\n WidgetPropertyCategory.DISPLAY,\n TextTypeEnum.getDisplayNames(),\n TextTypeEnum.DOUBLE.getIndex(), false, PROP_TEXT_ALIGNMENT);\n addIntegerProperty(PROP_PRECISION,\n \"Decimal places\",\n WidgetPropertyCategory.DISPLAY,\n 2,\n 0,\n 10, false,PROP_TEXT_TYPE);\n // Format\n addFontProperty(PROP_FONT,\n \"Font\", WidgetPropertyCategory.FORMAT, ColorAndFontUtil.toFontString(\"Arial\", 8), false, PROP_COLOR_FOREGROUND); //$NON-NLS-1$\n addBooleanProperty(PROP_TRANSPARENT,\n \"Transparent Background\",\n WidgetPropertyCategory.FORMAT,\n true,\n true, AbstractWidgetModel.PROP_COLOR_BACKGROUND);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected String getDefaultToolTip() {\n StringBuffer buffer = new StringBuffer();\n buffer.append(createTooltipParameter(PROP_ALIASES) + \"\\n\");\n buffer.append(\"Text:\\t\");\n buffer.append(createTooltipParameter(PROP_INPUT_TEXT));\n return buffer.toString();\n }\n\n /**\n * Gets the input text.\n *\n * @return the input text\n */\n public String getInputText() {\n return getStringProperty(PROP_INPUT_TEXT);\n }\n\n /**\n * Gets, if the marks should be shown or not.\n *\n * @return int 0 = Center, 1 = Top, 2 = Bottom, 3 = Left, 4 = Right\n */\n public int getTextAlignment() {\n return getArrayOptionProperty(PROP_TEXT_ALIGNMENT);\n }\n\n /**\n * Returns, if this widget should have a transparent background.\n *\n * @return boolean True, if it should have a transparent background, false otherwise\n */\n public boolean getTransparent() {\n return getBooleanProperty(PROP_TRANSPARENT);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getStringValueID() {\n return PROP_INPUT_TEXT;\n }\n\n}\n"},"message":{"kind":"string","value":"change Text Alignment category to format\n"},"old_file":{"kind":"string","value":"applications/plugins/org.csstudio.sds.components/src/org/csstudio/sds/components/model/TextInputModel.java"},"subject":{"kind":"string","value":"change Text Alignment category to format"}}},{"rowIdx":1245,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"epl-1.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"80d42828c913d4822c8c80a2779f2c8d2dc76418"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"miklossy/xtext-core,miklossy/xtext-core"},"new_contents":{"kind":"string","value":"/*******************************************************************************\n * Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *******************************************************************************/\npackage org.eclipse.xtext.parser.terminalrules;\n\nimport org.eclipse.xtext.Grammar;\nimport org.eclipse.xtext.GrammarUtil;\nimport org.eclipse.xtext.IGrammarAccess;\nimport org.eclipse.xtext.conversion.IValueConverter;\nimport org.eclipse.xtext.conversion.ValueConverter;\nimport org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService;\nimport org.eclipse.xtext.conversion.impl.AbstractNullSafeConverter;\nimport org.eclipse.xtext.parsetree.AbstractNode;\nimport org.eclipse.xtext.util.Strings;\n\nimport com.google.inject.Inject;\n\n/**\n * @author Sebastian Zarnekow - Initial contribution and API\n */\npublic class TerminalRuleTestLanguageConverters extends AbstractDeclarativeValueConverterService {\n\n\t// copied from Common.Terminals but without rule for int\n\tprivate Grammar g;\n\n\t@Inject\n\tpublic void setGrammar(IGrammarAccess ga) {\n\t\tthis.g = ga.getGrammar();\n\t}\n\n\t@ValueConverter(rule = \"ID\")\n\tpublic IValueConverter ID() {\n\t\treturn new AbstractNullSafeConverter() {\n\t\t\t@Override\n\t\t\tprotected String internalToValue(String string, AbstractNode node) {\n\t\t\t\treturn string.startsWith(\"^\") ? string.substring(1) : string;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String internalToString(String value) {\n\t\t\t\tif (GrammarUtil.getAllKeywords(g).contains(value)) {\n\t\t\t\t\treturn \"^\"+value;\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t}\n\t\t};\n\t}\n\n\t@ValueConverter(rule = \"STRING\")\n\tpublic IValueConverter STRING() {\n\t\treturn new AbstractNullSafeConverter() {\n\t\t\t@Override\n\t\t\tprotected String internalToValue(String string, AbstractNode node) {\n\t\t\t\treturn Strings.convertFromJavaString(string.substring(1, string.length() - 1));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String internalToString(String value) {\n\t\t\t\treturn '\"' + Strings.convertToJavaString(value) + '\"';\n\t\t\t}\n\t\t};\n\t}\n}\n"},"new_file":{"kind":"string","value":"tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/terminalrules/TerminalRuleTestLanguageConverters.java"},"old_contents":{"kind":"string","value":"/*******************************************************************************\n * Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *******************************************************************************/\npackage org.eclipse.xtext.parser.terminalrules;\n\nimport org.eclipse.xtext.Grammar;\nimport org.eclipse.xtext.GrammarUtil;\nimport org.eclipse.xtext.IGrammarAccess;\nimport org.eclipse.xtext.conversion.IValueConverter;\nimport org.eclipse.xtext.conversion.ValueConverter;\nimport org.eclipse.xtext.conversion.impl.AbstractAnnotationBasedValueConverterService;\nimport org.eclipse.xtext.conversion.impl.AbstractNullSafeConverter;\nimport org.eclipse.xtext.parsetree.AbstractNode;\nimport org.eclipse.xtext.util.Strings;\n\nimport com.google.inject.Inject;\n\n/**\n * @author Sebastian Zarnekow - Initial contribution and API\n */\npublic class TerminalRuleTestLanguageConverters extends AbstractAnnotationBasedValueConverterService {\n\n\t// copied from Common.Terminals but without rule for int\n\tprivate Grammar g;\n\n\t@Inject\n\tpublic void setGrammar(IGrammarAccess ga) {\n\t\tthis.g = ga.getGrammar();\n\t}\n\n\t@ValueConverter(rule = \"ID\")\n\tpublic IValueConverter ID() {\n\t\treturn new AbstractNullSafeConverter() {\n\t\t\t@Override\n\t\t\tprotected String internalToValue(String string, AbstractNode node) {\n\t\t\t\treturn string.startsWith(\"^\") ? string.substring(1) : string;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String internalToString(String value) {\n\t\t\t\tif (GrammarUtil.getAllKeywords(g).contains(value)) {\n\t\t\t\t\treturn \"^\"+value;\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t}\n\t\t};\n\t}\n\n\t@ValueConverter(rule = \"STRING\")\n\tpublic IValueConverter STRING() {\n\t\treturn new AbstractNullSafeConverter() {\n\t\t\t@Override\n\t\t\tprotected String internalToValue(String string, AbstractNode node) {\n\t\t\t\treturn Strings.convertFromJavaString(string.substring(1, string.length() - 1));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String internalToString(String value) {\n\t\t\t\treturn '\"' + Strings.convertToJavaString(value) + '\"';\n\t\t\t}\n\t\t};\n\t}\n}\n"},"message":{"kind":"string","value":"AbstractAnnotationBased ... renamed to AbstractDeclarative...\n"},"old_file":{"kind":"string","value":"tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/terminalrules/TerminalRuleTestLanguageConverters.java"},"subject":{"kind":"string","value":"AbstractAnnotationBased ... renamed to AbstractDeclarative..."}}},{"rowIdx":1246,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mpl-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1eeb6ff4c760b6e8a9dcbe6c55c0f4ca3c0a5180"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"etomica/etomica,ajschult/etomica,etomica/etomica,etomica/etomica,ajschult/etomica,ajschult/etomica"},"new_contents":{"kind":"string","value":"package etomica.potential;\n\nimport etomica.Atom;\nimport etomica.AtomSet;\nimport etomica.Default;\nimport etomica.EtomicaElement;\nimport etomica.EtomicaInfo;\nimport etomica.Simulation;\nimport etomica.Space;\nimport etomica.space.Vector;\n\n/**\n * @author David Kofke\n *\n * Inverse-power potential between an atom and all four boundaries of the phase.\n */\npublic class P1SoftBoundary extends Potential1 implements PotentialSoft, EtomicaElement {\n\n\tprivate final Vector gradient;\n\tprivate double radius;\n\tprivate Atom atom;\n\t\n\tpublic P1SoftBoundary() {\n\t\tthis(Simulation.getDefault().space);\n\t}\n \n\tpublic P1SoftBoundary(Space space) {\n\t\tsuper(space);\n\t\tgradient = space.makeVector();\n\t\tsetRadius(0.5*Default.ATOM_SIZE);\n\t}\n \n\tpublic static EtomicaInfo getEtomicaInfo() {\n\t\tEtomicaInfo info = new EtomicaInfo(\"PotentialSoft repulsive potential at the phase boundaries\");\n\t\treturn info;\n\t}\n \n\tpublic double energy(AtomSet a) {\n\t\tVector dimensions = ((Atom)a).node.parentPhase().boundary().dimensions();\n\t\tdouble rx = atom.coord.position().x(0);\n\t\tdouble ry = atom.coord.position().x(1);\n\t\tdouble dx1 = (dimensions.x(0) - rx);\n\t\tdouble dy1 = (dimensions.x(1) - ry);\n\t\treturn energy(rx) + energy(ry) + energy(dx1) + energy(dy1);\t\t\n\t}//end of energy\n\t\n\tprivate double energy(double r) {\n\t\tr /= radius;\n\t\tdouble r2 = r*r;\n\t\tdouble r6 = r2*r2*r2;\n\t\treturn r6*r6;\n\t}\n\t\n\tprivate double gradient(double r) {\n\t\tdouble rr = radius/r;\n\t\tdouble r2 = rr*rr;\n\t\tdouble r6 = r2*r2*r2;\n\t\treturn -12*r6*r6/r;\n\t}\n\t\n\tpublic Vector gradient(AtomSet a) {\n\t\tVector dimensions = boundary.dimensions();\n\t\tdouble rx = ((Atom)a).coord.position().x(0);\n\t\tdouble ry = atom.coord.position().x(1);\n\t\tdouble dx1 = (dimensions.x(0) - rx);\n\t\tdouble dy1 = (dimensions.x(1) - ry);\n\t\tdouble gradx = gradient(rx) - gradient(dx1);\n\t\tdouble grady = gradient(ry) - gradient(dy1);\n\t\tgradient.setX(0,gradx);\n\t\tgradient.setX(1,grady);\n\t\treturn gradient;\n\t}\n\t\n\tpublic double virial(AtomSet atoms) {\n\t return 0.0;\n }\n \n\t/**\n\t * Returns the radius.\n\t * @return double\n\t */\n\tpublic double getRadius() {\n\t\treturn radius;\n\t}\n\n\t/**\n\t * Sets the radius.\n\t * @param radius The radius to set\n\t */\n\tpublic void setRadius(double radius) {\n\t\tthis.radius = radius;\n\t}\n \n}\n"},"new_file":{"kind":"string","value":"etomica/potential/P1SoftBoundary.java"},"old_contents":{"kind":"string","value":"package etomica.potential;\n\nimport etomica.Atom;\nimport etomica.AtomSet;\nimport etomica.Default;\nimport etomica.EtomicaElement;\nimport etomica.EtomicaInfo;\nimport etomica.Simulation;\nimport etomica.Space;\nimport etomica.space.Vector;\n\n/**\n * @author David Kofke\n *\n * Inverse-power potential between an atom and all four boundaries of the phase.\n */\npublic class P1SoftBoundary extends Potential1 implements PotentialSoft, EtomicaElement {\n\n\tprivate final int D;\n\tprivate final Vector gradient;\n\tprivate double radius, radius2;\n\tprivate double cutoff = Double.MAX_VALUE;\n\tprivate Atom atom;\n\t\n\tpublic P1SoftBoundary() {\n\t\tthis(Simulation.getDefault().space);\n\t}\n \n\tpublic P1SoftBoundary(Space space) {\n\t\tsuper(space);\n\t\tD = space.D();\n\t\tgradient = space.makeVector();\n\t\tsetRadius(0.5*Default.ATOM_SIZE);\n\t}\n \n\tpublic static EtomicaInfo getEtomicaInfo() {\n\t\tEtomicaInfo info = new EtomicaInfo(\"PotentialSoft repulsive potential at the phase boundaries\");\n\t\treturn info;\n\t}\n \n\tpublic double energy(AtomSet a) {\n\t\tVector dimensions = ((Atom)a).node.parentPhase().boundary().dimensions();\n\t\tdouble rx = atom.coord.position().x(0);\n\t\tdouble ry = atom.coord.position().x(1);\n\t\tdouble dx1 = (dimensions.x(0) - rx);\n\t\tdouble dy1 = (dimensions.x(1) - ry);\n\t\treturn energy(rx) + energy(ry) + energy(dx1) + energy(dy1);\t\t\n\t}//end of energy\n\t\n\tprivate double energy(double r) {\n\t\tr /= radius;\n\t\tdouble r2 = r*r;\n\t\tdouble r6 = r2*r2*r2;\n\t\treturn r6*r6;\n\t}\n\t\n\tprivate double gradient(double r) {\n\t\tdouble rr = radius/r;\n\t\tdouble r2 = rr*rr;\n\t\tdouble r6 = r2*r2*r2;\n\t\treturn -12*r6*r6/r;\n\t}\n\t\n\tpublic Vector gradient(AtomSet a) {\n\t\tVector dimensions = boundary.dimensions();\n\t\tdouble rx = ((Atom)a).coord.position().x(0);\n\t\tdouble ry = atom.coord.position().x(1);\n\t\tdouble dx1 = (dimensions.x(0) - rx);\n\t\tdouble dy1 = (dimensions.x(1) - ry);\n\t\tdouble gradx = gradient(rx) - gradient(dx1);\n\t\tdouble grady = gradient(ry) - gradient(dy1);\n\t\tgradient.setX(0,gradx);\n\t\tgradient.setX(1,grady);\n\t\treturn gradient;\n\t}\n\t\n\tpublic double virial(AtomSet atoms) {\n\t return 0.0;\n }\n \n\t/**\n\t * Returns the radius.\n\t * @return double\n\t */\n\tpublic double getRadius() {\n\t\treturn radius;\n\t}\n\n\t/**\n\t * Sets the radius.\n\t * @param radius The radius to set\n\t */\n\tpublic void setRadius(double radius) {\n\t\tthis.radius = radius;\n\t\tradius2 = radius*radius;\n\t}\n \n}\n"},"message":{"kind":"string","value":"cleanup -- remove used fields\n"},"old_file":{"kind":"string","value":"etomica/potential/P1SoftBoundary.java"},"subject":{"kind":"string","value":"cleanup -- remove used fields"}}},{"rowIdx":1247,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"4d2f8303c6a329be274d8adc96a8e963fe298b05"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine"},"new_contents":{"kind":"string","value":"package org.intermine.bio.dataconversion;\n\n/*\n * Copyright (C) 2002-2013 FlyMine\n *\n * This code may be freely distributed and modified under the\n * terms of the GNU Lesser General Public Licence. This should\n * be distributed with the code. See the LICENSE file for more\n * information or http://www.gnu.org/copyleft/lesser.html.\n *\n */\n\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.log4j.Logger;\nimport org.intermine.dataconversion.ItemWriter;\nimport org.intermine.metadata.Model;\nimport org.intermine.objectstore.ObjectStoreException;\nimport org.intermine.util.FormattedTextParser;\nimport org.intermine.xml.full.Item;\n\n/**\n * Read the HuGE GWAS flat file and create GWAS items and GWASResults.\n * @author Richard Smith\n */\npublic class HugeGwasConverter extends BioFileConverter\n{\n //\n private static final String DATASET_TITLE = \"HuGE GWAS Integrator\";\n private static final String DATA_SOURCE_NAME = \"HuGE Navigator\";\n\n private String headerStart = \"rs Number(region location)\";\n private Map genes = new HashMap();\n private Map pubs = new HashMap();\n private Map snps = new HashMap();\n private Map studies = new HashMap();\n\n private static final String HUMAN_TAXON = \"9606\";\n private List invalidGenes = Arrays.asList(new String[] {\"nr\", \"intergenic\"});\n\n // approximately the minimum permitted double value in postgres\n private static final double MIN_POSTGRES_DOUBLE = 1.0E-307;\n\n private static final Logger LOG = Logger.getLogger(HugeGwasConverter.class);\n\n protected IdResolver rslv;\n\n /**\n * Constructor\n * @param writer the ItemWriter used to handle the resultant items\n * @param model the Model\n */\n public HugeGwasConverter(ItemWriter writer, Model model) {\n super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE);\n }\n\n /**\n * {@inheritDoc}\n */\n public void process(Reader reader) throws Exception {\n\n if (rslv == null) {\n rslv = IdResolverService.getHumanIdResolver();\n }\n\n Iterator lineIter = FormattedTextParser.parseTabDelimitedReader(reader);\n boolean doneHeader = false;\n\n while (lineIter.hasNext()) {\n String[] line = (String[]) lineIter.next();\n LOG.info(\"Line: \" + line);\n\n if (line[0].startsWith(headerStart)) {\n doneHeader = true;\n continue;\n }\n\n if (!doneHeader) {\n continue;\n }\n\n if (line.length <= 1) {\n continue;\n }\n\n Set rsNumbers = parseSnpRsNumbers(line[0]);\n if (rsNumbers.isEmpty()) {\n continue;\n }\n\n Set geneIdentifiers = getGenes(line[1]);\n String phenotype = line[3];\n String firstAuthor = line[4];\n String year = line[6];\n String pubIdentifier = getPub(line[7]);\n Map samples = parseSamples(line[8]);\n String riskAlleleStr = line[9];\n Double pValue = parsePValue(line[11]);\n\n // There may be multiple SNPs in one line, create a GWASResult per SNP.\n for (String rsNumber : rsNumbers) {\n Item result = createItem(\"GWASResult\");\n result.setReference(\"SNP\", getSnpIdentifier(rsNumber));\n if (!geneIdentifiers.isEmpty()) {\n result.setCollection(\"associatedGenes\", new ArrayList(geneIdentifiers));\n }\n result.setAttribute(\"phenotype\", phenotype);\n if (pValue != null) {\n result.setAttribute(\"pValue\", pValue.toString());\n }\n String studyIdentifier = getStudy(pubIdentifier, firstAuthor, year, phenotype,\n samples);\n result.setReference(\"study\", studyIdentifier);\n\n // set risk allele details\n String[] alleleParts = riskAlleleStr.split(\"\\\\[\");\n String alleleStr = alleleParts[0];\n if (alleleStr.startsWith(\"rs\")) {\n if (alleleStr.indexOf('-') >= 0) {\n String riskSnp = alleleStr.substring(0, alleleStr.indexOf('-'));\n if (riskSnp.equals(rsNumber)) {\n String allele = alleleStr.substring(alleleStr.indexOf('-') + 1);\n result.setAttribute(\"associatedVariantRiskAllele\", allele);\n }\n } else {\n LOG.warn(\"ALLELE: no allele found in '\" + alleleStr + \"'.\");\n }\n } else {\n result.setAttribute(\"associatedVariantRiskAllele\", alleleParts[0]);\n }\n if (alleleParts.length > 1) {\n String freqStr = alleleParts[1];\n try {\n Float freq = Float.parseFloat(freqStr.substring(0, freqStr.indexOf(']')));\n result.setAttribute(\"riskAlleleFreqInControls\", freq.toString());\n } catch (NumberFormatException e) {\n // wasn't a valid float, probably \"NR\"\n }\n }\n store(result);\n }\n }\n }\n\n /**\n * Read a p-value from a String of the format 5x10-6.\n * @param s the input string, e.g. 5x10-6\n * @return the extracted double or null if failed to parse\n */\n protected Double parsePValue(String s) {\n s = s.replace(\"x10\", \"E\");\n try {\n double pValue = Double.parseDouble(s);\n\n // Postgres JDBC driver is allowing double values outside the permitted range to be\n // stored which are then unusable. This a hack to prevent it.\n if (pValue < MIN_POSTGRES_DOUBLE) {\n pValue = 0.0;\n }\n\n return pValue;\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n private Map parseSamples(String fromFile) {\n Map samples = new HashMap();\n String[] parts = fromFile.split(\"/\");\n samples.put(\"initial\", parts[0]);\n if (parts.length == 1 || \"NR\".equals(parts[1])) {\n samples.put(\"replicate\", \"No replicate\");\n } else {\n samples.put(\"replicate\", parts[1]);\n }\n return samples;\n }\n\n /**\n * Extract a SNP rs id from a string of the format rs11099864(4q31.3).\n * @param s the string read from the file\n * @return the SNP rs number\n */\n protected String parseSnp(String s) {\n if (s.indexOf('(') > 0) {\n return s.substring(0, s.indexOf('(')).trim();\n }\n return s.trim();\n }\n\n private String getStudy(String pubIdentifier, String firstAuthor, String year, String phenotype,\n Map samples)\n throws ObjectStoreException {\n String studyIdentifier = studies.get(pubIdentifier);\n if (studyIdentifier == null) {\n Item gwas = createItem(\"GWAS\");\n gwas.setAttribute(\"firstAuthor\", firstAuthor);\n gwas.setAttribute(\"year\", year);\n gwas.setAttribute(\"name\", phenotype);\n gwas.setAttribute(\"initialSample\", samples.get(\"initial\"));\n gwas.setAttribute(\"replicateSample\", samples.get(\"replicate\"));\n gwas.setReference(\"publication\", pubIdentifier);\n store(gwas);\n\n studyIdentifier = gwas.getIdentifier();\n studies.put(pubIdentifier, studyIdentifier);\n }\n return studyIdentifier;\n }\n\n private String getPub(String pubMedId) throws ObjectStoreException {\n String pubIdentifier = pubs.get(pubMedId);\n if (pubIdentifier == null) {\n Item pub = createItem(\"Publication\");\n pub.setAttribute(\"pubMedId\", pubMedId);\n store(pub);\n\n pubIdentifier = pub.getIdentifier();\n pubs.put(pubMedId, pubIdentifier);\n }\n return pubIdentifier;\n }\n\n\n\n private Set parseSnpRsNumbers(String fromFile) {\n Set rsNumbers = new HashSet();\n for (String s : fromFile.split(\",\")) {\n String rsNumber = parseSnp(s);\n if (rsNumber.startsWith(\"rs\")) {\n rsNumbers.add(rsNumber);\n }\n }\n return rsNumbers;\n }\n\n private String getSnpIdentifier(String rsNumber) throws ObjectStoreException {\n if (!snps.containsKey(rsNumber)) {\n Item snp = createItem(\"SNP\");\n snp.setAttribute(\"primaryIdentifier\", rsNumber);\n snp.setReference(\"organism\", getOrganism(HUMAN_TAXON));\n store(snp);\n snps.put(rsNumber, snp.getIdentifier());\n }\n return snps.get(rsNumber);\n }\n\n private Set getGenes(String s) throws ObjectStoreException {\n Set geneIdentifiers = new HashSet();\n for (String symbol : s.split(\",\")) {\n symbol = symbol.trim();\n if (invalidGenes.contains(symbol.toLowerCase())) {\n continue;\n }\n\n symbol = resolveGene(symbol);\n if (symbol == null) {\n continue;\n }\n\n String geneIdentifier = genes.get(symbol);\n if (geneIdentifier == null) {\n Item gene = createItem(\"Gene\");\n gene.setAttribute(\"symbol\", symbol);\n gene.setReference(\"organism\", getOrganism(HUMAN_TAXON));\n geneIdentifier = gene.getIdentifier();\n\n store(gene);\n genes.put(symbol, geneIdentifier);\n }\n geneIdentifiers.add(geneIdentifier);\n }\n return geneIdentifiers;\n }\n\n /**\n * resolve old human symbol\n * @param taxonId id of organism for this gene\n * @param ih interactor holder\n * @throws ObjectStoreException\n */\n private String resolveGene(String identifier) {\n String id = identifier;\n\n if (rslv != null && rslv.hasTaxon(HUMAN_TAXON)) {\n int resCount = rslv.countResolutions(HUMAN_TAXON, identifier);\n if (resCount != 1) {\n LOG.info(\"RESOLVER: failed to resolve gene to one identifier, ignoring gene: \"\n + identifier + \" count: \" + resCount + \" Human identifier: \"\n + rslv.resolveId(HUMAN_TAXON, identifier));\n return null;\n }\n id = rslv.resolveId(HUMAN_TAXON, identifier).iterator().next();\n }\n return id;\n }\n}\n"},"new_file":{"kind":"string","value":"bio/sources/human/huge-gwas/main/src/org/intermine/bio/dataconversion/HugeGwasConverter.java"},"old_contents":{"kind":"string","value":"package org.intermine.bio.dataconversion;\n\n/*\n * Copyright (C) 2002-2013 FlyMine\n *\n * This code may be freely distributed and modified under the\n * terms of the GNU Lesser General Public Licence. This should\n * be distributed with the code. See the LICENSE file for more\n * information or http://www.gnu.org/copyleft/lesser.html.\n *\n */\n\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.log4j.Logger;\nimport org.intermine.dataconversion.ItemWriter;\nimport org.intermine.metadata.Model;\nimport org.intermine.objectstore.ObjectStoreException;\nimport org.intermine.util.FormattedTextParser;\nimport org.intermine.xml.full.Item;\n\n/**\n * Read the HuGE GWAS flat file and create GWAS items and GWASResults.\n * @author Richard Smith\n */\npublic class HugeGwasConverter extends BioFileConverter\n{\n //\n private static final String DATASET_TITLE = \"HuGE GWAS Integrator\";\n private static final String DATA_SOURCE_NAME = \"HuGE Navigator\";\n\n private String headerStart = \"rs Number(region location)\";\n private Map genes = new HashMap();\n private Map pubs = new HashMap();\n private Map snps = new HashMap();\n private Map studies = new HashMap();\n\n private static final String HUMAN_TAXON = \"9606\";\n private List invalidGenes = Arrays.asList(new String[] {\"nr\", \"intergenic\"});\n\n // approximately the minimum permitted double value in postgres\n private static final double MIN_POSTGRES_DOUBLE = 1.0E-307;\n\n private static final Logger LOG = Logger.getLogger(HugeGwasConverter.class);\n\n /**\n * Constructor\n * @param writer the ItemWriter used to handle the resultant items\n * @param model the Model\n */\n public HugeGwasConverter(ItemWriter writer, Model model) {\n super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE);\n }\n\n /**\n * {@inheritDoc}\n */\n public void process(Reader reader) throws Exception {\n Iterator lineIter = FormattedTextParser.parseTabDelimitedReader(reader);\n boolean doneHeader = false;\n\n while (lineIter.hasNext()) {\n String[] line = (String[]) lineIter.next();\n LOG.info(\"Line: \" + line);\n\n if (line[0].startsWith(headerStart)) {\n doneHeader = true;\n continue;\n }\n\n if (!doneHeader) {\n continue;\n }\n\n if (line.length <= 1) {\n continue;\n }\n\n Set rsNumbers = parseSnpRsNumbers(line[0]);\n if (rsNumbers.isEmpty()) {\n continue;\n }\n\n Set geneIdentifiers = getGenes(line[1]);\n String phenotype = line[3];\n String firstAuthor = line[4];\n String year = line[6];\n String pubIdentifier = getPub(line[7]);\n Map samples = parseSamples(line[8]);\n String riskAlleleStr = line[9];\n Double pValue = parsePValue(line[11]);\n\n // There may be multiple SNPs in one line, create a GWASResult per SNP.\n for (String rsNumber : rsNumbers) {\n Item result = createItem(\"GWASResult\");\n result.setReference(\"SNP\", getSnpIdentifier(rsNumber));\n if (!geneIdentifiers.isEmpty()) {\n result.setCollection(\"associatedGenes\", new ArrayList(geneIdentifiers));\n }\n result.setAttribute(\"phenotype\", phenotype);\n if (pValue != null) {\n result.setAttribute(\"pValue\", pValue.toString());\n }\n String studyIdentifier = getStudy(pubIdentifier, firstAuthor, year, phenotype,\n samples);\n result.setReference(\"study\", studyIdentifier);\n\n // set risk allele details\n String[] alleleParts = riskAlleleStr.split(\"\\\\[\");\n String alleleStr = alleleParts[0];\n if (alleleStr.startsWith(\"rs\")) {\n if (alleleStr.indexOf('-') >= 0) {\n String riskSnp = alleleStr.substring(0, alleleStr.indexOf('-'));\n if (riskSnp.equals(rsNumber)) {\n String allele = alleleStr.substring(alleleStr.indexOf('-') + 1);\n result.setAttribute(\"associatedVariantRiskAllele\", allele);\n }\n } else {\n LOG.warn(\"ALLELE: no allele found in '\" + alleleStr + \"'.\");\n }\n } else {\n result.setAttribute(\"associatedVariantRiskAllele\", alleleParts[0]);\n }\n if (alleleParts.length > 1) {\n String freqStr = alleleParts[1];\n try {\n Float freq = Float.parseFloat(freqStr.substring(0, freqStr.indexOf(']')));\n result.setAttribute(\"riskAlleleFreqInControls\", freq.toString());\n } catch (NumberFormatException e) {\n // wasn't a valid float, probably \"NR\"\n }\n }\n store(result);\n }\n }\n }\n\n /**\n * Read a p-value from a String of the format 5x10-6.\n * @param s the input string, e.g. 5x10-6\n * @return the extracted double or null if failed to parse\n */\n protected Double parsePValue(String s) {\n s = s.replace(\"x10\", \"E\");\n try {\n double pValue = Double.parseDouble(s);\n\n // Postgres JDBC driver is allowing double values outside the permitted range to be\n // stored which are then unusable. This a hack to prevent it.\n if (pValue < MIN_POSTGRES_DOUBLE) {\n pValue = 0.0;\n }\n\n return pValue;\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n private Map parseSamples(String fromFile) {\n Map samples = new HashMap();\n String[] parts = fromFile.split(\"/\");\n samples.put(\"initial\", parts[0]);\n if (parts.length == 1 || \"NR\".equals(parts[1])) {\n samples.put(\"replicate\", \"No replicate\");\n } else {\n samples.put(\"replicate\", parts[1]);\n }\n return samples;\n }\n\n /**\n * Extract a SNP rs id from a string of the format rs11099864(4q31.3).\n * @param s the string read from the file\n * @return the SNP rs number\n */\n protected String parseSnp(String s) {\n if (s.indexOf('(') > 0) {\n return s.substring(0, s.indexOf('(')).trim();\n }\n return s.trim();\n }\n\n private String getStudy(String pubIdentifier, String firstAuthor, String year, String phenotype,\n Map samples)\n throws ObjectStoreException {\n String studyIdentifier = studies.get(pubIdentifier);\n if (studyIdentifier == null) {\n Item gwas = createItem(\"GWAS\");\n gwas.setAttribute(\"firstAuthor\", firstAuthor);\n gwas.setAttribute(\"year\", year);\n gwas.setAttribute(\"name\", phenotype);\n gwas.setAttribute(\"initialSample\", samples.get(\"initial\"));\n gwas.setAttribute(\"replicateSample\", samples.get(\"replicate\"));\n gwas.setReference(\"publication\", pubIdentifier);\n store(gwas);\n\n studyIdentifier = gwas.getIdentifier();\n studies.put(pubIdentifier, studyIdentifier);\n }\n return studyIdentifier;\n }\n\n private String getPub(String pubMedId) throws ObjectStoreException {\n String pubIdentifier = pubs.get(pubMedId);\n if (pubIdentifier == null) {\n Item pub = createItem(\"Publication\");\n pub.setAttribute(\"pubMedId\", pubMedId);\n store(pub);\n\n pubIdentifier = pub.getIdentifier();\n pubs.put(pubMedId, pubIdentifier);\n }\n return pubIdentifier;\n }\n\n\n\n private Set parseSnpRsNumbers(String fromFile) {\n Set rsNumbers = new HashSet();\n for (String s : fromFile.split(\",\")) {\n String rsNumber = parseSnp(s);\n if (rsNumber.startsWith(\"rs\")) {\n rsNumbers.add(rsNumber);\n }\n }\n return rsNumbers;\n }\n\n private String getSnpIdentifier(String rsNumber) throws ObjectStoreException {\n if (!snps.containsKey(rsNumber)) {\n Item snp = createItem(\"SNP\");\n snp.setAttribute(\"primaryIdentifier\", rsNumber);\n snp.setReference(\"organism\", getOrganism(HUMAN_TAXON));\n store(snp);\n snps.put(rsNumber, snp.getIdentifier());\n }\n return snps.get(rsNumber);\n }\n\n private Set getGenes(String s) throws ObjectStoreException {\n Set geneIdentifiers = new HashSet();\n for (String symbol : s.split(\",\")) {\n symbol = symbol.trim();\n if (invalidGenes.contains(symbol.toLowerCase())) {\n continue;\n }\n String geneIdentifier = genes.get(symbol);\n if (geneIdentifier == null) {\n Item gene = createItem(\"Gene\");\n gene.setAttribute(\"symbol\", symbol);\n gene.setReference(\"organism\", getOrganism(HUMAN_TAXON));\n geneIdentifier = gene.getIdentifier();\n\n store(gene);\n genes.put(symbol, geneIdentifier);\n }\n geneIdentifiers.add(geneIdentifier);\n }\n return geneIdentifiers;\n }\n}\n"},"message":{"kind":"string","value":"HuGE - resolve old symbols of human #291\n\n\nFormer-commit-id: 842d1efb31fe9070ebf4d34406c269de0bcd5b43"},"old_file":{"kind":"string","value":"bio/sources/human/huge-gwas/main/src/org/intermine/bio/dataconversion/HugeGwasConverter.java"},"subject":{"kind":"string","value":"HuGE - resolve old symbols of human #291"}}},{"rowIdx":1248,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"3811abb414b59b561b62a764e8d064be0ed24b51"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tmyroadctfig/mpxj"},"new_contents":{"kind":"string","value":"/*\n * file: Props9.java\n * author: Jon Iles\n * copyright: Tapster Rock Limited\n * date: 07/11/2003\n */\n\n/*\n * This library is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at your\n * option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\npackage net.sf.mpxj.mpp;\n\n//import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.util.Iterator;\n\n/**\n * This class represents the Props files found in Microsoft Project MPP9 files.\n */\nfinal class Props9 extends Props\n{\n /**\n * Constructor, reads the property data from an input stream.\n *\n * @param is input stream for reading props data\n */\n Props9 (InputStream is)\n throws IOException\n {\n //FileOutputStream fos = new FileOutputStream (\"c:\\\\temp\\\\props9.\" + System.currentTimeMillis() + \".txt\");\n //PrintWriter pw = new PrintWriter (fos);\n\n byte[] header = new byte[16];\n byte[] data;\n is.read(header);\n\n int headerCount = MPPUtility.getShort(header, 12);\n int foundCount = 0;\n int availableBytes = is.available();\n\n while (foundCount < headerCount)\n {\n int itemSize = readInt(is);\n int itemKey = readInt(is);\n /*int attrib3 = */readInt(is);\n availableBytes -= 12;\n\n if (availableBytes < itemSize || itemSize < 1)\n {\n break;\n }\n\n data = new byte[itemSize];\n is.read(data);\n availableBytes -= itemSize;\n\n m_map.put(new Integer (itemKey), data);\n //pw.println(foundCount + \" \"+ attrib2 + \": \" + MPPUtility.hexdump(data, true));\n ++foundCount;\n\n //\n // Align to two byte boundary\n //\n if (data.length % 2 != 0)\n {\n is.skip(1);\n }\n }\n\n //pw.flush();\n //pw.close();\n }\n\n /**\n * This method dumps the contents of this properties block as a String.\n * Note that this facility is provided as a debugging aid.\n *\n * @return formatted contents of this block\n */\n public String toString ()\n {\n StringWriter sw = new StringWriter ();\n PrintWriter pw = new PrintWriter (sw);\n\n pw.println (\"BEGIN Props\");\n\n Iterator iter = m_map.keySet().iterator();\n Integer key;\n\n while (iter.hasNext() == true)\n {\n key = (Integer)iter.next();\n pw.println (\" Key: \" + key + \" Value: \");\n pw.println (MPPUtility.hexdump((byte[])m_map.get(key), true, 16, \" \"));\n }\n\n pw.println (\"END Props\");\n\n pw.println ();\n pw.close();\n return (sw.toString());\n }\n}\n"},"new_file":{"kind":"string","value":"net/sf/mpxj/mpp/Props9.java"},"old_contents":{"kind":"string","value":"/*\n * file: Props9.java\n * author: Jon Iles\n * copyright: Tapster Rock Limited\n * date: 07/11/2003\n */\n\n/*\n * This library is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at your\n * option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\npackage net.sf.mpxj.mpp;\n\n//import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.util.Iterator;\n\n/**\n * This class represents the Props files found in Microsoft Project MPP9 files.\n */\nfinal class Props9 extends Props\n{\n /**\n * Constructor, reads the property data from an input stream.\n *\n * @param is input stream for reading props data\n */\n Props9 (InputStream is)\n throws IOException\n {\n //FileOutputStream fos = new FileOutputStream (\"c:\\\\temp\\\\props9.\" + System.currentTimeMillis() + \".txt\");\n //PrintWriter pw = new PrintWriter (fos);\n\n byte[] header = new byte[16];\n byte[] data;\n is.read(header);\n\n int headerCount = MPPUtility.getShort(header, 12);\n int foundCount = 0;\n int availableBytes = is.available();\n\n while (foundCount < headerCount)\n {\n int attrib1 = readInt(is);\n int attrib2 = readInt(is);\n /*int attrib3 = */readInt(is);\n availableBytes -= 12;\n\n if (availableBytes < attrib1 || attrib1 < 1)\n {\n break;\n }\n\n data = new byte[attrib1];\n is.read(data);\n availableBytes -= attrib1;\n\n m_map.put(new Integer (attrib2), data);\n //pw.println(foundCount + \" \"+ attrib2 + \": \" + MPPUtility.hexdump(data, true));\n ++foundCount;\n\n //\n // Align to two byte boundary\n //\n if (data.length % 2 != 0)\n {\n is.skip(1);\n }\n }\n\n //pw.flush();\n //pw.close();\n }\n\n /**\n * This method dumps the contents of this properties block as a String.\n * Note that this facility is provided as a debugging aid.\n *\n * @return formatted contents of this block\n */\n public String toString ()\n {\n StringWriter sw = new StringWriter ();\n PrintWriter pw = new PrintWriter (sw);\n\n pw.println (\"BEGIN Props\");\n\n Iterator iter = m_map.keySet().iterator();\n Integer key;\n\n while (iter.hasNext() == true)\n {\n key = (Integer)iter.next();\n pw.println (\" Key: \" + key + \" Value: \");\n pw.println (MPPUtility.hexdump((byte[])m_map.get(key), true, 16, \" \"));\n }\n\n pw.println (\"END Props\");\n\n pw.println ();\n pw.close();\n return (sw.toString());\n }\n}\n"},"message":{"kind":"string","value":"Renamed variables for clarity.\n"},"old_file":{"kind":"string","value":"net/sf/mpxj/mpp/Props9.java"},"subject":{"kind":"string","value":"Renamed variables for clarity."}}},{"rowIdx":1249,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"59689f19d7017cd1be711992f09e884843a260bb"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb"},"new_contents":{"kind":"string","value":"/*\n * ALMA - Atacama Large Millimiter Array\n * (c) European Southern Observatory, 2002\n * Copyright by ESO (in the framework of the ALMA collaboration),\n * All rights reserved\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, \n * MA 02111-1307 USA\n */\npackage alma.contLogTest.LogLevelsImpl;\n\n\nimport junit.framework.Assert;\nimport junit.framework.TestCase;\n\nimport si.ijs.maci.Administrator;\nimport si.ijs.maci.AdministratorPOATie;\nimport si.ijs.maci.Container;\nimport si.ijs.maci.ContainerInfo;\nimport si.ijs.maci.LoggingConfigurableHelper;\nimport si.ijs.maci.LoggingConfigurableOperations;\n\nimport alma.ACSErrTypeCommon.CouldntPerformActionEx;\nimport alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx;\nimport alma.JavaContainerError.wrappers.AcsJContainerEx;\nimport alma.acs.component.client.ComponentClient;\nimport alma.acs.component.client.ComponentClientTestCase;\nimport alma.acs.container.AcsManagerProxy;\nimport alma.contLogTest.LogLevels;\nimport alma.maciErrType.NoPermissionEx;\n\n/**\n * Requires Java component \"TESTLOG1\" of type alma.contLogTest.LogLevels to be running.\n * \n * @author eallaert 30 October 2007\n */\npublic class LogLevelsTest extends ComponentClientTestCase\n{\n\tprivate ComponentClient hlc = null;\n\n private LogLevels m_testlogComp;\n private static String component[];\n\n /**\n\t * @param name\n\t * @throws java.lang.Exception\n\t */\n\tpublic LogLevelsTest() throws Exception\n\t{\n\t\tsuper(LogLevelsTest.class.getName());\n\t}\n\n\t/**\n\t * @see TestCase#setUp()\n\t */\n\tprotected void setUp() throws Exception\n\t{\n\t\tsuper.setUp();\n//\t\tif (false) {\n//\t\t\tString managerLoc = System.getProperty(\"ACS.manager\");\n//\t\t\tif (managerLoc == null) {\n//\t\t\t\tSystem.out\n//\t\t\t\t\t\t.println(\"Java property 'ACS.manager' must be set to the corbaloc of the ACS manager!\");\n//\t\t\t\tSystem.exit(-1);\n//\t\t\t}\n//\t\t\t/*\n//\t\t\tString clientName = \"LogLevelsClient\";\n//\t\t\ttry {\n//\t\t\t\thlc = new ComponentClient(null, managerLoc, clientName);\n//\t\t\t\tm_logger.info(\"got LogLevel client\");\n//\t\t\t} catch (Exception e) {\n//\t\t\t\ttry {\n//\t\t\t\t\tLogger logger = hlc.getContainerServices().getLogger();\n//\t\t\t\t\tlogger.log(Level.SEVERE, \"Client application failure\", e);\n//\t\t\t\t} catch (Exception e2) {\n//\t\t\t\t\te.printStackTrace(System.err);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\t*/\n//\t\t}\n\t}\n\n\t/**\n\t * @see TestCase#tearDown()\n\t */\n\tprotected void tearDown() throws Exception\n\t{\n//\t if (hlc != null)\n//\t\t{\n// \ttry \n// \t\t{\n// \t\thlc.tearDown();\n// \t\t}\n// \tcatch (Exception e3) \n// \t\t{\n// \t\t// bad luck\n// \t\te3.printStack\tTrace();\n// \t\t}\n//\t\t}\n\t\tsuper.tearDown();\n\t}\n\t\n\t\n//\tpublic void testGetLoggingConfigurableInterface() throws Exception {\n//\t\tLoggingConfigurableOperations containerLogConfig = getContainerLoggingIF(\"heikoContainer\");\n//\t\tString[] loggerNames = containerLogConfig.get_logger_names();\n//\t\tassertNotNull(loggerNames);\n//\t}\n//\t\n\t\n\tpublic void testGetLevels() throws Exception\n\t{\n\t\tint levels[];\n\t\tfor (int i = 0; i < component.length; i++)\n\t\t{\n\t\t m_testlogComp = alma.contLogTest.LogLevelsHelper.narrow(getContainerServices().getComponent(component[i]));\n\n\t\t\ttry {\n\t\t\t\tlevels = m_testlogComp.getLevels();\n\t\t\t} catch (CouldntPerformActionEx ex) {\n\t\t\t\tthrow AcsJCouldntPerformActionEx.fromCouldntPerformActionEx(ex);\n\t\t\t}\n\t\t\tm_logger.info(\"levels from component's getLevels method (hardcoded remote, local, effective): \"\n\t\t\t\t\t+ levels[0] + \", \" + levels[1] + \", \" + levels[2] + \", \" + levels[3] + \", \" + levels[4]);\n\t\t\t// levels[0-4]: hardcoded remote, hardcoded local, AcsLogger, AcsLogHandler, StdoutConsoleHandler\n\t\t\tAssert.assertTrue(levels[3] != -1);\n\t\t\tAssert.assertTrue(levels[4] != -1);\n\t\t\t// The AcsLogger setting should be the minimum of the one for AcsLogHandler and StdoutConsoleHandler\n\t\t\tint minLevel = levels[3];\n\t\t\tif (levels[3] > levels[4] || levels[3] == -1)\n\t\t\t\tminLevel = levels[4];\n\t\t\tAssert.assertEquals(levels[2], minLevel);\n\t\t}\n\t}\n\n\t\n\t/**\n\t * Gets a reference to the LoggingConfigurableOperations interface of a container with a given name. \n\t *

\n\t * Note that only in test code like here we are allowed to talk directly with the manager.\n\t * For operational code, the ContainerServices methods must be used and extended if necessary.\n\t * \n\t * @param containerName\n\t */\n\tpublic LoggingConfigurableOperations getContainerLoggingIF(String containerName) throws AcsJContainerEx, NoPermissionEx {\n \tAdministratorPOATie adminpoa = new AdministratorPOATie(new ManagerAdminClient(getName(), m_logger)); \n\t\tAdministrator adminCorbaObj = adminpoa._this(getContainerServices().getAdvancedContainerServices().getORB());\n\t\t\n\t\t// we need an new manager connection because the JUnit test does not have admin right.\n\t\tAcsManagerProxy adminProxy = m_acsManagerProxy.createInstance(); \n\t\tContainer containerRef;\n\t\ttry {\n\t\t\tadminProxy.loginToManager(adminCorbaObj, false);\n\t\t\tint adminManagerHandle = adminProxy.getManagerHandle();\n\t\t\tassertTrue(adminManagerHandle > 0);\n\t\t\t\n\t\t\t// ask the manager for the container reference\n\t\t\tContainerInfo[] containerInfos = adminProxy.getManager().get_container_info(adminManagerHandle, new int[0], containerName);\n\t\t\tassertEquals(1, containerInfos.length);\n\t\t\tcontainerRef = containerInfos[0].reference;\n\t\t} finally {\n\t\t\t// now that we got our reference, we can logout the manager client again.\n\t\t\t// Of course this is too dirty for operational code, because manager cannot keep track of \n\t\t\t// admin clients holding container references...\n\t\t\tadminProxy.logoutFromManager();\n\t\t}\n\t\t\n\t\t// cast up to LoggingConfigurable interface\n\t\treturn LoggingConfigurableHelper.narrow(containerRef);\n\t}\n\t\n\t\n\t/**\n\t * @TODO We usually don't require a main method for a JUnit test to run successfully.\n\t * Therefore instead of getting component names from the arg list, \n\t * they should be given in some Java property that can be evaluated in the setUp method.\n\t */\n\tpublic static void main(String[] args)\n\t{\n\t component = new String[args.length];\n\t for (int i = 0; i < args.length; i++)\n\t\t{\n component[i] = new String(args[i]);\n\t\t}\n\t\tjunit.textui.TestRunner.run(LogLevelsTest.class);\n\t}\n\n}\n\n\n"},"new_file":{"kind":"string","value":"LGPL/CommonSoftware/containerTests/contLogTest/test/alma/contLogTest/LogLevelsImpl/LogLevelsTest.java"},"old_contents":{"kind":"string","value":"/*\n * ALMA - Atacama Large Millimiter Array\n * (c) European Southern Observatory, 2002\n * Copyright by ESO (in the framework of the ALMA collaboration),\n * All rights reserved\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, \n * MA 02111-1307 USA\n */\npackage alma.contLogTest.LogLevelsImpl;\n\n\nimport java.util.Vector;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport junit.framework.Assert;\n\nimport alma.ACSErrTypeCommon.CouldntPerformActionEx;\nimport alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx;\nimport alma.acs.component.client.ComponentClient;\nimport alma.acs.component.client.ComponentClientTestCase;\nimport alma.contLogTest.LogLevels;\nimport alma.maci.loggingconfig.LoggingConfig;\n\n/**\n * Requires Java component \"TESTLOG1\" of type alma.contLogTest.LogLevels to be running.\n * \n * @author eallaert 30 October 2007\n */\npublic class LogLevelsTest extends ComponentClientTestCase\n{\n\tprivate ComponentClient hlc = null;\n\n private LogLevels m_testlogComp;\n private static String component[];\n\n /**\n\t * @param name\n\t * @throws java.lang.Exception\n\t */\n\tpublic LogLevelsTest() throws Exception\n\t{\n\t\tsuper(LogLevelsTest.class.getName());\n\t}\n\n\t/**\n\t * @see TestCase#setUp()\n\t */\n\tprotected void setUp() throws Exception\n\t{\n\t\tsuper.setUp();\n\t\tif (false) {\n\t\t\tString managerLoc = System.getProperty(\"ACS.manager\");\n\t\t\tif (managerLoc == null) {\n\t\t\t\tSystem.out\n\t\t\t\t\t\t.println(\"Java property 'ACS.manager' must be set to the corbaloc of the ACS manager!\");\n\t\t\t\tSystem.exit(-1);\n\t\t\t}\n\t\t\t/*\n\t\t\tString clientName = \"LogLevelsClient\";\n\t\t\ttry {\n\t\t\t\thlc = new ComponentClient(null, managerLoc, clientName);\n\t\t\t\tm_logger.info(\"got LogLevel client\");\n\t\t\t} catch (Exception e) {\n\t\t\t\ttry {\n\t\t\t\t\tLogger logger = hlc.getContainerServices().getLogger();\n\t\t\t\t\tlogger.log(Level.SEVERE, \"Client application failure\", e);\n\t\t\t\t} catch (Exception e2) {\n\t\t\t\t\te.printStackTrace(System.err);\n\t\t\t\t}\n\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\n\t/**\n\t * @see TestCase#tearDown()\n\t */\n\tprotected void tearDown() throws Exception\n\t{\n\t if (hlc != null)\n\t\t{\n \ttry \n \t\t{\n \t\thlc.tearDown();\n \t\t}\n \tcatch (Exception e3) \n \t\t{\n \t\t// bad luck\n \t\te3.printStackTrace();\n \t\t}\n\t\t}\n\t\tsuper.tearDown();\n\t}\n\t\n\tpublic void testGetLevels() throws Exception\n\t{\n\t\tint levels[];\n\t\tfor (int i = 0; i < component.length; i++)\n\t\t{\n\t\t m_testlogComp = alma.contLogTest.LogLevelsHelper.narrow(getContainerServices().getComponent(component[i]));\n\n\t\t\ttry {\n\t\t\t\tlevels = m_testlogComp.getLevels();\n\t\t\t} catch (CouldntPerformActionEx ex) {\n\t\t\t\tthrow AcsJCouldntPerformActionEx.fromCouldntPerformActionEx(ex);\n\t\t\t}\n\t\t\tm_logger.info(\"levels from component's getLevels method (hardcoded remote, local, effective): \"\n\t\t\t\t\t+ levels[0] + \", \" + levels[1] + \", \" + levels[2] + \", \" + levels[3] + \", \" + levels[4]);\n\t\t\t// levels[0-4]: hardcoded remote, hardcoded local, AcsLogger, AcsLogHandler, StdoutConsoleHandler\n\t\t\tAssert.assertTrue(levels[3] != -1);\n\t\t\tAssert.assertTrue(levels[4] != -1);\n\t\t\t// The AcsLogger setting should be the minimum of the one for AcsLogHandler and StdoutConsoleHandler\n\t\t\tint minLevel = levels[3];\n\t\t\tif (levels[3] > levels[4] || levels[3] == -1)\n\t\t\t\tminLevel = levels[4];\n\t\t\tAssert.assertEquals(levels[2], minLevel);\n\t\t}\n\t}\n\n\tpublic static void main(String[] args)\n\t{\n\t component = new String[args.length];\n\t for (int i = 0; i < args.length; i++)\n\t\t{\n component[i] = new String(args[i]);\n\t\t}\n\t\tjunit.textui.TestRunner.run(LogLevelsTest.class);\n\t}\n\n}\n\n\n"},"message":{"kind":"string","value":"new helper method getContainerLoggingIF to allow direct logging API calls on all containers\n\n\ngit-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@79779 523d945c-050c-4681-91ec-863ad3bb968a\n"},"old_file":{"kind":"string","value":"LGPL/CommonSoftware/containerTests/contLogTest/test/alma/contLogTest/LogLevelsImpl/LogLevelsTest.java"},"subject":{"kind":"string","value":"new helper method getContainerLoggingIF to allow direct logging API calls on all containers"}}},{"rowIdx":1250,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f596b4db71b69f49652351c3c0623552954fd78b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS"},"new_contents":{"kind":"string","value":"package org.endeavourhealth.queuereader;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Lists;\nimport com.google.gson.JsonSyntaxException;\nimport org.apache.commons.csv.*;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.FilenameUtils;\nimport org.endeavourhealth.common.cache.ObjectMapperPool;\nimport org.endeavourhealth.common.config.ConfigManager;\nimport org.endeavourhealth.common.fhir.PeriodHelper;\nimport org.endeavourhealth.common.utility.FileHelper;\nimport org.endeavourhealth.common.utility.FileInfo;\nimport org.endeavourhealth.common.utility.JsonSerializer;\nimport org.endeavourhealth.common.utility.SlackHelper;\nimport org.endeavourhealth.core.configuration.ConfigDeserialiser;\nimport org.endeavourhealth.core.configuration.PostMessageToExchangeConfig;\nimport org.endeavourhealth.core.configuration.QueueReaderConfiguration;\nimport org.endeavourhealth.core.csv.CsvHelper;\nimport org.endeavourhealth.core.database.dal.DalProvider;\nimport org.endeavourhealth.core.database.dal.admin.ServiceDalI;\nimport org.endeavourhealth.core.database.dal.admin.models.Service;\nimport org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI;\nimport org.endeavourhealth.core.database.dal.audit.ExchangeDalI;\nimport org.endeavourhealth.core.database.dal.audit.models.*;\nimport org.endeavourhealth.core.database.dal.ehr.ResourceDalI;\nimport org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper;\nimport org.endeavourhealth.core.database.rdbms.ConnectionManager;\nimport org.endeavourhealth.core.exceptions.TransformException;\nimport org.endeavourhealth.core.fhirStorage.FhirStorageService;\nimport org.endeavourhealth.core.fhirStorage.JsonServiceInterfaceEndpoint;\nimport org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange;\nimport org.endeavourhealth.core.queueing.QueueHelper;\nimport org.endeavourhealth.core.xml.TransformErrorSerializer;\nimport org.endeavourhealth.core.xml.transformError.TransformError;\nimport org.endeavourhealth.transform.barts.BartsCsvToFhirTransformer;\nimport org.endeavourhealth.transform.common.*;\nimport org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer;\nimport org.endeavourhealth.transform.emis.csv.helpers.EmisCsvHelper;\nimport org.hibernate.internal.SessionImpl;\nimport org.hl7.fhir.instance.model.EpisodeOfCare;\nimport org.hl7.fhir.instance.model.Patient;\nimport org.hl7.fhir.instance.model.ResourceType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.persistence.EntityManager;\nimport java.io.*;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.text.SimpleDateFormat;\nimport java.util.*;\n\npublic class Main {\n\tprivate static final Logger LOG = LoggerFactory.getLogger(Main.class);\n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tString configId = args[0];\n\n\t\tLOG.info(\"Initialising config manager\");\n\t\tConfigManager.initialize(\"queuereader\", configId);\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixEncounters\")) {\n\t\t\tString table = args[1];\n\t\t\tfixEncounters(table);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateAdastraSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tString destDirPath = args[2];\n\t\t\tString samplePatientsFile = args[3];\n\t\t\tcreateAdastraSubset(sourceDirPath, destDirPath, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateVisionSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tString destDirPath = args[2];\n\t\t\tString samplePatientsFile = args[3];\n\t\t\tcreateVisionSubset(sourceDirPath, destDirPath, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateTppSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tString destDirPath = args[2];\n\t\t\tString samplePatientsFile = args[3];\n\t\t\tcreateTppSubset(sourceDirPath, destDirPath, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateBartsSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tUUID serviceUuid = UUID.fromString(args[2]);\n\t\t\tUUID systemUuid = UUID.fromString(args[3]);\n\t\t\tString samplePatientsFile = args[4];\n\t\t\tcreateBartsSubset(sourceDirPath, serviceUuid, systemUuid, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixBartsOrgs\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tfixBartsOrgs(serviceId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"TestPreparedStatements\")) {\n\t\t\tString url = args[1];\n\t\t\tString user = args[2];\n\t\t\tString pass = args[3];\n\t\t\tString serviceId = args[4];\n\t\t\ttestPreparedStatements(url, user, pass, serviceId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"ApplyEmisAdminCaches\")) {\n\t\t\tapplyEmisAdminCaches();\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixSubscribers\")) {\n\t\t\tfixSubscriberDbs();\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"ConvertExchangeBody\")) {\n\t\t\tString systemId = args[1];\n\t\t\tconvertExchangeBody(UUID.fromString(systemId));\n\t\t\tSystem.exit(0);\n\t\t}\n\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixReferrals\")) {\n\t\t\tfixReferralRequests();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PopulateNewSearchTable\")) {\n\t\t\tString table = args[1];\n\t\t\tpopulateNewSearchTable(table);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixBartsEscapes\")) {\n\t\t\tString filePath = args[1];\n\t\t\tfixBartsEscapedFiles(filePath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PostToInbound\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tString systemId = args[2];\n\t\t\tString filePath = args[3];\n\t\t\tpostToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixDisabledExtract\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tString systemId = args[2];\n\t\t\tString sharedStoragePath = args[3];\n\t\t\tString tempDir = args[4];\n\t\t\tfixDisabledEmisExtract(serviceId, systemId, sharedStoragePath, tempDir);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"TestSlack\")) {\n\t\t\ttestSlack();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PostToInbound\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tboolean all = Boolean.parseBoolean(args[2]);\n\t\t\tpostToInbound(UUID.fromString(serviceId), all);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixPatientSearch\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tfixPatientSearch(serviceId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"Exit\")) {\n\n\t\t\tString exitCode = args[1];\n\t\t\tLOG.info(\"Exiting with error code \" + exitCode);\n\t\t\tint exitCodeInt = Integer.parseInt(exitCode);\n\t\t\tSystem.exit(exitCodeInt);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"RunSql\")) {\n\n\t\t\tString host = args[1];\n\t\t\tString username = args[2];\n\t\t\tString password = args[3];\n\t\t\tString sqlFile = args[4];\n\t\t\trunSql(host, username, password, sqlFile);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PopulateProtocolQueue\")) {\n\t\t\tString serviceId = null;\n\t\t\tif (args.length > 1) {\n\t\t\t\tserviceId = args[1];\n\t\t\t}\n\t\t\tString startingExchangeId = null;\n\t\t\tif (args.length > 2) {\n\t\t\t\tstartingExchangeId = args[2];\n\t\t\t}\n\t\t\tpopulateProtocolQueue(serviceId, startingExchangeId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindEncounterTerms\")) {\n\t\t\tString path = args[1];\n\t\t\tString outputPath = args[2];\n\t\t\tfindEncounterTerms(path, outputPath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindEmisStartDates\")) {\n\t\t\tString path = args[1];\n\t\t\tString outputPath = args[2];\n\t\t\tfindEmisStartDates(path, outputPath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"ExportHl7Encounters\")) {\n\t\t\tString sourceCsvPpath = args[1];\n\t\t\tString outputPath = args[2];\n\t\t\texportHl7Encounters(sourceCsvPpath, outputPath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixExchangeBatches\")) {\n\t\t\tfixExchangeBatches();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 0\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindCodes\")) {\n\t\t\tfindCodes();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 0\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindDeletedOrgs\")) {\n\t\t\tfindDeletedOrgs();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length != 1) {\n\t\t\tLOG.error(\"Usage: queuereader config_id\");\n\t\t\treturn;\n\t\t}\n\n\t\tLOG.info(\"--------------------------------------------------\");\n\t\tLOG.info(\"EDS Queue Reader \" + configId);\n\t\tLOG.info(\"--------------------------------------------------\");\n\n\t\tLOG.info(\"Fetching queuereader configuration\");\n\t\tString configXml = ConfigManager.getConfiguration(configId);\n\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\n\t\t/*LOG.info(\"Registering shutdown hook\");\n\t\tregisterShutdownHook();*/\n\n\t\t// Instantiate rabbit handler\n\t\tLOG.info(\"Creating EDS queue reader\");\n\t\tRabbitHandler rabbitHandler = new RabbitHandler(configuration, configId);\n\n\t\t// Begin consume\n\t\trabbitHandler.start();\n\t\tLOG.info(\"EDS Queue reader running (kill file location \" + TransformConfig.instance().getKillFileLocation() + \")\");\n\t}\n\n\tprivate static void convertExchangeBody(UUID systemUuid) {\n\t\ttry {\n\t\t\tLOG.info(\"Converting exchange bodies for system \" + systemUuid);\n\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\n\t\t\tList services = serviceDal.getAll();\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tList exchanges = exchangeDal.getExchangesByService(service.getId(), systemUuid, Integer.MAX_VALUE);\n\t\t\t\tif (exchanges.isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.debug(\"doing \" + service.getName() + \" with \" + exchanges.size() + \" exchanges\");\n\n\t\t\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\t\ttry {\n\t\t\t\t\t\t//already done\n\t\t\t\t\t\tExchangePayloadFile[] files = JsonSerializer.deserialize(exchangeBody, ExchangePayloadFile[].class);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} catch (JsonSyntaxException ex) {\n\t\t\t\t\t\t//if the JSON can't be parsed, then it'll be the old format of body that isn't JSON\n\t\t\t\t\t}\n\n\t\t\t\t\tList newFiles = new ArrayList<>();\n\n\t\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody);\n\t\t\t\t\tfor (String file: files) {\n\t\t\t\t\t\tExchangePayloadFile fileObj = new ExchangePayloadFile();\n\n\t\t\t\t\t\tString fileWithoutSharedStorage = file.substring(TransformConfig.instance().getSharedStoragePath().length()+1);\n\t\t\t\t\t\tfileObj.setPath(fileWithoutSharedStorage);\n\n\t\t\t\t\t\t//size\n\t\t\t\t\t\tList fileInfos = FileHelper.listFilesInSharedStorageWithInfo(file);\n\t\t\t\t\t\tfor (FileInfo info: fileInfos) {\n\t\t\t\t\t\t\tif (info.getFilePath().equals(file)) {\n\t\t\t\t\t\t\t\tlong size = info.getSize();\n\t\t\t\t\t\t\t\tfileObj.setSize(new Long(size));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//type\n\t\t\t\t\t\tif (systemUuid.toString().equalsIgnoreCase(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\") //live\n\t\t\t\t\t\t\t\t|| systemUuid.toString().equalsIgnoreCase(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\")) { //dev\n\t\t\t\t\t\t\t//emis\n\t\t\t\t\t\t\tString name = FilenameUtils.getName(file);\n\t\t\t\t\t\t\tString[] toks = name.split(\"_\");\n\n\t\t\t\t\t\t\tString first = toks[1];\n\t\t\t\t\t\t\tString second = toks[2];\n\t\t\t\t\t\t\tfileObj.setType(first + \"_\" + second);\n\n\t\t\t\t\t\t} else if (systemUuid.toString().equalsIgnoreCase(\"e517fa69-348a-45e9-a113-d9b59ad13095\")\n\t\t\t\t\t\t\t|| systemUuid.toString().equalsIgnoreCase(\"b0277098-0b6c-4d9d-86ef-5f399fb25f34\")) { //dev\n\n\t\t\t\t\t\t\t//cerner\n\t\t\t\t\t\t\tString name = FilenameUtils.getName(file);\n\t\t\t\t\t\t\tString type = BartsCsvToFhirTransformer.identifyFileType(name);\n\t\t\t\t\t\t\tfileObj.setType(type);\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthrow new Exception(\"Unknown system ID \" + systemUuid);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnewFiles.add(fileObj);\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = JsonSerializer.serialize(newFiles);\n\t\t\t\t\texchange.setBody(json);\n\n\t\t\t\t\texchangeDal.save(exchange);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Converting exchange bodies for system \" + systemUuid);\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}\n\n\t/*private static void fixBartsOrgs(String serviceId) {\n\t\ttry {\n\t\t\tLOG.info(\"Fixing Barts orgs\");\n\n\t\t\tResourceDalI dal = DalProvider.factoryResourceDal();\n\t\t\tList wrappers = dal.getResourcesByService(UUID.fromString(serviceId), ResourceType.Organization.toString());\n\t\t\tLOG.debug(\"Found \" + wrappers.size() + \" resources\");\n\t\t\tint done = 0;\n\t\t\tint fixed = 0;\n\t\t\tfor (ResourceWrapper wrapper: wrappers) {\n\n\t\t\t\tif (!wrapper.isDeleted()) {\n\n\t\t\t\t\tList history = dal.getResourceHistory(UUID.fromString(serviceId), wrapper.getResourceType(), wrapper.getResourceId());\n\t\t\t\t\tResourceWrapper mostRecent = history.get(0);\n\n\t\t\t\t\tString json = mostRecent.getResourceData();\n\t\t\t\t\tOrganization org = (Organization)FhirSerializationHelper.deserializeResource(json);\n\n\t\t\t\t\tString odsCode = IdentifierHelper.findOdsCode(org);\n\t\t\t\t\tif (Strings.isNullOrEmpty(odsCode)\n\t\t\t\t\t\t\t&& org.hasIdentifier()) {\n\n\t\t\t\t\t\tboolean hasBeenFixed = false;\n\n\t\t\t\t\t\tfor (Identifier identifier: org.getIdentifier()) {\n\t\t\t\t\t\t\tif (identifier.getSystem().equals(FhirIdentifierUri.IDENTIFIER_SYSTEM_ODS_CODE)\n\t\t\t\t\t\t\t\t\t&& identifier.hasId()) {\n\n\t\t\t\t\t\t\t\todsCode = identifier.getId();\n\t\t\t\t\t\t\t\tidentifier.setValue(odsCode);\n\t\t\t\t\t\t\t\tidentifier.setId(null);\n\t\t\t\t\t\t\t\thasBeenFixed = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (hasBeenFixed) {\n\t\t\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(org);\n\t\t\t\t\t\t\tmostRecent.setResourceData(newJson);\n\n\t\t\t\t\t\t\tLOG.debug(\"Fixed Organization \" + org.getId());\n\t\t\t\t\t\t\t*//*LOG.debug(json);\n\t\t\t\t\t\t\tLOG.debug(newJson);*//*\n\n\t\t\t\t\t\t\tsaveResourceWrapper(UUID.fromString(serviceId), mostRecent);\n\n\t\t\t\t\t\t\tfixed ++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tdone ++;\n\t\t\t\tif (done % 100 == 0) {\n\t\t\t\t\tLOG.debug(\"Done \" + done + \", Fixed \" + fixed);\n\t\t\t\t}\n\t\t\t}\n\t\t\tLOG.debug(\"Done \" + done + \", Fixed \" + fixed);\n\n\t\t\tLOG.info(\"Finished Barts orgs\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}*/\n\n\t/*private static void testPreparedStatements(String url, String user, String pass, String serviceId) {\n\t\ttry {\n\t\t\tLOG.info(\"Testing Prepared Statements\");\n\t\t\tLOG.info(\"Url: \" + url);\n\t\t\tLOG.info(\"user: \" + user);\n\t\t\tLOG.info(\"pass: \" + pass);\n\n\t\t\t//open connection\n\t\t\tClass.forName(\"com.mysql.cj.jdbc.Driver\");\n\n\t\t\t//create connection\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(\"user\", user);\n\t\t\tprops.setProperty(\"password\", pass);\n\n\t\t\tConnection conn = DriverManager.getConnection(url, props);\n\n\t\t\tString sql = \"SELECT * FROM internal_id_map WHERE service_id = ? AND id_type = ? AND source_id = ?\";\n\n\t\t\tlong start = System.currentTimeMillis();\n\n\t\t\tfor (int i=0; i<10000; i++) {\n\n\t\t\t\tPreparedStatement ps = null;\n\t\t\t\ttry {\n\t\t\t\t\tps = conn.prepareStatement(sql);\n\t\t\t\t\tps.setString(1, serviceId);\n\t\t\t\t\tps.setString(2, \"MILLPERSIDtoMRN\");\n\t\t\t\t\tps.setString(3, UUID.randomUUID().toString());\n\n\t\t\t\t\tResultSet rs = ps.executeQuery();\n\t\t\t\t\twhile (rs.next()) {\n\t\t\t\t\t\t//do nothing\n\t\t\t\t\t}\n\n\t\t\t\t} finally {\n\t\t\t\t\tif (ps != null) {\n\t\t\t\t\t\tps.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlong end = System.currentTimeMillis();\n\t\t\tLOG.info(\"Took \" + (end-start) + \" ms\");\n\n\t\t\t//close connection\n\t\t\tconn.close();\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixEncounters(String table) {\n\t\tLOG.info(\"Fixing encounters from \" + table);\n\n\t\ttry {\n\n\t\t\tSimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");\n\t\t\tDate cutoff = sdf.parse(\"2018-03-14 11:42\");\n\n\t\t\tEntityManager entityManager = ConnectionManager.getAdminEntityManager();\n\t\t\tSessionImpl session = (SessionImpl)entityManager.getDelegate();\n\t\t\tConnection connection = session.connection();\n\t\t\tStatement statement = connection.createStatement();\n\n\t\t\tList serviceIds = new ArrayList<>();\n\t\t\tMap hmSystems = new HashMap<>();\n\n\t\t\tString sql = \"SELECT service_id, system_id FROM \" + table + \" WHERE done = 0\";\n\t\t\tResultSet rs = statement.executeQuery(sql);\n\t\t\twhile (rs.next()) {\n\t\t\t\tUUID serviceId = UUID.fromString(rs.getString(1));\n\t\t\t\tUUID systemId = UUID.fromString(rs.getString(2));\n\t\t\t\tserviceIds.add(serviceId);\n\t\t\t\thmSystems.put(serviceId, systemId);\n\t\t\t}\n\t\t\trs.close();\n\t\t\tstatement.close();\n\t\t\tentityManager.close();\n\n\t\t\tfor (UUID serviceId: serviceIds) {\n\t\t\t\tUUID systemId = hmSystems.get(serviceId);\n\t\t\t\tLOG.info(\"Doing service \" + serviceId + \" and system \" + systemId);\n\n\t\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, systemId);\n\n\t\t\t\tList exchangeIdsToProcess = new ArrayList<>();\n\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tList audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId);\n\t\t\t\t\tfor (ExchangeTransformAudit audit: audits) {\n\t\t\t\t\t\tDate d = audit.getStarted();\n\t\t\t\t\t\tif (d.after(cutoff)) {\n\t\t\t\t\t\t\texchangeIdsToProcess.add(exchangeId);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tMap consultationNewChildMap = new HashMap<>();\n\t\t\t\tMap observationChildMap = new HashMap<>();\n\t\t\t\tMap newProblemChildren = new HashMap<>();\n\n\t\t\t\tfor (UUID exchangeId: exchangeIdsToProcess) {\n\t\t\t\t\tExchange exchange = exchangeDal.getExchange(exchangeId);\n\n\t\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyIntoFileList(exchange.getBody());\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(files);\n\n\t\t\t\t\tList interestingFiles = new ArrayList<>();\n\t\t\t\t\tfor (String file: files) {\n\t\t\t\t\t\tif (file.indexOf(\"CareRecord_Consultation\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"CareRecord_Observation\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"CareRecord_Diary\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"Prescribing_DrugRecord\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"Prescribing_IssueRecord\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"CareRecord_Problem\") > -1) {\n\t\t\t\t\t\t\tinterestingFiles.add(file);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfiles = interestingFiles.toArray(new String[0]);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\t\t\t\t\tEmisCsvToFhirTransformer.createParsers(serviceId, systemId, exchangeId, files, version, parsers);\n\n\t\t\t\t\tString dataSharingAgreementGuid = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(parsers);\n\t\t\t\t\tEmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchangeId, dataSharingAgreementGuid, true);\n\n\n\t\t\t\t\tConsultation consultationParser = (Consultation)parsers.get(Consultation.class);\n\t\t\t\t\twhile (consultationParser.nextRecord()) {\n\t\t\t\t\t\tCsvCell consultationGuid = consultationParser.getConsultationGuid();\n\t\t\t\t\t\tCsvCell patientGuid = consultationParser.getPatientGuid();\n\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid);\n\t\t\t\t\t\tconsultationNewChildMap.put(sourceId, new ReferenceList());\n\t\t\t\t\t}\n\n\t\t\t\t\tProblem problemParser = (Problem)parsers.get(Problem.class);\n\t\t\t\t\twhile (problemParser.nextRecord()) {\n\t\t\t\t\t\tCsvCell problemGuid = problemParser.getObservationGuid();\n\t\t\t\t\t\tCsvCell patientGuid = problemParser.getPatientGuid();\n\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\tnewProblemChildren.put(sourceId, new ReferenceList());\n\t\t\t\t\t}\n\n\t\t\t\t\t//run this pre-transformer to pre-cache some stuff in the csv helper, which\n\t\t\t\t\t//is needed when working out the resource type that each observation would be saved as\n\t\t\t\t\tObservationPreTransformer.transform(version, parsers, null, csvHelper);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tCsvCell observationGuid = observationParser.getObservationGuid();\n\t\t\t\t\t\tCsvCell patientGuid = observationParser.getPatientGuid();\n\t\t\t\t\t\tString obSourceId = EmisCsvHelper.createUniqueId(patientGuid, observationGuid);\n\n\t\t\t\t\t\tCsvCell codeId = observationParser.getCodeId();\n\t\t\t\t\t\tif (codeId.isEmpty()) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper);\n\n\t\t\t\t\t\tUUID obUuid = IdHelper.getEdsResourceId(serviceId, resourceType, obSourceId);\n\t\t\t\t\t\tif (obUuid == null) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + resourceType + \" and source ID \" + obSourceId);\n\t\t\t\t\t\t\t//resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tReference obReference = ReferenceHelper.createReference(resourceType, obUuid.toString());\n\n\t\t\t\t\t\tCsvCell consultationGuid = observationParser.getConsultationGuid();\n\t\t\t\t\t\tif (!consultationGuid.isEmpty()) {\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = consultationNewChildMap.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tconsultationNewChildMap.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(obReference);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tCsvCell problemGuid = observationParser.getProblemGuid();\n\t\t\t\t\t\tif (!problemGuid.isEmpty()) {\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = newProblemChildren.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tnewProblemChildren.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(obReference);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tCsvCell parentObGuid = observationParser.getParentObservationGuid();\n\t\t\t\t\t\tif (!parentObGuid.isEmpty()) {\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, parentObGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = observationChildMap.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tobservationChildMap.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(obReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tDiary diaryParser = (Diary)parsers.get(Diary.class);\n\t\t\t\t\twhile (diaryParser.nextRecord()) {\n\n\t\t\t\t\t\tCsvCell consultationGuid = diaryParser.getConsultationGuid();\n\t\t\t\t\t\tif (!consultationGuid.isEmpty()) {\n\n\t\t\t\t\t\t\tCsvCell diaryGuid = diaryParser.getDiaryGuid();\n\t\t\t\t\t\t\tCsvCell patientGuid = diaryParser.getPatientGuid();\n\t\t\t\t\t\t\tString diarySourceId = EmisCsvHelper.createUniqueId(patientGuid, diaryGuid);\n\t\t\t\t\t\t\tUUID diaryUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.ProcedureRequest, diarySourceId);\n\t\t\t\t\t\t\tif (diaryUuid == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + ResourceType.ProcedureRequest + \" and source ID \" + diarySourceId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tReference diaryReference = ReferenceHelper.createReference(ResourceType.ProcedureRequest, diaryUuid.toString());\n\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = consultationNewChildMap.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tconsultationNewChildMap.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(diaryReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tIssueRecord issueRecordParser = (IssueRecord)parsers.get(IssueRecord.class);\n\t\t\t\t\twhile (issueRecordParser.nextRecord()) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tCsvCell problemGuid = issueRecordParser.getProblemObservationGuid();\n\t\t\t\t\t\tif (!problemGuid.isEmpty()) {\n\n\t\t\t\t\t\t\tCsvCell issueRecordGuid = issueRecordParser.getIssueRecordGuid();\n\t\t\t\t\t\t\tCsvCell patientGuid = issueRecordParser.getPatientGuid();\n\t\t\t\t\t\t\tString issueRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, issueRecordGuid);\n\t\t\t\t\t\t\tUUID issueRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationOrder, issueRecordSourceId);\n\t\t\t\t\t\t\tif (issueRecordUuid == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + ResourceType.MedicationOrder + \" and source ID \" + issueRecordSourceId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tReference issueRecordReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, issueRecordUuid.toString());\n\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = newProblemChildren.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tnewProblemChildren.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(issueRecordReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tDrugRecord drugRecordParser = (DrugRecord)parsers.get(DrugRecord.class);\n\t\t\t\t\twhile (drugRecordParser.nextRecord()) {\n\n\t\t\t\t\t\tCsvCell problemGuid = drugRecordParser.getProblemObservationGuid();\n\t\t\t\t\t\tif (!problemGuid.isEmpty()) {\n\n\t\t\t\t\t\t\tCsvCell drugRecordGuid = drugRecordParser.getDrugRecordGuid();\n\t\t\t\t\t\t\tCsvCell patientGuid = drugRecordParser.getPatientGuid();\n\t\t\t\t\t\t\tString drugRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, drugRecordGuid);\n\t\t\t\t\t\t\tUUID drugRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationStatement, drugRecordSourceId);\n\t\t\t\t\t\t\tif (drugRecordUuid == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + ResourceType.MedicationStatement + \" and source ID \" + drugRecordSourceId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tReference drugRecordReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, drugRecordUuid.toString());\n\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = newProblemChildren.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tnewProblemChildren.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(drugRecordReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (AbstractCsvParser parser : parsers.values()) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparser.close();\n\t\t\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\t\t\t//don't worry if this fails, as we're done anyway\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\n\t\t\t\tLOG.info(\"Found \" + consultationNewChildMap.size() + \" Encounters to fix\");\n\t\t\t\tfor (String encounterSourceId: consultationNewChildMap.keySet()) {\n\n\t\t\t\t\tReferenceList childReferences = consultationNewChildMap.get(encounterSourceId);\n\n\t\t\t\t\t//map to UUID\n\t\t\t\t\tUUID encounterId = IdHelper.getEdsResourceId(serviceId, ResourceType.Encounter, encounterSourceId);\n\t\t\t\t\tif (encounterId == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//get history, which is most recent FIRST\n\t\t\t\t\tList history = resourceDal.getResourceHistory(serviceId, ResourceType.Encounter.toString(), encounterId);\n\t\t\t\t\tif (history.isEmpty()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t//throw new Exception(\"Empty history for Encounter \" + encounterId);\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper currentState = history.get(0);\n\t\t\t\t\tif (currentState.isDeleted()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//find last instance prior to cutoff and get its linked children\n\t\t\t\t\tfor (ResourceWrapper wrapper: history) {\n\t\t\t\t\t\tDate d = wrapper.getCreatedAt();\n\t\t\t\t\t\tif (!d.after(cutoff)) {\n\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\tEncounter encounter = (Encounter) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\tEncounterBuilder encounterBuilder = new EncounterBuilder(encounter);\n\t\t\t\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder);\n\n\t\t\t\t\t\t\t\tList previousChildren = containedListBuilder.getContainedListItems();\n\t\t\t\t\t\t\t\tchildReferences.add(previousChildren);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (childReferences.size() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = currentState.getResourceData();\n\t\t\t\t\tResource resource = FhirSerializationHelper.deserializeResource(json);\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(resource);\n\t\t\t\t\tif (!json.equals(newJson)) {\n\t\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);\n\t\t\t\t\t}\n\n\t\t\t\t\t*//*Encounter encounter = (Encounter)FhirSerializationHelper.deserializeResource(currentState.getResourceData());\n\t\t\t\t\tEncounterBuilder encounterBuilder = new EncounterBuilder(encounter);\n\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder);\n\n\t\t\t\t\tcontainedListBuilder.addReferences(childReferences);\n\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(encounter);\n\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);*//*\n\t\t\t\t}\n\n\n\t\t\t\tLOG.info(\"Found \" + observationChildMap.size() + \" Parent Observations to fix\");\n\t\t\t\tfor (String sourceId: observationChildMap.keySet()) {\n\n\t\t\t\t\tReferenceList childReferences = observationChildMap.get(sourceId);\n\n\t\t\t\t\t//map to UUID\n\t\t\t\t\tResourceType resourceType = null;\n\n\t\t\t\t\tUUID resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, sourceId);\n\t\t\t\t\tif (resourceId != null) {\n\t\t\t\t\t\tresourceType = ResourceType.Observation;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.DiagnosticReport, sourceId);\n\t\t\t\t\t\tif (resourceId != null) {\n\t\t\t\t\t\t\tresourceType = ResourceType.DiagnosticReport;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//get history, which is most recent FIRST\n\t\t\t\t\tList history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId);\n\t\t\t\t\tif (history.isEmpty()) {\n\t\t\t\t\t\t//throw new Exception(\"Empty history for \" + resourceType + \" \" + resourceId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper currentState = history.get(0);\n\t\t\t\t\tif (currentState.isDeleted()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//find last instance prior to cutoff and get its linked children\n\t\t\t\t\tfor (ResourceWrapper wrapper: history) {\n\t\t\t\t\t\tDate d = wrapper.getCreatedAt();\n\t\t\t\t\t\tif (!d.after(cutoff)) {\n\n\t\t\t\t\t\t\tif (resourceType == ResourceType.Observation) {\n\t\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\t\tObservation observation = (Observation) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\t\tif (observation.hasRelated()) {\n\t\t\t\t\t\t\t\t\t\tfor (Observation.ObservationRelatedComponent related : observation.getRelated()) {\n\t\t\t\t\t\t\t\t\t\t\tReference reference = related.getTarget();\n\t\t\t\t\t\t\t\t\t\t\tchildReferences.add(reference);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\t\tDiagnosticReport report = (DiagnosticReport) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\t\tif (report.hasResult()) {\n\t\t\t\t\t\t\t\t\t\tfor (Reference reference : report.getResult()) {\n\t\t\t\t\t\t\t\t\t\t\tchildReferences.add(reference);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (childReferences.size() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = currentState.getResourceData();\n\t\t\t\t\tResource resource = FhirSerializationHelper.deserializeResource(json);\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(resource);\n\t\t\t\t\tif (!json.equals(newJson)) {\n\t\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);\n\t\t\t\t\t}\n\n\t\t\t\t\t*//*Resource resource = FhirSerializationHelper.deserializeResource(currentState.getResourceData());\n\n\t\t\t\t\tboolean changed = false;\n\n\t\t\t\t\tif (resourceType == ResourceType.Observation) {\n\t\t\t\t\t\tObservationBuilder resourceBuilder = new ObservationBuilder((Observation)resource);\n\t\t\t\t\t\tfor (int i=0; i history = resourceDal.getResourceHistory(serviceId, ResourceType.Condition.toString(), conditionId);\n\t\t\t\t\tif (history.isEmpty()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t//throw new Exception(\"Empty history for Condition \" + conditionId);\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper currentState = history.get(0);\n\t\t\t\t\tif (currentState.isDeleted()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//find last instance prior to cutoff and get its linked children\n\t\t\t\t\tfor (ResourceWrapper wrapper: history) {\n\t\t\t\t\t\tDate d = wrapper.getCreatedAt();\n\t\t\t\t\t\tif (!d.after(cutoff)) {\n\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\tCondition previousVersion = (Condition) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\tConditionBuilder conditionBuilder = new ConditionBuilder(previousVersion);\n\t\t\t\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder);\n\n\t\t\t\t\t\t\t\tList previousChildren = containedListBuilder.getContainedListItems();\n\t\t\t\t\t\t\t\tchildReferences.add(previousChildren);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (childReferences.size() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = currentState.getResourceData();\n\t\t\t\t\tResource resource = FhirSerializationHelper.deserializeResource(json);\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(resource);\n\t\t\t\t\tif (!json.equals(newJson)) {\n\t\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);\n\t\t\t\t\t}\n\n\t\t\t\t\t*//*Condition condition = (Condition)FhirSerializationHelper.deserializeResource(currentState.getResourceData());\n\t\t\t\t\tConditionBuilder conditionBuilder = new ConditionBuilder(condition);\n\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder);\n\n\t\t\t\t\tcontainedListBuilder.addReferences(childReferences);\n\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(condition);\n\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);*//*\n\t\t\t\t}\n\n\t\t\t\t//mark as done\n\t\t\t\tString updateSql = \"UPDATE \" + table + \" SET done = 1 WHERE service_id = '\" + serviceId + \"';\";\n\t\t\t\tentityManager = ConnectionManager.getAdminEntityManager();\n\t\t\t\tsession = (SessionImpl)entityManager.getDelegate();\n\t\t\t\tconnection = session.connection();\n\t\t\t\tstatement = connection.createStatement();\n\t\t\t\tentityManager.getTransaction().begin();\n\t\t\t\tstatement.executeUpdate(updateSql);\n\t\t\t\tentityManager.getTransaction().commit();\n\t\t\t}\n\n\t\t\t*//**\n\t\t\t * For each practice:\n\t\t\t Go through all files processed since 14 March\n\t\t\t Cache all links as above\n\t\t\t Cache all Encounters saved too\n\n\t\t\t For each Encounter referenced at all:\n\t\t\t Retrieve latest version from resource current\n\t\t\t Retrieve version prior to 14 March\n\t\t\t Update current version with old references plus new ones\n\n\t\t\t For each parent observation:\n\t\t\t Retrieve latest version (could be observation or diagnostic report)\n\n\t\t\t For each problem:\n\t\t\t Retrieve latest version from resource current\n\t\t\t Check if still a problem:\n\t\t\t Retrieve version prior to 14 March\n\t\t\t Update current version with old references plus new ones\n\n\t\t\t *//*\n\n\t\t\tLOG.info(\"Finished Fixing encounters from \" + table);\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}*/\n\n\tprivate static void saveResourceWrapper(UUID serviceId, ResourceWrapper wrapper) throws Exception {\n\n\t\tif (wrapper.getResourceData() != null) {\n\t\t\tlong checksum = FhirStorageService.generateChecksum(wrapper.getResourceData());\n\t\t\twrapper.setResourceChecksum(new Long(checksum));\n\t\t}\n\n\t\tEntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId);\n\t\tSessionImpl session = (SessionImpl)entityManager.getDelegate();\n\t\tConnection connection = session.connection();\n\t\tStatement statement = connection.createStatement();\n\n\t\tentityManager.getTransaction().begin();\n\n\t\tString json = wrapper.getResourceData();\n\t\tjson = json.replace(\"'\", \"''\");\n\t\tjson = json.replace(\"\\\\\", \"\\\\\\\\\");\n\n\t\tString patientId = \"\";\n\t\tif (wrapper.getPatientId() != null) {\n\t\t\tpatientId = wrapper.getPatientId().toString();\n\t\t}\n\n\t\tString updateSql = \"UPDATE resource_current\"\n\t\t\t\t\t\t+ \" SET resource_data = '\" + json + \"',\"\n\t\t\t\t\t\t+ \" resource_checksum = \" + wrapper.getResourceChecksum()\n\t\t\t\t\t\t+ \" WHERE service_id = '\" + wrapper.getServiceId() + \"'\"\n\t\t\t\t\t\t+ \" AND patient_id = '\" + patientId + \"'\"\n\t\t\t\t\t\t+ \" AND resource_type = '\" + wrapper.getResourceType() + \"'\"\n\t\t\t\t\t\t+ \" AND resource_id = '\" + wrapper.getResourceId() + \"'\";\n\t\tstatement.executeUpdate(updateSql);\n\n\t\t//LOG.debug(updateSql);\n\n\t\t//SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:SS\");\n\t\t//String createdAtStr = sdf.format(wrapper.getCreatedAt());\n\n\t\tupdateSql = \"UPDATE resource_history\"\n\t\t\t\t+ \" SET resource_data = '\" + json + \"',\"\n\t\t\t\t+ \" resource_checksum = \" + wrapper.getResourceChecksum()\n\t\t\t\t+ \" WHERE resource_id = '\" + wrapper.getResourceId() + \"'\"\n\t\t\t\t+ \" AND resource_type = '\" + wrapper.getResourceType() + \"'\"\n\t\t\t\t//+ \" AND created_at = '\" + createdAtStr + \"'\"\n\t\t\t\t+ \" AND version = '\" + wrapper.getVersion() + \"'\";\n\t\tstatement.executeUpdate(updateSql);\n\n\t\t//LOG.debug(updateSql);\n\n\t\tentityManager.getTransaction().commit();\n\t}\n\n\t/*private static void populateNewSearchTable(String table) {\n\t\tLOG.info(\"Populating New Search Table\");\n\n\t\ttry {\n\n\t\t\tEntityManager entityManager = ConnectionManager.getEdsEntityManager();\n\t\t\tSessionImpl session = (SessionImpl)entityManager.getDelegate();\n\t\t\tConnection connection = session.connection();\n\t\t\tStatement statement = connection.createStatement();\n\n\t\t\tList patientIds = new ArrayList<>();\n\t\t\tMap serviceIds = new HashMap<>();\n\n\t\t\tString sql = \"SELECT patient_id, service_id FROM \" + table + \" WHERE done = 0\";\n\t\t\tResultSet rs = statement.executeQuery(sql);\n\t\t\twhile (rs.next()) {\n\t\t\t\tString patientId = rs.getString(1);\n\t\t\t\tString serviceId = rs.getString(2);\n\t\t\t\tpatientIds.add(patientId);\n\t\t\t\tserviceIds.put(patientId, serviceId);\n\t\t\t}\n\t\t\trs.close();\n\t\t\tstatement.close();\n\t\t\tentityManager.close();\n\n\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\tPatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearch2Dal();\n\n\t\t\tLOG.info(\"Found \" + patientIds.size() + \" to do\");\n\n\t\t\tfor (int i=0; i wrappers = resourceDal.getResourcesByPatient(serviceId, null, patientId, ResourceType.EpisodeOfCare.toString());\n\t\t\t\t\tfor (ResourceWrapper wrapper: wrappers) {\n\t\t\t\t\t\tif (!wrapper.isDeleted()) {\n\t\t\t\t\t\t\tEpisodeOfCare episodeOfCare = (EpisodeOfCare)FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\tpatientSearchDal.update(serviceId, episodeOfCare);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\n\t\t\t\tString updateSql = \"UPDATE \" + table + \" SET done = 1 WHERE patient_id = '\" + patientIdStr + \"' AND service_id = '\" + serviceIdStr + \"';\";\n\t\t\t\tentityManager = ConnectionManager.getEdsEntityManager();\n\t\t\t\tsession = (SessionImpl)entityManager.getDelegate();\n\t\t\t\tconnection = session.connection();\n\t\t\t\tstatement = connection.createStatement();\n\t\t\t\tentityManager.getTransaction().begin();\n\t\t\t\tstatement.executeUpdate(updateSql);\n\t\t\t\tentityManager.getTransaction().commit();\n\n\t\t\t\tif (i % 5000 == 0) {\n\t\t\t\t\tLOG.info(\"Done \" + (i+1) + \" of \" + patientIds.size());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentityManager.close();\n\n\t\t\tLOG.info(\"Finished Populating New Search Table\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\tprivate static void createBartsSubset(String sourceDir, UUID serviceUuid, UUID systemUuid, String samplePatientsFile) {\n\t\tLOG.info(\"Creating Barts Subset\");\n\n\t\ttry {\n\n\t\t\tSet personIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpersonIds.add(line);\n\t\t\t}\n\n\t\t\tcreateBartsSubsetForFile(sourceDir, serviceUuid, systemUuid, personIds);\n\n\t\t\tLOG.info(\"Finished Creating Barts Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\t/*private static void createBartsSubsetForFile(File sourceDir, File destDir, Set personIds) throws Exception {\n\n\t\tfor (File sourceFile: sourceDir.listFiles()) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing dir \" + sourceFile);\n\t\t\t\tcreateBartsSubsetForFile(sourceFile, destFile, personIds);\n\n\t\t\t} else {\n\n\t\t\t\t//we have some bad partial files in, so ignore them\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (ext.equalsIgnoreCase(\"filepart\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//if the file is empty, we still need the empty file in the filtered directory, so just copy it\n\t\t\t\tif (sourceFile.length() == 0) {\n\t\t\t\t\tLOG.info(\"Copying empty file \" + sourceFile);\n\t\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString baseName = FilenameUtils.getBaseName(name);\n\t\t\t\tString fileType = BartsCsvToFhirTransformer.identifyFileType(baseName);\n\n\t\t\t\tif (isCerner22File(fileType)) {\n\t\t\t\t\tLOG.info(\"Checking 2.2 file \" + sourceFile);\n\n\t\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\t\tdestFile.delete();\n\t\t\t\t\t}\n\n\t\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\t\t\t\t\tint lineIndex = -1;\n\n\t\t\t\t\tPrintWriter pw = null;\n\t\t\t\t\tint personIdColIndex = -1;\n\t\t\t\t\tint expectedCols = -1;\n\n\t\t\t\t\twhile (true) {\n\n\t\t\t\t\t\tString line = br.readLine();\n\t\t\t\t\t\tif (line == null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlineIndex ++;\n\n\t\t\t\t\t\tif (lineIndex == 0) {\n\n\t\t\t\t\t\t\tif (fileType.equalsIgnoreCase(\"FAMILYHISTORY\")) {\n\t\t\t\t\t\t\t\t//this file has no headers, so needs hard-coding\n\t\t\t\t\t\t\t\tpersonIdColIndex = 5;\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t//check headings for PersonID col\n\t\t\t\t\t\t\t\tString[] toks = line.split(\"\\\\|\", -1);\n\t\t\t\t\t\t\t\texpectedCols = toks.length;\n\n\t\t\t\t\t\t\t\tfor (int i=0; i personIds) throws Exception {\n\n\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\tList exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE);\n\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tList files = ExchangeHelper.parseExchangeBody(exchange.getBody());\n\n\t\t\tfor (ExchangePayloadFile fileObj : files) {\n\n\t\t\t\tString filePathWithoutSharedStorage = fileObj.getPath().substring(TransformConfig.instance().getSharedStoragePath().length()+1);\n\t\t\t\tString sourceFilePath = FilenameUtils.concat(sourceDir, filePathWithoutSharedStorage);\n\t\t\t\tFile sourceFile = new File(sourceFilePath);\n\n\t\t\t\tString destFilePath = fileObj.getPath();\n\t\t\t\tFile destFile = new File(destFilePath);\n\n\t\t\t\tFile destDir = destFile.getParentFile();\n\t\t\t\tif (!destDir.exists()) {\n\t\t\t\t\tdestDir.mkdirs();\n\t\t\t\t}\n\n\t\t\t\t//if the file is empty, we still need the empty file in the filtered directory, so just copy it\n\t\t\t\tif (sourceFile.length() == 0) {\n\t\t\t\t\tLOG.info(\"Copying empty file \" + sourceFile);\n\t\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString fileType = fileObj.getType();\n\n\t\t\t\tif (isCerner22File(fileType)) {\n\t\t\t\t\tLOG.info(\"Checking 2.2 file \" + sourceFile);\n\n\t\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\t\tdestFile.delete();\n\t\t\t\t\t}\n\n\t\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\t\t\t\t\tint lineIndex = -1;\n\n\t\t\t\t\tPrintWriter pw = null;\n\t\t\t\t\tint personIdColIndex = -1;\n\t\t\t\t\tint expectedCols = -1;\n\n\t\t\t\t\twhile (true) {\n\n\t\t\t\t\t\tString line = br.readLine();\n\t\t\t\t\t\tif (line == null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlineIndex++;\n\n\t\t\t\t\t\tif (lineIndex == 0) {\n\n\t\t\t\t\t\t\tif (fileType.equalsIgnoreCase(\"FAMILYHISTORY\")) {\n\t\t\t\t\t\t\t\t//this file has no headers, so needs hard-coding\n\t\t\t\t\t\t\t\tpersonIdColIndex = 5;\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t//check headings for PersonID col\n\t\t\t\t\t\t\t\tString[] toks = line.split(\"\\\\|\", -1);\n\t\t\t\t\t\t\t\texpectedCols = toks.length;\n\n\t\t\t\t\t\t\t\tfor (int i = 0; i < expectedCols; i++) {\n\t\t\t\t\t\t\t\t\tString col = toks[i];\n\t\t\t\t\t\t\t\t\tif (col.equalsIgnoreCase(\"PERSON_ID\")\n\t\t\t\t\t\t\t\t\t\t\t|| col.equalsIgnoreCase(\"#PERSON_ID\")) {\n\t\t\t\t\t\t\t\t\t\tpersonIdColIndex = i;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//if no person ID, then just copy the entire file\n\t\t\t\t\t\t\t\tif (personIdColIndex == -1) {\n\t\t\t\t\t\t\t\t\tbr.close();\n\t\t\t\t\t\t\t\t\tbr = null;\n\n\t\t\t\t\t\t\t\t\tLOG.info(\" Copying 2.2 file to \" + destFile);\n\t\t\t\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tLOG.info(\" Filtering 2.2 file to \" + destFile + \", person ID col at \" + personIdColIndex);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\t\t\t\t\t\t\tpw = new PrintWriter(bw);\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t//filter on personID\n\t\t\t\t\t\t\tString[] toks = line.split(\"\\\\|\", -1);\n\t\t\t\t\t\t\tif (expectedCols != -1\n\t\t\t\t\t\t\t\t\t&& toks.length != expectedCols) {\n\t\t\t\t\t\t\t\tthrow new Exception(\"Line \" + (lineIndex + 1) + \" has \" + toks.length + \" cols but expecting \" + expectedCols);\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tString personId = toks[personIdColIndex];\n\t\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes\n\t\t\t\t\t\t\t\t\t\t&& !personIds.contains(personId)) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpw.println(line);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (br != null) {\n\t\t\t\t\t\tbr.close();\n\t\t\t\t\t}\n\t\t\t\t\tif (pw != null) {\n\t\t\t\t\t\tpw.flush();\n\t\t\t\t\t\tpw.close();\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t//the 2.1 files are going to be a pain to split by patient, so just copy them over\n\t\t\t\t\tLOG.info(\"Copying 2.1 file \" + sourceFile);\n\t\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void copyFile(File src, File dst) throws Exception {\n\t\tFileInputStream fis = new FileInputStream(src);\n\t\tBufferedInputStream bis = new BufferedInputStream(fis);\n\t\tFiles.copy(bis, dst.toPath());\n\t\tbis.close();\n\t}\n\t\n\tprivate static boolean isCerner22File(String fileType) throws Exception {\n\n\t\tif (fileType.equalsIgnoreCase(\"PPATI\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPREL\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CDSEV\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPATH\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"RTTPE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"AEATT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"AEINV\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"AETRE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"OPREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"OPATT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALEN\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALSU\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALOF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"HPSSP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"IPEPI\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"IPWDS\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DELIV\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"BIRTH\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SCHAC\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"APPSL\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DIAGN\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PROCE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ORDER\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DOCRP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DOCREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CNTRQ\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"LETRS\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"LOREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ORGREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PRSNLREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CVREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"NOMREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALIP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CLEVE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ENCNT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"RESREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPNAM\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPADD\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPPHO\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPALI\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPINF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPAGP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCC\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCA\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCD\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PDRES\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PDREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ABREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CEPRS\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ORDDT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"STATREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"STATA\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ENCINF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SCHDETAIL\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SCHOFFER\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPGPORG\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"FAMILYHISTORY\")) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate static void fixSubscriberDbs() {\n\t\tLOG.info(\"Fixing Subscriber DBs\");\n\n\t\ttry {\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\tUUID emisSystem = UUID.fromString(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\");\n\t\t\tUUID emisSystemDev = UUID.fromString(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\");\n\n\t\t\tPostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig(\"EdsProtocol\");\n\n\t\t\tDate dateError = new SimpleDateFormat(\"yyyy-MM-dd\").parse(\"2018-05-11\");\n\n\t\t\tList services = serviceDal.getAll();\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tString endpointsJson = service.getEndpoints();\n\t\t\t\tif (Strings.isNullOrEmpty(endpointsJson)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Checking \" + service.getName() + \" \" + serviceId);\n\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tif (!endpointSystemId.equals(emisSystem)\n\t\t\t\t\t\t\t&& !endpointSystemId.equals(emisSystemDev)) {\n\t\t\t\t\t\tLOG.info(\" Skipping system ID \" + endpointSystemId + \" as not Emis\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId);\n\n\t\t\t\t\tboolean needsFixing = false;\n\n\t\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tList transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId);\n\t\t\t\t\t\t\tfor (ExchangeTransformAudit audit: transformAudits) {\n\t\t\t\t\t\t\t\tDate transfromStart = audit.getStarted();\n\t\t\t\t\t\t\t\tif (!transfromStart.before(dateError)) {\n\t\t\t\t\t\t\t\t\tneedsFixing = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tList batches = exchangeBatchDal.retrieveForExchangeId(exchangeId);\n\t\t\t\t\t\tExchange exchange = exchangeDal.getExchange(exchangeId);\n\t\t\t\t\t\tLOG.info(\" Posting exchange \" + exchangeId + \" with \" + batches.size() + \" batches\");\n\n\t\t\t\t\t\tList batchIds = new ArrayList<>();\n\n\t\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\n\t\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\t\tif (patientId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tUUID batchId = batch.getBatchId();\n\t\t\t\t\t\t\tbatchIds.add(batchId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray());\n\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr);\n\n\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(exchangeConfig);\n\t\t\t\t\t\tcomponent.process(exchange);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Subscriber DBs\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\t/*private static void fixReferralRequests() {\n\t\tLOG.info(\"Fixing Referral Requests\");\n\n\t\ttry {\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\tUUID emisSystem = UUID.fromString(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\");\n\t\t\tUUID emisSystemDev = UUID.fromString(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\");\n\n\t\t\tPostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig(\"EdsProtocol\");\n\n\t\t\tDate dateError = new SimpleDateFormat(\"yyyy-MM-dd\").parse(\"2018-04-24\");\n\n\t\t\tList services = serviceDal.getAll();\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tString endpointsJson = service.getEndpoints();\n\t\t\t\tif (Strings.isNullOrEmpty(endpointsJson)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Checking \" + service.getName() + \" \" + serviceId);\n\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tif (!endpointSystemId.equals(emisSystem)\n\t\t\t\t\t\t\t&& !endpointSystemId.equals(emisSystemDev)) {\n\t\t\t\t\t\tLOG.info(\" Skipping system ID \" + endpointSystemId + \" as not Emis\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId);\n\n\t\t\t\t\tboolean needsFixing = false;\n\t\t\t\t\tSet patientIdsToPost = new HashSet<>();\n\n\t\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tList transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId);\n\t\t\t\t\t\t\tfor (ExchangeTransformAudit audit: transformAudits) {\n\t\t\t\t\t\t\t\tDate transfromStart = audit.getStarted();\n\t\t\t\t\t\t\t\tif (!transfromStart.before(dateError)) {\n\t\t\t\t\t\t\t\t\tneedsFixing = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tList batches = exchangeBatchDal.retrieveForExchangeId(exchangeId);\n\t\t\t\t\t\tExchange exchange = exchangeDal.getExchange(exchangeId);\n\t\t\t\t\t\tLOG.info(\"Checking exchange \" + exchangeId + \" with \" + batches.size() + \" batches\");\n\n\t\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\n\t\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\t\tif (patientId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tUUID batchId = batch.getBatchId();\n\n\t\t\t\t\t\t\tList wrappers = resourceDal.getResourcesForBatch(serviceId, batchId);\n\n\t\t\t\t\t\t\tfor (ResourceWrapper wrapper: wrappers) {\n\t\t\t\t\t\t\t\tString resourceType = wrapper.getResourceType();\n\t\t\t\t\t\t\t\tif (!resourceType.equals(ResourceType.ReferralRequest.toString())\n\t\t\t\t\t\t\t\t\t\t|| wrapper.isDeleted()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tString json = wrapper.getResourceData();\n\t\t\t\t\t\t\t\tReferralRequest referral = (ReferralRequest)FhirSerializationHelper.deserializeResource(json);\n\n\t\t\t\t\t\t\t\t*//*if (!referral.hasServiceRequested()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tCodeableConcept reason = referral.getServiceRequested().get(0);\n\t\t\t\t\t\t\t\treferral.setReason(reason);\n\t\t\t\t\t\t\t\treferral.getServiceRequested().clear();*//*\n\n\t\t\t\t\t\t\t\tif (!referral.hasReason()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tCodeableConcept reason = referral.getReason();\n\t\t\t\t\t\t\t\treferral.setReason(null);\n\t\t\t\t\t\t\t\treferral.addServiceRequested(reason);\n\n\t\t\t\t\t\t\t\tjson = FhirSerializationHelper.serializeResource(referral);\n\t\t\t\t\t\t\t\twrapper.setResourceData(json);\n\n\t\t\t\t\t\t\t\tsaveResourceWrapper(serviceId, wrapper);\n\n\t\t\t\t\t\t\t\t//add to the set of patients we know need sending on to the protocol queue\n\t\t\t\t\t\t\t\tpatientIdsToPost.add(patientId);\n\n\t\t\t\t\t\t\t\tLOG.info(\"Fixed \" + resourceType + \" \" + wrapper.getResourceId() + \" in batch \" + batchId);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if our patient has just been fixed or was fixed before, post onto the protocol queue\n\t\t\t\t\t\t\tif (patientIdsToPost.contains(patientId)) {\n\n\t\t\t\t\t\t\t\tList batchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchIds.add(batchId);\n\n\t\t\t\t\t\t\t\tString batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray());\n\t\t\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr);\n\n\n\t\t\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(exchangeConfig);\n\t\t\t\t\t\t\t\tcomponent.process(exchange);\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Referral Requests\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}*/\n\n\tprivate static void applyEmisAdminCaches() {\n\t\tLOG.info(\"Applying Emis Admin Caches\");\n\n\t\ttry {\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\tUUID emisSystem = UUID.fromString(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\");\n\t\t\tUUID emisSystemDev = UUID.fromString(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\");\n\n\t\t\tList services = serviceDal.getAll();\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tString endpointsJson = service.getEndpoints();\n\t\t\t\tif (Strings.isNullOrEmpty(endpointsJson)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Checking \" + service.getName() + \" \" + serviceId);\n\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tif (!endpointSystemId.equals(emisSystem)\n\t\t\t\t\t\t\t&& !endpointSystemId.equals(emisSystemDev)) {\n\t\t\t\t\t\tLOG.info(\" Skipping system ID \" + endpointSystemId + \" as not Emis\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!exchangeDal.isServiceStarted(serviceId, endpointSystemId)) {\n\t\t\t\t\t\tLOG.info(\" Service not started, so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//get exchanges\n\t\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId);\n\t\t\t\t\tif (exchangeIds.isEmpty()) {\n\t\t\t\t\t\tLOG.info(\" No exchanges found, so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tUUID firstExchangeId = exchangeIds.get(0);\n\n\t\t\t\t\tList events = exchangeDal.getExchangeEvents(firstExchangeId);\n\t\t\t\t\tboolean appliedAdminCache = false;\n\t\t\t\t\tfor (ExchangeEvent event: events) {\n\t\t\t\t\t\tif (event.getEventDesc().equals(\"Applied Emis Admin Resource Cache\")) {\n\t\t\t\t\t\t\tappliedAdminCache = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (appliedAdminCache) {\n\t\t\t\t\t\tLOG.info(\" Have already applied admin cache, so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tExchange exchange = exchangeDal.getExchange(firstExchangeId);\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyOldWay(body);\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tLOG.info(\" No files in exchange \" + firstExchangeId + \" so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString firstFilePath = files[0];\n\t\t\t\t\tString name = FilenameUtils.getBaseName(firstFilePath); //file name without extension\n\t\t\t\t\tString[] toks = name.split(\"_\");\n\t\t\t\t\tif (toks.length != 5) {\n\t\t\t\t\t\tthrow new TransformException(\"Failed to extract data sharing agreement GUID from filename \" + firstFilePath);\n\t\t\t\t\t}\n\t\t\t\t\tString sharingAgreementGuid = toks[4];\n\n\t\t\t\t\tList batchIds = new ArrayList<>();\n\t\t\t\t\tTransformError transformError = new TransformError();\n\t\t\t\t\tFhirResourceFiler fhirResourceFiler = new FhirResourceFiler(firstExchangeId, serviceId, endpointSystemId, transformError, batchIds);\n\n\t\t\t\t\tEmisCsvHelper csvHelper = new EmisCsvHelper(fhirResourceFiler.getServiceId(), fhirResourceFiler.getSystemId(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfhirResourceFiler.getExchangeId(), sharingAgreementGuid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrue);\n\n\t\t\t\t\tExchangeTransformAudit transformAudit = new ExchangeTransformAudit();\n\t\t\t\t\ttransformAudit.setServiceId(serviceId);\n\t\t\t\t\ttransformAudit.setSystemId(endpointSystemId);\n\t\t\t\t\ttransformAudit.setExchangeId(firstExchangeId);\n\t\t\t\t\ttransformAudit.setId(UUID.randomUUID());\n\t\t\t\t\ttransformAudit.setStarted(new Date());\n\n\t\t\t\t\tLOG.info(\" Going to apply admin resource cache\");\n\t\t\t\t\tcsvHelper.applyAdminResourceCache(fhirResourceFiler);\n\n\t\t\t\t\tfhirResourceFiler.waitToFinish();\n\n\t\t\t\t\tfor (UUID batchId: batchIds) {\n\t\t\t\t\t\tLOG.info(\" Created batch ID \" + batchId + \" for exchange \" + firstExchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\ttransformAudit.setEnded(new Date());\n\t\t\t\t\ttransformAudit.setNumberBatchesCreated(new Integer(batchIds.size()));\n\n\t\t\t\t\tboolean hadError = false;\n\t\t\t\t\tif (transformError.getError().size() > 0) {\n\t\t\t\t\t\ttransformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError));\n\t\t\t\t\t\thadError = true;\n\t\t\t\t\t}\n\n\t\t\t\t\texchangeDal.save(transformAudit);\n\n\t\t\t\t\t//clear down the cache of reference mappings since they won't be of much use for the next Exchange\n\t\t\t\t\tIdHelper.clearCache();\n\n\t\t\t\t\tif (hadError) {\n\t\t\t\t\t\tLOG.error(\" <<<<< exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE);\n\n\t\t\t//sorting by timestamp seems unreliable when exchanges were posted close together?\n\t\t\tList tmp = new ArrayList<>();\n\t\t\tfor (int i=exchanges.size()-1; i>=0; i--) {\n\t\t\t\tExchange exchange = exchanges.get(i);\n\t\t\t\ttmp.add(exchange);\n\t\t\t}\n\t\t\texchanges = tmp;\n\t\t\t/*exchanges.sort((o1, o2) -> {\n\t\t\t\tDate d1 = o1.getTimestamp();\n\t\t\t\tDate d2 = o2.getTimestamp();\n\t\t\t\treturn d1.compareTo(d2);\n\t\t\t});*/\n\n\t\t\tLOG.info(\"Found \" + exchanges.size() + \" exchanges\");\n\t\t\t//continueOrQuit();\n\n\t\t\t//find the files for each exchange\n\t\t\tMap> hmExchangeFiles = new HashMap<>();\n\t\t\tMap> hmExchangeFilesWithoutStoragePrefix = new HashMap<>();\n\t\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\t\t//populate a map of the files with the shared storage prefix\n\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody);\n\t\t\t\tList fileList = Lists.newArrayList(files);\n\t\t\t\thmExchangeFiles.put(exchange, fileList);\n\n\t\t\t\t//populate a map of the same files without the prefix\n\t\t\t\tfiles = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody);\n\t\t\t\tfor (int i=0; i=0; i--) {\n\t\t\t\tExchange exchange = exchanges.get(i);\n\t\t\t\tboolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles);\n\n\t\t\t\tif (disabled) {\n\t\t\t\t\tindexDisabled = i;\n\n\t\t\t\t} else {\n\t\t\t\t\tif (indexDisabled == -1) {\n\t\t\t\t\t\tindexRebulked = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if we've found a non-disabled extract older than the disabled ones,\n\t\t\t\t\t\t//then we've gone far enough back\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//go back from when disabled to find the previous bulk load (i.e. the first one or one after it was previously not disabled)\n\t\t\tfor (int i=indexDisabled-1; i>=0; i--) {\n\t\t\t\tExchange exchange = exchanges.get(i);\n\t\t\t\tboolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles);\n\t\t\t\tif (disabled) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tindexOriginallyBulked = i;\n\t\t\t}\n\n\t\t\tif (indexDisabled == -1\n\t\t\t\t\t|| indexRebulked == -1\n\t\t\t\t\t|| indexOriginallyBulked == -1) {\n\t\t\t\tthrow new Exception(\"Failed to find exchanges for disabling (\" + indexDisabled + \"), re-bulking (\" + indexRebulked + \") or original bulk (\" + indexOriginallyBulked + \")\");\n\t\t\t}\n\n\t\t\tExchange exchangeDisabled = exchanges.get(indexDisabled);\n\t\t\tLOG.info(\"Disabled on \" + findExtractDate(exchangeDisabled, hmExchangeFiles) + \" \" + exchangeDisabled.getId());\n\n\t\t\tExchange exchangeRebulked = exchanges.get(indexRebulked);\n\t\t\tLOG.info(\"Rebulked on \" + findExtractDate(exchangeRebulked, hmExchangeFiles) + \" \" + exchangeRebulked.getId());\n\n\t\t\tExchange exchangeOriginallyBulked = exchanges.get(indexOriginallyBulked);\n\t\t\tLOG.info(\"Originally bulked on \" + findExtractDate(exchangeOriginallyBulked, hmExchangeFiles) + \" \" + exchangeOriginallyBulked.getId());\n\n\t\t\t//continueOrQuit();\n\n\t\t\tList rebulkFiles = hmExchangeFiles.get(exchangeRebulked);\n\n\t\t\tList tempFilesCreated = new ArrayList<>();\n\n\t\t\tSet patientGuidsDeletedOrTooOld = new HashSet<>();\n\n\t\t\tfor (String rebulkFile: rebulkFiles) {\n\t\t\t\tString fileType = findFileType(rebulkFile);\n\t\t\t\tif (!isPatientFile(fileType)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing \" + fileType);\n\n\t\t\t\tString guidColumnName = getGuidColumnName(fileType);\n\n\t\t\t\t//find all the guids in the re-bulk\n\t\t\t\tSet idsInRebulk = new HashSet<>();\n\n\t\t\t\tInputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(rebulkFile);\n\t\t\t\tCSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT);\n\n\t\t\t\tString[] headers = null;\n\t\t\t\ttry {\n\t\t\t\t\theaders = CsvHelper.getHeaderMapAsArray(csvParser);\n\n\t\t\t\t\tIterator iterator = csvParser.iterator();\n\n\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\tCSVRecord record = iterator.next();\n\n\t\t\t\t\t\t//get the patient and row guid out of the file and cache in our set\n\t\t\t\t\t\tString id = record.get(\"PatientGuid\");\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(guidColumnName)) {\n\t\t\t\t\t\t\tid += \"//\" + record.get(guidColumnName);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tidsInRebulk.add(id);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tcsvParser.close();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Found \" + idsInRebulk.size() + \" IDs in re-bulk file: \" + rebulkFile);\n\n\t\t\t\t//create a replacement file for the exchange the service was disabled\n\t\t\t\tString replacementDisabledFile = null;\n\t\t\t\tList disabledFiles = hmExchangeFilesWithoutStoragePrefix.get(exchangeDisabled);\n\t\t\t\tfor (String s: disabledFiles) {\n\t\t\t\t\tString disabledFileType = findFileType(s);\n\t\t\t\t\tif (disabledFileType.equals(fileType)) {\n\n\t\t\t\t\t\treplacementDisabledFile = FilenameUtils.concat(tempDir, s);\n\n\t\t\t\t\t\tFile dir = new File(replacementDisabledFile).getParentFile();\n\t\t\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\t\t\tif (!dir.mkdirs()) {\n\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to create directory \" + dir);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttempFilesCreated.add(s);\n\t\t\t\t\t\tLOG.info(\"Created replacement file \" + replacementDisabledFile);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tFileWriter fileWriter = new FileWriter(replacementDisabledFile);\n\t\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(fileWriter);\n\t\t\t\tCSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers));\n\t\t\t\tcsvPrinter.flush();\n\n\t\t\t\tSet pastIdsProcessed = new HashSet<>();\n\n\t\t\t\t//now go through all files of the same type PRIOR to the service was disabled\n\t\t\t\t//to find any rows that we'll need to explicitly delete because they were deleted while\n\t\t\t\t//the extract was disabled\n\t\t\t\tfor (int i=indexDisabled-1; i>=indexOriginallyBulked; i--) {\n\t\t\t\t\tExchange exchange = exchanges.get(i);\n\n\t\t\t\t\tString originalFile = null;\n\n\t\t\t\t\tList files = hmExchangeFiles.get(exchange);\n\t\t\t\t\tfor (String s: files) {\n\t\t\t\t\t\tString originalFileType = findFileType(s);\n\t\t\t\t\t\tif (originalFileType.equals(fileType)) {\n\t\t\t\t\t\t\toriginalFile = s;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (originalFile == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\" Reading \" + originalFile);\n\t\t\t\t\treader = FileHelper.readFileReaderFromSharedStorage(originalFile);\n\t\t\t\t\tcsvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator iterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord record = iterator.next();\n\t\t\t\t\t\t\tString patientGuid = record.get(\"PatientGuid\");\n\n\t\t\t\t\t\t\t//get the patient and row guid out of the file and cache in our set\n\t\t\t\t\t\t\tString uniqueId = patientGuid;\n\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(guidColumnName)) {\n\t\t\t\t\t\t\t\tuniqueId += \"//\" + record.get(guidColumnName);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if we're already handled this record in a more recent extract, then skip it\n\t\t\t\t\t\t\tif (pastIdsProcessed.contains(uniqueId)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpastIdsProcessed.add(uniqueId);\n\n\t\t\t\t\t\t\t//if this ID isn't deleted and isn't in the re-bulk then it means\n\t\t\t\t\t\t\t//it WAS deleted in Emis Web but we didn't receive the delete, because it was deleted\n\t\t\t\t\t\t\t//from Emis Web while the extract feed was disabled\n\n\t\t\t\t\t\t\t//if the record is deleted, then we won't expect it in the re-bulk\n\t\t\t\t\t\t\tboolean deleted = Boolean.parseBoolean(record.get(\"Deleted\"));\n\t\t\t\t\t\t\tif (deleted) {\n\n\t\t\t\t\t\t\t\t//if it's the Patient file, stick the patient GUID in a set so we know full patient record deletes\n\t\t\t\t\t\t\t\tif (fileType.equals(\"Admin_Patient\")) {\n\t\t\t\t\t\t\t\t\tpatientGuidsDeletedOrTooOld.add(patientGuid);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if it's not the patient file and we refer to a patient that we know\n\t\t\t\t\t\t\t//has been deleted, then skip this row, since we know we're deleting the entire patient record\n\t\t\t\t\t\t\tif (patientGuidsDeletedOrTooOld.contains(patientGuid)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if the re-bulk contains a record matching this one, then it's OK\n\t\t\t\t\t\t\tif (idsInRebulk.contains(uniqueId)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//the rebulk won't contain any data for patients that are now too old (i.e. deducted or deceased > 2 yrs ago),\n\t\t\t\t\t\t\t//so any patient ID in the original files but not in the rebulk can be treated like this and any data for them can be skipped\n\t\t\t\t\t\t\tif (fileType.equals(\"Admin_Patient\")) {\n\n\t\t\t\t\t\t\t\t//retrieve the Patient and EpisodeOfCare resource for the patient so we can confirm they are deceased or deducted\n\t\t\t\t\t\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\t\t\t\t\t\tUUID patientUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.Patient, patientGuid);\n\n\t\t\t\t\t\t\t\tPatient patientResource = (Patient)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.Patient, patientUuid.toString());\n\t\t\t\t\t\t\t\tif (patientResource.hasDeceased()) {\n\t\t\t\t\t\t\t\t\tpatientGuidsDeletedOrTooOld.add(patientGuid);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tUUID episodeUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.EpisodeOfCare, patientGuid); //we use the patient GUID for the episode too\n\t\t\t\t\t\t\t\tEpisodeOfCare episodeResource = (EpisodeOfCare)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.EpisodeOfCare, episodeUuid.toString());\n\t\t\t\t\t\t\t\tif (episodeResource.hasPeriod()\n\t\t\t\t\t\t\t\t\t\t&& !PeriodHelper.isActive(episodeResource.getPeriod())) {\n\n\t\t\t\t\t\t\t\t\tpatientGuidsDeletedOrTooOld.add(patientGuid);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//create a new CSV record, carrying over the GUIDs from the original but marking as deleted\n\t\t\t\t\t\t\tString[] newRecord = new String[headers.length];\n\n\t\t\t\t\t\t\tfor (int j=0; j 0) {\n\t\t\t\t\t\t\t\t\tsb.append(\",\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsb.append(record.get(j));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tLOG.info(sb.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcsvPrinter.flush();\n\t\t\t\tcsvPrinter.close();\n\n\n\n\t\t\t\t//also create a version of the CSV file with just the header and nothing else in\n\t\t\t\tfor (int i=indexDisabled+1; i exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex);\n\t\t\t\t\tfor (String s: exchangeFiles) {\n\t\t\t\t\t\tString exchangeFileType = findFileType(s);\n\t\t\t\t\t\tif (exchangeFileType.equals(fileType)) {\n\n\t\t\t\t\t\t\tString emptyTempFile = FilenameUtils.concat(tempDir, s);\n\n\t\t\t\t\t\t\tFile dir = new File(emptyTempFile).getParentFile();\n\t\t\t\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\t\t\t\tif (!dir.mkdirs()) {\n\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to create directory \" + dir);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfileWriter = new FileWriter(emptyTempFile);\n\t\t\t\t\t\t\tbufferedWriter = new BufferedWriter(fileWriter);\n\t\t\t\t\t\t\tcsvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers));\n\t\t\t\t\t\t\tcsvPrinter.flush();\n\t\t\t\t\t\t\tcsvPrinter.close();\n\n\t\t\t\t\t\t\ttempFilesCreated.add(s);\n\t\t\t\t\t\t\tLOG.info(\"Created empty file \" + emptyTempFile);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we also need to copy the restored sharing agreement file to replace all the period it was disabled\n\t\t\tString rebulkedSharingAgreementFile = null;\n\t\t\tfor (String s: rebulkFiles) {\n\t\t\t\tString fileType = findFileType(s);\n\t\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\t\t\t\t\trebulkedSharingAgreementFile = s;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i=indexDisabled; i exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex);\n\t\t\t\tfor (String s: exchangeFiles) {\n\t\t\t\t\tString exchangeFileType = findFileType(s);\n\t\t\t\t\tif (exchangeFileType.equals(\"Agreements_SharingOrganisation\")) {\n\n\t\t\t\t\t\tString replacementFile = FilenameUtils.concat(tempDir, s);\n\n\t\t\t\t\t\tInputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkedSharingAgreementFile);\n\t\t\t\t\t\tFiles.copy(inputStream, new File(replacementFile).toPath());\n\t\t\t\t\t\tinputStream.close();\n\n\t\t\t\t\t\ttempFilesCreated.add(s);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//create a script to copy the files into S3\n\t\t\tList copyScript = new ArrayList<>();\n\t\t\tcopyScript.add(\"#!/bin/bash\");\n\t\t\tcopyScript.add(\"\");\n\t\t\tfor (String s: tempFilesCreated) {\n\t\t\t\tString localFile = FilenameUtils.concat(tempDir, s);\n\t\t\t\tcopyScript.add(\"sudo aws s3 cp \" + localFile + \" s3://discoverysftplanding/endeavour/\" + s);\n\t\t\t}\n\n\t\t\tString scriptFile = FilenameUtils.concat(tempDir, \"copy.sh\");\n\t\t\tFileUtils.writeLines(new File(scriptFile), copyScript);\n\n\t\t\t/*continueOrQuit();\n\n\t\t\t//back up every file where the service was disabled\n\t\t\tfor (int i=indexDisabled; i files = hmExchangeFiles.get(exchange);\n\t\t\t\tfor (String file: files) {\n\t\t\t\t\t//first download from S3 to the local temp dir\n\t\t\t\t\tInputStream inputStream = FileHelper.readFileFromSharedStorage(file);\n\t\t\t\t\tString fileName = FilenameUtils.getName(file);\n\t\t\t\t\tString tempPath = FilenameUtils.concat(tempDir, fileName);\n\t\t\t\t\tFile downloadDestination = new File(tempPath);\n\n\t\t\t\t\tFiles.copy(inputStream, downloadDestination.toPath());\n\n\t\t\t\t\t//then write back to S3 in a sub-dir of the original file\n\t\t\t\t\tString backupPath = FilenameUtils.getPath(file);\n\t\t\t\t\tbackupPath = FilenameUtils.concat(backupPath, \"Original\");\n\t\t\t\t\tbackupPath = FilenameUtils.concat(backupPath, fileName);\n\n\t\t\t\t\tFileHelper.writeFileToSharedStorage(backupPath, downloadDestination);\n\t\t\t\t\tLOG.info(\"Backed up \" + file + \" -> \" + backupPath);\n\n\t\t\t\t\t//delete from temp dir\n\t\t\t\t\tdownloadDestination.delete();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinueOrQuit();\n\n\t\t\t//copy the new CSV files into the dir where it was disabled\n\t\t\tList disabledFiles = hmExchangeFiles.get(exchangeDisabled);\n\t\t\tfor (String disabledFile: disabledFiles) {\n\t\t\t\tString fileType = findFileType(disabledFile);\n\t\t\t\tif (!isPatientFile(fileType)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString tempFile = FilenameUtils.concat(tempDirLast.getAbsolutePath(), fileType + \".csv\");\n\t\t\t\tFile f = new File(tempFile);\n\t\t\t\tif (!f.exists()) {\n\t\t\t\t\tthrow new Exception(\"Failed to find expected temp file \" + f);\n\t\t\t\t}\n\n\t\t\t\tFileHelper.writeFileToSharedStorage(disabledFile, f);\n\t\t\t\tLOG.info(\"Copied \" + tempFile + \" -> \" + disabledFile);\n\t\t\t}\n\n\t\t\tcontinueOrQuit();\n\n\t\t\t//empty the patient files for any extracts while the service was disabled\n\t\t\tfor (int i=indexDisabled+1; i otherDisabledFiles = hmExchangeFiles.get(otherExchangeDisabled);\n\t\t\t\tfor (String otherDisabledFile: otherDisabledFiles) {\n\t\t\t\t\tString fileType = findFileType(otherDisabledFile);\n\t\t\t\t\tif (!isPatientFile(fileType)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString tempFile = FilenameUtils.concat(tempDirEmpty.getAbsolutePath(), fileType + \".csv\");\n\t\t\t\t\tFile f = new File(tempFile);\n\t\t\t\t\tif (!f.exists()) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find expected empty file \" + f);\n\t\t\t\t\t}\n\n\t\t\t\t\tFileHelper.writeFileToSharedStorage(otherDisabledFile, f);\n\t\t\t\t\tLOG.info(\"Copied \" + tempFile + \" -> \" + otherDisabledFile);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinueOrQuit();\n\n\t\t\t//copy the content of the sharing agreement file from when it was re-bulked\n\t\t\tfor (String rebulkFile: rebulkFiles) {\n\t\t\t\tString fileType = findFileType(rebulkFile);\n\t\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\n\t\t\t\t\tString tempFile = FilenameUtils.concat(tempDir, fileType + \".csv\");\n\t\t\t\t\tFile downloadDestination = new File(tempFile);\n\n\t\t\t\t\tInputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkFile);\n\t\t\t\t\tFiles.copy(inputStream, downloadDestination.toPath());\n\n\t\t\t\t\ttempFilesCreated.add(tempFile);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//replace the sharing agreement file for all disabled extracts with the non-disabled one\n\t\t\tfor (int i=indexDisabled; i files = hmExchangeFiles.get(exchange);\n\t\t\t\tfor (String file: files) {\n\t\t\t\t\tString fileType = findFileType(file);\n\t\t\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\n\t\t\t\t\t\tString tempFile = FilenameUtils.concat(tempDir, fileType + \".csv\");\n\t\t\t\t\t\tFile f = new File(tempFile);\n\t\t\t\t\t\tif (!f.exists()) {\n\t\t\t\t\t\t\tthrow new Exception(\"Failed to find expected empty file \" + f);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tFileHelper.writeFileToSharedStorage(file, f);\n\t\t\t\t\t\tLOG.info(\"Copied \" + tempFile + \" -> \" + file);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Disabled Emis Extracts Prior to Re-bulk for service \" + serviceId);\n\t\t\tcontinueOrQuit();\n\n\t\t\tfor (String tempFileCreated: tempFilesCreated) {\n\t\t\t\tFile f = new File(tempFileCreated);\n\t\t\t\tif (f.exists()) {\n\t\t\t\t\tf.delete();\n\t\t\t\t}\n\t\t\t}*/\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}\n\n\tprivate static String findExtractDate(Exchange exchange, Map> fileMap) throws Exception {\n\t\tList files = fileMap.get(exchange);\n\t\tString file = findSharingAgreementFile(files);\n\t\tString name = FilenameUtils.getBaseName(file);\n\t\tString[] toks = name.split(\"_\");\n\t\treturn toks[3];\n\t}\n\n\tprivate static boolean isDisabledInSharingAgreementFile(Exchange exchange, Map> fileMap) throws Exception {\n\t\tList files = fileMap.get(exchange);\n\t\tString file = findSharingAgreementFile(files);\n\n\t\tInputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(file);\n\t\tCSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT);\n\t\ttry {\n\t\t\tIterator iterator = csvParser.iterator();\n\t\t\tCSVRecord record = iterator.next();\n\n\t\t\tString s = record.get(\"Disabled\");\n\t\t\tboolean disabled = Boolean.parseBoolean(s);\n\t\t\treturn disabled;\n\n\t\t} finally {\n\t\t\tcsvParser.close();\n\t\t}\n\t}\n\n\tprivate static void continueOrQuit() throws Exception {\n\t\tLOG.info(\"Enter y to continue, anything else to quit\");\n\n\t\tbyte[] bytes = new byte[10];\n\t\tSystem.in.read(bytes);\n\t\tchar c = (char)bytes[0];\n\t\tif (c != 'y' && c != 'Y') {\n\t\t\tSystem.out.println(\"Read \" + c);\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate static String getGuidColumnName(String fileType) {\n\t\tif (fileType.equals(\"Admin_Patient\")) {\n\t\t\t//patient file just has patient GUID, nothing extra\n\t\t\treturn null;\n\n\t\t} else if (fileType.equals(\"CareRecord_Consultation\")) {\n\t\t\treturn \"ConsultationGuid\";\n\n\t\t} else if (fileType.equals(\"CareRecord_Diary\")) {\n\t\t\treturn \"DiaryGuid\";\n\n\t\t} else if (fileType.equals(\"CareRecord_Observation\")) {\n\t\t\treturn \"ObservationGuid\";\n\n\t\t} else if (fileType.equals(\"CareRecord_Problem\")) {\n\t\t\t//there is no separate problem GUID, as it's just a modified observation\n\t\t\treturn \"ObservationGuid\";\n\n\t\t} else if (fileType.equals(\"Prescribing_DrugRecord\")) {\n\t\t\treturn \"DrugRecordGuid\";\n\n\t\t} else if (fileType.equals(\"Prescribing_IssueRecord\")) {\n\t\t\treturn \"IssueRecordGuid\";\n\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(fileType);\n\t\t}\n\t}\n\n\tprivate static String findFileType(String filePath) {\n\t\tString fileName = FilenameUtils.getName(filePath);\n\t\tString[] toks = fileName.split(\"_\");\n\t\tString domain = toks[1];\n\t\tString name = toks[2];\n\n\t\treturn domain + \"_\" + name;\n\t}\n\n\tprivate static boolean isPatientFile(String fileType) {\n\t\tif (fileType.equals(\"Admin_Patient\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Consultation\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Diary\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Observation\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Problem\")\n\t\t\t\t|| fileType.equals(\"Prescribing_DrugRecord\")\n\t\t\t\t|| fileType.equals(\"Prescribing_IssueRecord\")) {\n\t\t\t//note the referral file doesn't have a Deleted column, so isn't in this list\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate static String findSharingAgreementFile(List files) throws Exception {\n\n\t\tfor (String file : files) {\n\t\t\tString fileType = findFileType(file);\n\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\t\t\t\treturn file;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Exception(\"Failed to find sharing agreement file in \" + files.get(0));\n\t}\n\n\n\n\tprivate static void testSlack() {\n\t\tLOG.info(\"Testing slack\");\n\n\t\ttry {\n\t\t\tSlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, \"Test Message from Queue Reader\");\n\t\t\tLOG.info(\"Finished testing slack\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}\n\n\tprivate static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) {\n\n\t\ttry {\n\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\t\tService service = serviceDalI.getById(serviceId);\n\t\t\tLOG.info(\"Posting to inbound exchange for \" + service.getName() + \" from file \" + filePath);\n\n\t\t\tFileReader fr = new FileReader(filePath);\n\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\tint count = 0;\n\t\t\tList exchangeIdBatch = new ArrayList<>();\n\n\t\t\twhile (true) {\n\t\t\t\tString line = br.readLine();\n\t\t\t\tif (line == null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tUUID exchangeId = UUID.fromString(line);\n\n\t\t\t\t//update the transform audit, so EDS UI knows we've re-queued this exchange\n\t\t\t\tExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId);\n\t\t\t\tif (audit != null\n\t\t\t\t\t\t&& !audit.isResubmitted()) {\n\t\t\t\t\taudit.setResubmitted(true);\n\t\t\t\t\tauditRepository.save(audit);\n\t\t\t\t}\n\n\t\t\t\tcount ++;\n\t\t\t\texchangeIdBatch.add(exchangeId);\n\t\t\t\tif (exchangeIdBatch.size() >= 1000) {\n\t\t\t\t\tQueueHelper.postToExchange(exchangeIdBatch, \"EdsInbound\", null, false);\n\t\t\t\t\texchangeIdBatch = new ArrayList<>();\n\t\t\t\t\tLOG.info(\"Done \" + count);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!exchangeIdBatch.isEmpty()) {\n\t\t\t\tQueueHelper.postToExchange(exchangeIdBatch, \"EdsInbound\", null, false);\n\t\t\t\tLOG.info(\"Done \" + count);\n\t\t\t}\n\n\t\t\tbr.close();\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Posting to inbound for \" + serviceId);\n\t}\n\n\t/*private static void postToInbound(UUID serviceId, boolean all) {\n\t\tLOG.info(\"Posting to inbound for \" + serviceId);\n\n\t\ttry {\n\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\t\tService service = serviceDalI.getById(serviceId);\n\n\t\t\tList systemIds = findSystemIds(service);\n\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\tExchangeTransformErrorState errorState = auditRepository.getErrorState(serviceId, systemId);\n\n\t\t\tfor (UUID exchangeId: errorState.getExchangeIdsInError()) {\n\n\t\t\t\t//update the transform audit, so EDS UI knows we've re-queued this exchange\n\t\t\t\tExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId);\n\n\t\t\t\t//skip any exchange IDs we've already re-queued up to be processed again\n\t\t\t\tif (audit.isResubmitted()) {\n\t\t\t\t\tLOG.debug(\"Not re-posting \" + audit.getExchangeId() + \" as it's already been resubmitted\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.debug(\"Re-posting \" + audit.getExchangeId());\n\t\t\t\taudit.setResubmitted(true);\n\t\t\t\tauditRepository.save(audit);\n\n\t\t\t\t//then re-submit the exchange to Rabbit MQ for the queue reader to pick up\n\t\t\t\tQueueHelper.postToExchange(exchangeId, \"EdsInbound\", null, false);\n\n\t\t\t\tif (!all) {\n\t\t\t\t\tLOG.info(\"Posted first exchange, so stopping\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Posting to inbound for \" + serviceId);\n\t}*/\n\n\t/*private static void fixPatientSearch(String serviceId) {\n\t\tLOG.info(\"Fixing patient search for \" + serviceId);\n\n\t\ttry {\n\n\t\t\tUUID serviceUuid = UUID.fromString(serviceId);\n\n\t\t\tExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDalI = DalProvider.factoryResourceDal();\n\t\t\tPatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal();\n\t\t\tParserPool parser = new ParserPool();\n\n\t\t\tSet patientsDone = new HashSet<>();\n\n\t\t\tList exchanges = exchangeDalI.getExchangeIdsForService(serviceUuid);\n\t\t\tLOG.info(\"Found \" + exchanges.size() + \" exchanges\");\n\n\t\t\tfor (UUID exchangeId: exchanges) {\n\t\t\t\tList batches = exchangeBatchDalI.retrieveForExchangeId(exchangeId);\n\t\t\t\tLOG.info(\"Found \" + batches.size() + \" batches in exchange \" + exchangeId);\n\n\t\t\t\tfor (ExchangeBatch batch: batches) {\n\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\tif (patientId == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (patientsDone.contains(patientId)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper wrapper = resourceDalI.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId);\n\t\t\t\t\tif (wrapper != null) {\n\t\t\t\t\t\tString json = wrapper.getResourceData();\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(json)) {\n\n\t\t\t\t\t\t\tPatient fhirPatient = (Patient) parser.parse(json);\n\t\t\t\t\t\t\tUUID systemUuid = wrapper.getSystemId();\n\n\t\t\t\t\t\t\tpatientSearchDal.update(serviceUuid, systemUuid, fhirPatient);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tpatientsDone.add(patientId);\n\n\t\t\t\t\tif (patientsDone.size() % 1000 == 0) {\n\t\t\t\t\t\tLOG.info(\"Done \" + patientsDone.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished fixing patient search for \" + serviceId);\n\t}*/\n\n\tprivate static void runSql(String host, String username, String password, String sqlFile) {\n\t\tLOG.info(\"Running SQL on \" + host + \" from \" + sqlFile);\n\n\t\tConnection conn = null;\n\t\tStatement statement = null;\n\n\n\t\ttry {\n\t\t\tFile f = new File(sqlFile);\n\t\t\tif (!f.exists()) {\n\t\t\t\tLOG.error(\"\" + f + \" doesn't exist\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tList lines = FileUtils.readLines(f);\n\t\t\t/*String combined = String.join(\"\\n\", lines);\n\n\t\t\tLOG.info(\"Going to run SQL\");\n\t\t\tLOG.info(combined);*/\n\n\t\t\t//load driver\n\t\t\tClass.forName(\"com.mysql.cj.jdbc.Driver\");\n\n\t\t\t//create connection\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(\"user\", username);\n\t\t\tprops.setProperty(\"password\", password);\n\n\t\t\tconn = DriverManager.getConnection(host, props);\n\t\t\tLOG.info(\"Opened connection\");\n\t\t\tstatement = conn.createStatement();\n\n\t\t\tlong totalStart = System.currentTimeMillis();\n\n\t\t\tfor (String sql: lines) {\n\n\t\t\t\tsql = sql.trim();\n\n\t\t\t\tif (sql.startsWith(\"--\")\n\t\t\t\t\t\t|| sql.startsWith(\"/*\")\n\t\t\t\t\t\t|| Strings.isNullOrEmpty(sql)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"\");\n\t\t\t\tLOG.info(sql);\n\n\t\t\t\tlong start = System.currentTimeMillis();\n\n\t\t\t\tboolean hasResultSet = statement.execute(sql);\n\n\t\t\t\tlong end = System.currentTimeMillis();\n\t\t\t\tLOG.info(\"SQL took \" + (end - start) + \"ms\");\n\n\t\t\t\tif (hasResultSet) {\n\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tResultSet rs = statement.getResultSet();\n\t\t\t\t\t\tint cols = rs.getMetaData().getColumnCount();\n\n\t\t\t\t\t\tList colHeaders = new ArrayList<>();\n\t\t\t\t\t\tfor (int i = 0; i < cols; i++) {\n\t\t\t\t\t\t\tString header = rs.getMetaData().getColumnName(i + 1);\n\t\t\t\t\t\t\tcolHeaders.add(header);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tString colHeaderStr = String.join(\", \", colHeaders);\n\t\t\t\t\t\tLOG.info(colHeaderStr);\n\n\t\t\t\t\t\twhile (rs.next()) {\n\t\t\t\t\t\t\tList row = new ArrayList<>();\n\t\t\t\t\t\t\tfor (int i = 0; i < cols; i++) {\n\t\t\t\t\t\t\t\tObject o = rs.getObject(i + 1);\n\t\t\t\t\t\t\t\tif (rs.wasNull()) {\n\t\t\t\t\t\t\t\t\trow.add(\"\");\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trow.add(o.toString());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tString rowStr = String.join(\", \", row);\n\t\t\t\t\t\t\tLOG.info(rowStr);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!statement.getMoreResults()) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tint updateCount = statement.getUpdateCount();\n\t\t\t\t\tLOG.info(\"Updated \" + updateCount + \" Row(s)\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlong totalEnd = System.currentTimeMillis();\n\t\t\tLOG.info(\"\");\n\t\t\tLOG.info(\"Total time taken \" + (totalEnd - totalStart) + \"ms\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t} finally {\n\n\t\t\tif (statement != null) {\n\t\t\t\ttry {\n\t\t\t\t\tstatement.close();\n\t\t\t\t} catch (Exception ex) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (conn != null) {\n\t\t\t\ttry {\n\t\t\t\t\tconn.close();\n\t\t\t\t} catch (Exception ex) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tLOG.info(\"Closed connection\");\n\t\t}\n\n\t\tLOG.info(\"Finished Testing DB Size Limit\");\n\t}\n\n\n\n\t/*private static void fixExchangeBatches() {\n\t\tLOG.info(\"Starting Fixing Exchange Batches\");\n\n\t\ttry {\n\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDalI = DalProvider.factoryResourceDal();\n\n\t\t\tList services = serviceDalI.getAll();\n\t\t\tfor (Service service: services) {\n\t\t\t\tLOG.info(\"Doing \" + service.getName());\n\n\t\t\t\tList exchangeIds = exchangeDalI.getExchangeIdsForService(service.getId());\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\t\t\t\t\tLOG.info(\" Exchange \" + exchangeId);\n\n\t\t\t\t\tList exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch exchangeBatch: exchangeBatches) {\n\n\t\t\t\t\t\tif (exchangeBatch.getEdsPatientId() != null) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tList resources = resourceDalI.getResourcesForBatch(exchangeBatch.getBatchId());\n\t\t\t\t\t\tif (resources.isEmpty()) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tResourceWrapper first = resources.get(0);\n\t\t\t\t\t\tUUID patientId = first.getPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\texchangeBatch.setEdsPatientId(patientId);\n\t\t\t\t\t\t\texchangeBatchDalI.save(exchangeBatch);\n\t\t\t\t\t\t\tLOG.info(\"Fixed batch \" + exchangeBatch.getBatchId() + \" -> \" + exchangeBatch.getEdsPatientId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Exchange Batches\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/**\n\t * exports ADT Encounters for patients based on a CSV file produced using the below SQL\n\t --USE EDS DATABASE\n\n\t -- barts b5a08769-cbbe-4093-93d6-b696cd1da483\n\t -- homerton 962d6a9a-5950-47ac-9e16-ebee56f9507a\n\n\t create table adt_patients (\n\t service_id character(36),\n\t system_id character(36),\n\t nhs_number character varying(10),\n\t patient_id character(36)\n\t );\n\n\t -- delete from adt_patients;\n\n\t select * from patient_search limit 10;\n\t select * from patient_link limit 10;\n\n\t insert into adt_patients\n\t select distinct ps.service_id, ps.system_id, ps.nhs_number, ps.patient_id\n\t from patient_search ps\n\t join patient_link pl\n\t on pl.patient_id = ps.patient_id\n\t join patient_link pl2\n\t on pl.person_id = pl2.person_id\n\t join patient_search ps2\n\t on ps2.patient_id = pl2.patient_id\n\t where\n\t ps.service_id IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a')\n\t and ps2.service_id NOT IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a');\n\n\n\t select count(1) from adt_patients limit 100;\n\t select * from adt_patients limit 100;\n\n\n\n\n\t ---MOVE TABLE TO HL7 RECEIVER DB\n\n\t select count(1) from adt_patients;\n\n\t -- top 1000 patients with messages\n\n\t select * from mapping.resource_uuid where resource_type = 'Patient' limit 10;\n\n\t select * from log.message limit 10;\n\n\t create table adt_patient_counts (\n\t nhs_number character varying(100),\n\t count int\n\t );\n\n\t insert into adt_patient_counts\n\t select pid1, count(1)\n\t from log.message\n\t where pid1 is not null\n\t and pid1 <> ''\n\t group by pid1;\n\n\t select * from adt_patient_counts order by count desc limit 100;\n\n\t alter table adt_patients\n\t add count int;\n\n\t update adt_patients\n\t set count = adt_patient_counts.count\n\t from adt_patient_counts\n\t where adt_patients.nhs_number = adt_patient_counts.nhs_number;\n\n\t select count(1) from adt_patients where nhs_number is null;\n\n\t select * from adt_patients\n\t where nhs_number is not null\n\t and count is not null\n\t order by count desc limit 1000;\n\t */\n\t/*private static void exportHl7Encounters(String sourceCsvPath, String outputPath) {\n\t\tLOG.info(\"Exporting HL7 Encounters from \" + sourceCsvPath + \" to \" + outputPath);\n\n\t\ttry {\n\n\t\t\tFile sourceFile = new File(sourceCsvPath);\n\t\t\tCSVParser csvParser = CSVParser.parse(sourceFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\n\t\t\t//\"service_id\",\"system_id\",\"nhs_number\",\"patient_id\",\"count\"\n\n\t\t\tint count = 0;\n\t\t\tHashMap> serviceAndSystemIds = new HashMap<>();\n\t\t\tHashMap patientIds = new HashMap<>();\n\n\t\t\tIterator csvIterator = csvParser.iterator();\n\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\t\t\t\tcount ++;\n\n\t\t\t\tString serviceId = csvRecord.get(\"service_id\");\n\t\t\t\tString systemId = csvRecord.get(\"system_id\");\n\t\t\t\tString patientId = csvRecord.get(\"patient_id\");\n\n\t\t\t\tUUID serviceUuid = UUID.fromString(serviceId);\n\t\t\t\tList systemIds = serviceAndSystemIds.get(serviceUuid);\n\t\t\t\tif (systemIds == null) {\n\t\t\t\t\tsystemIds = new ArrayList<>();\n\t\t\t\t\tserviceAndSystemIds.put(serviceUuid, systemIds);\n\t\t\t\t}\n\t\t\t\tsystemIds.add(UUID.fromString(systemId));\n\n\t\t\t\tpatientIds.put(UUID.fromString(patientId), new Integer(count));\n\t\t\t}\n\n\t\t\tcsvParser.close();\n\n\t\t\tExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal();\n\t\t\tResourceDalI resourceDalI = DalProvider.factoryResourceDal();\n\t\t\tExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal();\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tParserPool parser = new ParserPool();\n\n\t\t\tMap> patientRows = new HashMap<>();\n\t\t\tSimpleDateFormat sdfOutput = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\t\t\tfor (UUID serviceId: serviceAndSystemIds.keySet()) {\n\t\t\t\t//List systemIds = serviceAndSystemIds.get(serviceId);\n\n\t\t\t\tService service = serviceDalI.getById(serviceId);\n\t\t\t\tString serviceName = service.getName();\n\t\t\t\tLOG.info(\"Doing service \" + serviceId + \" \" + serviceName);\n\n\t\t\t\tList exchangeIds = exchangeDalI.getExchangeIdsForService(serviceId);\n\t\t\t\tLOG.info(\"Got \" + exchangeIds.size() + \" exchange IDs to scan\");\n\t\t\t\tint exchangeCount = 0;\n\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\texchangeCount ++;\n\t\t\t\t\tif (exchangeCount % 1000 == 0) {\n\t\t\t\t\t\tLOG.info(\"Done \" + exchangeCount + \" exchanges\");\n\t\t\t\t\t}\n\n\t\t\t\t\tList exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch exchangeBatch: exchangeBatches) {\n\t\t\t\t\t\tUUID patientId = exchangeBatch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null\n\t\t\t\t\t\t\t\t&& !patientIds.containsKey(patientId)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tInteger patientIdInt = patientIds.get(patientId);\n\n\t\t\t\t\t\t//get encounters for exchange batch\n\t\t\t\t\t\tUUID batchId = exchangeBatch.getBatchId();\n\t\t\t\t\t\tList resourceWrappers = resourceDalI.getResourcesForBatch(serviceId, batchId);\n\t\t\t\t\t\tfor (ResourceWrapper resourceWrapper: resourceWrappers) {\n\t\t\t\t\t\t\tif (resourceWrapper.isDeleted()) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tString resourceType = resourceWrapper.getResourceType();\n\t\t\t\t\t\t\tif (!resourceType.equals(ResourceType.Encounter.toString())) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tLOG.info(\"Processing \" + resourceWrapper.getResourceType() + \" \" + resourceWrapper.getResourceId());\n\t\t\t\t\t\t\tString json = resourceWrapper.getResourceData();\n\t\t\t\t\t\t\tEncounter fhirEncounter = (Encounter)parser.parse(json);\n\n\t\t\t\t\t\t\tDate date = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasPeriod()) {\n\t\t\t\t\t\t\t\tPeriod period = fhirEncounter.getPeriod();\n\t\t\t\t\t\t\t\tif (period.hasStart()) {\n\t\t\t\t\t\t\t\t\tdate = period.getStart();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString episodeId = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasEpisodeOfCare()) {\n\t\t\t\t\t\t\t\tReference episodeReference = fhirEncounter.getEpisodeOfCare().get(0);\n\t\t\t\t\t\t\t\tReferenceComponents comps = ReferenceHelper.getReferenceComponents(episodeReference);\n\t\t\t\t\t\t\t\tEpisodeOfCare fhirEpisode = (EpisodeOfCare)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId());\n\t\t\t\t\t\t\t\tif (fhirEpisode != null) {\n\t\t\t\t\t\t\t\t\tif (fhirEpisode.hasIdentifier()) {\n\t\t\t\t\t\t\t\t\t\tepisodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_BARTS_FIN_EPISODE_ID);\n\n\t\t\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(episodeId)) {\n\t\t\t\t\t\t\t\t\t\t\tepisodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_FIN_EPISODE_ID);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\tString adtType = null;\n\t\t\t\t\t\t\tString adtCode = null;\n\t\t\t\t\t\t\tExtension extension = ExtensionConverter.findExtension(fhirEncounter, FhirExtensionUri.HL7_MESSAGE_TYPE);\n\n\t\t\t\t\t\t\tif (extension != null) {\n\t\t\t\t\t\t\t\tCodeableConcept codeableConcept = (CodeableConcept) extension.getValue();\n\t\t\t\t\t\t\t\tCoding hl7MessageTypeCoding = CodeableConceptHelper.findCoding(codeableConcept, FhirUri.CODE_SYSTEM_HL7V2_MESSAGE_TYPE);\n\t\t\t\t\t\t\t\tif (hl7MessageTypeCoding != null) {\n\t\t\t\t\t\t\t\t\tadtType = hl7MessageTypeCoding.getDisplay();\n\t\t\t\t\t\t\t\t\tadtCode = hl7MessageTypeCoding.getCode();\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t//for older formats of the transformed resources, the HL7 message type can only be found from the raw original exchange body\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tExchange exchange = exchangeDalI.getExchange(exchangeId);\n\t\t\t\t\t\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\t\t\t\t\t\tBundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(exchangeBody);\n\t\t\t\t\t\t\t\t\tfor (Bundle.BundleEntryComponent entry: bundle.getEntry()) {\n\t\t\t\t\t\t\t\t\t\tif (entry.getResource() != null\n\t\t\t\t\t\t\t\t\t\t\t\t&& entry.getResource() instanceof MessageHeader) {\n\n\t\t\t\t\t\t\t\t\t\t\tMessageHeader header = (MessageHeader)entry.getResource();\n\t\t\t\t\t\t\t\t\t\t\tif (header.hasEvent()) {\n\t\t\t\t\t\t\t\t\t\t\t\tCoding coding = header.getEvent();\n\t\t\t\t\t\t\t\t\t\t\t\tadtType = coding.getDisplay();\n\t\t\t\t\t\t\t\t\t\t\t\tadtCode = coding.getCode();\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\t\t\t//if the exchange body isn't a FHIR bundle, then we'll get an error by treating as such, so just ignore them\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString cls = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasClass_()) {\n\t\t\t\t\t\t\t\tEncounter.EncounterClass encounterClass = fhirEncounter.getClass_();\n\t\t\t\t\t\t\t\tif (encounterClass == Encounter.EncounterClass.OTHER\n\t\t\t\t\t\t\t\t\t\t&& fhirEncounter.hasClass_Element()\n\t\t\t\t\t\t\t\t\t\t&& fhirEncounter.getClass_Element().hasExtension()) {\n\n\t\t\t\t\t\t\t\t\tfor (Extension classExtension: fhirEncounter.getClass_Element().getExtension()) {\n\t\t\t\t\t\t\t\t\t\tif (classExtension.getUrl().equals(FhirExtensionUri.ENCOUNTER_CLASS)) {\n\t\t\t\t\t\t\t\t\t\t\t//not 100% of the type of the value, so just append to a String\n\t\t\t\t\t\t\t\t\t\t\tcls = \"\" + classExtension.getValue();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(cls)) {\n\t\t\t\t\t\t\t\t\tcls = encounterClass.toCode();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString type = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasType()) {\n\t\t\t\t\t\t\t\t//only seem to ever have one type\n\t\t\t\t\t\t\t\tCodeableConcept codeableConcept = fhirEncounter.getType().get(0);\n\t\t\t\t\t\t\t\ttype = codeableConcept.getText();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString status = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasStatus()) {\n\t\t\t\t\t\t\t\tEncounter.EncounterState encounterState = fhirEncounter.getStatus();\n\t\t\t\t\t\t\t\tstatus = encounterState.toCode();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString location = null;\n\t\t\t\t\t\t\tString locationType = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasLocation()) {\n\t\t\t\t\t\t\t\t//first location is always the current location\n\t\t\t\t\t\t\t\tEncounter.EncounterLocationComponent encounterLocation = fhirEncounter.getLocation().get(0);\n\t\t\t\t\t\t\t\tif (encounterLocation.hasLocation()) {\n\t\t\t\t\t\t\t\t\tReference locationReference = encounterLocation.getLocation();\n\t\t\t\t\t\t\t\t\tReferenceComponents comps = ReferenceHelper.getReferenceComponents(locationReference);\n\t\t\t\t\t\t\t\t\tLocation fhirLocation = (Location)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId());\n\t\t\t\t\t\t\t\t\tif (fhirLocation != null) {\n\t\t\t\t\t\t\t\t\t\tif (fhirLocation.hasName()) {\n\t\t\t\t\t\t\t\t\t\t\tlocation = fhirLocation.getName();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (fhirLocation.hasType()) {\n\t\t\t\t\t\t\t\t\t\t\tCodeableConcept typeCodeableConcept = fhirLocation.getType();\n\t\t\t\t\t\t\t\t\t\t\tif (typeCodeableConcept.hasCoding()) {\n\t\t\t\t\t\t\t\t\t\t\t\tCoding coding = typeCodeableConcept.getCoding().get(0);\n\t\t\t\t\t\t\t\t\t\t\t\tlocationType = coding.getDisplay();\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString clinician = null;\n\n\t\t\t\t\t\t\tif (fhirEncounter.hasParticipant()) {\n\t\t\t\t\t\t\t\t//first participant seems to be the interesting one\n\t\t\t\t\t\t\t\tEncounter.EncounterParticipantComponent encounterParticipant = fhirEncounter.getParticipant().get(0);\n\t\t\t\t\t\t\t\tif (encounterParticipant.hasIndividual()) {\n\t\t\t\t\t\t\t\t\tReference practitionerReference = encounterParticipant.getIndividual();\n\t\t\t\t\t\t\t\t\tReferenceComponents comps = ReferenceHelper.getReferenceComponents(practitionerReference);\n\t\t\t\t\t\t\t\t\tPractitioner fhirPractitioner = (Practitioner)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId());\n\t\t\t\t\t\t\t\t\tif (fhirPractitioner != null) {\n\t\t\t\t\t\t\t\t\t\tif (fhirPractitioner.hasName()) {\n\t\t\t\t\t\t\t\t\t\t\tHumanName name = fhirPractitioner.getName();\n\t\t\t\t\t\t\t\t\t\t\tclinician = name.getText();\n\t\t\t\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(clinician)) {\n\t\t\t\t\t\t\t\t\t\t\t\tclinician = \"\";\n\n\t\t\t\t\t\t\t\t\t\t\t\tfor (StringType s: name.getPrefix()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += s.getValueNotNull();\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += \" \";\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tfor (StringType s: name.getGiven()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += s.getValueNotNull();\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += \" \";\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tfor (StringType s: name.getFamily()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += s.getValueNotNull();\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += \" \";\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tclinician = clinician.trim();\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tObject[] row = new Object[12];\n\n\t\t\t\t\t\t\trow[0] = serviceName;\n\t\t\t\t\t\t\trow[1] = patientIdInt.toString();\n\t\t\t\t\t\t\trow[2] = sdfOutput.format(date);\n\t\t\t\t\t\t\trow[3] = episodeId;\n\t\t\t\t\t\t\trow[4] = adtCode;\n\t\t\t\t\t\t\trow[5] = adtType;\n\t\t\t\t\t\t\trow[6] = cls;\n\t\t\t\t\t\t\trow[7] = type;\n\t\t\t\t\t\t\trow[8] = status;\n\t\t\t\t\t\t\trow[9] = location;\n\t\t\t\t\t\t\trow[10] = locationType;\n\t\t\t\t\t\t\trow[11] = clinician;\n\n\t\t\t\t\t\t\tList rows = patientRows.get(patientIdInt);\n\t\t\t\t\t\t\tif (rows == null) {\n\t\t\t\t\t\t\t\trows = new ArrayList<>();\n\t\t\t\t\t\t\t\tpatientRows.put(patientIdInt, rows);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trows.add(row);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tString[] outputColumnHeaders = new String[] {\"Source\", \"Patient\", \"Date\", \"Episode ID\", \"ADT Message Code\", \"ADT Message Type\", \"Class\", \"Type\", \"Status\", \"Location\", \"Location Type\", \"Clinician\"};\n\n\t\t\tFileWriter fileWriter = new FileWriter(outputPath);\n\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(fileWriter);\n\t\t\tCSVFormat format = CSVFormat.DEFAULT\n\t\t\t\t\t.withHeader(outputColumnHeaders)\n\t\t\t\t\t.withQuote('\"');\n\t\t\tCSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format);\n\n\t\t\tfor (int i=0; i <= count; i++) {\n\t\t\t\tInteger patientIdInt = new Integer(i);\n\t\t\t\tList rows = patientRows.get(patientIdInt);\n\t\t\t\tif (rows != null) {\n\t\t\t\t\tfor (Object[] row: rows) {\n\t\t\t\t\t\tcsvPrinter.printRecord(row);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcsvPrinter.close();\n\t\t\tbufferedWriter.close();\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Exporting Encounters from \" + sourceCsvPath + \" to \" + outputPath);\n\t}*/\n\n\t/*private static void registerShutdownHook() {\n\n\t\tRuntime.getRuntime().addShutdownHook(new Thread() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\n\t\t\t\tLOG.info(\"\");\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(5000);\n\t\t\t\t} catch (Throwable ex) {\n\t\t\t\t\tLOG.error(\"\", ex);\n\t\t\t\t}\n\t\t\t\tLOG.info(\"Done\");\n\t\t\t}\n\t\t});\n\t}*/\n\n\n\tprivate static void findEmisStartDates(String path, String outputPath) {\n\t\tLOG.info(\"Finding EMIS Start Dates in \" + path + \", writing to \" + outputPath);\n\n\t\ttry {\n\n\t\t\tSimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH.mm.ss\");\n\n\t\t\tMap startDates = new HashMap<>();\n\t\t\tMap servers = new HashMap<>();\n\n\t\t\tMap names = new HashMap<>();\n\t\t\tMap odsCodes = new HashMap<>();\n\t\t\tMap cdbNumbers = new HashMap<>();\n\t\t\tMap> distinctPatients = new HashMap<>();\n\n\t\t\tFile root = new File(path);\n\t\t\tfor (File sftpRoot: root.listFiles()) {\n\t\t\t\tLOG.info(\"Checking \" + sftpRoot);\n\n\t\t\t\tMap extracts = new HashMap<>();\n\t\t\t\tList extractDates = new ArrayList<>();\n\n\t\t\t\tfor (File extractRoot: sftpRoot.listFiles()) {\n\t\t\t\t\tDate d = sdf.parse(extractRoot.getName());\n\n\t\t\t\t\t//LOG.info(\"\" + extractRoot.getName() + \" -> \" + d);\n\n\t\t\t\t\textracts.put(d, extractRoot);\n\t\t\t\t\textractDates.add(d);\n\t\t\t\t}\n\n\t\t\t\tCollections.sort(extractDates);\n\n\t\t\t\tfor (Date extractDate: extractDates) {\n\t\t\t\t\tFile extractRoot = extracts.get(extractDate);\n\t\t\t\t\tLOG.info(\"Checking \" + extractRoot);\n\n\t\t\t\t\t//read the sharing agreements file\n\t\t\t\t\t//e.g. 291_Agreements_SharingOrganisation_20150211164536_45E7CD20-EE37-41AB-90D6-DC9D4B03D102.csv\n\t\t\t\t\tFile sharingAgreementsFile = null;\n\t\t\t\t\tfor (File f: extractRoot.listFiles()) {\n\t\t\t\t\t\tString name = f.getName().toLowerCase();\n\t\t\t\t\t\tif (name.indexOf(\"agreements_sharingorganisation\") > -1\n\t\t\t\t\t\t\t\t&& name.endsWith(\".csv\")) {\n\t\t\t\t\t\t\tsharingAgreementsFile = f;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (sharingAgreementsFile == null) {\n\t\t\t\t\t\tLOG.info(\"Null agreements file for \" + extractRoot);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCSVParser csvParser = CSVParser.parse(sharingAgreementsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\t\tString orgGuid = csvRecord.get(\"OrganisationGuid\");\n\t\t\t\t\t\t\tString activated = csvRecord.get(\"IsActivated\");\n\t\t\t\t\t\t\tString disabled = csvRecord.get(\"Disabled\");\n\n\t\t\t\t\t\t\tservers.put(orgGuid, sftpRoot.getName());\n\n\t\t\t\t\t\t\tif (activated.equalsIgnoreCase(\"true\")) {\n\t\t\t\t\t\t\t\tif (disabled.equalsIgnoreCase(\"false\")) {\n\n\t\t\t\t\t\t\t\t\tDate d = sdf.parse(extractRoot.getName());\n\t\t\t\t\t\t\t\t\tDate existingDate = startDates.get(orgGuid);\n\t\t\t\t\t\t\t\t\tif (existingDate == null) {\n\t\t\t\t\t\t\t\t\t\tstartDates.put(orgGuid, d);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (startDates.containsKey(orgGuid)) {\n\t\t\t\t\t\t\t\t\t\tstartDates.put(orgGuid, null);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\n\t\t\t\t\t//go through orgs file to get name, ods and cdb codes\n\t\t\t\t\tFile orgsFile = null;\n\t\t\t\t\tfor (File f: extractRoot.listFiles()) {\n\t\t\t\t\t\tString name = f.getName().toLowerCase();\n\t\t\t\t\t\tif (name.indexOf(\"admin_organisation_\") > -1\n\t\t\t\t\t\t\t\t&& name.endsWith(\".csv\")) {\n\t\t\t\t\t\t\torgsFile = f;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser = CSVParser.parse(orgsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\t\tString orgGuid = csvRecord.get(\"OrganisationGuid\");\n\t\t\t\t\t\t\tString name = csvRecord.get(\"OrganisationName\");\n\t\t\t\t\t\t\tString odsCode = csvRecord.get(\"ODSCode\");\n\t\t\t\t\t\t\tString cdb = csvRecord.get(\"CDB\");\n\n\t\t\t\t\t\t\tnames.put(orgGuid, name);\n\t\t\t\t\t\t\todsCodes.put(orgGuid, odsCode);\n\t\t\t\t\t\t\tcdbNumbers.put(orgGuid, cdb);\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\n\t\t\t\t\t//go through patients file to get count\n\t\t\t\t\tFile patientFile = null;\n\t\t\t\t\tfor (File f: extractRoot.listFiles()) {\n\t\t\t\t\t\tString name = f.getName().toLowerCase();\n\t\t\t\t\t\tif (name.indexOf(\"admin_patient_\") > -1\n\t\t\t\t\t\t\t\t&& name.endsWith(\".csv\")) {\n\t\t\t\t\t\t\tpatientFile = f;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser = CSVParser.parse(patientFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\t\tString orgGuid = csvRecord.get(\"OrganisationGuid\");\n\t\t\t\t\t\t\tString patientGuid = csvRecord.get(\"PatientGuid\");\n\t\t\t\t\t\t\tString deleted = csvRecord.get(\"Deleted\");\n\n\t\t\t\t\t\t\tSet distinctPatientSet = distinctPatients.get(orgGuid);\n\t\t\t\t\t\t\tif (distinctPatientSet == null) {\n\t\t\t\t\t\t\t\tdistinctPatientSet = new HashSet<>();\n\t\t\t\t\t\t\t\tdistinctPatients.put(orgGuid, distinctPatientSet);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (deleted.equalsIgnoreCase(\"true\")) {\n\t\t\t\t\t\t\t\tdistinctPatientSet.remove(patientGuid);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdistinctPatientSet.add(patientGuid);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSimpleDateFormat sdfOutput = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\tsb.append(\"Name,OdsCode,CDB,OrgGuid,StartDate,Server,Patients\");\n\n\t\t\tfor (String orgGuid: startDates.keySet()) {\n\t\t\t\tDate startDate = startDates.get(orgGuid);\n\t\t\t\tString server = servers.get(orgGuid);\n\t\t\t\tString name = names.get(orgGuid);\n\t\t\t\tString odsCode = odsCodes.get(orgGuid);\n\t\t\t\tString cdbNumber = cdbNumbers.get(orgGuid);\n\t\t\t\tSet distinctPatientSet = distinctPatients.get(orgGuid);\n\n\t\t\t\tString startDateDesc = null;\n\t\t\t\tif (startDate != null) {\n\t\t\t\t\tstartDateDesc = sdfOutput.format(startDate);\n\t\t\t\t}\n\n\t\t\t\tLong countDistinctPatients = null;\n\t\t\t\tif (distinctPatientSet != null) {\n\t\t\t\t\tcountDistinctPatients = new Long(distinctPatientSet.size());\n\t\t\t\t}\n\n\t\t\t\tsb.append(\"\\n\");\n\t\t\t\tsb.append(\"\\\"\" + name + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + odsCode + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + cdbNumber + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + orgGuid + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(startDateDesc);\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + server + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(countDistinctPatients);\n\t\t\t}\n\n\t\t\tLOG.info(sb.toString());\n\n\t\t\tFileUtils.writeStringToFile(new File(outputPath), sb.toString());\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Finding Start Dates in \" + path + \", writing to \" + outputPath);\n\t}\n\n\tprivate static void findEncounterTerms(String path, String outputPath) {\n\t\tLOG.info(\"Finding Encounter Terms from \" + path);\n\n\t\tMap hmResults = new HashMap<>();\n\n\t\t//source term, source term snomed ID, source term snomed term - count\n\n\t\ttry {\n\t\t\tFile root = new File(path);\n\t\t\tFile[] files = root.listFiles();\n\t\t\tfor (File readerRoot: files) { //emis001\n\t\t\t\tLOG.info(\"Finding terms in \" + readerRoot);\n\n\t\t\t\t//first read in all the coding files to build up our map of codes\n\t\t\t\tMap hmCodes = new HashMap<>();\n\n\t\t\t\tfor (File dateFolder: readerRoot.listFiles()) {\n\t\t\t\t\tLOG.info(\"Looking for codes in \" + dateFolder);\n\n\t\t\t\t\tFile f = findFile(dateFolder, \"Coding_ClinicalCode\");\n\t\t\t\t\tif (f == null) {\n\t\t\t\t\t\tLOG.error(\"Failed to find coding file in \" + dateFolder.getAbsolutePath());\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\tString codeId = csvRecord.get(\"CodeId\");\n\t\t\t\t\t\tString term = csvRecord.get(\"Term\");\n\t\t\t\t\t\tString snomed = csvRecord.get(\"SnomedCTConceptId\");\n\n\t\t\t\t\t\thmCodes.put(codeId, snomed + \",\\\"\" + term + \"\\\"\");\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser.close();\n\t\t\t\t}\n\n\t\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\t\t\tDate cutoff = dateFormat.parse(\"2017-01-01\");\n\n\t\t\t\t//now process the consultation files themselves\n\t\t\t\tfor (File dateFolder: readerRoot.listFiles()) {\n\t\t\t\t\tLOG.info(\"Looking for consultations in \" + dateFolder);\n\n\t\t\t\t\tFile f = findFile(dateFolder, \"CareRecord_Consultation\");\n\t\t\t\t\tif (f == null) {\n\t\t\t\t\t\tLOG.error(\"Failed to find consultation file in \" + dateFolder.getAbsolutePath());\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\tString term = csvRecord.get(\"ConsultationSourceTerm\");\n\t\t\t\t\t\tString codeId = csvRecord.get(\"ConsultationSourceCodeId\");\n\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(term)\n\t\t\t\t\t\t\t\t&& Strings.isNullOrEmpty(codeId)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString date = csvRecord.get(\"EffectiveDate\");\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(date)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDate d = dateFormat.parse(date);\n\t\t\t\t\t\tif (d.before(cutoff)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString line = \"\\\"\" + term + \"\\\",\";\n\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(codeId)) {\n\n\t\t\t\t\t\t\tString codeLookup = hmCodes.get(codeId);\n\t\t\t\t\t\t\tif (codeLookup == null) {\n\t\t\t\t\t\t\t\tLOG.error(\"Failed to find lookup for codeID \" + codeId);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tline += codeLookup;\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tline += \",\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tLong count = hmResults.get(line);\n\t\t\t\t\t\tif (count == null) {\n\t\t\t\t\t\t\tcount = new Long(1);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcount = new Long(count.longValue() + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\thmResults.put(line, count);\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser.close();\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\t//save results to file\n\t\t\tStringBuilder output = new StringBuilder();\n\t\t\toutput.append(\"\\\"consultation term\\\",\\\"snomed concept ID\\\",\\\"snomed term\\\",\\\"count\\\"\");\n\t\t\toutput.append(\"\\r\\n\");\n\n\t\t\tfor (String line: hmResults.keySet()) {\n\t\t\t\tLong count = hmResults.get(line);\n\t\t\t\tString combined = line + \",\" + count;\n\n\t\t\t\toutput.append(combined);\n\t\t\t\toutput.append(\"\\r\\n\");\n\t\t\t}\n\t\t\tLOG.info(\"FInished\");\n\t\t\tLOG.info(output.toString());\n\n\t\t\tFileUtils.writeStringToFile(new File(outputPath), output.toString());\n\n\t\t\tLOG.info(\"written output to \" + outputPath);\n\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished finding Encounter Terms from \" + path);\n\t}\n\n\tprivate static File findFile(File root, String token) throws Exception {\n\t\tfor (File f: root.listFiles()) {\n\t\t\tString s = f.getName();\n\t\t\tif (s.indexOf(token) > -1) {\n\t\t\t\treturn f;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/*private static void populateProtocolQueue(String serviceIdStr, String startingExchangeId) {\n\t\tLOG.info(\"Starting Populating Protocol Queue for \" + serviceIdStr);\n\n\t\tServiceDalI serviceRepository = DalProvider.factoryServiceDal();\n\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\tif (serviceIdStr.equalsIgnoreCase(\"All\")) {\n\t\t\tserviceIdStr = null;\n\t\t}\n\n\t\ttry {\n\n\t\t\tList services = new ArrayList<>();\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tservices = serviceRepository.getAll();\n\t\t\t} else {\n\t\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tservices.add(service);\n\t\t\t}\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tList exchangeIds = auditRepository.getExchangeIdsForService(service.getId());\n\t\t\t\tLOG.info(\"Found \" + exchangeIds.size() + \" exchangeIds for \" + service.getName());\n\n\t\t\t\tif (startingExchangeId != null) {\n\t\t\t\t\tUUID startingExchangeUuid = UUID.fromString(startingExchangeId);\n\t\t\t\t\tif (exchangeIds.contains(startingExchangeUuid)) {\n\t\t\t\t\t\t//if in the list, remove everything up to and including the starting exchange\n\t\t\t\t\t\tint index = exchangeIds.indexOf(startingExchangeUuid);\n\t\t\t\t\t\tLOG.info(\"Found starting exchange \" + startingExchangeId + \" at \" + index + \" so removing up to this point\");\n\t\t\t\t\t\tfor (int i=index; i>=0; i--) {\n\t\t\t\t\t\t\texchangeIds.remove(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstartingExchangeId = null;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if not in the list, skip all these exchanges\n\t\t\t\t\t\tLOG.info(\"List doesn't contain starting exchange \" + startingExchangeId + \" so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tQueueHelper.postToExchange(exchangeIds, \"edsProtocol\", null, true);\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Populating Protocol Queue for \" + serviceIdStr);\n\t}*/\n\n\t/*private static void findDeletedOrgs() {\n\t\tLOG.info(\"Starting finding deleted orgs\");\n\n\t\tServiceDalI serviceRepository = DalProvider.factoryServiceDal();\n\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\tList services = new ArrayList<>();\n\t\ttry {\n\t\t\tfor (Service service: serviceRepository.getAll()) {\n\t\t\t\tservices.add(service);\n\t\t\t}\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tservices.sort((o1, o2) -> {\n\t\t\tString name1 = o1.getName();\n\t\t\tString name2 = o2.getName();\n\t\t\treturn name1.compareToIgnoreCase(name2);\n\t\t});\n\n\t\tfor (Service service: services) {\n\n\t\t\ttry {\n\t\t\t\tUUID serviceUuid = service.getId();\n\t\t\t\tList exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 1, new Date(0), new Date());\n\n\t\t\t\tLOG.info(\"Service: \" + service.getName() + \" \" + service.getLocalId());\n\n\t\t\t\tif (exchangeByServices.isEmpty()) {\n\t\t\t\t\tLOG.info(\" no exchange found!\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\n\t\t\t\tExchange exchangeByService = exchangeByServices.get(0);\n\t\t\t\tUUID exchangeId = exchangeByService.getId();\n\t\t\t\tExchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\t\tMap headers = exchange.getHeaders();\n\n\t\t\t\tString systemUuidStr = headers.get(HeaderKeys.SenderSystemUuid);\n\t\t\t\tUUID systemUuid = UUID.fromString(systemUuidStr);\n\n\t\t\t\tint batches = countBatches(exchangeId, serviceUuid, systemUuid);\n\t\t\t\tLOG.info(\" Most recent exchange had \" + batches + \" batches\");\n\n\t\t\t\tif (batches > 1 && batches < 2000) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//go back until we find the FIRST exchange where it broke\n\t\t\t\texchangeByServices = auditRepository.getExchangesByService(serviceUuid, 250, new Date(0), new Date());\n\t\t\t\tfor (int i=0; i 2000) {\n\t\t\t\t\t\tLOG.info(\" \" + timestamp + \" had \" + batches);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (batches > 1 && batches < 2000) {\n\t\t\t\t\t\tLOG.info(\" \" + timestamp + \" had \" + batches);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"\", ex);\n\t\t\t}\n\n\t\t}\n\n\t\tLOG.info(\"Finished finding deleted orgs\");\n\t}*/\n\n\tprivate static int countBatches(UUID exchangeId, UUID serviceId, UUID systemId) throws Exception {\n\t\tint batches = 0;\n\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\tList audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId);\n\t\tfor (ExchangeTransformAudit audit: audits) {\n\t\t\tif (audit.getNumberBatchesCreated() != null) {\n\t\t\t\tbatches += audit.getNumberBatchesCreated();\n\t\t\t}\n\t\t}\n\t\treturn batches;\n\t}\n\n\t/*private static void fixExchanges(UUID justThisService) {\n\t\tLOG.info(\"Fixing exchanges\");\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId : exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tboolean changed = false;\n\n\t\t\t\t\tString body = exchange.getBody();\n\n\t\t\t\t\tString[] files = body.split(\"\\n\");\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (int i=0; i exchangeByServiceList = auditRepository.getExchangesByService(serviceId, Integer.MAX_VALUE);\n\n\t\t//go backwards as the most recent is first\n\t\tfor (int i=exchangeByServiceList.size()-1; i>=0; i--) {\n\t\t\tExchangeByService exchangeByService = exchangeByServiceList.get(i);\n\t\t\tUUID exchangeId = exchangeByService.getExchangeId();\n\t\t\tLOG.info(\"Doing exchange \" + exchangeId);\n\n\t\t\tEmisCsvHelper helper = null;\n\n\t\t\ttry {\n\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\tString[] files = exchangeBody.split(java.lang.System.lineSeparator());\n\n\t\t\t\tFile orgDirectory = validateAndFindCommonDirectory(sharedStoragePath, files);\n\t\t\t\tMap allParsers = new HashMap<>();\n\t\t\t\tString properVersion = null;\n\n\t\t\t\tString[] versions = new String[]{EmisCsvToFhirTransformer.VERSION_5_0, EmisCsvToFhirTransformer.VERSION_5_1, EmisCsvToFhirTransformer.VERSION_5_3, EmisCsvToFhirTransformer.VERSION_5_4};\n\t\t\t\tfor (String version: versions) {\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\tList parsers = new ArrayList<>();\n\n\t\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(Observation.class, orgDirectory, version, true, parsers);\n\t\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(DrugRecord.class, orgDirectory, version, true, parsers);\n\t\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(IssueRecord.class, orgDirectory, version, true, parsers);\n\n\t\t\t\t\t\tfor (AbstractCsvParser parser: parsers) {\n\t\t\t\t\t\t\tClass cls = parser.getClass();\n\t\t\t\t\t\t\tallParsers.put(cls, parser);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tproperVersion = version;\n\n\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t//ignore\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (allParsers.isEmpty()) {\n\t\t\t\t\tthrow new Exception(\"Failed to open parsers for exchange \" + exchangeId + \" in folder \" + orgDirectory);\n\t\t\t\t}\n\n\t\t\t\tUUID systemId = exchange.getHeaderAsUuid(HeaderKeys.SenderSystemUuid);\n\t\t\t\t//FhirResourceFiler dummyFiler = new FhirResourceFiler(exchangeId, serviceId, systemId, null, null, 10);\n\n\t\t\t\tif (helper == null) {\n\t\t\t\t\thelper = new EmisCsvHelper(findDataSharingAgreementGuid(new ArrayList<>(allParsers.values())));\n\t\t\t\t}\n\n\t\t\t\tObservationPreTransformer.transform(properVersion, allParsers, null, helper);\n\t\t\t\tIssueRecordPreTransformer.transform(properVersion, allParsers, null, helper);\n\t\t\t\tDrugRecordPreTransformer.transform(properVersion, allParsers, null, helper);\n\n\t\t\t\tMap> problemChildren = helper.getProblemChildMap();\n\n\t\t\t\tList exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\n\t\t\t\tfor (Map.Entry> entry : problemChildren.entrySet()) {\n\t\t\t\t\tString patientLocallyUniqueId = entry.getKey().split(\":\")[0];\n\n\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientLocallyUniqueId);\n\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find edsPatientId for local Patient ID \" + patientLocallyUniqueId + \" in exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\t//find the batch ID for our patient\n\t\t\t\t\tUUID batchId = null;\n\t\t\t\t\tfor (ExchangeBatch exchangeBatch: exchangeBatches) {\n\t\t\t\t\t\tif (exchangeBatch.getEdsPatientId() != null\n\t\t\t\t\t\t\t\t&& exchangeBatch.getEdsPatientId().equals(edsPatientId)) {\n\t\t\t\t\t\t\tbatchId = exchangeBatch.getBatchId();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (batchId == null) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find batch ID for eds Patient ID \" + edsPatientId + \" in exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\t//find the EDS ID for our problem\n\t\t\t\t\tUUID edsProblemId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Condition, entry.getKey());\n\t\t\t\t\tif (edsProblemId == null) {\n\t\t\t\t\t\tLOG.warn(\"No edsProblemId found for local ID \" + entry.getKey() + \" - assume bad data referring to non-existing problem?\");\n\t\t\t\t\t\t//throw new Exception(\"Failed to find edsProblemId for local Patient ID \" + problemLocallyUniqueId + \" in exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\t//convert our child IDs to EDS references\n\t\t\t\t\tList references = new ArrayList<>();\n\n\t\t\t\t\tHashSet contentsSet = new HashSet<>();\n\t\t\t\t\tcontentsSet.addAll(entry.getValue());\n\n\t\t\t\t\tfor (String referenceValue : contentsSet) {\n\t\t\t\t\t\tReference reference = ReferenceHelper.createReference(referenceValue);\n\t\t\t\t\t\tReferenceComponents components = ReferenceHelper.getReferenceComponents(reference);\n\t\t\t\t\t\tString locallyUniqueId = components.getId();\n\t\t\t\t\t\tResourceType resourceType = components.getResourceType();\n\t\t\t\t\t\tUUID edsResourceId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId);\n\n\t\t\t\t\t\tReference globallyUniqueReference = ReferenceHelper.createReference(resourceType, edsResourceId.toString());\n\t\t\t\t\t\treferences.add(globallyUniqueReference);\n\t\t\t\t\t}\n\n\t\t\t\t\t//find the resource for the problem itself\n\t\t\t\t\tResourceByExchangeBatch problemResourceByExchangeBatch = null;\n\t\t\t\t\tList resources = resourceRepository.getResourcesForBatch(batchId, ResourceType.Condition.toString());\n\t\t\t\t\tfor (ResourceByExchangeBatch resourceByExchangeBatch: resources) {\n\t\t\t\t\t\tif (resourceByExchangeBatch.getResourceId().equals(edsProblemId)) {\n\t\t\t\t\t\t\tproblemResourceByExchangeBatch = resourceByExchangeBatch;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (problemResourceByExchangeBatch == null) {\n\t\t\t\t\t\tthrow new Exception(\"Problem not found for edsProblemId \" + edsProblemId + \" for exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (problemResourceByExchangeBatch.getIsDeleted()) {\n\t\t\t\t\t\tLOG.warn(\"Problem \" + edsProblemId + \" is deleted, so not adding to it for exchange \" + exchangeId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = problemResourceByExchangeBatch.getResourceData();\n\t\t\t\t\tCondition fhirProblem = (Condition)PARSER_POOL.parse(json);\n\n\t\t\t\t\t//update the problems\n\t\t\t\t\tif (fhirProblem.hasContained()) {\n\t\t\t\t\t\tif (fhirProblem.getContained().size() > 1) {\n\t\t\t\t\t\t\tthrow new Exception(\"Problem \" + edsProblemId + \" is has \" + fhirProblem.getContained().size() + \" contained resources for exchange \" + exchangeId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfhirProblem.getContained().clear();\n\t\t\t\t\t}\n\n\t\t\t\t\tList_ list = new List_();\n\t\t\t\t\tlist.setId(\"Items\");\n\t\t\t\t\tfhirProblem.getContained().add(list);\n\n\t\t\t\t\tExtension extension = ExtensionConverter.findExtension(fhirProblem, FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE);\n\t\t\t\t\tif (extension == null) {\n\t\t\t\t\t\tReference listReference = ReferenceHelper.createInternalReference(\"Items\");\n\t\t\t\t\t\tfhirProblem.addExtension(ExtensionConverter.createExtension(FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE, listReference));\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (Reference reference : references) {\n\t\t\t\t\t\tlist.addEntry().setItem(reference);\n\t\t\t\t\t}\n\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(fhirProblem);\n\t\t\t\t\tif (newJson.equals(json)) {\n\t\t\t\t\t\tLOG.warn(\"Skipping edsProblemId \" + edsProblemId + \" as JSON hasn't changed\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tproblemResourceByExchangeBatch.setResourceData(newJson);\n\n\t\t\t\t\tString resourceType = problemResourceByExchangeBatch.getResourceType();\n\t\t\t\t\tUUID versionUuid = problemResourceByExchangeBatch.getVersion();\n\n\t\t\t\t\tResourceHistory problemResourceHistory = resourceRepository.getResourceHistoryByKey(edsProblemId, resourceType, versionUuid);\n\t\t\t\t\tproblemResourceHistory.setResourceData(newJson);\n\t\t\t\t\tproblemResourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\tResourceByService problemResourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType, edsProblemId);\n\t\t\t\t\tif (problemResourceByService.getResourceData() == null) {\n\t\t\t\t\t\tproblemResourceByService = null;\n\t\t\t\t\t\tLOG.warn(\"Not updating edsProblemId \" + edsProblemId + \" for exchange \" + exchangeId + \" as it's been subsequently delrted\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tproblemResourceByService.setResourceData(newJson);\n\t\t\t\t\t}\n\n\t\t\t\t\t//save back to THREE tables\n\t\t\t\t\tif (!testMode) {\n\n\t\t\t\t\t\tresourceRepository.save(problemResourceByExchangeBatch);\n\t\t\t\t\t\tresourceRepository.save(problemResourceHistory);\n\t\t\t\t\t\tif (problemResourceByService != null) {\n\t\t\t\t\t\t\tresourceRepository.save(problemResourceByService);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLOG.info(\"Fixed edsProblemId \" + edsProblemId + \" for exchange Id \" + exchangeId);\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOG.info(\"Would change edsProblemId \" + edsProblemId + \" to new JSON\");\n\t\t\t\t\t\tLOG.info(newJson);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed on exchange \" + exchangeId, ex);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished fixing problems for service \" + serviceId);\n\t}\n\n\tprivate static String findDataSharingAgreementGuid(List parsers) throws Exception {\n\n\t\t//we need a file name to work out the data sharing agreement ID, so just the first file we can find\n\t\tFile f = parsers\n\t\t\t\t.iterator()\n\t\t\t\t.next()\n\t\t\t\t.getFile();\n\n\t\tString name = Files.getNameWithoutExtension(f.getName());\n\t\tString[] toks = name.split(\"_\");\n\t\tif (toks.length != 5) {\n\t\t\tthrow new TransformException(\"Failed to extract data sharing agreement GUID from filename \" + f.getName());\n\t\t}\n\t\treturn toks[4];\n\t}\n\n\n\n\tprivate static void closeParsers(Collection parsers) {\n\t\tfor (AbstractCsvParser parser : parsers) {\n\t\t\ttry {\n\t\t\t\tparser.close();\n\t\t\t} catch (IOException ex) {\n\t\t\t\t//don't worry if this fails, as we're done anyway\n\t\t\t}\n\t\t}\n\t}\n\n\n\tprivate static File validateAndFindCommonDirectory(String sharedStoragePath, String[] files) throws Exception {\n\t\tString organisationDir = null;\n\n\t\tfor (String file: files) {\n\t\t\tFile f = new File(sharedStoragePath, file);\n\t\t\tif (!f.exists()) {\n\t\t\t\tLOG.error(\"Failed to find file {} in shared storage {}\", file, sharedStoragePath);\n\t\t\t\tthrow new FileNotFoundException(\"\" + f + \" doesn't exist\");\n\t\t\t}\n\t\t\t//LOG.info(\"Successfully found file {} in shared storage {}\", file, sharedStoragePath);\n\n\t\t\ttry {\n\t\t\t\tFile orgDir = f.getParentFile();\n\n\t\t\t\tif (organisationDir == null) {\n\t\t\t\t\torganisationDir = orgDir.getAbsolutePath();\n\t\t\t\t} else {\n\t\t\t\t\tif (!organisationDir.equalsIgnoreCase(orgDir.getAbsolutePath())) {\n\t\t\t\t\t\tthrow new Exception();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tthrow new FileNotFoundException(\"\" + f + \" isn't in the expected directory structure within \" + organisationDir);\n\t\t\t}\n\n\t\t}\n\t\treturn new File(organisationDir);\n\t}*/\n\n\t/*private static void testLogging() {\n\n\t\twhile (true) {\n\t\t\tSystem.out.println(\"Checking logging at \" + System.currentTimeMillis());\n\t\t\ttry {\n\t\t\t\tThread.sleep(4000);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\tLOG.trace(\"trace logging\");\n\t\t\tLOG.debug(\"debug logging\");\n\t\t\tLOG.info(\"info logging\");\n\t\t\tLOG.warn(\"warn logging\");\n\t\t\tLOG.error(\"error logging\");\n\t\t}\n\n\t}\n*/\n\t/*private static void fixExchangeProtocols() {\n\t\tLOG.info(\"Fixing exchange protocols\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT exchange_id FROM audit.Exchange LIMIT 1000;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\n\t\t\tLOG.info(\"Processing exchange \" + exchangeId);\n\t\t\tExchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed to parse headers for exchange \" + exchange.getExchangeId(), ex);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tLOG.error(\"Failed to find service ID for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\tList newIds = new ArrayList<>();\n\t\t\tString protocolJson = headers.get(HeaderKeys.Protocols);\n\n\t\t\tif (!headers.containsKey(HeaderKeys.Protocols)) {\n\n\t\t\t\ttry {\n\t\t\t\t\tList libraryItemList = LibraryRepositoryHelper.getProtocolsByServiceId(serviceIdStr);\n\n\t\t\t\t\t// Get protocols where service is publisher\n\t\t\t\t\tnewIds = libraryItemList.stream()\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\tlibraryItem -> libraryItem.getProtocol().getServiceContract().stream()\n\t\t\t\t\t\t\t\t\t\t\t.anyMatch(sc ->\n\t\t\t\t\t\t\t\t\t\t\t\t\tsc.getType().equals(ServiceContractType.PUBLISHER)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&& sc.getService().getUuid().equals(serviceIdStr)))\n\t\t\t\t\t\t\t.map(t -> t.getUuid().toString())\n\t\t\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.error(\"Failed to find protocols for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\ttry {\n\t\t\t\t\tJsonNode node = ObjectMapperPool.getInstance().readTree(protocolJson);\n\n\t\t\t\t\tfor (int i = 0; i < node.size(); i++) {\n\t\t\t\t\t\tJsonNode libraryItemNode = node.get(i);\n\t\t\t\t\t\tJsonNode idNode = libraryItemNode.get(\"uuid\");\n\t\t\t\t\t\tString id = idNode.asText();\n\t\t\t\t\t\tnewIds.add(id);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.error(\"Failed to read Json from \" + protocolJson + \" for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (newIds.isEmpty()) {\n\t\t\t\t\theaders.remove(HeaderKeys.Protocols);\n\n\t\t\t\t} else {\n\t\t\t\t\tString protocolsJson = ObjectMapperPool.getInstance().writeValueAsString(newIds.toArray());\n\t\t\t\t\theaders.put(HeaderKeys.Protocols, protocolsJson);\n\t\t\t\t}\n\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tLOG.error(\"Unable to serialize protocols to JSON for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\texchange.setHeaders(headerJson);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tLOG.error(\"Failed to write exchange headers to Json for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tauditRepository.save(exchange);\n\t\t}\n\n\t\tLOG.info(\"Finished fixing exchange protocols\");\n\t}*/\n\n\t/*private static void fixExchangeHeaders() {\n\t\tLOG.info(\"Fixing exchange headers\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\t\tOrganisationRepository organisationRepository = new OrganisationRepository();\n\n\t\tList exchanges = new AuditRepository().getAllExchanges();\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed to parse headers for exchange \" + exchange.getExchangeId(), ex);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (headers.containsKey(HeaderKeys.SenderLocalIdentifier)\n\t\t\t\t\t&& headers.containsKey(HeaderKeys.SenderOrganisationUuid)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tLOG.error(\"Failed to find service ID for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\tMap orgMap = service.getOrganisations();\n\t\t\tif (orgMap.size() != 1) {\n\t\t\t\tLOG.error(\"Wrong number of orgs in service \" + serviceId + \" for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID orgId = orgMap\n\t\t\t\t\t.keySet()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.collect(StreamExtension.firstOrNullCollector());\n\t\t\tOrganisation organisation = organisationRepository.getById(orgId);\n\t\t\tString odsCode = organisation.getNationalId();\n\n\t\t\theaders.put(HeaderKeys.SenderLocalIdentifier, odsCode);\n\t\t\theaders.put(HeaderKeys.SenderOrganisationUuid, orgId.toString());\n\n\t\t\ttry {\n\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t//not throwing this exception further up, since it should never happen\n\t\t\t\t//and means we don't need to litter try/catches everywhere this is called from\n\t\t\t\tLOG.error(\"Failed to write exchange headers to Json\", e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\texchange.setHeaders(headerJson);\n\n\t\t\tauditRepository.save(exchange);\n\n\t\t\tLOG.info(\"Creating exchange \" + exchange.getExchangeId());\n\t\t}\n\n\t\tLOG.info(\"Finished fixing exchange headers\");\n\t}*/\n\n\t/*private static void fixExchangeHeaders() {\n\t\tLOG.info(\"Fixing exchange headers\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\t\tOrganisationRepository organisationRepository = new OrganisationRepository();\n\t\tLibraryRepository libraryRepository = new LibraryRepository();\n\n\t\tList exchanges = new AuditRepository().getAllExchanges();\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed to parse headers for exchange \" + exchange.getExchangeId(), ex);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tLOG.error(\"Failed to find service ID for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tboolean changed = false;\n\n\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\ttry {\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint : endpoints) {\n\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tString endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString();\n\n\t\t\t\t\tActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId);\n\t\t\t\t\tItem item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId());\n\t\t\t\t\tLibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent());\n\t\t\t\t\tSystem system = libraryItem.getSystem();\n\t\t\t\t\tfor (TechnicalInterface technicalInterface : system.getTechnicalInterface()) {\n\n\t\t\t\t\t\tif (endpointInterfaceId.equals(technicalInterface.getUuid())) {\n\n\t\t\t\t\t\t\tif (!headers.containsKey(HeaderKeys.SourceSystem)) {\n\t\t\t\t\t\t\t\theaders.put(HeaderKeys.SourceSystem, technicalInterface.getMessageFormat());\n\t\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!headers.containsKey(HeaderKeys.SystemVersion)) {\n\t\t\t\t\t\t\t\theaders.put(HeaderKeys.SystemVersion, technicalInterface.getMessageFormatVersion());\n\t\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!headers.containsKey(HeaderKeys.SenderSystemUuid)) {\n\t\t\t\t\t\t\t\theaders.put(HeaderKeys.SenderSystemUuid, endpointSystemId.toString());\n\t\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to find endpoint details for \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (changed) {\n\t\t\t\ttry {\n\t\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t\t//not throwing this exception further up, since it should never happen\n\t\t\t\t\t//and means we don't need to litter try/catches everywhere this is called from\n\t\t\t\t\tLOG.error(\"Failed to write exchange headers to Json\", e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\texchange.setHeaders(headerJson);\n\t\t\t\tauditRepository.save(exchange);\n\n\t\t\t\tLOG.info(\"Fixed exchange \" + exchange.getExchangeId());\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished fixing exchange headers\");\n\t}*/\n\n\t/*private static void testConnection(String configName) {\n\t\ttry {\n\n\t\t\tJsonNode config = ConfigManager.getConfigurationAsJson(configName, \"enterprise\");\n\t\t\tString driverClass = config.get(\"driverClass\").asText();\n\t\t\tString url = config.get(\"url\").asText();\n\t\t\tString username = config.get(\"username\").asText();\n\t\t\tString password = config.get(\"password\").asText();\n\n\t\t\t//force the driver to be loaded\n\t\t\tClass.forName(driverClass);\n\n\t\t\tConnection conn = DriverManager.getConnection(url, username, password);\n\t\t\tconn.setAutoCommit(false);\n\t\t\tLOG.info(\"Connection ok\");\n\n\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"\", e);\n\t\t}\n\t}*/\n\t/*private static void testConnection() {\n\t\ttry {\n\n\t\t\tJsonNode config = ConfigManager.getConfigurationAsJson(\"postgres\", \"enterprise\");\n\t\t\tString url = config.get(\"url\").asText();\n\t\t\tString username = config.get(\"username\").asText();\n\t\t\tString password = config.get(\"password\").asText();\n\n\t\t\t//force the driver to be loaded\n\t\t\tClass.forName(\"org.postgresql.Driver\");\n\n\t\t\tConnection conn = DriverManager.getConnection(url, username, password);\n\t\t\tconn.setAutoCommit(false);\n\t\t\tLOG.info(\"Connection ok\");\n\n\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"\", e);\n\t\t}\n\t}*/\n\n\n\t/*private static void startEnterpriseStream(UUID serviceId, String configName, UUID exchangeIdStartFrom, UUID batchIdStartFrom) throws Exception {\n\n\t\tLOG.info(\"Starting Enterprise Streaming for \" + serviceId + \" using \" + configName + \" starting from exchange \" + exchangeIdStartFrom + \" and batch \" + batchIdStartFrom);\n\n\t\tLOG.info(\"Testing database connection\");\n\t\ttestConnection(configName);\n\n\t\tService service = new ServiceRepository().getById(serviceId);\n\t\tList orgIds = new ArrayList<>(service.getOrganisations().keySet());\n\t\tUUID orgId = orgIds.get(0);\n\n\t\tList exchangeByServiceList = new AuditRepository().getExchangesByService(serviceId, Integer.MAX_VALUE);\n\n\t\tfor (int i=exchangeByServiceList.size()-1; i>=0; i--) {\n\t\t\tExchangeByService exchangeByService = exchangeByServiceList.get(i);\n\t\t//for (ExchangeByService exchangeByService: exchangeByServiceList) {\n\t\t\tUUID exchangeId = exchangeByService.getExchangeId();\n\n\t\t\tif (exchangeIdStartFrom != null) {\n\t\t\t\tif (!exchangeIdStartFrom.equals(exchangeId)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\t//once we have a match, set to null so we don't skip any subsequent ones\n\t\t\t\t\texchangeIdStartFrom = null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\t\t\tString senderOrgUuidStr = exchange.getHeader(HeaderKeys.SenderOrganisationUuid);\n\t\t\tUUID senderOrgUuid = UUID.fromString(senderOrgUuidStr);\n\n\t\t\t//this one had 90,000 batches and doesn't need doing again\n\t\t\t*//*if (exchangeId.equals(UUID.fromString(\"b9b93be0-afd8-11e6-8c16-c1d5a00342f3\"))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId);\n\t\t\t\tcontinue;\n\t\t\t}*//*\n\n\t\t\tList exchangeBatches = new ExchangeBatchRepository().retrieveForExchangeId(exchangeId);\n\t\t\tLOG.info(\"Processing exchange \" + exchangeId + \" with \" + exchangeBatches.size() + \" batches\");\n\n\t\t\tfor (int j=0; j exchangeIdsDone = new HashSet<>();\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\t\t\tUUID batchId = row.get(1, UUID.class);\n\t\t\tDate date = row.getTimestamp(2);\n\t\t\t//LOG.info(\"Exchange \" + exchangeId + \" batch \" + batchId + \" date \" + date);\n\n\t\t\tif (exchangeIdsDone.contains(exchangeId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (auditRepository.getExchange(exchangeId) != null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID serviceId = findServiceId(batchId, session);\n\t\t\tif (serviceId == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tExchange exchange = new Exchange();\n\t\t\tExchangeByService exchangeByService = new ExchangeByService();\n\t\t\tExchangeEvent exchangeEvent = new ExchangeEvent();\n\n\t\t\tMap headers = new HashMap<>();\n\t\t\theaders.put(HeaderKeys.SenderServiceUuid, serviceId.toString());\n\n\t\t\tString headersJson = null;\n\t\t\ttry {\n\t\t\t\theadersJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t//not throwing this exception further up, since it should never happen\n\t\t\t\t//and means we don't need to litter try/catches everywhere this is called from\n\t\t\t\tLOG.error(\"Failed to write exchange headers to Json\", e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\texchange.setBody(\"Body not available, as exchange re-created\");\n\t\t\texchange.setExchangeId(exchangeId);\n\t\t\texchange.setHeaders(headersJson);\n\t\t\texchange.setTimestamp(date);\n\n\t\t\texchangeByService.setExchangeId(exchangeId);\n\t\t\texchangeByService.setServiceId(serviceId);\n\t\t\texchangeByService.setTimestamp(date);\n\n\t\t\texchangeEvent.setEventDesc(\"Created_By_Conversion\");\n\t\t\texchangeEvent.setExchangeId(exchangeId);\n\t\t\texchangeEvent.setTimestamp(new Date());\n\n\t\t\tauditRepository.save(exchange);\n\t\t\tauditRepository.save(exchangeEvent);\n\t\t\tauditRepository.save(exchangeByService);\n\n\t\t\texchangeIdsDone.add(exchangeId);\n\n\t\t\tLOG.info(\"Creating exchange \" + exchangeId);\n\t\t}\n\n\t\tLOG.info(\"Finished exchange fix\");\n\t}\n\n\tprivate static UUID findServiceId(UUID batchId, Session session) {\n\n\t\tStatement stmt = new SimpleStatement(\"select resource_type, resource_id from ehr.resource_by_exchange_batch where batch_id = \" + batchId + \" LIMIT 1;\");\n\t\tResultSet rs = session.execute(stmt);\n\t\tif (rs.isExhausted()) {\n\t\t\tLOG.error(\"Failed to find resource_by_exchange_batch for batch_id \" + batchId);\n\t\t\treturn null;\n\t\t}\n\n\t\tRow row = rs.one();\n\t\tString resourceType = row.getString(0);\n\t\tUUID resourceId = row.get(1, UUID.class);\n\n\t\tstmt = new SimpleStatement(\"select service_id from ehr.resource_history where resource_type = '\" + resourceType + \"' and resource_id = \" + resourceId + \" LIMIT 1;\");\n\t\trs = session.execute(stmt);\n\t\tif (rs.isExhausted()) {\n\t\t\tLOG.error(\"Failed to find resource_history for resource_type \" + resourceType + \" and resource_id \" + resourceId);\n\t\t\treturn null;\n\t\t}\n\n\t\trow = rs.one();\n\t\tUUID serviceId = row.get(0, UUID.class);\n\t\treturn serviceId;\n\t}*/\n\n\t/*private static void fixExchangeEvents() {\n\n\t\tList events = new AuditRepository().getAllExchangeEvents();\n\t\tfor (ExchangeEvent event: events) {\n\t\t\tif (event.getEventDesc() != null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString eventDesc = \"\";\n\t\t\tint eventType = event.getEvent().intValue();\n\t\t\tswitch (eventType) {\n\t\t\t\tcase 1:\n\t\t\t\t\teventDesc = \"Receive\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\teventDesc = \"Validate\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\teventDesc = \"Transform_Start\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\teventDesc = \"Transform_End\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\teventDesc = \"Send\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\teventDesc = \"??? \" + eventType;\n\t\t\t}\n\n\t\t\tevent.setEventDesc(eventDesc);\n\t\t\tnew AuditRepository().save(null, event);\n\t\t}\n\n\t}*/\n\n\t/*private static void fixExchanges() {\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\n\t\tMap> existingOnes = new HashMap();\n\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\n\t\tList exchanges = auditRepository.getAllExchanges();\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tUUID exchangeUuid = exchange.getExchangeId();\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to read headers for exchange \" + exchangeUuid + \" and Json \" + headerJson);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t*//*String serviceId = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (serviceId == null) {\n\t\t\t\tLOG.warn(\"No service ID found for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tUUID serviceUuid = UUID.fromString(serviceId);\n\n\t\t\tSet exchangeIdsDone = existingOnes.get(serviceUuid);\n\t\t\tif (exchangeIdsDone == null) {\n\t\t\t\texchangeIdsDone = new HashSet<>();\n\n\t\t\t\tList exchangeByServices = auditRepository.getExchangesByService(serviceUuid, Integer.MAX_VALUE);\n\t\t\t\tfor (ExchangeByService exchangeByService: exchangeByServices) {\n\t\t\t\t\texchangeIdsDone.add(exchangeByService.getExchangeId());\n\t\t\t\t}\n\n\t\t\t\texistingOnes.put(serviceUuid, exchangeIdsDone);\n\t\t\t}\n\n\t\t\t//create the exchange by service entity\n\t\t\tif (!exchangeIdsDone.contains(exchangeUuid)) {\n\n\t\t\t\tDate timestamp = exchange.getTimestamp();\n\n\t\t\t\tExchangeByService newOne = new ExchangeByService();\n\t\t\t\tnewOne.setExchangeId(exchangeUuid);\n\t\t\t\tnewOne.setServiceId(serviceUuid);\n\t\t\t\tnewOne.setTimestamp(timestamp);\n\n\t\t\t\tauditRepository.save(newOne);\n\t\t\t}*//*\n\n\t\t\ttry {\n\t\t\t\theaders.remove(HeaderKeys.BatchIdsJson);\n\t\t\t\tString newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\texchange.setHeaders(newHeaderJson);\n\n\t\t\t\tauditRepository.save(exchange);\n\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tLOG.error(\"Failed to populate batch IDs for exchange \" + exchangeUuid, e);\n\t\t\t}\n\n\t\t\tif (!headers.containsKey(HeaderKeys.BatchIdsJson)) {\n\n\t\t\t\t//fix the batch IDs not being in the exchange\n\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeUuid);\n\t\t\t\tif (!batches.isEmpty()) {\n\n\t\t\t\t\tList batchUuids = batches\n\t\t\t\t\t\t\t.stream()\n\t\t\t\t\t\t\t.map(t -> t.getBatchId())\n\t\t\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tString batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchUuids.toArray());\n\t\t\t\t\t\theaders.put(HeaderKeys.BatchIdsJson, batchUuidsStr);\n\t\t\t\t\t\tString newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\t\t\texchange.setHeaders(newHeaderJson);\n\n\t\t\t\t\t\tauditRepository.save(exchange, null);\n\n\t\t\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t\t\tLOG.error(\"Failed to populate batch IDs for exchange \" + exchangeUuid, e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t//}\n\t\t}\n\t}*/\n\n\t/*private static UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException {\n\n\t\tList endpoints = null;\n\t\ttry {\n\t\t\tendpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\n\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\n\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\tString endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString();\n\n\t\t\t\tLibraryRepository libraryRepository = new LibraryRepository();\n\t\t\t\tActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId);\n\t\t\t\tItem item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId());\n\t\t\t\tLibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent());\n\t\t\t\tSystem system = libraryItem.getSystem();\n\t\t\t\tfor (TechnicalInterface technicalInterface: system.getTechnicalInterface()) {\n\n\t\t\t\t\tif (endpointInterfaceId.equals(technicalInterface.getUuid())\n\t\t\t\t\t\t\t&& technicalInterface.getMessageFormat().equalsIgnoreCase(software)\n\t\t\t\t\t\t\t&& technicalInterface.getMessageFormatVersion().equalsIgnoreCase(messageVersion)) {\n\n\t\t\t\t\t\treturn endpointSystemId;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new PipelineException(\"Failed to process endpoints from service \" + service.getId());\n\t\t}\n\n\t\treturn null;\n\t}\n*/\n\t/*private static void addSystemIdToExchangeHeaders() throws Exception {\n\t\tLOG.info(\"populateExchangeBatchPatients\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\t\t//OrganisationRepository organisationRepository = new OrganisationRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT exchange_id FROM audit.exchange LIMIT 500;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\n\t\t\torg.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to read headers for exchange \" + exchangeId + \" and Json \" + headerJson);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" as no service UUID\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" as already got system UUID\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\n\t\t\t\t//work out service ID\n\t\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\n\t\t\t\tString software = headers.get(HeaderKeys.SourceSystem);\n\t\t\t\tString version = headers.get(HeaderKeys.SystemVersion);\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tUUID systemUuid = findSystemId(service, software, version);\n\n\t\t\t\theaders.put(HeaderKeys.SenderSystemUuid, systemUuid.toString());\n\n\t\t\t\t//work out protocol IDs\n\t\t\t\ttry {\n\t\t\t\t\tString newProtocolIdsJson = DetermineRelevantProtocolIds.getProtocolIdsForPublisherService(serviceIdStr);\n\t\t\t\t\theaders.put(HeaderKeys.ProtocolIds, newProtocolIdsJson);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tLOG.error(\"Failed to recalculate protocols for \" + exchangeId + \": \" + ex.getMessage());\n\t\t\t\t}\n\n\t\t\t\t//save to DB\n\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\texchange.setHeaders(headerJson);\n\t\t\t\tauditRepository.save(exchange);\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Error with exchange \" + exchangeId, ex);\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished populateExchangeBatchPatients\");\n\t}*/\n\n\n\t/*private static void populateExchangeBatchPatients() throws Exception {\n\t\tLOG.info(\"populateExchangeBatchPatients\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\t//ServiceRepository serviceRepository = new ServiceRepository();\n\t\t//OrganisationRepository organisationRepository = new OrganisationRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT exchange_id FROM audit.exchange LIMIT 500;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\n\t\t\torg.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to read headers for exchange \" + exchangeId + \" and Json \" + headerJson);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))\n\t\t\t\t\t|| Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" because no service or system in header\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tUUID serviceId = UUID.fromString(headers.get(HeaderKeys.SenderServiceUuid));\n\t\t\t\tUUID systemId = UUID.fromString(headers.get(HeaderKeys.SenderSystemUuid));\n\n\t\t\t\tList exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\tfor (ExchangeBatch exchangeBatch : exchangeBatches) {\n\n\t\t\t\t\tif (exchangeBatch.getEdsPatientId() != null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tUUID batchId = exchangeBatch.getBatchId();\n\t\t\t\t\tList resourceWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Patient.toString());\n\t\t\t\t\tif (resourceWrappers.isEmpty()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tList patientIds = new ArrayList<>();\n\t\t\t\t\tfor (ResourceByExchangeBatch resourceWrapper : resourceWrappers) {\n\t\t\t\t\t\tUUID patientId = resourceWrapper.getResourceId();\n\n\t\t\t\t\t\tif (resourceWrapper.getIsDeleted()) {\n\t\t\t\t\t\t\tdeleteEntirePatientRecord(patientId, serviceId, systemId, exchangeId, batchId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!patientIds.contains(patientId)) {\n\t\t\t\t\t\t\tpatientIds.add(patientId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (patientIds.size() != 1) {\n\t\t\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" and batch \" + batchId + \" because found \" + patientIds.size() + \" patient IDs\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tUUID patientId = patientIds.get(0);\n\t\t\t\t\texchangeBatch.setEdsPatientId(patientId);\n\n\t\t\t\t\texchangeBatchRepository.save(exchangeBatch);\n\t\t\t\t}\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Error with exchange \" + exchangeId, ex);\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished populateExchangeBatchPatients\");\n\t}\n\n\tprivate static void deleteEntirePatientRecord(UUID patientId, UUID serviceId, UUID systemId, UUID exchangeId, UUID batchId) throws Exception {\n\n\t\tFhirStorageService storageService = new FhirStorageService(serviceId, systemId);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tList resourceWrappers = resourceRepository.getResourcesByPatient(serviceId, systemId, patientId);\n\t\tfor (ResourceByPatient resourceWrapper: resourceWrappers) {\n\t\t\tString json = resourceWrapper.getResourceData();\n\t\t\tResource resource = new JsonParser().parse(json);\n\n\t\t\tstorageService.exchangeBatchDelete(exchangeId, batchId, resource);\n\t\t}\n\n\n\t}*/\n\n\t/*private static void convertPatientSearch() {\n\t\tLOG.info(\"Converting Patient Search\");\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tfor (UUID systemId : findSystemIds(service)) {\n\n\t\t\t\t\tList resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.EpisodeOfCare.toString());\n\t\t\t\t\tfor (ResourceByService resourceWrapper: resourceWrappers) {\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tEpisodeOfCare episodeOfCare = (EpisodeOfCare) new JsonParser().parse(resourceWrapper.getResourceData());\n\t\t\t\t\t\t\tString patientId = ReferenceHelper.getReferenceId(episodeOfCare.getPatient());\n\n\t\t\t\t\t\t\tResourceHistory patientWrapper = resourceRepository.getCurrentVersion(ResourceType.Patient.toString(), UUID.fromString(patientId));\n\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(patientWrapper.getResourceData())) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tPatient patient = (Patient) new JsonParser().parse(patientWrapper.getResourceData());\n\n\t\t\t\t\t\t\tPatientSearchHelper.update(serviceId, systemId, patient);\n\t\t\t\t\t\t\tPatientSearchHelper.update(serviceId, systemId, episodeOfCare);\n\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tLOG.error(\"Failed on \" + resourceWrapper.getResourceType() + \" \" + resourceWrapper.getResourceId(), ex);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Converted Patient Search\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t}*/\n\n\tprivate static List findSystemIds(Service service) throws Exception {\n\n\t\tList ret = new ArrayList<>();\n\n\t\tList endpoints = null;\n\t\ttry {\n\t\t\tendpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\tret.add(endpointSystemId);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new Exception(\"Failed to process endpoints from service \" + service.getId());\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/*private static void convertPatientLink() {\n\t\tLOG.info(\"Converting Patient Link\");\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tfor (UUID systemId : findSystemIds(service)) {\n\n\t\t\t\t\tList resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.Patient.toString());\n\t\t\t\t\tfor (ResourceByService resourceWrapper: resourceWrappers) {\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tPatient patient = (Patient)new JsonParser().parse(resourceWrapper.getResourceData());\n\t\t\t\t\t\t\tPatientLinkHelper.updatePersonId(patient);\n\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tLOG.error(\"Failed on \" + resourceWrapper.getResourceType() + \" \" + resourceWrapper.getResourceId(), ex);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Converted Patient Link\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixConfidentialPatients(String sharedStoragePath, UUID justThisService) {\n\t\tLOG.info(\"Fixing Confidential Patients using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tParserPool parserPool = new ParserPool();\n\t\tMappingManager mappingManager = CassandraConnector.getInstance().getMappingManager();\n\t\tMapper mapperResourceHistory = mappingManager.mapper(ResourceHistory.class);\n\t\tMapper mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class);\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\t\t\t\tMap resourcesFixed = new HashMap<>();\n\t\t\t\tMap> exchangeBatchesToPutInProtocolQueue = new HashMap<>();\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (systemIds.size() > 1) {\n\t\t\t\t\t\tthrow new Exception(\"Multiple system IDs for service \" + serviceId);\n\t\t\t\t\t}\n\t\t\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId);\n\n\t\t\t\t\tSet batchIdsToPutInProtocolQueue = new HashSet<>();\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tString dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f);\n\n\t\t\t\t\tEmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId);\n\t\t\t\t\tResourceFiler filer = new ResourceFiler(exchangeId, serviceId, systemId, null, null, 1);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers);\n\n\t\t\t\t\tProblemPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tObservationPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tDrugRecordPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tIssueRecordPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tDiaryPreTransformer.transform(version, parsers, filer, helper);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient)parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class);\n\t\t\t\t\twhile (patientParser.nextRecord()) {\n\t\t\t\t\t\tif (patientParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !patientParser.getDeleted()) {\n\t\t\t\t\t\t\tPatientTransformer.createResource(patientParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpatientParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class);\n\t\t\t\t\twhile (consultationParser.nextRecord()) {\n\t\t\t\t\t\tif (consultationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !consultationParser.getDeleted()) {\n\t\t\t\t\t\t\tConsultationTransformer.createResource(consultationParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsultationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tif (observationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !observationParser.getDeleted()) {\n\t\t\t\t\t\t\tObservationTransformer.createResource(observationParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class);\n\t\t\t\t\twhile (diaryParser.nextRecord()) {\n\t\t\t\t\t\tif (diaryParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !diaryParser.getDeleted()) {\n\t\t\t\t\t\t\tDiaryTransformer.createResource(diaryParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdiaryParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class);\n\t\t\t\t\twhile (drugRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (drugRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !drugRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tDrugRecordTransformer.createResource(drugRecordParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdrugRecordParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class);\n\t\t\t\t\twhile (issueRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (issueRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !issueRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tIssueRecordTransformer.createResource(issueRecordParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tissueRecordParser.close();\n\n\t\t\t\t\tfiler.waitToFinish(); //just to close the thread pool, even though it's not been used\n\t\t\t\t\tList resources = filer.getNewResources();\n\t\t\t\t\tfor (Resource resource: resources) {\n\n\t\t\t\t\t\tString patientId = IdHelper.getPatientId(resource);\n\t\t\t\t\t\tUUID edsPatientId = UUID.fromString(patientId);\n\n\t\t\t\t\t\tResourceType resourceType = resource.getResourceType();\n\t\t\t\t\t\tUUID resourceId = UUID.fromString(resource.getId());\n\n\t\t\t\t\t\tboolean foundResourceInDbBatch = false;\n\n\t\t\t\t\t\tList batchIds = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\tif (batchIds != null) {\n\t\t\t\t\t\t\tfor (UUID batchId : batchIds) {\n\n\t\t\t\t\t\t\t\tList resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), resourceId);\n\t\t\t\t\t\t\t\tif (resourceByExchangeBatches.isEmpty()) {\n\t\t\t\t\t\t\t\t\t//if we've deleted data, this will be null\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfoundResourceInDbBatch = true;\n\n\t\t\t\t\t\t\t\tfor (ResourceByExchangeBatch resourceByExchangeBatch : resourceByExchangeBatches) {\n\n\t\t\t\t\t\t\t\t\tString json = resourceByExchangeBatch.getResourceData();\n\t\t\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(json)) {\n\t\t\t\t\t\t\t\t\t\tLOG.warn(\"JSON already in resource \" + resourceType + \" \" + resourceId);\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\tjson = parserPool.composeString(resource);\n\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setIsDeleted(false);\n\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setSchemaVersion(\"0.1\");\n\n\t\t\t\t\t\t\t\t\t\tLOG.info(\"Saved resource by batch \" + resourceType + \" \" + resourceId + \" in batch \" + batchId);\n\n\t\t\t\t\t\t\t\t\t\tUUID versionUuid = resourceByExchangeBatch.getVersion();\n\t\t\t\t\t\t\t\t\t\tResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(resourceId, resourceType.toString(), versionUuid);\n\t\t\t\t\t\t\t\t\t\tif (resourceHistory == null) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find resource history for \" + resourceType + \" \" + resourceId + \" and version \" + versionUuid);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setIsDeleted(false);\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json));\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setSchemaVersion(\"0.1\");\n\n\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByExchangeBatch);\n\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceHistory);\n\t\t\t\t\t\t\t\t\t\tbatchIdsToPutInProtocolQueue.add(batchId);\n\n\t\t\t\t\t\t\t\t\t\tString key = resourceType.toString() + \":\" + resourceId;\n\t\t\t\t\t\t\t\t\t\tresourcesFixed.put(key, resourceHistory);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t//if a patient became confidential, we will have deleted all resources for that\n\t\t\t\t\t\t\t\t\t//patient, so we need to undo that too\n\t\t\t\t\t\t\t\t\t//to undelete WHOLE patient record\n\t\t\t\t\t\t\t\t\t//1. if THIS resource is a patient\n\t\t\t\t\t\t\t\t\t//2. get all other deletes from the same exchange batch\n\t\t\t\t\t\t\t\t\t//3. delete those from resource_by_exchange_batch (the deleted ones only)\n\t\t\t\t\t\t\t\t\t//4. delete same ones from resource_history\n\t\t\t\t\t\t\t\t\t//5. retrieve most recent resource_history\n\t\t\t\t\t\t\t\t\t//6. if not deleted, add to resources fixed\n\t\t\t\t\t\t\t\t\tif (resourceType == ResourceType.Patient) {\n\n\t\t\t\t\t\t\t\t\t\tList resourcesInSameBatch = resourceRepository.getResourcesForBatch(batchId);\n\t\t\t\t\t\t\t\t\t\tLOG.info(\"Undeleting \" + resourcesInSameBatch.size() + \" resources for batch \" + batchId);\n\t\t\t\t\t\t\t\t\t\tfor (ResourceByExchangeBatch resourceInSameBatch: resourcesInSameBatch) {\n\t\t\t\t\t\t\t\t\t\t\tif (!resourceInSameBatch.getIsDeleted()) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t//patient and episode resources will be restored by the above stuff, so don't try\n\t\t\t\t\t\t\t\t\t\t\t//to do it again\n\t\t\t\t\t\t\t\t\t\t\tif (resourceInSameBatch.getResourceType().equals(ResourceType.Patient.toString())\n\t\t\t\t\t\t\t\t\t\t\t\t\t|| resourceInSameBatch.getResourceType().equals(ResourceType.EpisodeOfCare.toString())) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(resourceInSameBatch.getResourceId(), resourceInSameBatch.getResourceType(), resourceInSameBatch.getVersion());\n\n\t\t\t\t\t\t\t\t\t\t\tmapperResourceByExchangeBatch.delete(resourceInSameBatch);\n\t\t\t\t\t\t\t\t\t\t\tmapperResourceHistory.delete(deletedResourceHistory);\n\t\t\t\t\t\t\t\t\t\t\tbatchIdsToPutInProtocolQueue.add(batchId);\n\n\t\t\t\t\t\t\t\t\t\t\t//check the most recent version of our resource, and if it's not deleted, add to the list to update the resource_by_service table\n\t\t\t\t\t\t\t\t\t\t\tResourceHistory mostRecentDeletedResourceHistory = resourceRepository.getCurrentVersion(resourceInSameBatch.getResourceType(), resourceInSameBatch.getResourceId());\n\t\t\t\t\t\t\t\t\t\t\tif (mostRecentDeletedResourceHistory != null\n\t\t\t\t\t\t\t\t\t\t\t\t\t&& !mostRecentDeletedResourceHistory.getIsDeleted()) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tString key2 = mostRecentDeletedResourceHistory.getResourceType().toString() + \":\" + mostRecentDeletedResourceHistory.getResourceId();\n\t\t\t\t\t\t\t\t\t\t\t\tresourcesFixed.put(key2, mostRecentDeletedResourceHistory);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//if we didn't find records in the DB to update, then\n\t\t\t\t\t\tif (!foundResourceInDbBatch) {\n\n\t\t\t\t\t\t\t//we can't generate a back-dated time UUID, but we need one so the resource_history\n\t\t\t\t\t\t\t//table is in order. To get a suitable time UUID, we just pull out the first exchange batch for our exchange,\n\t\t\t\t\t\t\t//and the batch ID is actually a time UUID that was allocated around the right time\n\t\t\t\t\t\t\tExchangeBatch firstBatch = exchangeBatchRepository.retrieveFirstForExchangeId(exchangeId);\n\n\t\t\t\t\t\t\t//if there was no batch for the exchange, then the exchange wasn't processed at all. So skip this exchange\n\t\t\t\t\t\t\t//and we'll pick up the same patient data in a following exchange\n\t\t\t\t\t\t\tif (firstBatch == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tUUID versionUuid = firstBatch.getBatchId();\n\n\t\t\t\t\t\t\t//find suitable batch ID\n\t\t\t\t\t\t\tUUID batchId = null;\n\t\t\t\t\t\t\tif (batchIds != null\n\t\t\t\t\t\t\t\t\t&& batchIds.size() > 0) {\n\t\t\t\t\t\t\t\tbatchId = batchIds.get(batchIds.size()-1);\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t//create new batch ID if not found\n\t\t\t\t\t\t\t\tExchangeBatch exchangeBatch = new ExchangeBatch();\n\t\t\t\t\t\t\t\texchangeBatch.setBatchId(UUIDs.timeBased());\n\t\t\t\t\t\t\t\texchangeBatch.setExchangeId(exchangeId);\n\t\t\t\t\t\t\t\texchangeBatch.setInsertedAt(new Date());\n\t\t\t\t\t\t\t\texchangeBatch.setEdsPatientId(edsPatientId);\n\t\t\t\t\t\t\t\texchangeBatchRepository.save(exchangeBatch);\n\n\t\t\t\t\t\t\t\tbatchId = exchangeBatch.getBatchId();\n\n\t\t\t\t\t\t\t\t//add to map for next resource\n\t\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbatchIds.add(batchId);\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(edsPatientId, batchIds);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString json = parserPool.composeString(resource);\n\n\t\t\t\t\t\t\tResourceHistory resourceHistory = new ResourceHistory();\n\t\t\t\t\t\t\tresourceHistory.setResourceId(resourceId);\n\t\t\t\t\t\t\tresourceHistory.setResourceType(resourceType.toString());\n\t\t\t\t\t\t\tresourceHistory.setVersion(versionUuid);\n\t\t\t\t\t\t\tresourceHistory.setCreatedAt(new Date());\n\t\t\t\t\t\t\tresourceHistory.setServiceId(serviceId);\n\t\t\t\t\t\t\tresourceHistory.setSystemId(systemId);\n\t\t\t\t\t\t\tresourceHistory.setIsDeleted(false);\n\t\t\t\t\t\t\tresourceHistory.setSchemaVersion(\"0.1\");\n\t\t\t\t\t\t\tresourceHistory.setResourceData(json);\n\t\t\t\t\t\t\tresourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json));\n\n\t\t\t\t\t\t\tResourceByExchangeBatch resourceByExchangeBatch = new ResourceByExchangeBatch();\n\t\t\t\t\t\t\tresourceByExchangeBatch.setBatchId(batchId);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setExchangeId(exchangeId);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceType(resourceType.toString());\n\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceId(resourceId);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setVersion(versionUuid);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setIsDeleted(false);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setSchemaVersion(\"0.1\");\n\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceData(json);\n\n\t\t\t\t\t\t\tresourceRepository.save(resourceHistory);\n\t\t\t\t\t\t\tresourceRepository.save(resourceByExchangeBatch);\n\n\t\t\t\t\t\t\tbatchIdsToPutInProtocolQueue.add(batchId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!batchIdsToPutInProtocolQueue.isEmpty()) {\n\t\t\t\t\t\texchangeBatchesToPutInProtocolQueue.put(exchangeId, batchIdsToPutInProtocolQueue);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//update the resource_by_service table (and the resource_by_patient view)\n\t\t\t\tfor (ResourceHistory resourceHistory: resourcesFixed.values()) {\n\t\t\t\t\tUUID latestVersionUpdatedUuid = resourceHistory.getVersion();\n\n\t\t\t\t\tResourceHistory latestVersion = resourceRepository.getCurrentVersion(resourceHistory.getResourceType(), resourceHistory.getResourceId());\n\t\t\t\t\tUUID latestVersionUuid = latestVersion.getVersion();\n\n\t\t\t\t\t//if there have been subsequent updates to the resource, then skip it\n\t\t\t\t\tif (!latestVersionUuid.equals(latestVersionUpdatedUuid)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tResource resource = parserPool.parse(resourceHistory.getResourceData());\n\t\t\t\t\tResourceMetadata metadata = MetadataFactory.createMetadata(resource);\n\t\t\t\t\tUUID patientId = ((PatientCompartment)metadata).getPatientId();\n\n\t\t\t\t\tResourceByService resourceByService = new ResourceByService();\n\t\t\t\t\tresourceByService.setServiceId(resourceHistory.getServiceId());\n\t\t\t\t\tresourceByService.setSystemId(resourceHistory.getSystemId());\n\t\t\t\t\tresourceByService.setResourceType(resourceHistory.getResourceType());\n\t\t\t\t\tresourceByService.setResourceId(resourceHistory.getResourceId());\n\t\t\t\t\tresourceByService.setCurrentVersion(resourceHistory.getVersion());\n\t\t\t\t\tresourceByService.setUpdatedAt(resourceHistory.getCreatedAt());\n\t\t\t\t\tresourceByService.setPatientId(patientId);\n\t\t\t\t\tresourceByService.setSchemaVersion(resourceHistory.getSchemaVersion());\n\t\t\t\t\tresourceByService.setResourceMetadata(JsonSerializer.serialize(metadata));\n\t\t\t\t\tresourceByService.setResourceData(resourceHistory.getResourceData());\n\n\t\t\t\t\tresourceRepository.save(resourceByService);\n\n\t\t\t\t\t//call out to our patient search and person matching services\n\t\t\t\t\tif (resource instanceof Patient) {\n\t\t\t\t\t\tPatientLinkHelper.updatePersonId((Patient)resource);\n\t\t\t\t\t\tPatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (Patient)resource);\n\n\t\t\t\t\t} else if (resource instanceof EpisodeOfCare) {\n\t\t\t\t\t\tPatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (EpisodeOfCare)resource);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!exchangeBatchesToPutInProtocolQueue.isEmpty()) {\n\t\t\t\t\t//find the config for our protocol queue\n\t\t\t\t\tString configXml = ConfigManager.getConfiguration(\"inbound\", \"queuereader\");\n\n\t\t\t\t\t//the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary\n\t\t\t\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\t\t\t\t\tPipeline pipeline = configuration.getPipeline();\n\n\t\t\t\t\tPostMessageToExchangeConfig config = pipeline\n\t\t\t\t\t\t\t.getPipelineComponents()\n\t\t\t\t\t\t\t.stream()\n\t\t\t\t\t\t\t.filter(t -> t instanceof PostMessageToExchangeConfig)\n\t\t\t\t\t\t\t.map(t -> (PostMessageToExchangeConfig) t)\n\t\t\t\t\t\t\t.filter(t -> t.getExchange().equalsIgnoreCase(\"EdsProtocol\"))\n\t\t\t\t\t\t\t.collect(StreamExtension.singleOrNullCollector());\n\n\t\t\t\t\t//post to the protocol exchange\n\t\t\t\t\tfor (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) {\n\t\t\t\t\t\tSet batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId);\n\n\t\t\t\t\t\torg.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\t\tString batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds);\n\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString);\n\n\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(config);\n\t\t\t\t\t\tcomponent.process(exchange);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Confidential Patients\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixDeletedAppointments(String sharedStoragePath, boolean saveChanges, UUID justThisService) {\n\t\tLOG.info(\"Fixing Deleted Appointments using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tParserPool parserPool = new ParserPool();\n\t\tMappingManager mappingManager = CassandraConnector.getInstance().getMappingManager();\n\t\tMapper mapperResourceHistory = mappingManager.mapper(ResourceHistory.class);\n\t\tMapper mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class);\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (systemIds.size() > 1) {\n\t\t\t\t\t\tthrow new Exception(\"Multiple system IDs for service \" + serviceId);\n\t\t\t\t\t}\n\t\t\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId);\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch batch : batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class, dir, version, true, parsers);\n\n\t\t\t\t\t//find any deleted patients\n\t\t\t\t\tList deletedPatientUuids = new ArrayList<>();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class);\n\t\t\t\t\twhile (patientParser.nextRecord()) {\n\t\t\t\t\t\tif (patientParser.getDeleted()) {\n\t\t\t\t\t\t\t//find the EDS patient ID for this local guid\n\t\t\t\t\t\t\tString patientGuid = patientParser.getPatientGuid();\n\t\t\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid);\n\t\t\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find patient ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + ResourceType.Patient + \" local ID \" + patientGuid);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdeletedPatientUuids.add(edsPatientId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpatientParser.close();\n\n\t\t\t\t\t//go through the appts file to find properly deleted appt GUIDS\n\t\t\t\t\tList deletedApptUuids = new ArrayList<>();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.appointment.Slot apptParser = (org.endeavourhealth.transform.emis.csv.schema.appointment.Slot) parsers.get(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class);\n\t\t\t\t\twhile (apptParser.nextRecord()) {\n\t\t\t\t\t\tif (apptParser.getDeleted()) {\n\t\t\t\t\t\t\tString patientGuid = apptParser.getPatientGuid();\n\t\t\t\t\t\t\tString slotGuid = apptParser.getSlotGuid();\n\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(patientGuid)) {\n\t\t\t\t\t\t\t\tString uniqueLocalId = EmisCsvHelper.createUniqueId(patientGuid, slotGuid);\n\t\t\t\t\t\t\t\tUUID edsApptId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Appointment, uniqueLocalId);\n\t\t\t\t\t\t\t\tdeletedApptUuids.add(edsApptId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tapptParser.close();\n\n\t\t\t\t\tfor (UUID edsPatientId : deletedPatientUuids) {\n\n\t\t\t\t\t\tList batchIds = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t//if there are no batches for this patient, we'll be handling this data in another exchange\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (UUID batchId : batchIds) {\n\t\t\t\t\t\t\tList apptWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Appointment.toString());\n\t\t\t\t\t\t\tfor (ResourceByExchangeBatch apptWrapper : apptWrappers) {\n\n\t\t\t\t\t\t\t\t//ignore non-deleted appts\n\t\t\t\t\t\t\t\tif (!apptWrapper.getIsDeleted()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//if the appt was deleted legitamately, then skip it\n\t\t\t\t\t\t\t\tUUID apptId = apptWrapper.getResourceId();\n\t\t\t\t\t\t\t\tif (deletedApptUuids.contains(apptId)) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(apptWrapper.getResourceId(), apptWrapper.getResourceType(), apptWrapper.getVersion());\n\n\t\t\t\t\t\t\t\tif (saveChanges) {\n\t\t\t\t\t\t\t\t\tmapperResourceByExchangeBatch.delete(apptWrapper);\n\t\t\t\t\t\t\t\t\tmapperResourceHistory.delete(deletedResourceHistory);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tLOG.info(\"Un-deleted \" + apptWrapper.getResourceType() + \" \" + apptWrapper.getResourceId() + \" in batch \" + batchId + \" patient \" + edsPatientId);\n\n\t\t\t\t\t\t\t\t//now get the most recent instance of the appointment, and if it's NOT deleted, insert into the resource_by_service table\n\t\t\t\t\t\t\t\tResourceHistory mostRecentResourceHistory = resourceRepository.getCurrentVersion(apptWrapper.getResourceType(), apptWrapper.getResourceId());\n\t\t\t\t\t\t\t\tif (mostRecentResourceHistory != null\n\t\t\t\t\t\t\t\t\t\t&& !mostRecentResourceHistory.getIsDeleted()) {\n\n\t\t\t\t\t\t\t\t\tResource resource = parserPool.parse(mostRecentResourceHistory.getResourceData());\n\t\t\t\t\t\t\t\t\tResourceMetadata metadata = MetadataFactory.createMetadata(resource);\n\t\t\t\t\t\t\t\t\tUUID patientId = ((PatientCompartment) metadata).getPatientId();\n\n\t\t\t\t\t\t\t\t\tResourceByService resourceByService = new ResourceByService();\n\t\t\t\t\t\t\t\t\tresourceByService.setServiceId(mostRecentResourceHistory.getServiceId());\n\t\t\t\t\t\t\t\t\tresourceByService.setSystemId(mostRecentResourceHistory.getSystemId());\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceType(mostRecentResourceHistory.getResourceType());\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceId(mostRecentResourceHistory.getResourceId());\n\t\t\t\t\t\t\t\t\tresourceByService.setCurrentVersion(mostRecentResourceHistory.getVersion());\n\t\t\t\t\t\t\t\t\tresourceByService.setUpdatedAt(mostRecentResourceHistory.getCreatedAt());\n\t\t\t\t\t\t\t\t\tresourceByService.setPatientId(patientId);\n\t\t\t\t\t\t\t\t\tresourceByService.setSchemaVersion(mostRecentResourceHistory.getSchemaVersion());\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceMetadata(JsonSerializer.serialize(metadata));\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceData(mostRecentResourceHistory.getResourceData());\n\n\t\t\t\t\t\t\t\t\tif (saveChanges) {\n\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByService);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tLOG.info(\"Restored \" + apptWrapper.getResourceType() + \" \" + apptWrapper.getResourceId() + \" to resource_by_service table\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Deleted Appointments Patients\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\n\t/*private static void fixReviews(String sharedStoragePath, UUID justThisService) {\n\t\tLOG.info(\"Fixing Reviews using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tParserPool parserPool = new ParserPool();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\t\t\t\tMap problemCodes = new HashMap<>();\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId + \" with \" + batches.size() + \" batches\");\n\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Problem problemParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class);\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\n\t\t\t\t\twhile (problemParser.nextRecord()) {\n\t\t\t\t\t\tString patientGuid = problemParser.getPatientGuid();\n\t\t\t\t\t\tString observationGuid = problemParser.getObservationGuid();\n\t\t\t\t\t\tString key = patientGuid + \":\" + observationGuid;\n\t\t\t\t\t\tif (!problemCodes.containsKey(key)) {\n\t\t\t\t\t\t\tproblemCodes.put(key, null);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tproblemParser.close();\n\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tString patientGuid = observationParser.getPatientGuid();\n\t\t\t\t\t\tString observationGuid = observationParser.getObservationGuid();\n\t\t\t\t\t\tString key = patientGuid + \":\" + observationGuid;\n\t\t\t\t\t\tif (problemCodes.containsKey(key)) {\n\t\t\t\t\t\t\tLong codeId = observationParser.getCodeId();\n\t\t\t\t\t\t\tif (codeId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tproblemCodes.put(key, codeId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\t\t\t\t\tLOG.info(\"Found \" + problemCodes.size() + \" problem codes so far\");\n\n\t\t\t\t\tString dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f);\n\n\t\t\t\t\tEmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId);\n\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tString problemGuid = observationParser.getProblemGuid();\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(problemGuid)) {\n\t\t\t\t\t\t\tString patientGuid = observationParser.getPatientGuid();\n\t\t\t\t\t\t\tLong codeId = observationParser.getCodeId();\n\t\t\t\t\t\t\tif (codeId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString key = patientGuid + \":\" + problemGuid;\n\t\t\t\t\t\t\tLong problemCodeId = problemCodes.get(key);\n\t\t\t\t\t\t\tif (problemCodeId == null\n\t\t\t\t\t\t\t\t\t|| problemCodeId.longValue() != codeId.longValue()) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if here, our code is the same as the problem, so it's a review\n\t\t\t\t\t\t\tString locallyUniqueId = patientGuid + \":\" + observationParser.getObservationGuid();\n\t\t\t\t\t\t\tResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, helper);\n\n\t\t\t\t\t\t\tfor (UUID systemId: systemIds) {\n\n\t\t\t\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid);\n\t\t\t\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find patient ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + ResourceType.Patient + \" local ID \" + patientGuid);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tUUID edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId);\n\t\t\t\t\t\t\t\tif (edsObservationId == null) {\n\n\t\t\t\t\t\t\t\t\t//try observations as diagnostic reports, because it could be one of those instead\n\t\t\t\t\t\t\t\t\tif (resourceType == ResourceType.Observation) {\n\t\t\t\t\t\t\t\t\t\tresourceType = ResourceType.DiagnosticReport;\n\t\t\t\t\t\t\t\t\t\tedsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (edsObservationId == null) {\n\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find observation ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + resourceType + \" local ID \" + locallyUniqueId);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\t\t//if there are no batches for this patient, we'll be handling this data in another exchange\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t//throw new Exception(\"Failed to find batch ID for patient \" + edsPatientId + \" in exchange \" + exchangeId + \" for resource \" + resourceType + \" \" + edsObservationId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor (UUID batchId: batchIds) {\n\n\t\t\t\t\t\t\t\t\tList resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), edsObservationId);\n\t\t\t\t\t\t\t\t\tif (resourceByExchangeBatches.isEmpty()) {\n\t\t\t\t\t\t\t\t\t\t//if we've deleted data, this will be null\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t//throw new Exception(\"No resources found for batch \" + batchId + \" resource type \" + resourceType + \" and resource id \" + edsObservationId);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tfor (ResourceByExchangeBatch resourceByExchangeBatch: resourceByExchangeBatches) {\n\n\t\t\t\t\t\t\t\t\t\tString json = resourceByExchangeBatch.getResourceData();\n\t\t\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(json)) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"No JSON in resource \" + resourceType + \" \" + edsObservationId + \" in batch \" + batchId);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tResource resource = parserPool.parse(json);\n\t\t\t\t\t\t\t\t\t\tif (addReviewExtension((DomainResource)resource)) {\n\t\t\t\t\t\t\t\t\t\t\tjson = parserPool.composeString(resource);\n\t\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\t\tLOG.info(\"Changed \" + resourceType + \" \" + edsObservationId + \" to have extension in batch \" + batchId);\n\n\t\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByExchangeBatch);\n\n\t\t\t\t\t\t\t\t\t\t\tUUID versionUuid = resourceByExchangeBatch.getVersion();\n\t\t\t\t\t\t\t\t\t\t\tResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(edsObservationId, resourceType.toString(), versionUuid);\n\t\t\t\t\t\t\t\t\t\t\tif (resourceHistory == null) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find resource history for \" + resourceType + \" \" + edsObservationId + \" and version \" + versionUuid);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json));\n\t\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceHistory);\n\n\t\t\t\t\t\t\t\t\t\t\tResourceByService resourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType.toString(), edsObservationId);\n\t\t\t\t\t\t\t\t\t\t\tif (resourceByService != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tUUID serviceVersionUuid = resourceByService.getCurrentVersion();\n\t\t\t\t\t\t\t\t\t\t\t\tif (serviceVersionUuid.equals(versionUuid)) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tresourceByService.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByService);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tLOG.info(\"\" + resourceType + \" \" + edsObservationId + \" already has extension\");\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//1. find out resource type originall saved from\n\t\t\t\t\t\t\t//2. retrieve from resource_by_exchange_batch\n\t\t\t\t\t\t\t//3. update resource in resource_by_exchange_batch\n\t\t\t\t\t\t\t//4. retrieve from resource_history\n\t\t\t\t\t\t\t//5. update resource_history\n\t\t\t\t\t\t\t//6. retrieve record from resource_by_service\n\t\t\t\t\t\t\t//7. if resource_by_service version UUID matches the resource_history updated, then update that too\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Reviews\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static boolean addReviewExtension(DomainResource resource) {\n\n\t\tif (ExtensionConverter.hasExtension(resource, FhirExtensionUri.IS_REVIEW)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tExtension extension = ExtensionConverter.createExtension(FhirExtensionUri.IS_REVIEW, new BooleanType(true));\n\t\tresource.addExtension(extension);\n\n\t\treturn true;\n\t}*/\n\n\n\t/*private static void runProtocolsForConfidentialPatients(String sharedStoragePath, UUID justThisService) {\n\t\tLOG.info(\"Running Protocols for Confidential Patients using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//once we match the servce, set this to null to do all other services\n\t\t\t\tjustThisService = null;\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\n\t\t\t\tList interestingPatientGuids = new ArrayList<>();\n\t\t\t\tMap>> batchesPerPatientPerExchange = new HashMap<>();\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId);\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch batch : batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbatchesPerPatientPerExchange.put(exchangeId, batchesPerPatient);\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class);\n\t\t\t\t\twhile (patientParser.nextRecord()) {\n\t\t\t\t\t\tif (patientParser.getIsConfidential() || patientParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(patientParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpatientParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class);\n\t\t\t\t\twhile (consultationParser.nextRecord()) {\n\t\t\t\t\t\tif (consultationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !consultationParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(consultationParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsultationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tif (observationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !observationParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(observationParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class);\n\t\t\t\t\twhile (diaryParser.nextRecord()) {\n\t\t\t\t\t\tif (diaryParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !diaryParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(diaryParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdiaryParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class);\n\t\t\t\t\twhile (drugRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (drugRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !drugRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(drugRecordParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdrugRecordParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class);\n\t\t\t\t\twhile (issueRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (issueRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !issueRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(issueRecordParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tissueRecordParser.close();\n\t\t\t\t}\n\n\t\t\t\tMap> exchangeBatchesToPutInProtocolQueue = new HashMap<>();\n\n\t\t\t\tfor (String interestingPatientGuid: interestingPatientGuids) {\n\n\t\t\t\t\tif (systemIds.size() > 1) {\n\t\t\t\t\t\tthrow new Exception(\"Multiple system IDs for service \" + serviceId);\n\t\t\t\t\t}\n\t\t\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, interestingPatientGuid);\n\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find patient ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + ResourceType.Patient + \" local ID \" + interestingPatientGuid);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (UUID exchangeId: batchesPerPatientPerExchange.keySet()) {\n\t\t\t\t\t\tMap> batchesPerPatient = batchesPerPatientPerExchange.get(exchangeId);\n\t\t\t\t\t\tList batches = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\tif (batches != null) {\n\n\t\t\t\t\t\t\tSet batchesForExchange = exchangeBatchesToPutInProtocolQueue.get(exchangeId);\n\t\t\t\t\t\t\tif (batchesForExchange == null) {\n\t\t\t\t\t\t\t\tbatchesForExchange = new HashSet<>();\n\t\t\t\t\t\t\t\texchangeBatchesToPutInProtocolQueue.put(exchangeId, batchesForExchange);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbatchesForExchange.addAll(batches);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif (!exchangeBatchesToPutInProtocolQueue.isEmpty()) {\n\t\t\t\t\t//find the config for our protocol queue\n\t\t\t\t\tString configXml = ConfigManager.getConfiguration(\"inbound\", \"queuereader\");\n\n\t\t\t\t\t//the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary\n\t\t\t\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\t\t\t\t\tPipeline pipeline = configuration.getPipeline();\n\n\t\t\t\t\tPostMessageToExchangeConfig config = pipeline\n\t\t\t\t\t\t\t.getPipelineComponents()\n\t\t\t\t\t\t\t.stream()\n\t\t\t\t\t\t\t.filter(t -> t instanceof PostMessageToExchangeConfig)\n\t\t\t\t\t\t\t.map(t -> (PostMessageToExchangeConfig) t)\n\t\t\t\t\t\t\t.filter(t -> t.getExchange().equalsIgnoreCase(\"EdsProtocol\"))\n\t\t\t\t\t\t\t.collect(StreamExtension.singleOrNullCollector());\n\n\t\t\t\t\t//post to the protocol exchange\n\t\t\t\t\tfor (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) {\n\t\t\t\t\t\tSet batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId);\n\n\t\t\t\t\t\torg.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\t\tString batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds);\n\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString);\n\t\t\t\t\t\tLOG.info(\"Posting exchange \" + exchangeId + \" batch \" + batchIdString);\n\n\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(config);\n\t\t\t\t\t\tcomponent.process(exchange);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Running Protocols for Confidential Patients\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixOrgs() {\n\n\t\tLOG.info(\"Posting orgs to protocol queue\");\n\n\t\tString[] orgIds = new String[]{\n\t\t\"332f31a2-7b28-47cb-af6f-18f65440d43d\",\n\t\t\"c893d66b-eb89-4657-9f53-94c5867e7ed9\"};\n\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\n\t\tMap> exchangeBatches = new HashMap<>();\n\n\t\tfor (String orgId: orgIds) {\n\n\t\t\tLOG.info(\"Doing org ID \" + orgId);\n\t\t\tUUID orgUuid = UUID.fromString(orgId);\n\n\t\t\ttry {\n\n\t\t\t\t//select batch_id from ehr.resource_by_exchange_batch where resource_type = 'Organization' and resource_id = 8f465517-729b-4ad9-b405-92b487047f19 LIMIT 1 ALLOW FILTERING;\n\t\t\t\tResourceByExchangeBatch resourceByExchangeBatch = resourceRepository.getFirstResourceByExchangeBatch(ResourceType.Organization.toString(), orgUuid);\n\t\t\t\tUUID batchId = resourceByExchangeBatch.getBatchId();\n\n\t\t\t\t//select exchange_id from ehr.exchange_batch where batch_id = 1a940e10-1535-11e7-a29d-a90b99186399 LIMIT 1 ALLOW FILTERING;\n\t\t\t\tExchangeBatch exchangeBatch = exchangeBatchRepository.retrieveFirstForBatchId(batchId);\n\t\t\t\tUUID exchangeId = exchangeBatch.getExchangeId();\n\n\t\t\t\tSet list = exchangeBatches.get(exchangeId);\n\t\t\t\tif (list == null) {\n\t\t\t\t\tlist = new HashSet<>();\n\t\t\t\t\texchangeBatches.put(exchangeId, list);\n\t\t\t\t}\n\t\t\t\tlist.add(batchId);\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"\", ex);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t//find the config for our protocol queue (which is in the inbound config)\n\t\t\tString configXml = ConfigManager.getConfiguration(\"inbound\", \"queuereader\");\n\n\t\t\t//the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary\n\t\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\t\t\tPipeline pipeline = configuration.getPipeline();\n\n\t\t\tPostMessageToExchangeConfig config = pipeline\n\t\t\t\t\t.getPipelineComponents()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(t -> t instanceof PostMessageToExchangeConfig)\n\t\t\t\t\t.map(t -> (PostMessageToExchangeConfig) t)\n\t\t\t\t\t.filter(t -> t.getExchange().equalsIgnoreCase(\"EdsProtocol\"))\n\t\t\t\t\t.collect(StreamExtension.singleOrNullCollector());\n\n\t\t\t//post to the protocol exchange\n\t\t\tfor (UUID exchangeId : exchangeBatches.keySet()) {\n\t\t\t\tSet batchIds = exchangeBatches.get(exchangeId);\n\n\t\t\t\torg.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\tString batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds);\n\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString);\n\t\t\t\tLOG.info(\"Posting exchange \" + exchangeId + \" batch \" + batchIdString);\n\n\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(config);\n\t\t\t\tcomponent.process(exchange);\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\n\t\t\tLOG.error(\"\", ex);\n\t\t\treturn;\n\t\t}\n\n\n\t\tLOG.info(\"Finished posting orgs to protocol queue\");\n\t}*/\n\n\t/*private static void findCodes() {\n\n\t\tLOG.info(\"Finding missing codes\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT service_id, system_id, exchange_id, version FROM audit.exchange_transform_audit ALLOW FILTERING;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID serviceId = row.get(0, UUID.class);\n\t\t\tUUID systemId = row.get(1, UUID.class);\n\t\t\tUUID exchangeId = row.get(2, UUID.class);\n\t\t\tUUID version = row.get(3, UUID.class);\n\n\t\t\tExchangeTransformAudit audit = auditRepository.getExchangeTransformAudit(serviceId, systemId, exchangeId, version);\n\t\t\tString xml = audit.getErrorXml();\n\t\t\tif (xml == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString codePrefix = \"Failed to find clinical code CodeableConcept for codeId \";\n\t\t\tint codeIndex = xml.indexOf(codePrefix);\n\t\t\tif (codeIndex > -1) {\n\t\t\t\tint startIndex = codeIndex + codePrefix.length();\n\t\t\t\tint tagEndIndex = xml.indexOf(\"<\", startIndex);\n\n\t\t\t\tString code = xml.substring(startIndex, tagEndIndex);\n\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tString name = service.getName();\n\n\t\t\t\tLOG.info(name + \" clinical code \" + code + \" from \" + audit.getStarted());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcodePrefix = \"Failed to find medication CodeableConcept for codeId \";\n\t\t\tcodeIndex = xml.indexOf(codePrefix);\n\t\t\tif (codeIndex > -1) {\n\t\t\t\tint startIndex = codeIndex + codePrefix.length();\n\t\t\t\tint tagEndIndex = xml.indexOf(\"<\", startIndex);\n\n\t\t\t\tString code = xml.substring(startIndex, tagEndIndex);\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tString name = service.getName();\n\n\t\t\t\tLOG.info(name + \" drug code \" + code + \" from \" + audit.getStarted());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished finding missing codes\");\n\t}*/\n\n\tprivate static void createTppSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) {\n\t\tLOG.info(\"Creating TPP Subset\");\n\n\t\ttry {\n\n\t\t\tSet personIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpersonIds.add(line);\n\t\t\t}\n\n\t\t\tFile sourceDir = new File(sourceDirPath);\n\t\t\tFile destDir = new File(destDirPath);\n\n\t\t\tif (!destDir.exists()) {\n\t\t\t\tdestDir.mkdirs();\n\t\t\t}\n\n\t\t\tcreateTppSubsetForFile(sourceDir, destDir, personIds);\n\n\t\t\tLOG.info(\"Finished Creating TPP Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\tprivate static void createTppSubsetForFile(File sourceDir, File destDir, Set personIds) throws Exception {\n\n\t\tFile[] files = sourceDir.listFiles();\n\t\tLOG.info(\"Found \" + files.length + \" files in \" + sourceDir);\n\n\t\tfor (File sourceFile: files) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\t//LOG.info(\"Doing dir \" + sourceFile);\n\t\t\t\tcreateTppSubsetForFile(sourceFile, destFile, personIds);\n\n\t\t\t} else {\n\n\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\tdestFile.delete();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Checking file \" + sourceFile);\n\n\t\t\t\t//skip any non-CSV file\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (!ext.equalsIgnoreCase(\"csv\")) {\n\t\t\t\t\tLOG.info(\"Skipping as not a CSV file\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\t\tCSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withHeader();\n\n\t\t\t\tCSVParser parser = new CSVParser(br, format);\n\n\t\t\t\tString filterColumn = null;\n\n\t\t\t\tMap headerMap = parser.getHeaderMap();\n\t\t\t\tif (headerMap.containsKey(\"IDPatient\")) {\n\t\t\t\t\tfilterColumn = \"IDPatient\";\n\n\t\t\t\t} else if (name.equalsIgnoreCase(\"SRPatient.csv\")) {\n\t\t\t\t\tfilterColumn = \"RowIdentifier\";\n\n\t\t\t\t} else {\n\t\t\t\t\t//if no patient column, just copy the file\n\t\t\t\t\tparser.close();\n\n\t\t\t\t\tLOG.info(\"Copying non-patient file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString[] columnHeaders = new String[headerMap.size()];\n\t\t\t\tIterator headerIterator = headerMap.keySet().iterator();\n\t\t\t\twhile (headerIterator.hasNext()) {\n\t\t\t\t\tString headerName = headerIterator.next();\n\t\t\t\t\tint headerIndex = headerMap.get(headerName);\n\t\t\t\t\tcolumnHeaders[headerIndex] = headerName;\n\t\t\t\t}\n\n\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\n\t\t\t\tCSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders));\n\n\t\t\t\tIterator csvIterator = parser.iterator();\n\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\tString patientId = csvRecord.get(filterColumn);\n\t\t\t\t\tif (personIds.contains(patientId)) {\n\n\t\t\t\t\t\tprinter.printRecord(csvRecord);\n\t\t\t\t\t\tprinter.flush();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparser.close();\n\t\t\t\tprinter.close();\n\n\t\t\t\t/*} else {\n\t\t\t\t\t//the 2.1 files are going to be a pain to split by patient, so just copy them over\n\t\t\t\t\tLOG.info(\"Copying 2.1 file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void createVisionSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) {\n\t\tLOG.info(\"Creating Vision Subset\");\n\n\t\ttry {\n\n\t\t\tSet personIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpersonIds.add(line);\n\t\t\t}\n\n\t\t\tFile sourceDir = new File(sourceDirPath);\n\t\t\tFile destDir = new File(destDirPath);\n\n\t\t\tif (!destDir.exists()) {\n\t\t\t\tdestDir.mkdirs();\n\t\t\t}\n\n\t\t\tcreateVisionSubsetForFile(sourceDir, destDir, personIds);\n\n\t\t\tLOG.info(\"Finished Creating Vision Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\tprivate static void createVisionSubsetForFile(File sourceDir, File destDir, Set personIds) throws Exception {\n\n\t\tFile[] files = sourceDir.listFiles();\n\t\tLOG.info(\"Found \" + files.length + \" files in \" + sourceDir);\n\n\t\tfor (File sourceFile: files) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\tcreateVisionSubsetForFile(sourceFile, destFile, personIds);\n\n\t\t\t} else {\n\n\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\tdestFile.delete();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Checking file \" + sourceFile);\n\n\t\t\t\t//skip any non-CSV file\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (!ext.equalsIgnoreCase(\"csv\")) {\n\t\t\t\t\tLOG.info(\"Skipping as not a CSV file\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\t\tCSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL);\n\n\t\t\t\tCSVParser parser = new CSVParser(br, format);\n\n\t\t\t\tint filterColumn = -1;\n\n\t\t\t\tif (name.contains(\"encounter_data\") || name.contains(\"journal_data\") ||\n\t\t\t\t\t\tname.contains(\"patient_data\") || name.contains(\"referral_data\")) {\n\n\t\t\t\t\tfilterColumn = 0;\n\t\t\t\t} else {\n\t\t\t\t\t//if no patient column, just copy the file\n\t\t\t\t\tparser.close();\n\n\t\t\t\t\tLOG.info(\"Copying non-patient file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\n\t\t\t\tCSVPrinter printer = new CSVPrinter(bw, format);\n\n\t\t\t\tIterator csvIterator = parser.iterator();\n\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\tString patientId = csvRecord.get(filterColumn);\n\t\t\t\t\tif (personIds.contains(patientId)) {\n\n\t\t\t\t\t\tprinter.printRecord(csvRecord);\n\t\t\t\t\t\tprinter.flush();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparser.close();\n\t\t\t\tprinter.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void createAdastraSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) {\n\t\tLOG.info(\"Creating Adastra Subset\");\n\n\t\ttry {\n\n\t\t\tSet caseIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//adastra extract files are all keyed on caseId\n\t\t\t\tcaseIds.add(line);\n\t\t\t}\n\n\t\t\tFile sourceDir = new File(sourceDirPath);\n\t\t\tFile destDir = new File(destDirPath);\n\n\t\t\tif (!destDir.exists()) {\n\t\t\t\tdestDir.mkdirs();\n\t\t\t}\n\n\t\t\tcreateAdastraSubsetForFile(sourceDir, destDir, caseIds);\n\n\t\t\tLOG.info(\"Finished Creating Adastra Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\tprivate static void createAdastraSubsetForFile(File sourceDir, File destDir, Set caseIds) throws Exception {\n\n\t\tFile[] files = sourceDir.listFiles();\n\t\tLOG.info(\"Found \" + files.length + \" files in \" + sourceDir);\n\n\t\tfor (File sourceFile: files) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\tcreateAdastraSubsetForFile(sourceFile, destFile, caseIds);\n\n\t\t\t} else {\n\n\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\tdestFile.delete();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Checking file \" + sourceFile);\n\n\t\t\t\t//skip any non-CSV file\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (!ext.equalsIgnoreCase(\"csv\")) {\n\t\t\t\t\tLOG.info(\"Skipping as not a CSV file\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\t\t//fully quote destination file to fix CRLF in columns\n\t\t\t\tCSVFormat format = CSVFormat.DEFAULT.withDelimiter('|');\n\n\t\t\t\tCSVParser parser = new CSVParser(br, format);\n\n\t\t\t\tint filterColumn = -1;\n\n\t\t\t\t//CaseRef column at 0\n\t\t\t\tif (name.contains(\"NOTES\") || name.contains(\"CASEQUESTIONS\") ||\n\t\t\t\t\t\tname.contains(\"OUTCOMES\") || name.contains(\"CONSULTATION\") ||\n\t\t\t\t\t\tname.contains(\"CLINICALCODES\") || name.contains(\"PRESCRIPTIONS\") ||\n\t\t\t\t\t\tname.contains(\"PATIENT\")) {\n\n\t\t\t\t\tfilterColumn = 0;\n\n\t\t\t\t} else if (name.contains(\"CASE\")) {\n\t\t\t\t\t//CaseRef column at 2\n\t\t\t\t\tfilterColumn = 2;\n\n\t\t\t\t} else if (name.contains(\"PROVIDER\")) {\n\t\t\t\t\t//CaseRef column at 7\n\t\t\t\t\tfilterColumn = 7;\n\n\t\t\t\t} else {\n\t\t\t\t\t//if no patient column, just copy the file\n\t\t\t\t\tparser.close();\n\n\t\t\t\t\tLOG.info(\"Copying non-patient file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\n\t\t\t\tCSVPrinter printer = new CSVPrinter(bw, format);\n\n\t\t\t\tIterator csvIterator = parser.iterator();\n\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\tString caseId = csvRecord.get(filterColumn);\n\t\t\t\t\tif (caseIds.contains(caseId)) {\n\n\t\t\t\t\t\tprinter.printRecord(csvRecord);\n\t\t\t\t\t\tprinter.flush();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparser.close();\n\t\t\t\tprinter.close();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*class ResourceFiler extends FhirResourceFiler {\n\tpublic ResourceFiler(UUID exchangeId, UUID serviceId, UUID systemId, TransformError transformError,\n\t\t\t\t\t\t\t List batchIdsCreated, int maxFilingThreads) {\n\t\tsuper(exchangeId, serviceId, systemId, transformError, batchIdsCreated, maxFilingThreads);\n\t}\n\n\tprivate List newResources = new ArrayList<>();\n\n\tpublic List getNewResources() {\n\t\treturn newResources;\n\t}\n\n\t@Override\n\tpublic void saveAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception {\n\t\tthrow new Exception(\"shouldn't be calling saveAdminResource\");\n\t}\n\n\t@Override\n\tpublic void deleteAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception {\n\t\tthrow new Exception(\"shouldn't be calling deleteAdminResource\");\n\t}\n\n\t@Override\n\tpublic void savePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception {\n\n\t\tfor (Resource resource: resources) {\n\t\t\tif (mapIds) {\n\t\t\t\tIdHelper.mapIds(getServiceId(), getSystemId(), resource);\n\t\t\t}\n\t\t\tnewResources.add(resource);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deletePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception {\n\t\tthrow new Exception(\"shouldn't be calling deletePatientResource\");\n\t}\n}*/\n"},"new_file":{"kind":"string","value":"src/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java"},"old_contents":{"kind":"string","value":"package org.endeavourhealth.queuereader;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Lists;\nimport com.google.gson.JsonSyntaxException;\nimport org.apache.commons.csv.*;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.FilenameUtils;\nimport org.endeavourhealth.common.cache.ObjectMapperPool;\nimport org.endeavourhealth.common.config.ConfigManager;\nimport org.endeavourhealth.common.fhir.PeriodHelper;\nimport org.endeavourhealth.common.utility.FileHelper;\nimport org.endeavourhealth.common.utility.FileInfo;\nimport org.endeavourhealth.common.utility.JsonSerializer;\nimport org.endeavourhealth.common.utility.SlackHelper;\nimport org.endeavourhealth.core.configuration.ConfigDeserialiser;\nimport org.endeavourhealth.core.configuration.PostMessageToExchangeConfig;\nimport org.endeavourhealth.core.configuration.QueueReaderConfiguration;\nimport org.endeavourhealth.core.csv.CsvHelper;\nimport org.endeavourhealth.core.database.dal.DalProvider;\nimport org.endeavourhealth.core.database.dal.admin.ServiceDalI;\nimport org.endeavourhealth.core.database.dal.admin.models.Service;\nimport org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI;\nimport org.endeavourhealth.core.database.dal.audit.ExchangeDalI;\nimport org.endeavourhealth.core.database.dal.audit.models.*;\nimport org.endeavourhealth.core.database.dal.ehr.ResourceDalI;\nimport org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper;\nimport org.endeavourhealth.core.database.rdbms.ConnectionManager;\nimport org.endeavourhealth.core.exceptions.TransformException;\nimport org.endeavourhealth.core.fhirStorage.FhirStorageService;\nimport org.endeavourhealth.core.fhirStorage.JsonServiceInterfaceEndpoint;\nimport org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange;\nimport org.endeavourhealth.core.queueing.QueueHelper;\nimport org.endeavourhealth.core.xml.TransformErrorSerializer;\nimport org.endeavourhealth.core.xml.transformError.TransformError;\nimport org.endeavourhealth.transform.barts.BartsCsvToFhirTransformer;\nimport org.endeavourhealth.transform.common.*;\nimport org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer;\nimport org.endeavourhealth.transform.emis.csv.helpers.EmisCsvHelper;\nimport org.hibernate.internal.SessionImpl;\nimport org.hl7.fhir.instance.model.EpisodeOfCare;\nimport org.hl7.fhir.instance.model.Patient;\nimport org.hl7.fhir.instance.model.ResourceType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.persistence.EntityManager;\nimport java.io.*;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.text.SimpleDateFormat;\nimport java.util.*;\n\npublic class Main {\n\tprivate static final Logger LOG = LoggerFactory.getLogger(Main.class);\n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tString configId = args[0];\n\n\t\tLOG.info(\"Initialising config manager\");\n\t\tConfigManager.initialize(\"queuereader\", configId);\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixEncounters\")) {\n\t\t\tString table = args[1];\n\t\t\tfixEncounters(table);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateAdastraSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tString destDirPath = args[2];\n\t\t\tString samplePatientsFile = args[3];\n\t\t\tcreateAdastraSubset(sourceDirPath, destDirPath, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateVisionSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tString destDirPath = args[2];\n\t\t\tString samplePatientsFile = args[3];\n\t\t\tcreateVisionSubset(sourceDirPath, destDirPath, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateTppSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tString destDirPath = args[2];\n\t\t\tString samplePatientsFile = args[3];\n\t\t\tcreateTppSubset(sourceDirPath, destDirPath, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"CreateBartsSubset\")) {\n\t\t\tString sourceDirPath = args[1];\n\t\t\tUUID serviceUuid = UUID.fromString(args[2]);\n\t\t\tUUID systemUuid = UUID.fromString(args[3]);\n\t\t\tString samplePatientsFile = args[4];\n\t\t\tcreateBartsSubset(sourceDirPath, serviceUuid, systemUuid, samplePatientsFile);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixBartsOrgs\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tfixBartsOrgs(serviceId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"TestPreparedStatements\")) {\n\t\t\tString url = args[1];\n\t\t\tString user = args[2];\n\t\t\tString pass = args[3];\n\t\t\tString serviceId = args[4];\n\t\t\ttestPreparedStatements(url, user, pass, serviceId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"ApplyEmisAdminCaches\")) {\n\t\t\tapplyEmisAdminCaches();\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixSubscribers\")) {\n\t\t\tfixSubscriberDbs();\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"ConvertExchangeBody\")) {\n\t\t\tString systemId = args[1];\n\t\t\tconvertExchangeBody(UUID.fromString(systemId));\n\t\t\tSystem.exit(0);\n\t\t}\n\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixReferrals\")) {\n\t\t\tfixReferralRequests();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PopulateNewSearchTable\")) {\n\t\t\tString table = args[1];\n\t\t\tpopulateNewSearchTable(table);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixBartsEscapes\")) {\n\t\t\tString filePath = args[1];\n\t\t\tfixBartsEscapedFiles(filePath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PostToInbound\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tString systemId = args[2];\n\t\t\tString filePath = args[3];\n\t\t\tpostToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\tif (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixDisabledExtract\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tString systemId = args[2];\n\t\t\tString sharedStoragePath = args[3];\n\t\t\tString tempDir = args[4];\n\t\t\tfixDisabledEmisExtract(serviceId, systemId, sharedStoragePath, tempDir);\n\t\t\tSystem.exit(0);\n\t\t}\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"TestSlack\")) {\n\t\t\ttestSlack();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PostToInbound\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tboolean all = Boolean.parseBoolean(args[2]);\n\t\t\tpostToInbound(UUID.fromString(serviceId), all);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixPatientSearch\")) {\n\t\t\tString serviceId = args[1];\n\t\t\tfixPatientSearch(serviceId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"Exit\")) {\n\n\t\t\tString exitCode = args[1];\n\t\t\tLOG.info(\"Exiting with error code \" + exitCode);\n\t\t\tint exitCodeInt = Integer.parseInt(exitCode);\n\t\t\tSystem.exit(exitCodeInt);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"RunSql\")) {\n\n\t\t\tString host = args[1];\n\t\t\tString username = args[2];\n\t\t\tString password = args[3];\n\t\t\tString sqlFile = args[4];\n\t\t\trunSql(host, username, password, sqlFile);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"PopulateProtocolQueue\")) {\n\t\t\tString serviceId = null;\n\t\t\tif (args.length > 1) {\n\t\t\t\tserviceId = args[1];\n\t\t\t}\n\t\t\tString startingExchangeId = null;\n\t\t\tif (args.length > 2) {\n\t\t\t\tstartingExchangeId = args[2];\n\t\t\t}\n\t\t\tpopulateProtocolQueue(serviceId, startingExchangeId);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindEncounterTerms\")) {\n\t\t\tString path = args[1];\n\t\t\tString outputPath = args[2];\n\t\t\tfindEncounterTerms(path, outputPath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindEmisStartDates\")) {\n\t\t\tString path = args[1];\n\t\t\tString outputPath = args[2];\n\t\t\tfindEmisStartDates(path, outputPath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"ExportHl7Encounters\")) {\n\t\t\tString sourceCsvPpath = args[1];\n\t\t\tString outputPath = args[2];\n\t\t\texportHl7Encounters(sourceCsvPpath, outputPath);\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 1\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FixExchangeBatches\")) {\n\t\t\tfixExchangeBatches();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 0\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindCodes\")) {\n\t\t\tfindCodes();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\t/*if (args.length >= 0\n\t\t\t\t&& args[0].equalsIgnoreCase(\"FindDeletedOrgs\")) {\n\t\t\tfindDeletedOrgs();\n\t\t\tSystem.exit(0);\n\t\t}*/\n\n\t\tif (args.length != 1) {\n\t\t\tLOG.error(\"Usage: queuereader config_id\");\n\t\t\treturn;\n\t\t}\n\n\t\tLOG.info(\"--------------------------------------------------\");\n\t\tLOG.info(\"EDS Queue Reader \" + configId);\n\t\tLOG.info(\"--------------------------------------------------\");\n\n\t\tLOG.info(\"Fetching queuereader configuration\");\n\t\tString configXml = ConfigManager.getConfiguration(configId);\n\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\n\t\t/*LOG.info(\"Registering shutdown hook\");\n\t\tregisterShutdownHook();*/\n\n\t\t// Instantiate rabbit handler\n\t\tLOG.info(\"Creating EDS queue reader\");\n\t\tRabbitHandler rabbitHandler = new RabbitHandler(configuration, configId);\n\n\t\t// Begin consume\n\t\trabbitHandler.start();\n\t\tLOG.info(\"EDS Queue reader running (kill file location \" + TransformConfig.instance().getKillFileLocation() + \")\");\n\t}\n\n\tprivate static void convertExchangeBody(UUID systemUuid) {\n\t\ttry {\n\t\t\tLOG.info(\"Converting exchange bodies for system \" + systemUuid);\n\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\n\t\t\tList services = serviceDal.getAll();\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tList exchanges = exchangeDal.getExchangesByService(service.getId(), systemUuid, Integer.MAX_VALUE);\n\t\t\t\tif (exchanges.isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.debug(\"doing \" + service.getName() + \" with \" + exchanges.size() + \" exchanges\");\n\n\t\t\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\t\ttry {\n\t\t\t\t\t\t//already done\n\t\t\t\t\t\tExchangePayloadFile[] files = JsonSerializer.deserialize(exchangeBody, ExchangePayloadFile[].class);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} catch (JsonSyntaxException ex) {\n\t\t\t\t\t\t//if the JSON can't be parsed, then it'll be the old format of body that isn't JSON\n\t\t\t\t\t}\n\n\t\t\t\t\tList newFiles = new ArrayList<>();\n\n\t\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody);\n\t\t\t\t\tfor (String file: files) {\n\t\t\t\t\t\tExchangePayloadFile fileObj = new ExchangePayloadFile();\n\n\t\t\t\t\t\tString fileWithoutSharedStorage = file.substring(TransformConfig.instance().getSharedStoragePath().length()+1);\n\t\t\t\t\t\tfileObj.setPath(fileWithoutSharedStorage);\n\n\t\t\t\t\t\t//size\n\t\t\t\t\t\tList fileInfos = FileHelper.listFilesInSharedStorageWithInfo(file);\n\t\t\t\t\t\tfor (FileInfo info: fileInfos) {\n\t\t\t\t\t\t\tif (info.getFilePath().equals(file)) {\n\t\t\t\t\t\t\t\tlong size = info.getSize();\n\t\t\t\t\t\t\t\tfileObj.setSize(new Long(size));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//type\n\t\t\t\t\t\tif (systemUuid.toString().equalsIgnoreCase(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\") //live\n\t\t\t\t\t\t\t\t|| systemUuid.toString().equalsIgnoreCase(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\")) { //dev\n\t\t\t\t\t\t\t//emis\n\t\t\t\t\t\t\tString name = FilenameUtils.getName(file);\n\t\t\t\t\t\t\tString[] toks = name.split(\"_\");\n\n\t\t\t\t\t\t\tString first = toks[1];\n\t\t\t\t\t\t\tString second = toks[2];\n\t\t\t\t\t\t\tfileObj.setType(first + \"_\" + second);\n\n\t\t\t\t\t\t} else if (systemUuid.toString().equalsIgnoreCase(\"e517fa69-348a-45e9-a113-d9b59ad13095\")) {\n\t\t\t\t\t\t\t//cerner\n\t\t\t\t\t\t\tString name = FilenameUtils.getName(file);\n\t\t\t\t\t\t\tString type = BartsCsvToFhirTransformer.identifyFileType(name);\n\t\t\t\t\t\t\tfileObj.setType(type);\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthrow new Exception(\"Unknown system ID \" + systemUuid);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnewFiles.add(fileObj);\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = JsonSerializer.serialize(newFiles);\n\t\t\t\t\texchange.setBody(json);\n\n\t\t\t\t\texchangeDal.save(exchange);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Converting exchange bodies for system \" + systemUuid);\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}\n\n\t/*private static void fixBartsOrgs(String serviceId) {\n\t\ttry {\n\t\t\tLOG.info(\"Fixing Barts orgs\");\n\n\t\t\tResourceDalI dal = DalProvider.factoryResourceDal();\n\t\t\tList wrappers = dal.getResourcesByService(UUID.fromString(serviceId), ResourceType.Organization.toString());\n\t\t\tLOG.debug(\"Found \" + wrappers.size() + \" resources\");\n\t\t\tint done = 0;\n\t\t\tint fixed = 0;\n\t\t\tfor (ResourceWrapper wrapper: wrappers) {\n\n\t\t\t\tif (!wrapper.isDeleted()) {\n\n\t\t\t\t\tList history = dal.getResourceHistory(UUID.fromString(serviceId), wrapper.getResourceType(), wrapper.getResourceId());\n\t\t\t\t\tResourceWrapper mostRecent = history.get(0);\n\n\t\t\t\t\tString json = mostRecent.getResourceData();\n\t\t\t\t\tOrganization org = (Organization)FhirSerializationHelper.deserializeResource(json);\n\n\t\t\t\t\tString odsCode = IdentifierHelper.findOdsCode(org);\n\t\t\t\t\tif (Strings.isNullOrEmpty(odsCode)\n\t\t\t\t\t\t\t&& org.hasIdentifier()) {\n\n\t\t\t\t\t\tboolean hasBeenFixed = false;\n\n\t\t\t\t\t\tfor (Identifier identifier: org.getIdentifier()) {\n\t\t\t\t\t\t\tif (identifier.getSystem().equals(FhirIdentifierUri.IDENTIFIER_SYSTEM_ODS_CODE)\n\t\t\t\t\t\t\t\t\t&& identifier.hasId()) {\n\n\t\t\t\t\t\t\t\todsCode = identifier.getId();\n\t\t\t\t\t\t\t\tidentifier.setValue(odsCode);\n\t\t\t\t\t\t\t\tidentifier.setId(null);\n\t\t\t\t\t\t\t\thasBeenFixed = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (hasBeenFixed) {\n\t\t\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(org);\n\t\t\t\t\t\t\tmostRecent.setResourceData(newJson);\n\n\t\t\t\t\t\t\tLOG.debug(\"Fixed Organization \" + org.getId());\n\t\t\t\t\t\t\t*//*LOG.debug(json);\n\t\t\t\t\t\t\tLOG.debug(newJson);*//*\n\n\t\t\t\t\t\t\tsaveResourceWrapper(UUID.fromString(serviceId), mostRecent);\n\n\t\t\t\t\t\t\tfixed ++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tdone ++;\n\t\t\t\tif (done % 100 == 0) {\n\t\t\t\t\tLOG.debug(\"Done \" + done + \", Fixed \" + fixed);\n\t\t\t\t}\n\t\t\t}\n\t\t\tLOG.debug(\"Done \" + done + \", Fixed \" + fixed);\n\n\t\t\tLOG.info(\"Finished Barts orgs\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}*/\n\n\t/*private static void testPreparedStatements(String url, String user, String pass, String serviceId) {\n\t\ttry {\n\t\t\tLOG.info(\"Testing Prepared Statements\");\n\t\t\tLOG.info(\"Url: \" + url);\n\t\t\tLOG.info(\"user: \" + user);\n\t\t\tLOG.info(\"pass: \" + pass);\n\n\t\t\t//open connection\n\t\t\tClass.forName(\"com.mysql.cj.jdbc.Driver\");\n\n\t\t\t//create connection\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(\"user\", user);\n\t\t\tprops.setProperty(\"password\", pass);\n\n\t\t\tConnection conn = DriverManager.getConnection(url, props);\n\n\t\t\tString sql = \"SELECT * FROM internal_id_map WHERE service_id = ? AND id_type = ? AND source_id = ?\";\n\n\t\t\tlong start = System.currentTimeMillis();\n\n\t\t\tfor (int i=0; i<10000; i++) {\n\n\t\t\t\tPreparedStatement ps = null;\n\t\t\t\ttry {\n\t\t\t\t\tps = conn.prepareStatement(sql);\n\t\t\t\t\tps.setString(1, serviceId);\n\t\t\t\t\tps.setString(2, \"MILLPERSIDtoMRN\");\n\t\t\t\t\tps.setString(3, UUID.randomUUID().toString());\n\n\t\t\t\t\tResultSet rs = ps.executeQuery();\n\t\t\t\t\twhile (rs.next()) {\n\t\t\t\t\t\t//do nothing\n\t\t\t\t\t}\n\n\t\t\t\t} finally {\n\t\t\t\t\tif (ps != null) {\n\t\t\t\t\t\tps.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlong end = System.currentTimeMillis();\n\t\t\tLOG.info(\"Took \" + (end-start) + \" ms\");\n\n\t\t\t//close connection\n\t\t\tconn.close();\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixEncounters(String table) {\n\t\tLOG.info(\"Fixing encounters from \" + table);\n\n\t\ttry {\n\n\t\t\tSimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");\n\t\t\tDate cutoff = sdf.parse(\"2018-03-14 11:42\");\n\n\t\t\tEntityManager entityManager = ConnectionManager.getAdminEntityManager();\n\t\t\tSessionImpl session = (SessionImpl)entityManager.getDelegate();\n\t\t\tConnection connection = session.connection();\n\t\t\tStatement statement = connection.createStatement();\n\n\t\t\tList serviceIds = new ArrayList<>();\n\t\t\tMap hmSystems = new HashMap<>();\n\n\t\t\tString sql = \"SELECT service_id, system_id FROM \" + table + \" WHERE done = 0\";\n\t\t\tResultSet rs = statement.executeQuery(sql);\n\t\t\twhile (rs.next()) {\n\t\t\t\tUUID serviceId = UUID.fromString(rs.getString(1));\n\t\t\t\tUUID systemId = UUID.fromString(rs.getString(2));\n\t\t\t\tserviceIds.add(serviceId);\n\t\t\t\thmSystems.put(serviceId, systemId);\n\t\t\t}\n\t\t\trs.close();\n\t\t\tstatement.close();\n\t\t\tentityManager.close();\n\n\t\t\tfor (UUID serviceId: serviceIds) {\n\t\t\t\tUUID systemId = hmSystems.get(serviceId);\n\t\t\t\tLOG.info(\"Doing service \" + serviceId + \" and system \" + systemId);\n\n\t\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, systemId);\n\n\t\t\t\tList exchangeIdsToProcess = new ArrayList<>();\n\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tList audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId);\n\t\t\t\t\tfor (ExchangeTransformAudit audit: audits) {\n\t\t\t\t\t\tDate d = audit.getStarted();\n\t\t\t\t\t\tif (d.after(cutoff)) {\n\t\t\t\t\t\t\texchangeIdsToProcess.add(exchangeId);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tMap consultationNewChildMap = new HashMap<>();\n\t\t\t\tMap observationChildMap = new HashMap<>();\n\t\t\t\tMap newProblemChildren = new HashMap<>();\n\n\t\t\t\tfor (UUID exchangeId: exchangeIdsToProcess) {\n\t\t\t\t\tExchange exchange = exchangeDal.getExchange(exchangeId);\n\n\t\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyIntoFileList(exchange.getBody());\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(files);\n\n\t\t\t\t\tList interestingFiles = new ArrayList<>();\n\t\t\t\t\tfor (String file: files) {\n\t\t\t\t\t\tif (file.indexOf(\"CareRecord_Consultation\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"CareRecord_Observation\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"CareRecord_Diary\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"Prescribing_DrugRecord\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"Prescribing_IssueRecord\") > -1\n\t\t\t\t\t\t\t\t|| file.indexOf(\"CareRecord_Problem\") > -1) {\n\t\t\t\t\t\t\tinterestingFiles.add(file);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfiles = interestingFiles.toArray(new String[0]);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\t\t\t\t\tEmisCsvToFhirTransformer.createParsers(serviceId, systemId, exchangeId, files, version, parsers);\n\n\t\t\t\t\tString dataSharingAgreementGuid = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(parsers);\n\t\t\t\t\tEmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchangeId, dataSharingAgreementGuid, true);\n\n\n\t\t\t\t\tConsultation consultationParser = (Consultation)parsers.get(Consultation.class);\n\t\t\t\t\twhile (consultationParser.nextRecord()) {\n\t\t\t\t\t\tCsvCell consultationGuid = consultationParser.getConsultationGuid();\n\t\t\t\t\t\tCsvCell patientGuid = consultationParser.getPatientGuid();\n\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid);\n\t\t\t\t\t\tconsultationNewChildMap.put(sourceId, new ReferenceList());\n\t\t\t\t\t}\n\n\t\t\t\t\tProblem problemParser = (Problem)parsers.get(Problem.class);\n\t\t\t\t\twhile (problemParser.nextRecord()) {\n\t\t\t\t\t\tCsvCell problemGuid = problemParser.getObservationGuid();\n\t\t\t\t\t\tCsvCell patientGuid = problemParser.getPatientGuid();\n\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\tnewProblemChildren.put(sourceId, new ReferenceList());\n\t\t\t\t\t}\n\n\t\t\t\t\t//run this pre-transformer to pre-cache some stuff in the csv helper, which\n\t\t\t\t\t//is needed when working out the resource type that each observation would be saved as\n\t\t\t\t\tObservationPreTransformer.transform(version, parsers, null, csvHelper);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tCsvCell observationGuid = observationParser.getObservationGuid();\n\t\t\t\t\t\tCsvCell patientGuid = observationParser.getPatientGuid();\n\t\t\t\t\t\tString obSourceId = EmisCsvHelper.createUniqueId(patientGuid, observationGuid);\n\n\t\t\t\t\t\tCsvCell codeId = observationParser.getCodeId();\n\t\t\t\t\t\tif (codeId.isEmpty()) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper);\n\n\t\t\t\t\t\tUUID obUuid = IdHelper.getEdsResourceId(serviceId, resourceType, obSourceId);\n\t\t\t\t\t\tif (obUuid == null) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + resourceType + \" and source ID \" + obSourceId);\n\t\t\t\t\t\t\t//resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tReference obReference = ReferenceHelper.createReference(resourceType, obUuid.toString());\n\n\t\t\t\t\t\tCsvCell consultationGuid = observationParser.getConsultationGuid();\n\t\t\t\t\t\tif (!consultationGuid.isEmpty()) {\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = consultationNewChildMap.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tconsultationNewChildMap.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(obReference);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tCsvCell problemGuid = observationParser.getProblemGuid();\n\t\t\t\t\t\tif (!problemGuid.isEmpty()) {\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = newProblemChildren.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tnewProblemChildren.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(obReference);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tCsvCell parentObGuid = observationParser.getParentObservationGuid();\n\t\t\t\t\t\tif (!parentObGuid.isEmpty()) {\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, parentObGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = observationChildMap.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tobservationChildMap.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(obReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tDiary diaryParser = (Diary)parsers.get(Diary.class);\n\t\t\t\t\twhile (diaryParser.nextRecord()) {\n\n\t\t\t\t\t\tCsvCell consultationGuid = diaryParser.getConsultationGuid();\n\t\t\t\t\t\tif (!consultationGuid.isEmpty()) {\n\n\t\t\t\t\t\t\tCsvCell diaryGuid = diaryParser.getDiaryGuid();\n\t\t\t\t\t\t\tCsvCell patientGuid = diaryParser.getPatientGuid();\n\t\t\t\t\t\t\tString diarySourceId = EmisCsvHelper.createUniqueId(patientGuid, diaryGuid);\n\t\t\t\t\t\t\tUUID diaryUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.ProcedureRequest, diarySourceId);\n\t\t\t\t\t\t\tif (diaryUuid == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + ResourceType.ProcedureRequest + \" and source ID \" + diarySourceId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tReference diaryReference = ReferenceHelper.createReference(ResourceType.ProcedureRequest, diaryUuid.toString());\n\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = consultationNewChildMap.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tconsultationNewChildMap.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(diaryReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tIssueRecord issueRecordParser = (IssueRecord)parsers.get(IssueRecord.class);\n\t\t\t\t\twhile (issueRecordParser.nextRecord()) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tCsvCell problemGuid = issueRecordParser.getProblemObservationGuid();\n\t\t\t\t\t\tif (!problemGuid.isEmpty()) {\n\n\t\t\t\t\t\t\tCsvCell issueRecordGuid = issueRecordParser.getIssueRecordGuid();\n\t\t\t\t\t\t\tCsvCell patientGuid = issueRecordParser.getPatientGuid();\n\t\t\t\t\t\t\tString issueRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, issueRecordGuid);\n\t\t\t\t\t\t\tUUID issueRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationOrder, issueRecordSourceId);\n\t\t\t\t\t\t\tif (issueRecordUuid == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + ResourceType.MedicationOrder + \" and source ID \" + issueRecordSourceId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tReference issueRecordReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, issueRecordUuid.toString());\n\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = newProblemChildren.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tnewProblemChildren.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(issueRecordReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tDrugRecord drugRecordParser = (DrugRecord)parsers.get(DrugRecord.class);\n\t\t\t\t\twhile (drugRecordParser.nextRecord()) {\n\n\t\t\t\t\t\tCsvCell problemGuid = drugRecordParser.getProblemObservationGuid();\n\t\t\t\t\t\tif (!problemGuid.isEmpty()) {\n\n\t\t\t\t\t\t\tCsvCell drugRecordGuid = drugRecordParser.getDrugRecordGuid();\n\t\t\t\t\t\t\tCsvCell patientGuid = drugRecordParser.getPatientGuid();\n\t\t\t\t\t\t\tString drugRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, drugRecordGuid);\n\t\t\t\t\t\t\tUUID drugRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationStatement, drugRecordSourceId);\n\t\t\t\t\t\t\tif (drugRecordUuid == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t//LOG.error(\"Null observation UUID for resource type \" + ResourceType.MedicationStatement + \" and source ID \" + drugRecordSourceId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tReference drugRecordReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, drugRecordUuid.toString());\n\n\t\t\t\t\t\t\tString sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid);\n\t\t\t\t\t\t\tReferenceList referenceList = newProblemChildren.get(sourceId);\n\t\t\t\t\t\t\tif (referenceList == null) {\n\t\t\t\t\t\t\t\treferenceList = new ReferenceList();\n\t\t\t\t\t\t\t\tnewProblemChildren.put(sourceId, referenceList);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferenceList.add(drugRecordReference);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (AbstractCsvParser parser : parsers.values()) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tparser.close();\n\t\t\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\t\t\t//don't worry if this fails, as we're done anyway\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\n\t\t\t\tLOG.info(\"Found \" + consultationNewChildMap.size() + \" Encounters to fix\");\n\t\t\t\tfor (String encounterSourceId: consultationNewChildMap.keySet()) {\n\n\t\t\t\t\tReferenceList childReferences = consultationNewChildMap.get(encounterSourceId);\n\n\t\t\t\t\t//map to UUID\n\t\t\t\t\tUUID encounterId = IdHelper.getEdsResourceId(serviceId, ResourceType.Encounter, encounterSourceId);\n\t\t\t\t\tif (encounterId == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//get history, which is most recent FIRST\n\t\t\t\t\tList history = resourceDal.getResourceHistory(serviceId, ResourceType.Encounter.toString(), encounterId);\n\t\t\t\t\tif (history.isEmpty()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t//throw new Exception(\"Empty history for Encounter \" + encounterId);\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper currentState = history.get(0);\n\t\t\t\t\tif (currentState.isDeleted()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//find last instance prior to cutoff and get its linked children\n\t\t\t\t\tfor (ResourceWrapper wrapper: history) {\n\t\t\t\t\t\tDate d = wrapper.getCreatedAt();\n\t\t\t\t\t\tif (!d.after(cutoff)) {\n\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\tEncounter encounter = (Encounter) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\tEncounterBuilder encounterBuilder = new EncounterBuilder(encounter);\n\t\t\t\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder);\n\n\t\t\t\t\t\t\t\tList previousChildren = containedListBuilder.getContainedListItems();\n\t\t\t\t\t\t\t\tchildReferences.add(previousChildren);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (childReferences.size() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = currentState.getResourceData();\n\t\t\t\t\tResource resource = FhirSerializationHelper.deserializeResource(json);\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(resource);\n\t\t\t\t\tif (!json.equals(newJson)) {\n\t\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);\n\t\t\t\t\t}\n\n\t\t\t\t\t*//*Encounter encounter = (Encounter)FhirSerializationHelper.deserializeResource(currentState.getResourceData());\n\t\t\t\t\tEncounterBuilder encounterBuilder = new EncounterBuilder(encounter);\n\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder);\n\n\t\t\t\t\tcontainedListBuilder.addReferences(childReferences);\n\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(encounter);\n\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);*//*\n\t\t\t\t}\n\n\n\t\t\t\tLOG.info(\"Found \" + observationChildMap.size() + \" Parent Observations to fix\");\n\t\t\t\tfor (String sourceId: observationChildMap.keySet()) {\n\n\t\t\t\t\tReferenceList childReferences = observationChildMap.get(sourceId);\n\n\t\t\t\t\t//map to UUID\n\t\t\t\t\tResourceType resourceType = null;\n\n\t\t\t\t\tUUID resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, sourceId);\n\t\t\t\t\tif (resourceId != null) {\n\t\t\t\t\t\tresourceType = ResourceType.Observation;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.DiagnosticReport, sourceId);\n\t\t\t\t\t\tif (resourceId != null) {\n\t\t\t\t\t\t\tresourceType = ResourceType.DiagnosticReport;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//get history, which is most recent FIRST\n\t\t\t\t\tList history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId);\n\t\t\t\t\tif (history.isEmpty()) {\n\t\t\t\t\t\t//throw new Exception(\"Empty history for \" + resourceType + \" \" + resourceId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper currentState = history.get(0);\n\t\t\t\t\tif (currentState.isDeleted()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//find last instance prior to cutoff and get its linked children\n\t\t\t\t\tfor (ResourceWrapper wrapper: history) {\n\t\t\t\t\t\tDate d = wrapper.getCreatedAt();\n\t\t\t\t\t\tif (!d.after(cutoff)) {\n\n\t\t\t\t\t\t\tif (resourceType == ResourceType.Observation) {\n\t\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\t\tObservation observation = (Observation) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\t\tif (observation.hasRelated()) {\n\t\t\t\t\t\t\t\t\t\tfor (Observation.ObservationRelatedComponent related : observation.getRelated()) {\n\t\t\t\t\t\t\t\t\t\t\tReference reference = related.getTarget();\n\t\t\t\t\t\t\t\t\t\t\tchildReferences.add(reference);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\t\tDiagnosticReport report = (DiagnosticReport) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\t\tif (report.hasResult()) {\n\t\t\t\t\t\t\t\t\t\tfor (Reference reference : report.getResult()) {\n\t\t\t\t\t\t\t\t\t\t\tchildReferences.add(reference);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (childReferences.size() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = currentState.getResourceData();\n\t\t\t\t\tResource resource = FhirSerializationHelper.deserializeResource(json);\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(resource);\n\t\t\t\t\tif (!json.equals(newJson)) {\n\t\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);\n\t\t\t\t\t}\n\n\t\t\t\t\t*//*Resource resource = FhirSerializationHelper.deserializeResource(currentState.getResourceData());\n\n\t\t\t\t\tboolean changed = false;\n\n\t\t\t\t\tif (resourceType == ResourceType.Observation) {\n\t\t\t\t\t\tObservationBuilder resourceBuilder = new ObservationBuilder((Observation)resource);\n\t\t\t\t\t\tfor (int i=0; i history = resourceDal.getResourceHistory(serviceId, ResourceType.Condition.toString(), conditionId);\n\t\t\t\t\tif (history.isEmpty()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t//throw new Exception(\"Empty history for Condition \" + conditionId);\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper currentState = history.get(0);\n\t\t\t\t\tif (currentState.isDeleted()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//find last instance prior to cutoff and get its linked children\n\t\t\t\t\tfor (ResourceWrapper wrapper: history) {\n\t\t\t\t\t\tDate d = wrapper.getCreatedAt();\n\t\t\t\t\t\tif (!d.after(cutoff)) {\n\t\t\t\t\t\t\tif (wrapper.getResourceData() != null) {\n\t\t\t\t\t\t\t\tCondition previousVersion = (Condition) FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\t\tConditionBuilder conditionBuilder = new ConditionBuilder(previousVersion);\n\t\t\t\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder);\n\n\t\t\t\t\t\t\t\tList previousChildren = containedListBuilder.getContainedListItems();\n\t\t\t\t\t\t\t\tchildReferences.add(previousChildren);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (childReferences.size() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = currentState.getResourceData();\n\t\t\t\t\tResource resource = FhirSerializationHelper.deserializeResource(json);\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(resource);\n\t\t\t\t\tif (!json.equals(newJson)) {\n\t\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);\n\t\t\t\t\t}\n\n\t\t\t\t\t*//*Condition condition = (Condition)FhirSerializationHelper.deserializeResource(currentState.getResourceData());\n\t\t\t\t\tConditionBuilder conditionBuilder = new ConditionBuilder(condition);\n\t\t\t\t\tContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder);\n\n\t\t\t\t\tcontainedListBuilder.addReferences(childReferences);\n\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(condition);\n\t\t\t\t\tcurrentState.setResourceData(newJson);\n\t\t\t\t\tcurrentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\tsaveResourceWrapper(serviceId, currentState);*//*\n\t\t\t\t}\n\n\t\t\t\t//mark as done\n\t\t\t\tString updateSql = \"UPDATE \" + table + \" SET done = 1 WHERE service_id = '\" + serviceId + \"';\";\n\t\t\t\tentityManager = ConnectionManager.getAdminEntityManager();\n\t\t\t\tsession = (SessionImpl)entityManager.getDelegate();\n\t\t\t\tconnection = session.connection();\n\t\t\t\tstatement = connection.createStatement();\n\t\t\t\tentityManager.getTransaction().begin();\n\t\t\t\tstatement.executeUpdate(updateSql);\n\t\t\t\tentityManager.getTransaction().commit();\n\t\t\t}\n\n\t\t\t*//**\n\t\t\t * For each practice:\n\t\t\t Go through all files processed since 14 March\n\t\t\t Cache all links as above\n\t\t\t Cache all Encounters saved too\n\n\t\t\t For each Encounter referenced at all:\n\t\t\t Retrieve latest version from resource current\n\t\t\t Retrieve version prior to 14 March\n\t\t\t Update current version with old references plus new ones\n\n\t\t\t For each parent observation:\n\t\t\t Retrieve latest version (could be observation or diagnostic report)\n\n\t\t\t For each problem:\n\t\t\t Retrieve latest version from resource current\n\t\t\t Check if still a problem:\n\t\t\t Retrieve version prior to 14 March\n\t\t\t Update current version with old references plus new ones\n\n\t\t\t *//*\n\n\t\t\tLOG.info(\"Finished Fixing encounters from \" + table);\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}*/\n\n\tprivate static void saveResourceWrapper(UUID serviceId, ResourceWrapper wrapper) throws Exception {\n\n\t\tif (wrapper.getResourceData() != null) {\n\t\t\tlong checksum = FhirStorageService.generateChecksum(wrapper.getResourceData());\n\t\t\twrapper.setResourceChecksum(new Long(checksum));\n\t\t}\n\n\t\tEntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId);\n\t\tSessionImpl session = (SessionImpl)entityManager.getDelegate();\n\t\tConnection connection = session.connection();\n\t\tStatement statement = connection.createStatement();\n\n\t\tentityManager.getTransaction().begin();\n\n\t\tString json = wrapper.getResourceData();\n\t\tjson = json.replace(\"'\", \"''\");\n\t\tjson = json.replace(\"\\\\\", \"\\\\\\\\\");\n\n\t\tString patientId = \"\";\n\t\tif (wrapper.getPatientId() != null) {\n\t\t\tpatientId = wrapper.getPatientId().toString();\n\t\t}\n\n\t\tString updateSql = \"UPDATE resource_current\"\n\t\t\t\t\t\t+ \" SET resource_data = '\" + json + \"',\"\n\t\t\t\t\t\t+ \" resource_checksum = \" + wrapper.getResourceChecksum()\n\t\t\t\t\t\t+ \" WHERE service_id = '\" + wrapper.getServiceId() + \"'\"\n\t\t\t\t\t\t+ \" AND patient_id = '\" + patientId + \"'\"\n\t\t\t\t\t\t+ \" AND resource_type = '\" + wrapper.getResourceType() + \"'\"\n\t\t\t\t\t\t+ \" AND resource_id = '\" + wrapper.getResourceId() + \"'\";\n\t\tstatement.executeUpdate(updateSql);\n\n\t\t//LOG.debug(updateSql);\n\n\t\t//SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:SS\");\n\t\t//String createdAtStr = sdf.format(wrapper.getCreatedAt());\n\n\t\tupdateSql = \"UPDATE resource_history\"\n\t\t\t\t+ \" SET resource_data = '\" + json + \"',\"\n\t\t\t\t+ \" resource_checksum = \" + wrapper.getResourceChecksum()\n\t\t\t\t+ \" WHERE resource_id = '\" + wrapper.getResourceId() + \"'\"\n\t\t\t\t+ \" AND resource_type = '\" + wrapper.getResourceType() + \"'\"\n\t\t\t\t//+ \" AND created_at = '\" + createdAtStr + \"'\"\n\t\t\t\t+ \" AND version = '\" + wrapper.getVersion() + \"'\";\n\t\tstatement.executeUpdate(updateSql);\n\n\t\t//LOG.debug(updateSql);\n\n\t\tentityManager.getTransaction().commit();\n\t}\n\n\t/*private static void populateNewSearchTable(String table) {\n\t\tLOG.info(\"Populating New Search Table\");\n\n\t\ttry {\n\n\t\t\tEntityManager entityManager = ConnectionManager.getEdsEntityManager();\n\t\t\tSessionImpl session = (SessionImpl)entityManager.getDelegate();\n\t\t\tConnection connection = session.connection();\n\t\t\tStatement statement = connection.createStatement();\n\n\t\t\tList patientIds = new ArrayList<>();\n\t\t\tMap serviceIds = new HashMap<>();\n\n\t\t\tString sql = \"SELECT patient_id, service_id FROM \" + table + \" WHERE done = 0\";\n\t\t\tResultSet rs = statement.executeQuery(sql);\n\t\t\twhile (rs.next()) {\n\t\t\t\tString patientId = rs.getString(1);\n\t\t\t\tString serviceId = rs.getString(2);\n\t\t\t\tpatientIds.add(patientId);\n\t\t\t\tserviceIds.put(patientId, serviceId);\n\t\t\t}\n\t\t\trs.close();\n\t\t\tstatement.close();\n\t\t\tentityManager.close();\n\n\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\tPatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearch2Dal();\n\n\t\t\tLOG.info(\"Found \" + patientIds.size() + \" to do\");\n\n\t\t\tfor (int i=0; i wrappers = resourceDal.getResourcesByPatient(serviceId, null, patientId, ResourceType.EpisodeOfCare.toString());\n\t\t\t\t\tfor (ResourceWrapper wrapper: wrappers) {\n\t\t\t\t\t\tif (!wrapper.isDeleted()) {\n\t\t\t\t\t\t\tEpisodeOfCare episodeOfCare = (EpisodeOfCare)FhirSerializationHelper.deserializeResource(wrapper.getResourceData());\n\t\t\t\t\t\t\tpatientSearchDal.update(serviceId, episodeOfCare);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\n\t\t\t\tString updateSql = \"UPDATE \" + table + \" SET done = 1 WHERE patient_id = '\" + patientIdStr + \"' AND service_id = '\" + serviceIdStr + \"';\";\n\t\t\t\tentityManager = ConnectionManager.getEdsEntityManager();\n\t\t\t\tsession = (SessionImpl)entityManager.getDelegate();\n\t\t\t\tconnection = session.connection();\n\t\t\t\tstatement = connection.createStatement();\n\t\t\t\tentityManager.getTransaction().begin();\n\t\t\t\tstatement.executeUpdate(updateSql);\n\t\t\t\tentityManager.getTransaction().commit();\n\n\t\t\t\tif (i % 5000 == 0) {\n\t\t\t\t\tLOG.info(\"Done \" + (i+1) + \" of \" + patientIds.size());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentityManager.close();\n\n\t\t\tLOG.info(\"Finished Populating New Search Table\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\tprivate static void createBartsSubset(String sourceDir, UUID serviceUuid, UUID systemUuid, String samplePatientsFile) {\n\t\tLOG.info(\"Creating Barts Subset\");\n\n\t\ttry {\n\n\t\t\tSet personIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpersonIds.add(line);\n\t\t\t}\n\n\t\t\tcreateBartsSubsetForFile(sourceDir, serviceUuid, systemUuid, personIds);\n\n\t\t\tLOG.info(\"Finished Creating Barts Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\t/*private static void createBartsSubsetForFile(File sourceDir, File destDir, Set personIds) throws Exception {\n\n\t\tfor (File sourceFile: sourceDir.listFiles()) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing dir \" + sourceFile);\n\t\t\t\tcreateBartsSubsetForFile(sourceFile, destFile, personIds);\n\n\t\t\t} else {\n\n\t\t\t\t//we have some bad partial files in, so ignore them\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (ext.equalsIgnoreCase(\"filepart\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//if the file is empty, we still need the empty file in the filtered directory, so just copy it\n\t\t\t\tif (sourceFile.length() == 0) {\n\t\t\t\t\tLOG.info(\"Copying empty file \" + sourceFile);\n\t\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString baseName = FilenameUtils.getBaseName(name);\n\t\t\t\tString fileType = BartsCsvToFhirTransformer.identifyFileType(baseName);\n\n\t\t\t\tif (isCerner22File(fileType)) {\n\t\t\t\t\tLOG.info(\"Checking 2.2 file \" + sourceFile);\n\n\t\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\t\tdestFile.delete();\n\t\t\t\t\t}\n\n\t\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\t\t\t\t\tint lineIndex = -1;\n\n\t\t\t\t\tPrintWriter pw = null;\n\t\t\t\t\tint personIdColIndex = -1;\n\t\t\t\t\tint expectedCols = -1;\n\n\t\t\t\t\twhile (true) {\n\n\t\t\t\t\t\tString line = br.readLine();\n\t\t\t\t\t\tif (line == null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlineIndex ++;\n\n\t\t\t\t\t\tif (lineIndex == 0) {\n\n\t\t\t\t\t\t\tif (fileType.equalsIgnoreCase(\"FAMILYHISTORY\")) {\n\t\t\t\t\t\t\t\t//this file has no headers, so needs hard-coding\n\t\t\t\t\t\t\t\tpersonIdColIndex = 5;\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t//check headings for PersonID col\n\t\t\t\t\t\t\t\tString[] toks = line.split(\"\\\\|\", -1);\n\t\t\t\t\t\t\t\texpectedCols = toks.length;\n\n\t\t\t\t\t\t\t\tfor (int i=0; i personIds) throws Exception {\n\n\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\tList exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE);\n\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tList files = ExchangeHelper.parseExchangeBody(exchange.getBody());\n\n\t\t\tfor (ExchangePayloadFile fileObj : files) {\n\n\t\t\t\tString filePathWithoutSharedStorage = fileObj.getPath().substring(TransformConfig.instance().getSharedStoragePath().length()+1);\n\t\t\t\tString sourceFilePath = FilenameUtils.concat(sourceDir, filePathWithoutSharedStorage);\n\t\t\t\tFile sourceFile = new File(sourceFilePath);\n\n\t\t\t\tString destFilePath = fileObj.getPath();\n\t\t\t\tFile destFile = new File(destFilePath);\n\n\t\t\t\tFile destDir = destFile.getParentFile();\n\t\t\t\tif (!destDir.exists()) {\n\t\t\t\t\tdestDir.mkdirs();\n\t\t\t\t}\n\n\t\t\t\t//if the file is empty, we still need the empty file in the filtered directory, so just copy it\n\t\t\t\tif (sourceFile.length() == 0) {\n\t\t\t\t\tLOG.info(\"Copying empty file \" + sourceFile);\n\t\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString fileType = fileObj.getType();\n\n\t\t\t\tif (isCerner22File(fileType)) {\n\t\t\t\t\tLOG.info(\"Checking 2.2 file \" + sourceFile);\n\n\t\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\t\tdestFile.delete();\n\t\t\t\t\t}\n\n\t\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\t\t\t\t\tint lineIndex = -1;\n\n\t\t\t\t\tPrintWriter pw = null;\n\t\t\t\t\tint personIdColIndex = -1;\n\t\t\t\t\tint expectedCols = -1;\n\n\t\t\t\t\twhile (true) {\n\n\t\t\t\t\t\tString line = br.readLine();\n\t\t\t\t\t\tif (line == null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlineIndex++;\n\n\t\t\t\t\t\tif (lineIndex == 0) {\n\n\t\t\t\t\t\t\tif (fileType.equalsIgnoreCase(\"FAMILYHISTORY\")) {\n\t\t\t\t\t\t\t\t//this file has no headers, so needs hard-coding\n\t\t\t\t\t\t\t\tpersonIdColIndex = 5;\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t//check headings for PersonID col\n\t\t\t\t\t\t\t\tString[] toks = line.split(\"\\\\|\", -1);\n\t\t\t\t\t\t\t\texpectedCols = toks.length;\n\n\t\t\t\t\t\t\t\tfor (int i = 0; i < expectedCols; i++) {\n\t\t\t\t\t\t\t\t\tString col = toks[i];\n\t\t\t\t\t\t\t\t\tif (col.equalsIgnoreCase(\"PERSON_ID\")\n\t\t\t\t\t\t\t\t\t\t\t|| col.equalsIgnoreCase(\"#PERSON_ID\")) {\n\t\t\t\t\t\t\t\t\t\tpersonIdColIndex = i;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//if no person ID, then just copy the entire file\n\t\t\t\t\t\t\t\tif (personIdColIndex == -1) {\n\t\t\t\t\t\t\t\t\tbr.close();\n\t\t\t\t\t\t\t\t\tbr = null;\n\n\t\t\t\t\t\t\t\t\tLOG.info(\" Copying 2.2 file to \" + destFile);\n\t\t\t\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tLOG.info(\" Filtering 2.2 file to \" + destFile + \", person ID col at \" + personIdColIndex);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\t\t\t\t\t\t\tpw = new PrintWriter(bw);\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t//filter on personID\n\t\t\t\t\t\t\tString[] toks = line.split(\"\\\\|\", -1);\n\t\t\t\t\t\t\tif (expectedCols != -1\n\t\t\t\t\t\t\t\t\t&& toks.length != expectedCols) {\n\t\t\t\t\t\t\t\tthrow new Exception(\"Line \" + (lineIndex + 1) + \" has \" + toks.length + \" cols but expecting \" + expectedCols);\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tString personId = toks[personIdColIndex];\n\t\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes\n\t\t\t\t\t\t\t\t\t\t&& !personIds.contains(personId)) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpw.println(line);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (br != null) {\n\t\t\t\t\t\tbr.close();\n\t\t\t\t\t}\n\t\t\t\t\tif (pw != null) {\n\t\t\t\t\t\tpw.flush();\n\t\t\t\t\t\tpw.close();\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t//the 2.1 files are going to be a pain to split by patient, so just copy them over\n\t\t\t\t\tLOG.info(\"Copying 2.1 file \" + sourceFile);\n\t\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void copyFile(File src, File dst) throws Exception {\n\t\tFileInputStream fis = new FileInputStream(src);\n\t\tBufferedInputStream bis = new BufferedInputStream(fis);\n\t\tFiles.copy(bis, dst.toPath());\n\t\tbis.close();\n\t}\n\t\n\tprivate static boolean isCerner22File(String fileType) throws Exception {\n\n\t\tif (fileType.equalsIgnoreCase(\"PPATI\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPREL\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CDSEV\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPATH\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"RTTPE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"AEATT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"AEINV\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"AETRE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"OPREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"OPATT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALEN\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALSU\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALOF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"HPSSP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"IPEPI\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"IPWDS\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DELIV\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"BIRTH\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SCHAC\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"APPSL\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DIAGN\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PROCE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ORDER\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DOCRP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"DOCREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CNTRQ\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"LETRS\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"LOREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ORGREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PRSNLREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CVREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"NOMREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"EALIP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CLEVE\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ENCNT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"RESREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPNAM\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPADD\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPPHO\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPALI\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPINF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPAGP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCC\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCP\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCA\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SURCD\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PDRES\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PDREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ABREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"CEPRS\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ORDDT\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"STATREF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"STATA\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"ENCINF\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SCHDETAIL\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"SCHOFFER\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"PPGPORG\")\n\t\t\t\t|| fileType.equalsIgnoreCase(\"FAMILYHISTORY\")) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate static void fixSubscriberDbs() {\n\t\tLOG.info(\"Fixing Subscriber DBs\");\n\n\t\ttry {\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\tUUID emisSystem = UUID.fromString(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\");\n\t\t\tUUID emisSystemDev = UUID.fromString(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\");\n\n\t\t\tPostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig(\"EdsProtocol\");\n\n\t\t\tDate dateError = new SimpleDateFormat(\"yyyy-MM-dd\").parse(\"2018-05-11\");\n\n\t\t\tList services = serviceDal.getAll();\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tString endpointsJson = service.getEndpoints();\n\t\t\t\tif (Strings.isNullOrEmpty(endpointsJson)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Checking \" + service.getName() + \" \" + serviceId);\n\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tif (!endpointSystemId.equals(emisSystem)\n\t\t\t\t\t\t\t&& !endpointSystemId.equals(emisSystemDev)) {\n\t\t\t\t\t\tLOG.info(\" Skipping system ID \" + endpointSystemId + \" as not Emis\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId);\n\n\t\t\t\t\tboolean needsFixing = false;\n\n\t\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tList transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId);\n\t\t\t\t\t\t\tfor (ExchangeTransformAudit audit: transformAudits) {\n\t\t\t\t\t\t\t\tDate transfromStart = audit.getStarted();\n\t\t\t\t\t\t\t\tif (!transfromStart.before(dateError)) {\n\t\t\t\t\t\t\t\t\tneedsFixing = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tList batches = exchangeBatchDal.retrieveForExchangeId(exchangeId);\n\t\t\t\t\t\tExchange exchange = exchangeDal.getExchange(exchangeId);\n\t\t\t\t\t\tLOG.info(\" Posting exchange \" + exchangeId + \" with \" + batches.size() + \" batches\");\n\n\t\t\t\t\t\tList batchIds = new ArrayList<>();\n\n\t\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\n\t\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\t\tif (patientId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tUUID batchId = batch.getBatchId();\n\t\t\t\t\t\t\tbatchIds.add(batchId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray());\n\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr);\n\n\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(exchangeConfig);\n\t\t\t\t\t\tcomponent.process(exchange);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Subscriber DBs\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\t/*private static void fixReferralRequests() {\n\t\tLOG.info(\"Fixing Referral Requests\");\n\n\t\ttry {\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\tUUID emisSystem = UUID.fromString(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\");\n\t\t\tUUID emisSystemDev = UUID.fromString(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\");\n\n\t\t\tPostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig(\"EdsProtocol\");\n\n\t\t\tDate dateError = new SimpleDateFormat(\"yyyy-MM-dd\").parse(\"2018-04-24\");\n\n\t\t\tList services = serviceDal.getAll();\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tString endpointsJson = service.getEndpoints();\n\t\t\t\tif (Strings.isNullOrEmpty(endpointsJson)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Checking \" + service.getName() + \" \" + serviceId);\n\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tif (!endpointSystemId.equals(emisSystem)\n\t\t\t\t\t\t\t&& !endpointSystemId.equals(emisSystemDev)) {\n\t\t\t\t\t\tLOG.info(\" Skipping system ID \" + endpointSystemId + \" as not Emis\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId);\n\n\t\t\t\t\tboolean needsFixing = false;\n\t\t\t\t\tSet patientIdsToPost = new HashSet<>();\n\n\t\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tList transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId);\n\t\t\t\t\t\t\tfor (ExchangeTransformAudit audit: transformAudits) {\n\t\t\t\t\t\t\t\tDate transfromStart = audit.getStarted();\n\t\t\t\t\t\t\t\tif (!transfromStart.before(dateError)) {\n\t\t\t\t\t\t\t\t\tneedsFixing = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!needsFixing) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tList batches = exchangeBatchDal.retrieveForExchangeId(exchangeId);\n\t\t\t\t\t\tExchange exchange = exchangeDal.getExchange(exchangeId);\n\t\t\t\t\t\tLOG.info(\"Checking exchange \" + exchangeId + \" with \" + batches.size() + \" batches\");\n\n\t\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\n\t\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\t\tif (patientId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tUUID batchId = batch.getBatchId();\n\n\t\t\t\t\t\t\tList wrappers = resourceDal.getResourcesForBatch(serviceId, batchId);\n\n\t\t\t\t\t\t\tfor (ResourceWrapper wrapper: wrappers) {\n\t\t\t\t\t\t\t\tString resourceType = wrapper.getResourceType();\n\t\t\t\t\t\t\t\tif (!resourceType.equals(ResourceType.ReferralRequest.toString())\n\t\t\t\t\t\t\t\t\t\t|| wrapper.isDeleted()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tString json = wrapper.getResourceData();\n\t\t\t\t\t\t\t\tReferralRequest referral = (ReferralRequest)FhirSerializationHelper.deserializeResource(json);\n\n\t\t\t\t\t\t\t\t*//*if (!referral.hasServiceRequested()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tCodeableConcept reason = referral.getServiceRequested().get(0);\n\t\t\t\t\t\t\t\treferral.setReason(reason);\n\t\t\t\t\t\t\t\treferral.getServiceRequested().clear();*//*\n\n\t\t\t\t\t\t\t\tif (!referral.hasReason()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tCodeableConcept reason = referral.getReason();\n\t\t\t\t\t\t\t\treferral.setReason(null);\n\t\t\t\t\t\t\t\treferral.addServiceRequested(reason);\n\n\t\t\t\t\t\t\t\tjson = FhirSerializationHelper.serializeResource(referral);\n\t\t\t\t\t\t\t\twrapper.setResourceData(json);\n\n\t\t\t\t\t\t\t\tsaveResourceWrapper(serviceId, wrapper);\n\n\t\t\t\t\t\t\t\t//add to the set of patients we know need sending on to the protocol queue\n\t\t\t\t\t\t\t\tpatientIdsToPost.add(patientId);\n\n\t\t\t\t\t\t\t\tLOG.info(\"Fixed \" + resourceType + \" \" + wrapper.getResourceId() + \" in batch \" + batchId);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if our patient has just been fixed or was fixed before, post onto the protocol queue\n\t\t\t\t\t\t\tif (patientIdsToPost.contains(patientId)) {\n\n\t\t\t\t\t\t\t\tList batchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchIds.add(batchId);\n\n\t\t\t\t\t\t\t\tString batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray());\n\t\t\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr);\n\n\n\t\t\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(exchangeConfig);\n\t\t\t\t\t\t\t\tcomponent.process(exchange);\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Referral Requests\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}*/\n\n\tprivate static void applyEmisAdminCaches() {\n\t\tLOG.info(\"Applying Emis Admin Caches\");\n\n\t\ttry {\n\t\t\tServiceDalI serviceDal = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\t\tUUID emisSystem = UUID.fromString(\"991a9068-01d3-4ff2-86ed-249bd0541fb3\");\n\t\t\tUUID emisSystemDev = UUID.fromString(\"55c08fa5-ef1e-4e94-aadc-e3d6adc80774\");\n\n\t\t\tList services = serviceDal.getAll();\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tString endpointsJson = service.getEndpoints();\n\t\t\t\tif (Strings.isNullOrEmpty(endpointsJson)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Checking \" + service.getName() + \" \" + serviceId);\n\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tif (!endpointSystemId.equals(emisSystem)\n\t\t\t\t\t\t\t&& !endpointSystemId.equals(emisSystemDev)) {\n\t\t\t\t\t\tLOG.info(\" Skipping system ID \" + endpointSystemId + \" as not Emis\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!exchangeDal.isServiceStarted(serviceId, endpointSystemId)) {\n\t\t\t\t\t\tLOG.info(\" Service not started, so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//get exchanges\n\t\t\t\t\tList exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId);\n\t\t\t\t\tif (exchangeIds.isEmpty()) {\n\t\t\t\t\t\tLOG.info(\" No exchanges found, so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tUUID firstExchangeId = exchangeIds.get(0);\n\n\t\t\t\t\tList events = exchangeDal.getExchangeEvents(firstExchangeId);\n\t\t\t\t\tboolean appliedAdminCache = false;\n\t\t\t\t\tfor (ExchangeEvent event: events) {\n\t\t\t\t\t\tif (event.getEventDesc().equals(\"Applied Emis Admin Resource Cache\")) {\n\t\t\t\t\t\t\tappliedAdminCache = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (appliedAdminCache) {\n\t\t\t\t\t\tLOG.info(\" Have already applied admin cache, so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tExchange exchange = exchangeDal.getExchange(firstExchangeId);\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyOldWay(body);\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tLOG.info(\" No files in exchange \" + firstExchangeId + \" so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString firstFilePath = files[0];\n\t\t\t\t\tString name = FilenameUtils.getBaseName(firstFilePath); //file name without extension\n\t\t\t\t\tString[] toks = name.split(\"_\");\n\t\t\t\t\tif (toks.length != 5) {\n\t\t\t\t\t\tthrow new TransformException(\"Failed to extract data sharing agreement GUID from filename \" + firstFilePath);\n\t\t\t\t\t}\n\t\t\t\t\tString sharingAgreementGuid = toks[4];\n\n\t\t\t\t\tList batchIds = new ArrayList<>();\n\t\t\t\t\tTransformError transformError = new TransformError();\n\t\t\t\t\tFhirResourceFiler fhirResourceFiler = new FhirResourceFiler(firstExchangeId, serviceId, endpointSystemId, transformError, batchIds);\n\n\t\t\t\t\tEmisCsvHelper csvHelper = new EmisCsvHelper(fhirResourceFiler.getServiceId(), fhirResourceFiler.getSystemId(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfhirResourceFiler.getExchangeId(), sharingAgreementGuid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrue);\n\n\t\t\t\t\tExchangeTransformAudit transformAudit = new ExchangeTransformAudit();\n\t\t\t\t\ttransformAudit.setServiceId(serviceId);\n\t\t\t\t\ttransformAudit.setSystemId(endpointSystemId);\n\t\t\t\t\ttransformAudit.setExchangeId(firstExchangeId);\n\t\t\t\t\ttransformAudit.setId(UUID.randomUUID());\n\t\t\t\t\ttransformAudit.setStarted(new Date());\n\n\t\t\t\t\tLOG.info(\" Going to apply admin resource cache\");\n\t\t\t\t\tcsvHelper.applyAdminResourceCache(fhirResourceFiler);\n\n\t\t\t\t\tfhirResourceFiler.waitToFinish();\n\n\t\t\t\t\tfor (UUID batchId: batchIds) {\n\t\t\t\t\t\tLOG.info(\" Created batch ID \" + batchId + \" for exchange \" + firstExchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\ttransformAudit.setEnded(new Date());\n\t\t\t\t\ttransformAudit.setNumberBatchesCreated(new Integer(batchIds.size()));\n\n\t\t\t\t\tboolean hadError = false;\n\t\t\t\t\tif (transformError.getError().size() > 0) {\n\t\t\t\t\t\ttransformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError));\n\t\t\t\t\t\thadError = true;\n\t\t\t\t\t}\n\n\t\t\t\t\texchangeDal.save(transformAudit);\n\n\t\t\t\t\t//clear down the cache of reference mappings since they won't be of much use for the next Exchange\n\t\t\t\t\tIdHelper.clearCache();\n\n\t\t\t\t\tif (hadError) {\n\t\t\t\t\t\tLOG.error(\" <<<<< exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE);\n\n\t\t\t//sorting by timestamp seems unreliable when exchanges were posted close together?\n\t\t\tList tmp = new ArrayList<>();\n\t\t\tfor (int i=exchanges.size()-1; i>=0; i--) {\n\t\t\t\tExchange exchange = exchanges.get(i);\n\t\t\t\ttmp.add(exchange);\n\t\t\t}\n\t\t\texchanges = tmp;\n\t\t\t/*exchanges.sort((o1, o2) -> {\n\t\t\t\tDate d1 = o1.getTimestamp();\n\t\t\t\tDate d2 = o2.getTimestamp();\n\t\t\t\treturn d1.compareTo(d2);\n\t\t\t});*/\n\n\t\t\tLOG.info(\"Found \" + exchanges.size() + \" exchanges\");\n\t\t\t//continueOrQuit();\n\n\t\t\t//find the files for each exchange\n\t\t\tMap> hmExchangeFiles = new HashMap<>();\n\t\t\tMap> hmExchangeFilesWithoutStoragePrefix = new HashMap<>();\n\t\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\t\t//populate a map of the files with the shared storage prefix\n\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\tString[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody);\n\t\t\t\tList fileList = Lists.newArrayList(files);\n\t\t\t\thmExchangeFiles.put(exchange, fileList);\n\n\t\t\t\t//populate a map of the same files without the prefix\n\t\t\t\tfiles = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody);\n\t\t\t\tfor (int i=0; i=0; i--) {\n\t\t\t\tExchange exchange = exchanges.get(i);\n\t\t\t\tboolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles);\n\n\t\t\t\tif (disabled) {\n\t\t\t\t\tindexDisabled = i;\n\n\t\t\t\t} else {\n\t\t\t\t\tif (indexDisabled == -1) {\n\t\t\t\t\t\tindexRebulked = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if we've found a non-disabled extract older than the disabled ones,\n\t\t\t\t\t\t//then we've gone far enough back\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//go back from when disabled to find the previous bulk load (i.e. the first one or one after it was previously not disabled)\n\t\t\tfor (int i=indexDisabled-1; i>=0; i--) {\n\t\t\t\tExchange exchange = exchanges.get(i);\n\t\t\t\tboolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles);\n\t\t\t\tif (disabled) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tindexOriginallyBulked = i;\n\t\t\t}\n\n\t\t\tif (indexDisabled == -1\n\t\t\t\t\t|| indexRebulked == -1\n\t\t\t\t\t|| indexOriginallyBulked == -1) {\n\t\t\t\tthrow new Exception(\"Failed to find exchanges for disabling (\" + indexDisabled + \"), re-bulking (\" + indexRebulked + \") or original bulk (\" + indexOriginallyBulked + \")\");\n\t\t\t}\n\n\t\t\tExchange exchangeDisabled = exchanges.get(indexDisabled);\n\t\t\tLOG.info(\"Disabled on \" + findExtractDate(exchangeDisabled, hmExchangeFiles) + \" \" + exchangeDisabled.getId());\n\n\t\t\tExchange exchangeRebulked = exchanges.get(indexRebulked);\n\t\t\tLOG.info(\"Rebulked on \" + findExtractDate(exchangeRebulked, hmExchangeFiles) + \" \" + exchangeRebulked.getId());\n\n\t\t\tExchange exchangeOriginallyBulked = exchanges.get(indexOriginallyBulked);\n\t\t\tLOG.info(\"Originally bulked on \" + findExtractDate(exchangeOriginallyBulked, hmExchangeFiles) + \" \" + exchangeOriginallyBulked.getId());\n\n\t\t\t//continueOrQuit();\n\n\t\t\tList rebulkFiles = hmExchangeFiles.get(exchangeRebulked);\n\n\t\t\tList tempFilesCreated = new ArrayList<>();\n\n\t\t\tSet patientGuidsDeletedOrTooOld = new HashSet<>();\n\n\t\t\tfor (String rebulkFile: rebulkFiles) {\n\t\t\t\tString fileType = findFileType(rebulkFile);\n\t\t\t\tif (!isPatientFile(fileType)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing \" + fileType);\n\n\t\t\t\tString guidColumnName = getGuidColumnName(fileType);\n\n\t\t\t\t//find all the guids in the re-bulk\n\t\t\t\tSet idsInRebulk = new HashSet<>();\n\n\t\t\t\tInputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(rebulkFile);\n\t\t\t\tCSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT);\n\n\t\t\t\tString[] headers = null;\n\t\t\t\ttry {\n\t\t\t\t\theaders = CsvHelper.getHeaderMapAsArray(csvParser);\n\n\t\t\t\t\tIterator iterator = csvParser.iterator();\n\n\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\tCSVRecord record = iterator.next();\n\n\t\t\t\t\t\t//get the patient and row guid out of the file and cache in our set\n\t\t\t\t\t\tString id = record.get(\"PatientGuid\");\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(guidColumnName)) {\n\t\t\t\t\t\t\tid += \"//\" + record.get(guidColumnName);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tidsInRebulk.add(id);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tcsvParser.close();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Found \" + idsInRebulk.size() + \" IDs in re-bulk file: \" + rebulkFile);\n\n\t\t\t\t//create a replacement file for the exchange the service was disabled\n\t\t\t\tString replacementDisabledFile = null;\n\t\t\t\tList disabledFiles = hmExchangeFilesWithoutStoragePrefix.get(exchangeDisabled);\n\t\t\t\tfor (String s: disabledFiles) {\n\t\t\t\t\tString disabledFileType = findFileType(s);\n\t\t\t\t\tif (disabledFileType.equals(fileType)) {\n\n\t\t\t\t\t\treplacementDisabledFile = FilenameUtils.concat(tempDir, s);\n\n\t\t\t\t\t\tFile dir = new File(replacementDisabledFile).getParentFile();\n\t\t\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\t\t\tif (!dir.mkdirs()) {\n\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to create directory \" + dir);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttempFilesCreated.add(s);\n\t\t\t\t\t\tLOG.info(\"Created replacement file \" + replacementDisabledFile);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tFileWriter fileWriter = new FileWriter(replacementDisabledFile);\n\t\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(fileWriter);\n\t\t\t\tCSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers));\n\t\t\t\tcsvPrinter.flush();\n\n\t\t\t\tSet pastIdsProcessed = new HashSet<>();\n\n\t\t\t\t//now go through all files of the same type PRIOR to the service was disabled\n\t\t\t\t//to find any rows that we'll need to explicitly delete because they were deleted while\n\t\t\t\t//the extract was disabled\n\t\t\t\tfor (int i=indexDisabled-1; i>=indexOriginallyBulked; i--) {\n\t\t\t\t\tExchange exchange = exchanges.get(i);\n\n\t\t\t\t\tString originalFile = null;\n\n\t\t\t\t\tList files = hmExchangeFiles.get(exchange);\n\t\t\t\t\tfor (String s: files) {\n\t\t\t\t\t\tString originalFileType = findFileType(s);\n\t\t\t\t\t\tif (originalFileType.equals(fileType)) {\n\t\t\t\t\t\t\toriginalFile = s;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (originalFile == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\" Reading \" + originalFile);\n\t\t\t\t\treader = FileHelper.readFileReaderFromSharedStorage(originalFile);\n\t\t\t\t\tcsvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator iterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord record = iterator.next();\n\t\t\t\t\t\t\tString patientGuid = record.get(\"PatientGuid\");\n\n\t\t\t\t\t\t\t//get the patient and row guid out of the file and cache in our set\n\t\t\t\t\t\t\tString uniqueId = patientGuid;\n\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(guidColumnName)) {\n\t\t\t\t\t\t\t\tuniqueId += \"//\" + record.get(guidColumnName);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if we're already handled this record in a more recent extract, then skip it\n\t\t\t\t\t\t\tif (pastIdsProcessed.contains(uniqueId)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpastIdsProcessed.add(uniqueId);\n\n\t\t\t\t\t\t\t//if this ID isn't deleted and isn't in the re-bulk then it means\n\t\t\t\t\t\t\t//it WAS deleted in Emis Web but we didn't receive the delete, because it was deleted\n\t\t\t\t\t\t\t//from Emis Web while the extract feed was disabled\n\n\t\t\t\t\t\t\t//if the record is deleted, then we won't expect it in the re-bulk\n\t\t\t\t\t\t\tboolean deleted = Boolean.parseBoolean(record.get(\"Deleted\"));\n\t\t\t\t\t\t\tif (deleted) {\n\n\t\t\t\t\t\t\t\t//if it's the Patient file, stick the patient GUID in a set so we know full patient record deletes\n\t\t\t\t\t\t\t\tif (fileType.equals(\"Admin_Patient\")) {\n\t\t\t\t\t\t\t\t\tpatientGuidsDeletedOrTooOld.add(patientGuid);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if it's not the patient file and we refer to a patient that we know\n\t\t\t\t\t\t\t//has been deleted, then skip this row, since we know we're deleting the entire patient record\n\t\t\t\t\t\t\tif (patientGuidsDeletedOrTooOld.contains(patientGuid)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if the re-bulk contains a record matching this one, then it's OK\n\t\t\t\t\t\t\tif (idsInRebulk.contains(uniqueId)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//the rebulk won't contain any data for patients that are now too old (i.e. deducted or deceased > 2 yrs ago),\n\t\t\t\t\t\t\t//so any patient ID in the original files but not in the rebulk can be treated like this and any data for them can be skipped\n\t\t\t\t\t\t\tif (fileType.equals(\"Admin_Patient\")) {\n\n\t\t\t\t\t\t\t\t//retrieve the Patient and EpisodeOfCare resource for the patient so we can confirm they are deceased or deducted\n\t\t\t\t\t\t\t\tResourceDalI resourceDal = DalProvider.factoryResourceDal();\n\t\t\t\t\t\t\t\tUUID patientUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.Patient, patientGuid);\n\n\t\t\t\t\t\t\t\tPatient patientResource = (Patient)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.Patient, patientUuid.toString());\n\t\t\t\t\t\t\t\tif (patientResource.hasDeceased()) {\n\t\t\t\t\t\t\t\t\tpatientGuidsDeletedOrTooOld.add(patientGuid);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tUUID episodeUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.EpisodeOfCare, patientGuid); //we use the patient GUID for the episode too\n\t\t\t\t\t\t\t\tEpisodeOfCare episodeResource = (EpisodeOfCare)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.EpisodeOfCare, episodeUuid.toString());\n\t\t\t\t\t\t\t\tif (episodeResource.hasPeriod()\n\t\t\t\t\t\t\t\t\t\t&& !PeriodHelper.isActive(episodeResource.getPeriod())) {\n\n\t\t\t\t\t\t\t\t\tpatientGuidsDeletedOrTooOld.add(patientGuid);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//create a new CSV record, carrying over the GUIDs from the original but marking as deleted\n\t\t\t\t\t\t\tString[] newRecord = new String[headers.length];\n\n\t\t\t\t\t\t\tfor (int j=0; j 0) {\n\t\t\t\t\t\t\t\t\tsb.append(\",\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsb.append(record.get(j));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tLOG.info(sb.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcsvPrinter.flush();\n\t\t\t\tcsvPrinter.close();\n\n\n\n\t\t\t\t//also create a version of the CSV file with just the header and nothing else in\n\t\t\t\tfor (int i=indexDisabled+1; i exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex);\n\t\t\t\t\tfor (String s: exchangeFiles) {\n\t\t\t\t\t\tString exchangeFileType = findFileType(s);\n\t\t\t\t\t\tif (exchangeFileType.equals(fileType)) {\n\n\t\t\t\t\t\t\tString emptyTempFile = FilenameUtils.concat(tempDir, s);\n\n\t\t\t\t\t\t\tFile dir = new File(emptyTempFile).getParentFile();\n\t\t\t\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\t\t\t\tif (!dir.mkdirs()) {\n\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to create directory \" + dir);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfileWriter = new FileWriter(emptyTempFile);\n\t\t\t\t\t\t\tbufferedWriter = new BufferedWriter(fileWriter);\n\t\t\t\t\t\t\tcsvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers));\n\t\t\t\t\t\t\tcsvPrinter.flush();\n\t\t\t\t\t\t\tcsvPrinter.close();\n\n\t\t\t\t\t\t\ttempFilesCreated.add(s);\n\t\t\t\t\t\t\tLOG.info(\"Created empty file \" + emptyTempFile);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we also need to copy the restored sharing agreement file to replace all the period it was disabled\n\t\t\tString rebulkedSharingAgreementFile = null;\n\t\t\tfor (String s: rebulkFiles) {\n\t\t\t\tString fileType = findFileType(s);\n\t\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\t\t\t\t\trebulkedSharingAgreementFile = s;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i=indexDisabled; i exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex);\n\t\t\t\tfor (String s: exchangeFiles) {\n\t\t\t\t\tString exchangeFileType = findFileType(s);\n\t\t\t\t\tif (exchangeFileType.equals(\"Agreements_SharingOrganisation\")) {\n\n\t\t\t\t\t\tString replacementFile = FilenameUtils.concat(tempDir, s);\n\n\t\t\t\t\t\tInputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkedSharingAgreementFile);\n\t\t\t\t\t\tFiles.copy(inputStream, new File(replacementFile).toPath());\n\t\t\t\t\t\tinputStream.close();\n\n\t\t\t\t\t\ttempFilesCreated.add(s);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//create a script to copy the files into S3\n\t\t\tList copyScript = new ArrayList<>();\n\t\t\tcopyScript.add(\"#!/bin/bash\");\n\t\t\tcopyScript.add(\"\");\n\t\t\tfor (String s: tempFilesCreated) {\n\t\t\t\tString localFile = FilenameUtils.concat(tempDir, s);\n\t\t\t\tcopyScript.add(\"sudo aws s3 cp \" + localFile + \" s3://discoverysftplanding/endeavour/\" + s);\n\t\t\t}\n\n\t\t\tString scriptFile = FilenameUtils.concat(tempDir, \"copy.sh\");\n\t\t\tFileUtils.writeLines(new File(scriptFile), copyScript);\n\n\t\t\t/*continueOrQuit();\n\n\t\t\t//back up every file where the service was disabled\n\t\t\tfor (int i=indexDisabled; i files = hmExchangeFiles.get(exchange);\n\t\t\t\tfor (String file: files) {\n\t\t\t\t\t//first download from S3 to the local temp dir\n\t\t\t\t\tInputStream inputStream = FileHelper.readFileFromSharedStorage(file);\n\t\t\t\t\tString fileName = FilenameUtils.getName(file);\n\t\t\t\t\tString tempPath = FilenameUtils.concat(tempDir, fileName);\n\t\t\t\t\tFile downloadDestination = new File(tempPath);\n\n\t\t\t\t\tFiles.copy(inputStream, downloadDestination.toPath());\n\n\t\t\t\t\t//then write back to S3 in a sub-dir of the original file\n\t\t\t\t\tString backupPath = FilenameUtils.getPath(file);\n\t\t\t\t\tbackupPath = FilenameUtils.concat(backupPath, \"Original\");\n\t\t\t\t\tbackupPath = FilenameUtils.concat(backupPath, fileName);\n\n\t\t\t\t\tFileHelper.writeFileToSharedStorage(backupPath, downloadDestination);\n\t\t\t\t\tLOG.info(\"Backed up \" + file + \" -> \" + backupPath);\n\n\t\t\t\t\t//delete from temp dir\n\t\t\t\t\tdownloadDestination.delete();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinueOrQuit();\n\n\t\t\t//copy the new CSV files into the dir where it was disabled\n\t\t\tList disabledFiles = hmExchangeFiles.get(exchangeDisabled);\n\t\t\tfor (String disabledFile: disabledFiles) {\n\t\t\t\tString fileType = findFileType(disabledFile);\n\t\t\t\tif (!isPatientFile(fileType)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString tempFile = FilenameUtils.concat(tempDirLast.getAbsolutePath(), fileType + \".csv\");\n\t\t\t\tFile f = new File(tempFile);\n\t\t\t\tif (!f.exists()) {\n\t\t\t\t\tthrow new Exception(\"Failed to find expected temp file \" + f);\n\t\t\t\t}\n\n\t\t\t\tFileHelper.writeFileToSharedStorage(disabledFile, f);\n\t\t\t\tLOG.info(\"Copied \" + tempFile + \" -> \" + disabledFile);\n\t\t\t}\n\n\t\t\tcontinueOrQuit();\n\n\t\t\t//empty the patient files for any extracts while the service was disabled\n\t\t\tfor (int i=indexDisabled+1; i otherDisabledFiles = hmExchangeFiles.get(otherExchangeDisabled);\n\t\t\t\tfor (String otherDisabledFile: otherDisabledFiles) {\n\t\t\t\t\tString fileType = findFileType(otherDisabledFile);\n\t\t\t\t\tif (!isPatientFile(fileType)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString tempFile = FilenameUtils.concat(tempDirEmpty.getAbsolutePath(), fileType + \".csv\");\n\t\t\t\t\tFile f = new File(tempFile);\n\t\t\t\t\tif (!f.exists()) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find expected empty file \" + f);\n\t\t\t\t\t}\n\n\t\t\t\t\tFileHelper.writeFileToSharedStorage(otherDisabledFile, f);\n\t\t\t\t\tLOG.info(\"Copied \" + tempFile + \" -> \" + otherDisabledFile);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinueOrQuit();\n\n\t\t\t//copy the content of the sharing agreement file from when it was re-bulked\n\t\t\tfor (String rebulkFile: rebulkFiles) {\n\t\t\t\tString fileType = findFileType(rebulkFile);\n\t\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\n\t\t\t\t\tString tempFile = FilenameUtils.concat(tempDir, fileType + \".csv\");\n\t\t\t\t\tFile downloadDestination = new File(tempFile);\n\n\t\t\t\t\tInputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkFile);\n\t\t\t\t\tFiles.copy(inputStream, downloadDestination.toPath());\n\n\t\t\t\t\ttempFilesCreated.add(tempFile);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//replace the sharing agreement file for all disabled extracts with the non-disabled one\n\t\t\tfor (int i=indexDisabled; i files = hmExchangeFiles.get(exchange);\n\t\t\t\tfor (String file: files) {\n\t\t\t\t\tString fileType = findFileType(file);\n\t\t\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\n\t\t\t\t\t\tString tempFile = FilenameUtils.concat(tempDir, fileType + \".csv\");\n\t\t\t\t\t\tFile f = new File(tempFile);\n\t\t\t\t\t\tif (!f.exists()) {\n\t\t\t\t\t\t\tthrow new Exception(\"Failed to find expected empty file \" + f);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tFileHelper.writeFileToSharedStorage(file, f);\n\t\t\t\t\t\tLOG.info(\"Copied \" + tempFile + \" -> \" + file);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Disabled Emis Extracts Prior to Re-bulk for service \" + serviceId);\n\t\t\tcontinueOrQuit();\n\n\t\t\tfor (String tempFileCreated: tempFilesCreated) {\n\t\t\t\tFile f = new File(tempFileCreated);\n\t\t\t\tif (f.exists()) {\n\t\t\t\t\tf.delete();\n\t\t\t\t}\n\t\t\t}*/\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}\n\n\tprivate static String findExtractDate(Exchange exchange, Map> fileMap) throws Exception {\n\t\tList files = fileMap.get(exchange);\n\t\tString file = findSharingAgreementFile(files);\n\t\tString name = FilenameUtils.getBaseName(file);\n\t\tString[] toks = name.split(\"_\");\n\t\treturn toks[3];\n\t}\n\n\tprivate static boolean isDisabledInSharingAgreementFile(Exchange exchange, Map> fileMap) throws Exception {\n\t\tList files = fileMap.get(exchange);\n\t\tString file = findSharingAgreementFile(files);\n\n\t\tInputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(file);\n\t\tCSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT);\n\t\ttry {\n\t\t\tIterator iterator = csvParser.iterator();\n\t\t\tCSVRecord record = iterator.next();\n\n\t\t\tString s = record.get(\"Disabled\");\n\t\t\tboolean disabled = Boolean.parseBoolean(s);\n\t\t\treturn disabled;\n\n\t\t} finally {\n\t\t\tcsvParser.close();\n\t\t}\n\t}\n\n\tprivate static void continueOrQuit() throws Exception {\n\t\tLOG.info(\"Enter y to continue, anything else to quit\");\n\n\t\tbyte[] bytes = new byte[10];\n\t\tSystem.in.read(bytes);\n\t\tchar c = (char)bytes[0];\n\t\tif (c != 'y' && c != 'Y') {\n\t\t\tSystem.out.println(\"Read \" + c);\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate static String getGuidColumnName(String fileType) {\n\t\tif (fileType.equals(\"Admin_Patient\")) {\n\t\t\t//patient file just has patient GUID, nothing extra\n\t\t\treturn null;\n\n\t\t} else if (fileType.equals(\"CareRecord_Consultation\")) {\n\t\t\treturn \"ConsultationGuid\";\n\n\t\t} else if (fileType.equals(\"CareRecord_Diary\")) {\n\t\t\treturn \"DiaryGuid\";\n\n\t\t} else if (fileType.equals(\"CareRecord_Observation\")) {\n\t\t\treturn \"ObservationGuid\";\n\n\t\t} else if (fileType.equals(\"CareRecord_Problem\")) {\n\t\t\t//there is no separate problem GUID, as it's just a modified observation\n\t\t\treturn \"ObservationGuid\";\n\n\t\t} else if (fileType.equals(\"Prescribing_DrugRecord\")) {\n\t\t\treturn \"DrugRecordGuid\";\n\n\t\t} else if (fileType.equals(\"Prescribing_IssueRecord\")) {\n\t\t\treturn \"IssueRecordGuid\";\n\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(fileType);\n\t\t}\n\t}\n\n\tprivate static String findFileType(String filePath) {\n\t\tString fileName = FilenameUtils.getName(filePath);\n\t\tString[] toks = fileName.split(\"_\");\n\t\tString domain = toks[1];\n\t\tString name = toks[2];\n\n\t\treturn domain + \"_\" + name;\n\t}\n\n\tprivate static boolean isPatientFile(String fileType) {\n\t\tif (fileType.equals(\"Admin_Patient\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Consultation\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Diary\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Observation\")\n\t\t\t\t|| fileType.equals(\"CareRecord_Problem\")\n\t\t\t\t|| fileType.equals(\"Prescribing_DrugRecord\")\n\t\t\t\t|| fileType.equals(\"Prescribing_IssueRecord\")) {\n\t\t\t//note the referral file doesn't have a Deleted column, so isn't in this list\n\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate static String findSharingAgreementFile(List files) throws Exception {\n\n\t\tfor (String file : files) {\n\t\t\tString fileType = findFileType(file);\n\t\t\tif (fileType.equals(\"Agreements_SharingOrganisation\")) {\n\t\t\t\treturn file;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Exception(\"Failed to find sharing agreement file in \" + files.get(0));\n\t}\n\n\n\n\tprivate static void testSlack() {\n\t\tLOG.info(\"Testing slack\");\n\n\t\ttry {\n\t\t\tSlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, \"Test Message from Queue Reader\");\n\t\t\tLOG.info(\"Finished testing slack\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}\n\n\tprivate static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) {\n\n\t\ttry {\n\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\t\tService service = serviceDalI.getById(serviceId);\n\t\t\tLOG.info(\"Posting to inbound exchange for \" + service.getName() + \" from file \" + filePath);\n\n\t\t\tFileReader fr = new FileReader(filePath);\n\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\tint count = 0;\n\t\t\tList exchangeIdBatch = new ArrayList<>();\n\n\t\t\twhile (true) {\n\t\t\t\tString line = br.readLine();\n\t\t\t\tif (line == null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tUUID exchangeId = UUID.fromString(line);\n\n\t\t\t\t//update the transform audit, so EDS UI knows we've re-queued this exchange\n\t\t\t\tExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId);\n\t\t\t\tif (audit != null\n\t\t\t\t\t\t&& !audit.isResubmitted()) {\n\t\t\t\t\taudit.setResubmitted(true);\n\t\t\t\t\tauditRepository.save(audit);\n\t\t\t\t}\n\n\t\t\t\tcount ++;\n\t\t\t\texchangeIdBatch.add(exchangeId);\n\t\t\t\tif (exchangeIdBatch.size() >= 1000) {\n\t\t\t\t\tQueueHelper.postToExchange(exchangeIdBatch, \"EdsInbound\", null, false);\n\t\t\t\t\texchangeIdBatch = new ArrayList<>();\n\t\t\t\t\tLOG.info(\"Done \" + count);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!exchangeIdBatch.isEmpty()) {\n\t\t\t\tQueueHelper.postToExchange(exchangeIdBatch, \"EdsInbound\", null, false);\n\t\t\t\tLOG.info(\"Done \" + count);\n\t\t\t}\n\n\t\t\tbr.close();\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Posting to inbound for \" + serviceId);\n\t}\n\n\t/*private static void postToInbound(UUID serviceId, boolean all) {\n\t\tLOG.info(\"Posting to inbound for \" + serviceId);\n\n\t\ttry {\n\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\t\tService service = serviceDalI.getById(serviceId);\n\n\t\t\tList systemIds = findSystemIds(service);\n\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\tExchangeTransformErrorState errorState = auditRepository.getErrorState(serviceId, systemId);\n\n\t\t\tfor (UUID exchangeId: errorState.getExchangeIdsInError()) {\n\n\t\t\t\t//update the transform audit, so EDS UI knows we've re-queued this exchange\n\t\t\t\tExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId);\n\n\t\t\t\t//skip any exchange IDs we've already re-queued up to be processed again\n\t\t\t\tif (audit.isResubmitted()) {\n\t\t\t\t\tLOG.debug(\"Not re-posting \" + audit.getExchangeId() + \" as it's already been resubmitted\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.debug(\"Re-posting \" + audit.getExchangeId());\n\t\t\t\taudit.setResubmitted(true);\n\t\t\t\tauditRepository.save(audit);\n\n\t\t\t\t//then re-submit the exchange to Rabbit MQ for the queue reader to pick up\n\t\t\t\tQueueHelper.postToExchange(exchangeId, \"EdsInbound\", null, false);\n\n\t\t\t\tif (!all) {\n\t\t\t\t\tLOG.info(\"Posted first exchange, so stopping\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Posting to inbound for \" + serviceId);\n\t}*/\n\n\t/*private static void fixPatientSearch(String serviceId) {\n\t\tLOG.info(\"Fixing patient search for \" + serviceId);\n\n\t\ttry {\n\n\t\t\tUUID serviceUuid = UUID.fromString(serviceId);\n\n\t\t\tExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDalI = DalProvider.factoryResourceDal();\n\t\t\tPatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal();\n\t\t\tParserPool parser = new ParserPool();\n\n\t\t\tSet patientsDone = new HashSet<>();\n\n\t\t\tList exchanges = exchangeDalI.getExchangeIdsForService(serviceUuid);\n\t\t\tLOG.info(\"Found \" + exchanges.size() + \" exchanges\");\n\n\t\t\tfor (UUID exchangeId: exchanges) {\n\t\t\t\tList batches = exchangeBatchDalI.retrieveForExchangeId(exchangeId);\n\t\t\t\tLOG.info(\"Found \" + batches.size() + \" batches in exchange \" + exchangeId);\n\n\t\t\t\tfor (ExchangeBatch batch: batches) {\n\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\tif (patientId == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (patientsDone.contains(patientId)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tResourceWrapper wrapper = resourceDalI.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId);\n\t\t\t\t\tif (wrapper != null) {\n\t\t\t\t\t\tString json = wrapper.getResourceData();\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(json)) {\n\n\t\t\t\t\t\t\tPatient fhirPatient = (Patient) parser.parse(json);\n\t\t\t\t\t\t\tUUID systemUuid = wrapper.getSystemId();\n\n\t\t\t\t\t\t\tpatientSearchDal.update(serviceUuid, systemUuid, fhirPatient);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tpatientsDone.add(patientId);\n\n\t\t\t\t\tif (patientsDone.size() % 1000 == 0) {\n\t\t\t\t\t\tLOG.info(\"Done \" + patientsDone.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished fixing patient search for \" + serviceId);\n\t}*/\n\n\tprivate static void runSql(String host, String username, String password, String sqlFile) {\n\t\tLOG.info(\"Running SQL on \" + host + \" from \" + sqlFile);\n\n\t\tConnection conn = null;\n\t\tStatement statement = null;\n\n\n\t\ttry {\n\t\t\tFile f = new File(sqlFile);\n\t\t\tif (!f.exists()) {\n\t\t\t\tLOG.error(\"\" + f + \" doesn't exist\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tList lines = FileUtils.readLines(f);\n\t\t\t/*String combined = String.join(\"\\n\", lines);\n\n\t\t\tLOG.info(\"Going to run SQL\");\n\t\t\tLOG.info(combined);*/\n\n\t\t\t//load driver\n\t\t\tClass.forName(\"com.mysql.cj.jdbc.Driver\");\n\n\t\t\t//create connection\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(\"user\", username);\n\t\t\tprops.setProperty(\"password\", password);\n\n\t\t\tconn = DriverManager.getConnection(host, props);\n\t\t\tLOG.info(\"Opened connection\");\n\t\t\tstatement = conn.createStatement();\n\n\t\t\tlong totalStart = System.currentTimeMillis();\n\n\t\t\tfor (String sql: lines) {\n\n\t\t\t\tsql = sql.trim();\n\n\t\t\t\tif (sql.startsWith(\"--\")\n\t\t\t\t\t\t|| sql.startsWith(\"/*\")\n\t\t\t\t\t\t|| Strings.isNullOrEmpty(sql)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"\");\n\t\t\t\tLOG.info(sql);\n\n\t\t\t\tlong start = System.currentTimeMillis();\n\n\t\t\t\tboolean hasResultSet = statement.execute(sql);\n\n\t\t\t\tlong end = System.currentTimeMillis();\n\t\t\t\tLOG.info(\"SQL took \" + (end - start) + \"ms\");\n\n\t\t\t\tif (hasResultSet) {\n\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tResultSet rs = statement.getResultSet();\n\t\t\t\t\t\tint cols = rs.getMetaData().getColumnCount();\n\n\t\t\t\t\t\tList colHeaders = new ArrayList<>();\n\t\t\t\t\t\tfor (int i = 0; i < cols; i++) {\n\t\t\t\t\t\t\tString header = rs.getMetaData().getColumnName(i + 1);\n\t\t\t\t\t\t\tcolHeaders.add(header);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tString colHeaderStr = String.join(\", \", colHeaders);\n\t\t\t\t\t\tLOG.info(colHeaderStr);\n\n\t\t\t\t\t\twhile (rs.next()) {\n\t\t\t\t\t\t\tList row = new ArrayList<>();\n\t\t\t\t\t\t\tfor (int i = 0; i < cols; i++) {\n\t\t\t\t\t\t\t\tObject o = rs.getObject(i + 1);\n\t\t\t\t\t\t\t\tif (rs.wasNull()) {\n\t\t\t\t\t\t\t\t\trow.add(\"\");\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trow.add(o.toString());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tString rowStr = String.join(\", \", row);\n\t\t\t\t\t\t\tLOG.info(rowStr);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!statement.getMoreResults()) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tint updateCount = statement.getUpdateCount();\n\t\t\t\t\tLOG.info(\"Updated \" + updateCount + \" Row(s)\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlong totalEnd = System.currentTimeMillis();\n\t\t\tLOG.info(\"\");\n\t\t\tLOG.info(\"Total time taken \" + (totalEnd - totalStart) + \"ms\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t} finally {\n\n\t\t\tif (statement != null) {\n\t\t\t\ttry {\n\t\t\t\t\tstatement.close();\n\t\t\t\t} catch (Exception ex) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (conn != null) {\n\t\t\t\ttry {\n\t\t\t\t\tconn.close();\n\t\t\t\t} catch (Exception ex) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tLOG.info(\"Closed connection\");\n\t\t}\n\n\t\tLOG.info(\"Finished Testing DB Size Limit\");\n\t}\n\n\n\n\t/*private static void fixExchangeBatches() {\n\t\tLOG.info(\"Starting Fixing Exchange Batches\");\n\n\t\ttry {\n\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal();\n\t\t\tExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal();\n\t\t\tResourceDalI resourceDalI = DalProvider.factoryResourceDal();\n\n\t\t\tList services = serviceDalI.getAll();\n\t\t\tfor (Service service: services) {\n\t\t\t\tLOG.info(\"Doing \" + service.getName());\n\n\t\t\t\tList exchangeIds = exchangeDalI.getExchangeIdsForService(service.getId());\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\t\t\t\t\tLOG.info(\" Exchange \" + exchangeId);\n\n\t\t\t\t\tList exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch exchangeBatch: exchangeBatches) {\n\n\t\t\t\t\t\tif (exchangeBatch.getEdsPatientId() != null) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tList resources = resourceDalI.getResourcesForBatch(exchangeBatch.getBatchId());\n\t\t\t\t\t\tif (resources.isEmpty()) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tResourceWrapper first = resources.get(0);\n\t\t\t\t\t\tUUID patientId = first.getPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\texchangeBatch.setEdsPatientId(patientId);\n\t\t\t\t\t\t\texchangeBatchDalI.save(exchangeBatch);\n\t\t\t\t\t\t\tLOG.info(\"Fixed batch \" + exchangeBatch.getBatchId() + \" -> \" + exchangeBatch.getEdsPatientId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Exchange Batches\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/**\n\t * exports ADT Encounters for patients based on a CSV file produced using the below SQL\n\t --USE EDS DATABASE\n\n\t -- barts b5a08769-cbbe-4093-93d6-b696cd1da483\n\t -- homerton 962d6a9a-5950-47ac-9e16-ebee56f9507a\n\n\t create table adt_patients (\n\t service_id character(36),\n\t system_id character(36),\n\t nhs_number character varying(10),\n\t patient_id character(36)\n\t );\n\n\t -- delete from adt_patients;\n\n\t select * from patient_search limit 10;\n\t select * from patient_link limit 10;\n\n\t insert into adt_patients\n\t select distinct ps.service_id, ps.system_id, ps.nhs_number, ps.patient_id\n\t from patient_search ps\n\t join patient_link pl\n\t on pl.patient_id = ps.patient_id\n\t join patient_link pl2\n\t on pl.person_id = pl2.person_id\n\t join patient_search ps2\n\t on ps2.patient_id = pl2.patient_id\n\t where\n\t ps.service_id IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a')\n\t and ps2.service_id NOT IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a');\n\n\n\t select count(1) from adt_patients limit 100;\n\t select * from adt_patients limit 100;\n\n\n\n\n\t ---MOVE TABLE TO HL7 RECEIVER DB\n\n\t select count(1) from adt_patients;\n\n\t -- top 1000 patients with messages\n\n\t select * from mapping.resource_uuid where resource_type = 'Patient' limit 10;\n\n\t select * from log.message limit 10;\n\n\t create table adt_patient_counts (\n\t nhs_number character varying(100),\n\t count int\n\t );\n\n\t insert into adt_patient_counts\n\t select pid1, count(1)\n\t from log.message\n\t where pid1 is not null\n\t and pid1 <> ''\n\t group by pid1;\n\n\t select * from adt_patient_counts order by count desc limit 100;\n\n\t alter table adt_patients\n\t add count int;\n\n\t update adt_patients\n\t set count = adt_patient_counts.count\n\t from adt_patient_counts\n\t where adt_patients.nhs_number = adt_patient_counts.nhs_number;\n\n\t select count(1) from adt_patients where nhs_number is null;\n\n\t select * from adt_patients\n\t where nhs_number is not null\n\t and count is not null\n\t order by count desc limit 1000;\n\t */\n\t/*private static void exportHl7Encounters(String sourceCsvPath, String outputPath) {\n\t\tLOG.info(\"Exporting HL7 Encounters from \" + sourceCsvPath + \" to \" + outputPath);\n\n\t\ttry {\n\n\t\t\tFile sourceFile = new File(sourceCsvPath);\n\t\t\tCSVParser csvParser = CSVParser.parse(sourceFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\n\t\t\t//\"service_id\",\"system_id\",\"nhs_number\",\"patient_id\",\"count\"\n\n\t\t\tint count = 0;\n\t\t\tHashMap> serviceAndSystemIds = new HashMap<>();\n\t\t\tHashMap patientIds = new HashMap<>();\n\n\t\t\tIterator csvIterator = csvParser.iterator();\n\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\t\t\t\tcount ++;\n\n\t\t\t\tString serviceId = csvRecord.get(\"service_id\");\n\t\t\t\tString systemId = csvRecord.get(\"system_id\");\n\t\t\t\tString patientId = csvRecord.get(\"patient_id\");\n\n\t\t\t\tUUID serviceUuid = UUID.fromString(serviceId);\n\t\t\t\tList systemIds = serviceAndSystemIds.get(serviceUuid);\n\t\t\t\tif (systemIds == null) {\n\t\t\t\t\tsystemIds = new ArrayList<>();\n\t\t\t\t\tserviceAndSystemIds.put(serviceUuid, systemIds);\n\t\t\t\t}\n\t\t\t\tsystemIds.add(UUID.fromString(systemId));\n\n\t\t\t\tpatientIds.put(UUID.fromString(patientId), new Integer(count));\n\t\t\t}\n\n\t\t\tcsvParser.close();\n\n\t\t\tExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal();\n\t\t\tResourceDalI resourceDalI = DalProvider.factoryResourceDal();\n\t\t\tExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal();\n\t\t\tServiceDalI serviceDalI = DalProvider.factoryServiceDal();\n\t\t\tParserPool parser = new ParserPool();\n\n\t\t\tMap> patientRows = new HashMap<>();\n\t\t\tSimpleDateFormat sdfOutput = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\t\t\tfor (UUID serviceId: serviceAndSystemIds.keySet()) {\n\t\t\t\t//List systemIds = serviceAndSystemIds.get(serviceId);\n\n\t\t\t\tService service = serviceDalI.getById(serviceId);\n\t\t\t\tString serviceName = service.getName();\n\t\t\t\tLOG.info(\"Doing service \" + serviceId + \" \" + serviceName);\n\n\t\t\t\tList exchangeIds = exchangeDalI.getExchangeIdsForService(serviceId);\n\t\t\t\tLOG.info(\"Got \" + exchangeIds.size() + \" exchange IDs to scan\");\n\t\t\t\tint exchangeCount = 0;\n\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\texchangeCount ++;\n\t\t\t\t\tif (exchangeCount % 1000 == 0) {\n\t\t\t\t\t\tLOG.info(\"Done \" + exchangeCount + \" exchanges\");\n\t\t\t\t\t}\n\n\t\t\t\t\tList exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch exchangeBatch: exchangeBatches) {\n\t\t\t\t\t\tUUID patientId = exchangeBatch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null\n\t\t\t\t\t\t\t\t&& !patientIds.containsKey(patientId)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tInteger patientIdInt = patientIds.get(patientId);\n\n\t\t\t\t\t\t//get encounters for exchange batch\n\t\t\t\t\t\tUUID batchId = exchangeBatch.getBatchId();\n\t\t\t\t\t\tList resourceWrappers = resourceDalI.getResourcesForBatch(serviceId, batchId);\n\t\t\t\t\t\tfor (ResourceWrapper resourceWrapper: resourceWrappers) {\n\t\t\t\t\t\t\tif (resourceWrapper.isDeleted()) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tString resourceType = resourceWrapper.getResourceType();\n\t\t\t\t\t\t\tif (!resourceType.equals(ResourceType.Encounter.toString())) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tLOG.info(\"Processing \" + resourceWrapper.getResourceType() + \" \" + resourceWrapper.getResourceId());\n\t\t\t\t\t\t\tString json = resourceWrapper.getResourceData();\n\t\t\t\t\t\t\tEncounter fhirEncounter = (Encounter)parser.parse(json);\n\n\t\t\t\t\t\t\tDate date = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasPeriod()) {\n\t\t\t\t\t\t\t\tPeriod period = fhirEncounter.getPeriod();\n\t\t\t\t\t\t\t\tif (period.hasStart()) {\n\t\t\t\t\t\t\t\t\tdate = period.getStart();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString episodeId = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasEpisodeOfCare()) {\n\t\t\t\t\t\t\t\tReference episodeReference = fhirEncounter.getEpisodeOfCare().get(0);\n\t\t\t\t\t\t\t\tReferenceComponents comps = ReferenceHelper.getReferenceComponents(episodeReference);\n\t\t\t\t\t\t\t\tEpisodeOfCare fhirEpisode = (EpisodeOfCare)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId());\n\t\t\t\t\t\t\t\tif (fhirEpisode != null) {\n\t\t\t\t\t\t\t\t\tif (fhirEpisode.hasIdentifier()) {\n\t\t\t\t\t\t\t\t\t\tepisodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_BARTS_FIN_EPISODE_ID);\n\n\t\t\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(episodeId)) {\n\t\t\t\t\t\t\t\t\t\t\tepisodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_FIN_EPISODE_ID);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\tString adtType = null;\n\t\t\t\t\t\t\tString adtCode = null;\n\t\t\t\t\t\t\tExtension extension = ExtensionConverter.findExtension(fhirEncounter, FhirExtensionUri.HL7_MESSAGE_TYPE);\n\n\t\t\t\t\t\t\tif (extension != null) {\n\t\t\t\t\t\t\t\tCodeableConcept codeableConcept = (CodeableConcept) extension.getValue();\n\t\t\t\t\t\t\t\tCoding hl7MessageTypeCoding = CodeableConceptHelper.findCoding(codeableConcept, FhirUri.CODE_SYSTEM_HL7V2_MESSAGE_TYPE);\n\t\t\t\t\t\t\t\tif (hl7MessageTypeCoding != null) {\n\t\t\t\t\t\t\t\t\tadtType = hl7MessageTypeCoding.getDisplay();\n\t\t\t\t\t\t\t\t\tadtCode = hl7MessageTypeCoding.getCode();\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t//for older formats of the transformed resources, the HL7 message type can only be found from the raw original exchange body\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tExchange exchange = exchangeDalI.getExchange(exchangeId);\n\t\t\t\t\t\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\t\t\t\t\t\tBundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(exchangeBody);\n\t\t\t\t\t\t\t\t\tfor (Bundle.BundleEntryComponent entry: bundle.getEntry()) {\n\t\t\t\t\t\t\t\t\t\tif (entry.getResource() != null\n\t\t\t\t\t\t\t\t\t\t\t\t&& entry.getResource() instanceof MessageHeader) {\n\n\t\t\t\t\t\t\t\t\t\t\tMessageHeader header = (MessageHeader)entry.getResource();\n\t\t\t\t\t\t\t\t\t\t\tif (header.hasEvent()) {\n\t\t\t\t\t\t\t\t\t\t\t\tCoding coding = header.getEvent();\n\t\t\t\t\t\t\t\t\t\t\t\tadtType = coding.getDisplay();\n\t\t\t\t\t\t\t\t\t\t\t\tadtCode = coding.getCode();\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\t\t\t//if the exchange body isn't a FHIR bundle, then we'll get an error by treating as such, so just ignore them\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString cls = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasClass_()) {\n\t\t\t\t\t\t\t\tEncounter.EncounterClass encounterClass = fhirEncounter.getClass_();\n\t\t\t\t\t\t\t\tif (encounterClass == Encounter.EncounterClass.OTHER\n\t\t\t\t\t\t\t\t\t\t&& fhirEncounter.hasClass_Element()\n\t\t\t\t\t\t\t\t\t\t&& fhirEncounter.getClass_Element().hasExtension()) {\n\n\t\t\t\t\t\t\t\t\tfor (Extension classExtension: fhirEncounter.getClass_Element().getExtension()) {\n\t\t\t\t\t\t\t\t\t\tif (classExtension.getUrl().equals(FhirExtensionUri.ENCOUNTER_CLASS)) {\n\t\t\t\t\t\t\t\t\t\t\t//not 100% of the type of the value, so just append to a String\n\t\t\t\t\t\t\t\t\t\t\tcls = \"\" + classExtension.getValue();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(cls)) {\n\t\t\t\t\t\t\t\t\tcls = encounterClass.toCode();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString type = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasType()) {\n\t\t\t\t\t\t\t\t//only seem to ever have one type\n\t\t\t\t\t\t\t\tCodeableConcept codeableConcept = fhirEncounter.getType().get(0);\n\t\t\t\t\t\t\t\ttype = codeableConcept.getText();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString status = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasStatus()) {\n\t\t\t\t\t\t\t\tEncounter.EncounterState encounterState = fhirEncounter.getStatus();\n\t\t\t\t\t\t\t\tstatus = encounterState.toCode();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString location = null;\n\t\t\t\t\t\t\tString locationType = null;\n\t\t\t\t\t\t\tif (fhirEncounter.hasLocation()) {\n\t\t\t\t\t\t\t\t//first location is always the current location\n\t\t\t\t\t\t\t\tEncounter.EncounterLocationComponent encounterLocation = fhirEncounter.getLocation().get(0);\n\t\t\t\t\t\t\t\tif (encounterLocation.hasLocation()) {\n\t\t\t\t\t\t\t\t\tReference locationReference = encounterLocation.getLocation();\n\t\t\t\t\t\t\t\t\tReferenceComponents comps = ReferenceHelper.getReferenceComponents(locationReference);\n\t\t\t\t\t\t\t\t\tLocation fhirLocation = (Location)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId());\n\t\t\t\t\t\t\t\t\tif (fhirLocation != null) {\n\t\t\t\t\t\t\t\t\t\tif (fhirLocation.hasName()) {\n\t\t\t\t\t\t\t\t\t\t\tlocation = fhirLocation.getName();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (fhirLocation.hasType()) {\n\t\t\t\t\t\t\t\t\t\t\tCodeableConcept typeCodeableConcept = fhirLocation.getType();\n\t\t\t\t\t\t\t\t\t\t\tif (typeCodeableConcept.hasCoding()) {\n\t\t\t\t\t\t\t\t\t\t\t\tCoding coding = typeCodeableConcept.getCoding().get(0);\n\t\t\t\t\t\t\t\t\t\t\t\tlocationType = coding.getDisplay();\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString clinician = null;\n\n\t\t\t\t\t\t\tif (fhirEncounter.hasParticipant()) {\n\t\t\t\t\t\t\t\t//first participant seems to be the interesting one\n\t\t\t\t\t\t\t\tEncounter.EncounterParticipantComponent encounterParticipant = fhirEncounter.getParticipant().get(0);\n\t\t\t\t\t\t\t\tif (encounterParticipant.hasIndividual()) {\n\t\t\t\t\t\t\t\t\tReference practitionerReference = encounterParticipant.getIndividual();\n\t\t\t\t\t\t\t\t\tReferenceComponents comps = ReferenceHelper.getReferenceComponents(practitionerReference);\n\t\t\t\t\t\t\t\t\tPractitioner fhirPractitioner = (Practitioner)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId());\n\t\t\t\t\t\t\t\t\tif (fhirPractitioner != null) {\n\t\t\t\t\t\t\t\t\t\tif (fhirPractitioner.hasName()) {\n\t\t\t\t\t\t\t\t\t\t\tHumanName name = fhirPractitioner.getName();\n\t\t\t\t\t\t\t\t\t\t\tclinician = name.getText();\n\t\t\t\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(clinician)) {\n\t\t\t\t\t\t\t\t\t\t\t\tclinician = \"\";\n\n\t\t\t\t\t\t\t\t\t\t\t\tfor (StringType s: name.getPrefix()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += s.getValueNotNull();\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += \" \";\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tfor (StringType s: name.getGiven()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += s.getValueNotNull();\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += \" \";\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tfor (StringType s: name.getFamily()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += s.getValueNotNull();\n\t\t\t\t\t\t\t\t\t\t\t\t\tclinician += \" \";\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tclinician = clinician.trim();\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tObject[] row = new Object[12];\n\n\t\t\t\t\t\t\trow[0] = serviceName;\n\t\t\t\t\t\t\trow[1] = patientIdInt.toString();\n\t\t\t\t\t\t\trow[2] = sdfOutput.format(date);\n\t\t\t\t\t\t\trow[3] = episodeId;\n\t\t\t\t\t\t\trow[4] = adtCode;\n\t\t\t\t\t\t\trow[5] = adtType;\n\t\t\t\t\t\t\trow[6] = cls;\n\t\t\t\t\t\t\trow[7] = type;\n\t\t\t\t\t\t\trow[8] = status;\n\t\t\t\t\t\t\trow[9] = location;\n\t\t\t\t\t\t\trow[10] = locationType;\n\t\t\t\t\t\t\trow[11] = clinician;\n\n\t\t\t\t\t\t\tList rows = patientRows.get(patientIdInt);\n\t\t\t\t\t\t\tif (rows == null) {\n\t\t\t\t\t\t\t\trows = new ArrayList<>();\n\t\t\t\t\t\t\t\tpatientRows.put(patientIdInt, rows);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trows.add(row);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tString[] outputColumnHeaders = new String[] {\"Source\", \"Patient\", \"Date\", \"Episode ID\", \"ADT Message Code\", \"ADT Message Type\", \"Class\", \"Type\", \"Status\", \"Location\", \"Location Type\", \"Clinician\"};\n\n\t\t\tFileWriter fileWriter = new FileWriter(outputPath);\n\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(fileWriter);\n\t\t\tCSVFormat format = CSVFormat.DEFAULT\n\t\t\t\t\t.withHeader(outputColumnHeaders)\n\t\t\t\t\t.withQuote('\"');\n\t\t\tCSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format);\n\n\t\t\tfor (int i=0; i <= count; i++) {\n\t\t\t\tInteger patientIdInt = new Integer(i);\n\t\t\t\tList rows = patientRows.get(patientIdInt);\n\t\t\t\tif (rows != null) {\n\t\t\t\t\tfor (Object[] row: rows) {\n\t\t\t\t\t\tcsvPrinter.printRecord(row);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcsvPrinter.close();\n\t\t\tbufferedWriter.close();\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Exporting Encounters from \" + sourceCsvPath + \" to \" + outputPath);\n\t}*/\n\n\t/*private static void registerShutdownHook() {\n\n\t\tRuntime.getRuntime().addShutdownHook(new Thread() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\n\t\t\t\tLOG.info(\"\");\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(5000);\n\t\t\t\t} catch (Throwable ex) {\n\t\t\t\t\tLOG.error(\"\", ex);\n\t\t\t\t}\n\t\t\t\tLOG.info(\"Done\");\n\t\t\t}\n\t\t});\n\t}*/\n\n\n\tprivate static void findEmisStartDates(String path, String outputPath) {\n\t\tLOG.info(\"Finding EMIS Start Dates in \" + path + \", writing to \" + outputPath);\n\n\t\ttry {\n\n\t\t\tSimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH.mm.ss\");\n\n\t\t\tMap startDates = new HashMap<>();\n\t\t\tMap servers = new HashMap<>();\n\n\t\t\tMap names = new HashMap<>();\n\t\t\tMap odsCodes = new HashMap<>();\n\t\t\tMap cdbNumbers = new HashMap<>();\n\t\t\tMap> distinctPatients = new HashMap<>();\n\n\t\t\tFile root = new File(path);\n\t\t\tfor (File sftpRoot: root.listFiles()) {\n\t\t\t\tLOG.info(\"Checking \" + sftpRoot);\n\n\t\t\t\tMap extracts = new HashMap<>();\n\t\t\t\tList extractDates = new ArrayList<>();\n\n\t\t\t\tfor (File extractRoot: sftpRoot.listFiles()) {\n\t\t\t\t\tDate d = sdf.parse(extractRoot.getName());\n\n\t\t\t\t\t//LOG.info(\"\" + extractRoot.getName() + \" -> \" + d);\n\n\t\t\t\t\textracts.put(d, extractRoot);\n\t\t\t\t\textractDates.add(d);\n\t\t\t\t}\n\n\t\t\t\tCollections.sort(extractDates);\n\n\t\t\t\tfor (Date extractDate: extractDates) {\n\t\t\t\t\tFile extractRoot = extracts.get(extractDate);\n\t\t\t\t\tLOG.info(\"Checking \" + extractRoot);\n\n\t\t\t\t\t//read the sharing agreements file\n\t\t\t\t\t//e.g. 291_Agreements_SharingOrganisation_20150211164536_45E7CD20-EE37-41AB-90D6-DC9D4B03D102.csv\n\t\t\t\t\tFile sharingAgreementsFile = null;\n\t\t\t\t\tfor (File f: extractRoot.listFiles()) {\n\t\t\t\t\t\tString name = f.getName().toLowerCase();\n\t\t\t\t\t\tif (name.indexOf(\"agreements_sharingorganisation\") > -1\n\t\t\t\t\t\t\t\t&& name.endsWith(\".csv\")) {\n\t\t\t\t\t\t\tsharingAgreementsFile = f;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (sharingAgreementsFile == null) {\n\t\t\t\t\t\tLOG.info(\"Null agreements file for \" + extractRoot);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCSVParser csvParser = CSVParser.parse(sharingAgreementsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\t\tString orgGuid = csvRecord.get(\"OrganisationGuid\");\n\t\t\t\t\t\t\tString activated = csvRecord.get(\"IsActivated\");\n\t\t\t\t\t\t\tString disabled = csvRecord.get(\"Disabled\");\n\n\t\t\t\t\t\t\tservers.put(orgGuid, sftpRoot.getName());\n\n\t\t\t\t\t\t\tif (activated.equalsIgnoreCase(\"true\")) {\n\t\t\t\t\t\t\t\tif (disabled.equalsIgnoreCase(\"false\")) {\n\n\t\t\t\t\t\t\t\t\tDate d = sdf.parse(extractRoot.getName());\n\t\t\t\t\t\t\t\t\tDate existingDate = startDates.get(orgGuid);\n\t\t\t\t\t\t\t\t\tif (existingDate == null) {\n\t\t\t\t\t\t\t\t\t\tstartDates.put(orgGuid, d);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (startDates.containsKey(orgGuid)) {\n\t\t\t\t\t\t\t\t\t\tstartDates.put(orgGuid, null);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\n\t\t\t\t\t//go through orgs file to get name, ods and cdb codes\n\t\t\t\t\tFile orgsFile = null;\n\t\t\t\t\tfor (File f: extractRoot.listFiles()) {\n\t\t\t\t\t\tString name = f.getName().toLowerCase();\n\t\t\t\t\t\tif (name.indexOf(\"admin_organisation_\") > -1\n\t\t\t\t\t\t\t\t&& name.endsWith(\".csv\")) {\n\t\t\t\t\t\t\torgsFile = f;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser = CSVParser.parse(orgsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\t\tString orgGuid = csvRecord.get(\"OrganisationGuid\");\n\t\t\t\t\t\t\tString name = csvRecord.get(\"OrganisationName\");\n\t\t\t\t\t\t\tString odsCode = csvRecord.get(\"ODSCode\");\n\t\t\t\t\t\t\tString cdb = csvRecord.get(\"CDB\");\n\n\t\t\t\t\t\t\tnames.put(orgGuid, name);\n\t\t\t\t\t\t\todsCodes.put(orgGuid, odsCode);\n\t\t\t\t\t\t\tcdbNumbers.put(orgGuid, cdb);\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\n\t\t\t\t\t//go through patients file to get count\n\t\t\t\t\tFile patientFile = null;\n\t\t\t\t\tfor (File f: extractRoot.listFiles()) {\n\t\t\t\t\t\tString name = f.getName().toLowerCase();\n\t\t\t\t\t\tif (name.indexOf(\"admin_patient_\") > -1\n\t\t\t\t\t\t\t\t&& name.endsWith(\".csv\")) {\n\t\t\t\t\t\t\tpatientFile = f;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser = CSVParser.parse(patientFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\t\tString orgGuid = csvRecord.get(\"OrganisationGuid\");\n\t\t\t\t\t\t\tString patientGuid = csvRecord.get(\"PatientGuid\");\n\t\t\t\t\t\t\tString deleted = csvRecord.get(\"Deleted\");\n\n\t\t\t\t\t\t\tSet distinctPatientSet = distinctPatients.get(orgGuid);\n\t\t\t\t\t\t\tif (distinctPatientSet == null) {\n\t\t\t\t\t\t\t\tdistinctPatientSet = new HashSet<>();\n\t\t\t\t\t\t\t\tdistinctPatients.put(orgGuid, distinctPatientSet);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (deleted.equalsIgnoreCase(\"true\")) {\n\t\t\t\t\t\t\t\tdistinctPatientSet.remove(patientGuid);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdistinctPatientSet.add(patientGuid);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcsvParser.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSimpleDateFormat sdfOutput = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\tsb.append(\"Name,OdsCode,CDB,OrgGuid,StartDate,Server,Patients\");\n\n\t\t\tfor (String orgGuid: startDates.keySet()) {\n\t\t\t\tDate startDate = startDates.get(orgGuid);\n\t\t\t\tString server = servers.get(orgGuid);\n\t\t\t\tString name = names.get(orgGuid);\n\t\t\t\tString odsCode = odsCodes.get(orgGuid);\n\t\t\t\tString cdbNumber = cdbNumbers.get(orgGuid);\n\t\t\t\tSet distinctPatientSet = distinctPatients.get(orgGuid);\n\n\t\t\t\tString startDateDesc = null;\n\t\t\t\tif (startDate != null) {\n\t\t\t\t\tstartDateDesc = sdfOutput.format(startDate);\n\t\t\t\t}\n\n\t\t\t\tLong countDistinctPatients = null;\n\t\t\t\tif (distinctPatientSet != null) {\n\t\t\t\t\tcountDistinctPatients = new Long(distinctPatientSet.size());\n\t\t\t\t}\n\n\t\t\t\tsb.append(\"\\n\");\n\t\t\t\tsb.append(\"\\\"\" + name + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + odsCode + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + cdbNumber + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + orgGuid + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(startDateDesc);\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(\"\\\"\" + server + \"\\\"\");\n\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(countDistinctPatients);\n\t\t\t}\n\n\t\t\tLOG.info(sb.toString());\n\n\t\t\tFileUtils.writeStringToFile(new File(outputPath), sb.toString());\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Finding Start Dates in \" + path + \", writing to \" + outputPath);\n\t}\n\n\tprivate static void findEncounterTerms(String path, String outputPath) {\n\t\tLOG.info(\"Finding Encounter Terms from \" + path);\n\n\t\tMap hmResults = new HashMap<>();\n\n\t\t//source term, source term snomed ID, source term snomed term - count\n\n\t\ttry {\n\t\t\tFile root = new File(path);\n\t\t\tFile[] files = root.listFiles();\n\t\t\tfor (File readerRoot: files) { //emis001\n\t\t\t\tLOG.info(\"Finding terms in \" + readerRoot);\n\n\t\t\t\t//first read in all the coding files to build up our map of codes\n\t\t\t\tMap hmCodes = new HashMap<>();\n\n\t\t\t\tfor (File dateFolder: readerRoot.listFiles()) {\n\t\t\t\t\tLOG.info(\"Looking for codes in \" + dateFolder);\n\n\t\t\t\t\tFile f = findFile(dateFolder, \"Coding_ClinicalCode\");\n\t\t\t\t\tif (f == null) {\n\t\t\t\t\t\tLOG.error(\"Failed to find coding file in \" + dateFolder.getAbsolutePath());\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\tString codeId = csvRecord.get(\"CodeId\");\n\t\t\t\t\t\tString term = csvRecord.get(\"Term\");\n\t\t\t\t\t\tString snomed = csvRecord.get(\"SnomedCTConceptId\");\n\n\t\t\t\t\t\thmCodes.put(codeId, snomed + \",\\\"\" + term + \"\\\"\");\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser.close();\n\t\t\t\t}\n\n\t\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\t\t\tDate cutoff = dateFormat.parse(\"2017-01-01\");\n\n\t\t\t\t//now process the consultation files themselves\n\t\t\t\tfor (File dateFolder: readerRoot.listFiles()) {\n\t\t\t\t\tLOG.info(\"Looking for consultations in \" + dateFolder);\n\n\t\t\t\t\tFile f = findFile(dateFolder, \"CareRecord_Consultation\");\n\t\t\t\t\tif (f == null) {\n\t\t\t\t\t\tLOG.error(\"Failed to find consultation file in \" + dateFolder.getAbsolutePath());\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader());\n\t\t\t\t\tIterator csvIterator = csvParser.iterator();\n\n\t\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\t\tString term = csvRecord.get(\"ConsultationSourceTerm\");\n\t\t\t\t\t\tString codeId = csvRecord.get(\"ConsultationSourceCodeId\");\n\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(term)\n\t\t\t\t\t\t\t\t&& Strings.isNullOrEmpty(codeId)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString date = csvRecord.get(\"EffectiveDate\");\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(date)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDate d = dateFormat.parse(date);\n\t\t\t\t\t\tif (d.before(cutoff)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString line = \"\\\"\" + term + \"\\\",\";\n\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(codeId)) {\n\n\t\t\t\t\t\t\tString codeLookup = hmCodes.get(codeId);\n\t\t\t\t\t\t\tif (codeLookup == null) {\n\t\t\t\t\t\t\t\tLOG.error(\"Failed to find lookup for codeID \" + codeId);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tline += codeLookup;\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tline += \",\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tLong count = hmResults.get(line);\n\t\t\t\t\t\tif (count == null) {\n\t\t\t\t\t\t\tcount = new Long(1);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcount = new Long(count.longValue() + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\thmResults.put(line, count);\n\t\t\t\t\t}\n\n\t\t\t\t\tcsvParser.close();\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\t//save results to file\n\t\t\tStringBuilder output = new StringBuilder();\n\t\t\toutput.append(\"\\\"consultation term\\\",\\\"snomed concept ID\\\",\\\"snomed term\\\",\\\"count\\\"\");\n\t\t\toutput.append(\"\\r\\n\");\n\n\t\t\tfor (String line: hmResults.keySet()) {\n\t\t\t\tLong count = hmResults.get(line);\n\t\t\t\tString combined = line + \",\" + count;\n\n\t\t\t\toutput.append(combined);\n\t\t\t\toutput.append(\"\\r\\n\");\n\t\t\t}\n\t\t\tLOG.info(\"FInished\");\n\t\t\tLOG.info(output.toString());\n\n\t\t\tFileUtils.writeStringToFile(new File(outputPath), output.toString());\n\n\t\t\tLOG.info(\"written output to \" + outputPath);\n\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished finding Encounter Terms from \" + path);\n\t}\n\n\tprivate static File findFile(File root, String token) throws Exception {\n\t\tfor (File f: root.listFiles()) {\n\t\t\tString s = f.getName();\n\t\t\tif (s.indexOf(token) > -1) {\n\t\t\t\treturn f;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/*private static void populateProtocolQueue(String serviceIdStr, String startingExchangeId) {\n\t\tLOG.info(\"Starting Populating Protocol Queue for \" + serviceIdStr);\n\n\t\tServiceDalI serviceRepository = DalProvider.factoryServiceDal();\n\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\tif (serviceIdStr.equalsIgnoreCase(\"All\")) {\n\t\t\tserviceIdStr = null;\n\t\t}\n\n\t\ttry {\n\n\t\t\tList services = new ArrayList<>();\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tservices = serviceRepository.getAll();\n\t\t\t} else {\n\t\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tservices.add(service);\n\t\t\t}\n\n\t\t\tfor (Service service: services) {\n\n\t\t\t\tList exchangeIds = auditRepository.getExchangeIdsForService(service.getId());\n\t\t\t\tLOG.info(\"Found \" + exchangeIds.size() + \" exchangeIds for \" + service.getName());\n\n\t\t\t\tif (startingExchangeId != null) {\n\t\t\t\t\tUUID startingExchangeUuid = UUID.fromString(startingExchangeId);\n\t\t\t\t\tif (exchangeIds.contains(startingExchangeUuid)) {\n\t\t\t\t\t\t//if in the list, remove everything up to and including the starting exchange\n\t\t\t\t\t\tint index = exchangeIds.indexOf(startingExchangeUuid);\n\t\t\t\t\t\tLOG.info(\"Found starting exchange \" + startingExchangeId + \" at \" + index + \" so removing up to this point\");\n\t\t\t\t\t\tfor (int i=index; i>=0; i--) {\n\t\t\t\t\t\t\texchangeIds.remove(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstartingExchangeId = null;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if not in the list, skip all these exchanges\n\t\t\t\t\t\tLOG.info(\"List doesn't contain starting exchange \" + startingExchangeId + \" so skipping\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tQueueHelper.postToExchange(exchangeIds, \"edsProtocol\", null, true);\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tLOG.info(\"Finished Populating Protocol Queue for \" + serviceIdStr);\n\t}*/\n\n\t/*private static void findDeletedOrgs() {\n\t\tLOG.info(\"Starting finding deleted orgs\");\n\n\t\tServiceDalI serviceRepository = DalProvider.factoryServiceDal();\n\t\tExchangeDalI auditRepository = DalProvider.factoryExchangeDal();\n\n\t\tList services = new ArrayList<>();\n\t\ttry {\n\t\t\tfor (Service service: serviceRepository.getAll()) {\n\t\t\t\tservices.add(service);\n\t\t\t}\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t\tservices.sort((o1, o2) -> {\n\t\t\tString name1 = o1.getName();\n\t\t\tString name2 = o2.getName();\n\t\t\treturn name1.compareToIgnoreCase(name2);\n\t\t});\n\n\t\tfor (Service service: services) {\n\n\t\t\ttry {\n\t\t\t\tUUID serviceUuid = service.getId();\n\t\t\t\tList exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 1, new Date(0), new Date());\n\n\t\t\t\tLOG.info(\"Service: \" + service.getName() + \" \" + service.getLocalId());\n\n\t\t\t\tif (exchangeByServices.isEmpty()) {\n\t\t\t\t\tLOG.info(\" no exchange found!\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\n\t\t\t\tExchange exchangeByService = exchangeByServices.get(0);\n\t\t\t\tUUID exchangeId = exchangeByService.getId();\n\t\t\t\tExchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\t\tMap headers = exchange.getHeaders();\n\n\t\t\t\tString systemUuidStr = headers.get(HeaderKeys.SenderSystemUuid);\n\t\t\t\tUUID systemUuid = UUID.fromString(systemUuidStr);\n\n\t\t\t\tint batches = countBatches(exchangeId, serviceUuid, systemUuid);\n\t\t\t\tLOG.info(\" Most recent exchange had \" + batches + \" batches\");\n\n\t\t\t\tif (batches > 1 && batches < 2000) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//go back until we find the FIRST exchange where it broke\n\t\t\t\texchangeByServices = auditRepository.getExchangesByService(serviceUuid, 250, new Date(0), new Date());\n\t\t\t\tfor (int i=0; i 2000) {\n\t\t\t\t\t\tLOG.info(\" \" + timestamp + \" had \" + batches);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (batches > 1 && batches < 2000) {\n\t\t\t\t\t\tLOG.info(\" \" + timestamp + \" had \" + batches);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"\", ex);\n\t\t\t}\n\n\t\t}\n\n\t\tLOG.info(\"Finished finding deleted orgs\");\n\t}*/\n\n\tprivate static int countBatches(UUID exchangeId, UUID serviceId, UUID systemId) throws Exception {\n\t\tint batches = 0;\n\t\tExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();\n\t\tList audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId);\n\t\tfor (ExchangeTransformAudit audit: audits) {\n\t\t\tif (audit.getNumberBatchesCreated() != null) {\n\t\t\t\tbatches += audit.getNumberBatchesCreated();\n\t\t\t}\n\t\t}\n\t\treturn batches;\n\t}\n\n\t/*private static void fixExchanges(UUID justThisService) {\n\t\tLOG.info(\"Fixing exchanges\");\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId : exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tboolean changed = false;\n\n\t\t\t\t\tString body = exchange.getBody();\n\n\t\t\t\t\tString[] files = body.split(\"\\n\");\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (int i=0; i exchangeByServiceList = auditRepository.getExchangesByService(serviceId, Integer.MAX_VALUE);\n\n\t\t//go backwards as the most recent is first\n\t\tfor (int i=exchangeByServiceList.size()-1; i>=0; i--) {\n\t\t\tExchangeByService exchangeByService = exchangeByServiceList.get(i);\n\t\t\tUUID exchangeId = exchangeByService.getExchangeId();\n\t\t\tLOG.info(\"Doing exchange \" + exchangeId);\n\n\t\t\tEmisCsvHelper helper = null;\n\n\t\t\ttry {\n\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\t\t\t\tString exchangeBody = exchange.getBody();\n\t\t\t\tString[] files = exchangeBody.split(java.lang.System.lineSeparator());\n\n\t\t\t\tFile orgDirectory = validateAndFindCommonDirectory(sharedStoragePath, files);\n\t\t\t\tMap allParsers = new HashMap<>();\n\t\t\t\tString properVersion = null;\n\n\t\t\t\tString[] versions = new String[]{EmisCsvToFhirTransformer.VERSION_5_0, EmisCsvToFhirTransformer.VERSION_5_1, EmisCsvToFhirTransformer.VERSION_5_3, EmisCsvToFhirTransformer.VERSION_5_4};\n\t\t\t\tfor (String version: versions) {\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\tList parsers = new ArrayList<>();\n\n\t\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(Observation.class, orgDirectory, version, true, parsers);\n\t\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(DrugRecord.class, orgDirectory, version, true, parsers);\n\t\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(IssueRecord.class, orgDirectory, version, true, parsers);\n\n\t\t\t\t\t\tfor (AbstractCsvParser parser: parsers) {\n\t\t\t\t\t\t\tClass cls = parser.getClass();\n\t\t\t\t\t\t\tallParsers.put(cls, parser);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tproperVersion = version;\n\n\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t//ignore\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (allParsers.isEmpty()) {\n\t\t\t\t\tthrow new Exception(\"Failed to open parsers for exchange \" + exchangeId + \" in folder \" + orgDirectory);\n\t\t\t\t}\n\n\t\t\t\tUUID systemId = exchange.getHeaderAsUuid(HeaderKeys.SenderSystemUuid);\n\t\t\t\t//FhirResourceFiler dummyFiler = new FhirResourceFiler(exchangeId, serviceId, systemId, null, null, 10);\n\n\t\t\t\tif (helper == null) {\n\t\t\t\t\thelper = new EmisCsvHelper(findDataSharingAgreementGuid(new ArrayList<>(allParsers.values())));\n\t\t\t\t}\n\n\t\t\t\tObservationPreTransformer.transform(properVersion, allParsers, null, helper);\n\t\t\t\tIssueRecordPreTransformer.transform(properVersion, allParsers, null, helper);\n\t\t\t\tDrugRecordPreTransformer.transform(properVersion, allParsers, null, helper);\n\n\t\t\t\tMap> problemChildren = helper.getProblemChildMap();\n\n\t\t\t\tList exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\n\t\t\t\tfor (Map.Entry> entry : problemChildren.entrySet()) {\n\t\t\t\t\tString patientLocallyUniqueId = entry.getKey().split(\":\")[0];\n\n\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientLocallyUniqueId);\n\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find edsPatientId for local Patient ID \" + patientLocallyUniqueId + \" in exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\t//find the batch ID for our patient\n\t\t\t\t\tUUID batchId = null;\n\t\t\t\t\tfor (ExchangeBatch exchangeBatch: exchangeBatches) {\n\t\t\t\t\t\tif (exchangeBatch.getEdsPatientId() != null\n\t\t\t\t\t\t\t\t&& exchangeBatch.getEdsPatientId().equals(edsPatientId)) {\n\t\t\t\t\t\t\tbatchId = exchangeBatch.getBatchId();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (batchId == null) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find batch ID for eds Patient ID \" + edsPatientId + \" in exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\t//find the EDS ID for our problem\n\t\t\t\t\tUUID edsProblemId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Condition, entry.getKey());\n\t\t\t\t\tif (edsProblemId == null) {\n\t\t\t\t\t\tLOG.warn(\"No edsProblemId found for local ID \" + entry.getKey() + \" - assume bad data referring to non-existing problem?\");\n\t\t\t\t\t\t//throw new Exception(\"Failed to find edsProblemId for local Patient ID \" + problemLocallyUniqueId + \" in exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\t//convert our child IDs to EDS references\n\t\t\t\t\tList references = new ArrayList<>();\n\n\t\t\t\t\tHashSet contentsSet = new HashSet<>();\n\t\t\t\t\tcontentsSet.addAll(entry.getValue());\n\n\t\t\t\t\tfor (String referenceValue : contentsSet) {\n\t\t\t\t\t\tReference reference = ReferenceHelper.createReference(referenceValue);\n\t\t\t\t\t\tReferenceComponents components = ReferenceHelper.getReferenceComponents(reference);\n\t\t\t\t\t\tString locallyUniqueId = components.getId();\n\t\t\t\t\t\tResourceType resourceType = components.getResourceType();\n\t\t\t\t\t\tUUID edsResourceId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId);\n\n\t\t\t\t\t\tReference globallyUniqueReference = ReferenceHelper.createReference(resourceType, edsResourceId.toString());\n\t\t\t\t\t\treferences.add(globallyUniqueReference);\n\t\t\t\t\t}\n\n\t\t\t\t\t//find the resource for the problem itself\n\t\t\t\t\tResourceByExchangeBatch problemResourceByExchangeBatch = null;\n\t\t\t\t\tList resources = resourceRepository.getResourcesForBatch(batchId, ResourceType.Condition.toString());\n\t\t\t\t\tfor (ResourceByExchangeBatch resourceByExchangeBatch: resources) {\n\t\t\t\t\t\tif (resourceByExchangeBatch.getResourceId().equals(edsProblemId)) {\n\t\t\t\t\t\t\tproblemResourceByExchangeBatch = resourceByExchangeBatch;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (problemResourceByExchangeBatch == null) {\n\t\t\t\t\t\tthrow new Exception(\"Problem not found for edsProblemId \" + edsProblemId + \" for exchange \" + exchangeId);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (problemResourceByExchangeBatch.getIsDeleted()) {\n\t\t\t\t\t\tLOG.warn(\"Problem \" + edsProblemId + \" is deleted, so not adding to it for exchange \" + exchangeId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString json = problemResourceByExchangeBatch.getResourceData();\n\t\t\t\t\tCondition fhirProblem = (Condition)PARSER_POOL.parse(json);\n\n\t\t\t\t\t//update the problems\n\t\t\t\t\tif (fhirProblem.hasContained()) {\n\t\t\t\t\t\tif (fhirProblem.getContained().size() > 1) {\n\t\t\t\t\t\t\tthrow new Exception(\"Problem \" + edsProblemId + \" is has \" + fhirProblem.getContained().size() + \" contained resources for exchange \" + exchangeId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfhirProblem.getContained().clear();\n\t\t\t\t\t}\n\n\t\t\t\t\tList_ list = new List_();\n\t\t\t\t\tlist.setId(\"Items\");\n\t\t\t\t\tfhirProblem.getContained().add(list);\n\n\t\t\t\t\tExtension extension = ExtensionConverter.findExtension(fhirProblem, FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE);\n\t\t\t\t\tif (extension == null) {\n\t\t\t\t\t\tReference listReference = ReferenceHelper.createInternalReference(\"Items\");\n\t\t\t\t\t\tfhirProblem.addExtension(ExtensionConverter.createExtension(FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE, listReference));\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (Reference reference : references) {\n\t\t\t\t\t\tlist.addEntry().setItem(reference);\n\t\t\t\t\t}\n\n\t\t\t\t\tString newJson = FhirSerializationHelper.serializeResource(fhirProblem);\n\t\t\t\t\tif (newJson.equals(json)) {\n\t\t\t\t\t\tLOG.warn(\"Skipping edsProblemId \" + edsProblemId + \" as JSON hasn't changed\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tproblemResourceByExchangeBatch.setResourceData(newJson);\n\n\t\t\t\t\tString resourceType = problemResourceByExchangeBatch.getResourceType();\n\t\t\t\t\tUUID versionUuid = problemResourceByExchangeBatch.getVersion();\n\n\t\t\t\t\tResourceHistory problemResourceHistory = resourceRepository.getResourceHistoryByKey(edsProblemId, resourceType, versionUuid);\n\t\t\t\t\tproblemResourceHistory.setResourceData(newJson);\n\t\t\t\t\tproblemResourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(newJson));\n\n\t\t\t\t\tResourceByService problemResourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType, edsProblemId);\n\t\t\t\t\tif (problemResourceByService.getResourceData() == null) {\n\t\t\t\t\t\tproblemResourceByService = null;\n\t\t\t\t\t\tLOG.warn(\"Not updating edsProblemId \" + edsProblemId + \" for exchange \" + exchangeId + \" as it's been subsequently delrted\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tproblemResourceByService.setResourceData(newJson);\n\t\t\t\t\t}\n\n\t\t\t\t\t//save back to THREE tables\n\t\t\t\t\tif (!testMode) {\n\n\t\t\t\t\t\tresourceRepository.save(problemResourceByExchangeBatch);\n\t\t\t\t\t\tresourceRepository.save(problemResourceHistory);\n\t\t\t\t\t\tif (problemResourceByService != null) {\n\t\t\t\t\t\t\tresourceRepository.save(problemResourceByService);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLOG.info(\"Fixed edsProblemId \" + edsProblemId + \" for exchange Id \" + exchangeId);\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLOG.info(\"Would change edsProblemId \" + edsProblemId + \" to new JSON\");\n\t\t\t\t\t\tLOG.info(newJson);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed on exchange \" + exchangeId, ex);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished fixing problems for service \" + serviceId);\n\t}\n\n\tprivate static String findDataSharingAgreementGuid(List parsers) throws Exception {\n\n\t\t//we need a file name to work out the data sharing agreement ID, so just the first file we can find\n\t\tFile f = parsers\n\t\t\t\t.iterator()\n\t\t\t\t.next()\n\t\t\t\t.getFile();\n\n\t\tString name = Files.getNameWithoutExtension(f.getName());\n\t\tString[] toks = name.split(\"_\");\n\t\tif (toks.length != 5) {\n\t\t\tthrow new TransformException(\"Failed to extract data sharing agreement GUID from filename \" + f.getName());\n\t\t}\n\t\treturn toks[4];\n\t}\n\n\n\n\tprivate static void closeParsers(Collection parsers) {\n\t\tfor (AbstractCsvParser parser : parsers) {\n\t\t\ttry {\n\t\t\t\tparser.close();\n\t\t\t} catch (IOException ex) {\n\t\t\t\t//don't worry if this fails, as we're done anyway\n\t\t\t}\n\t\t}\n\t}\n\n\n\tprivate static File validateAndFindCommonDirectory(String sharedStoragePath, String[] files) throws Exception {\n\t\tString organisationDir = null;\n\n\t\tfor (String file: files) {\n\t\t\tFile f = new File(sharedStoragePath, file);\n\t\t\tif (!f.exists()) {\n\t\t\t\tLOG.error(\"Failed to find file {} in shared storage {}\", file, sharedStoragePath);\n\t\t\t\tthrow new FileNotFoundException(\"\" + f + \" doesn't exist\");\n\t\t\t}\n\t\t\t//LOG.info(\"Successfully found file {} in shared storage {}\", file, sharedStoragePath);\n\n\t\t\ttry {\n\t\t\t\tFile orgDir = f.getParentFile();\n\n\t\t\t\tif (organisationDir == null) {\n\t\t\t\t\torganisationDir = orgDir.getAbsolutePath();\n\t\t\t\t} else {\n\t\t\t\t\tif (!organisationDir.equalsIgnoreCase(orgDir.getAbsolutePath())) {\n\t\t\t\t\t\tthrow new Exception();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tthrow new FileNotFoundException(\"\" + f + \" isn't in the expected directory structure within \" + organisationDir);\n\t\t\t}\n\n\t\t}\n\t\treturn new File(organisationDir);\n\t}*/\n\n\t/*private static void testLogging() {\n\n\t\twhile (true) {\n\t\t\tSystem.out.println(\"Checking logging at \" + System.currentTimeMillis());\n\t\t\ttry {\n\t\t\t\tThread.sleep(4000);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t\tLOG.trace(\"trace logging\");\n\t\t\tLOG.debug(\"debug logging\");\n\t\t\tLOG.info(\"info logging\");\n\t\t\tLOG.warn(\"warn logging\");\n\t\t\tLOG.error(\"error logging\");\n\t\t}\n\n\t}\n*/\n\t/*private static void fixExchangeProtocols() {\n\t\tLOG.info(\"Fixing exchange protocols\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT exchange_id FROM audit.Exchange LIMIT 1000;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\n\t\t\tLOG.info(\"Processing exchange \" + exchangeId);\n\t\t\tExchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed to parse headers for exchange \" + exchange.getExchangeId(), ex);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tLOG.error(\"Failed to find service ID for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\tList newIds = new ArrayList<>();\n\t\t\tString protocolJson = headers.get(HeaderKeys.Protocols);\n\n\t\t\tif (!headers.containsKey(HeaderKeys.Protocols)) {\n\n\t\t\t\ttry {\n\t\t\t\t\tList libraryItemList = LibraryRepositoryHelper.getProtocolsByServiceId(serviceIdStr);\n\n\t\t\t\t\t// Get protocols where service is publisher\n\t\t\t\t\tnewIds = libraryItemList.stream()\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\tlibraryItem -> libraryItem.getProtocol().getServiceContract().stream()\n\t\t\t\t\t\t\t\t\t\t\t.anyMatch(sc ->\n\t\t\t\t\t\t\t\t\t\t\t\t\tsc.getType().equals(ServiceContractType.PUBLISHER)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&& sc.getService().getUuid().equals(serviceIdStr)))\n\t\t\t\t\t\t\t.map(t -> t.getUuid().toString())\n\t\t\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.error(\"Failed to find protocols for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\ttry {\n\t\t\t\t\tJsonNode node = ObjectMapperPool.getInstance().readTree(protocolJson);\n\n\t\t\t\t\tfor (int i = 0; i < node.size(); i++) {\n\t\t\t\t\t\tJsonNode libraryItemNode = node.get(i);\n\t\t\t\t\t\tJsonNode idNode = libraryItemNode.get(\"uuid\");\n\t\t\t\t\t\tString id = idNode.asText();\n\t\t\t\t\t\tnewIds.add(id);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.error(\"Failed to read Json from \" + protocolJson + \" for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (newIds.isEmpty()) {\n\t\t\t\t\theaders.remove(HeaderKeys.Protocols);\n\n\t\t\t\t} else {\n\t\t\t\t\tString protocolsJson = ObjectMapperPool.getInstance().writeValueAsString(newIds.toArray());\n\t\t\t\t\theaders.put(HeaderKeys.Protocols, protocolsJson);\n\t\t\t\t}\n\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tLOG.error(\"Unable to serialize protocols to JSON for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\texchange.setHeaders(headerJson);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tLOG.error(\"Failed to write exchange headers to Json for exchange \" + exchange.getExchangeId(), e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tauditRepository.save(exchange);\n\t\t}\n\n\t\tLOG.info(\"Finished fixing exchange protocols\");\n\t}*/\n\n\t/*private static void fixExchangeHeaders() {\n\t\tLOG.info(\"Fixing exchange headers\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\t\tOrganisationRepository organisationRepository = new OrganisationRepository();\n\n\t\tList exchanges = new AuditRepository().getAllExchanges();\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed to parse headers for exchange \" + exchange.getExchangeId(), ex);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (headers.containsKey(HeaderKeys.SenderLocalIdentifier)\n\t\t\t\t\t&& headers.containsKey(HeaderKeys.SenderOrganisationUuid)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tLOG.error(\"Failed to find service ID for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\tMap orgMap = service.getOrganisations();\n\t\t\tif (orgMap.size() != 1) {\n\t\t\t\tLOG.error(\"Wrong number of orgs in service \" + serviceId + \" for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID orgId = orgMap\n\t\t\t\t\t.keySet()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.collect(StreamExtension.firstOrNullCollector());\n\t\t\tOrganisation organisation = organisationRepository.getById(orgId);\n\t\t\tString odsCode = organisation.getNationalId();\n\n\t\t\theaders.put(HeaderKeys.SenderLocalIdentifier, odsCode);\n\t\t\theaders.put(HeaderKeys.SenderOrganisationUuid, orgId.toString());\n\n\t\t\ttry {\n\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t//not throwing this exception further up, since it should never happen\n\t\t\t\t//and means we don't need to litter try/catches everywhere this is called from\n\t\t\t\tLOG.error(\"Failed to write exchange headers to Json\", e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\texchange.setHeaders(headerJson);\n\n\t\t\tauditRepository.save(exchange);\n\n\t\t\tLOG.info(\"Creating exchange \" + exchange.getExchangeId());\n\t\t}\n\n\t\tLOG.info(\"Finished fixing exchange headers\");\n\t}*/\n\n\t/*private static void fixExchangeHeaders() {\n\t\tLOG.info(\"Fixing exchange headers\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\t\tOrganisationRepository organisationRepository = new OrganisationRepository();\n\t\tLibraryRepository libraryRepository = new LibraryRepository();\n\n\t\tList exchanges = new AuditRepository().getAllExchanges();\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Failed to parse headers for exchange \" + exchange.getExchangeId(), ex);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (Strings.isNullOrEmpty(serviceIdStr)) {\n\t\t\t\tLOG.error(\"Failed to find service ID for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tboolean changed = false;\n\n\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\ttry {\n\t\t\t\tList endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\n\t\t\t\tfor (JsonServiceInterfaceEndpoint endpoint : endpoints) {\n\n\t\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\t\tString endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString();\n\n\t\t\t\t\tActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId);\n\t\t\t\t\tItem item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId());\n\t\t\t\t\tLibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent());\n\t\t\t\t\tSystem system = libraryItem.getSystem();\n\t\t\t\t\tfor (TechnicalInterface technicalInterface : system.getTechnicalInterface()) {\n\n\t\t\t\t\t\tif (endpointInterfaceId.equals(technicalInterface.getUuid())) {\n\n\t\t\t\t\t\t\tif (!headers.containsKey(HeaderKeys.SourceSystem)) {\n\t\t\t\t\t\t\t\theaders.put(HeaderKeys.SourceSystem, technicalInterface.getMessageFormat());\n\t\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!headers.containsKey(HeaderKeys.SystemVersion)) {\n\t\t\t\t\t\t\t\theaders.put(HeaderKeys.SystemVersion, technicalInterface.getMessageFormatVersion());\n\t\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!headers.containsKey(HeaderKeys.SenderSystemUuid)) {\n\t\t\t\t\t\t\t\theaders.put(HeaderKeys.SenderSystemUuid, endpointSystemId.toString());\n\t\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to find endpoint details for \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (changed) {\n\t\t\t\ttry {\n\t\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t\t//not throwing this exception further up, since it should never happen\n\t\t\t\t\t//and means we don't need to litter try/catches everywhere this is called from\n\t\t\t\t\tLOG.error(\"Failed to write exchange headers to Json\", e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\texchange.setHeaders(headerJson);\n\t\t\t\tauditRepository.save(exchange);\n\n\t\t\t\tLOG.info(\"Fixed exchange \" + exchange.getExchangeId());\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished fixing exchange headers\");\n\t}*/\n\n\t/*private static void testConnection(String configName) {\n\t\ttry {\n\n\t\t\tJsonNode config = ConfigManager.getConfigurationAsJson(configName, \"enterprise\");\n\t\t\tString driverClass = config.get(\"driverClass\").asText();\n\t\t\tString url = config.get(\"url\").asText();\n\t\t\tString username = config.get(\"username\").asText();\n\t\t\tString password = config.get(\"password\").asText();\n\n\t\t\t//force the driver to be loaded\n\t\t\tClass.forName(driverClass);\n\n\t\t\tConnection conn = DriverManager.getConnection(url, username, password);\n\t\t\tconn.setAutoCommit(false);\n\t\t\tLOG.info(\"Connection ok\");\n\n\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"\", e);\n\t\t}\n\t}*/\n\t/*private static void testConnection() {\n\t\ttry {\n\n\t\t\tJsonNode config = ConfigManager.getConfigurationAsJson(\"postgres\", \"enterprise\");\n\t\t\tString url = config.get(\"url\").asText();\n\t\t\tString username = config.get(\"username\").asText();\n\t\t\tString password = config.get(\"password\").asText();\n\n\t\t\t//force the driver to be loaded\n\t\t\tClass.forName(\"org.postgresql.Driver\");\n\n\t\t\tConnection conn = DriverManager.getConnection(url, username, password);\n\t\t\tconn.setAutoCommit(false);\n\t\t\tLOG.info(\"Connection ok\");\n\n\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"\", e);\n\t\t}\n\t}*/\n\n\n\t/*private static void startEnterpriseStream(UUID serviceId, String configName, UUID exchangeIdStartFrom, UUID batchIdStartFrom) throws Exception {\n\n\t\tLOG.info(\"Starting Enterprise Streaming for \" + serviceId + \" using \" + configName + \" starting from exchange \" + exchangeIdStartFrom + \" and batch \" + batchIdStartFrom);\n\n\t\tLOG.info(\"Testing database connection\");\n\t\ttestConnection(configName);\n\n\t\tService service = new ServiceRepository().getById(serviceId);\n\t\tList orgIds = new ArrayList<>(service.getOrganisations().keySet());\n\t\tUUID orgId = orgIds.get(0);\n\n\t\tList exchangeByServiceList = new AuditRepository().getExchangesByService(serviceId, Integer.MAX_VALUE);\n\n\t\tfor (int i=exchangeByServiceList.size()-1; i>=0; i--) {\n\t\t\tExchangeByService exchangeByService = exchangeByServiceList.get(i);\n\t\t//for (ExchangeByService exchangeByService: exchangeByServiceList) {\n\t\t\tUUID exchangeId = exchangeByService.getExchangeId();\n\n\t\t\tif (exchangeIdStartFrom != null) {\n\t\t\t\tif (!exchangeIdStartFrom.equals(exchangeId)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\t//once we have a match, set to null so we don't skip any subsequent ones\n\t\t\t\t\texchangeIdStartFrom = null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\t\t\tString senderOrgUuidStr = exchange.getHeader(HeaderKeys.SenderOrganisationUuid);\n\t\t\tUUID senderOrgUuid = UUID.fromString(senderOrgUuidStr);\n\n\t\t\t//this one had 90,000 batches and doesn't need doing again\n\t\t\t*//*if (exchangeId.equals(UUID.fromString(\"b9b93be0-afd8-11e6-8c16-c1d5a00342f3\"))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId);\n\t\t\t\tcontinue;\n\t\t\t}*//*\n\n\t\t\tList exchangeBatches = new ExchangeBatchRepository().retrieveForExchangeId(exchangeId);\n\t\t\tLOG.info(\"Processing exchange \" + exchangeId + \" with \" + exchangeBatches.size() + \" batches\");\n\n\t\t\tfor (int j=0; j exchangeIdsDone = new HashSet<>();\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\t\t\tUUID batchId = row.get(1, UUID.class);\n\t\t\tDate date = row.getTimestamp(2);\n\t\t\t//LOG.info(\"Exchange \" + exchangeId + \" batch \" + batchId + \" date \" + date);\n\n\t\t\tif (exchangeIdsDone.contains(exchangeId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (auditRepository.getExchange(exchangeId) != null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tUUID serviceId = findServiceId(batchId, session);\n\t\t\tif (serviceId == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tExchange exchange = new Exchange();\n\t\t\tExchangeByService exchangeByService = new ExchangeByService();\n\t\t\tExchangeEvent exchangeEvent = new ExchangeEvent();\n\n\t\t\tMap headers = new HashMap<>();\n\t\t\theaders.put(HeaderKeys.SenderServiceUuid, serviceId.toString());\n\n\t\t\tString headersJson = null;\n\t\t\ttry {\n\t\t\t\theadersJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t//not throwing this exception further up, since it should never happen\n\t\t\t\t//and means we don't need to litter try/catches everywhere this is called from\n\t\t\t\tLOG.error(\"Failed to write exchange headers to Json\", e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\texchange.setBody(\"Body not available, as exchange re-created\");\n\t\t\texchange.setExchangeId(exchangeId);\n\t\t\texchange.setHeaders(headersJson);\n\t\t\texchange.setTimestamp(date);\n\n\t\t\texchangeByService.setExchangeId(exchangeId);\n\t\t\texchangeByService.setServiceId(serviceId);\n\t\t\texchangeByService.setTimestamp(date);\n\n\t\t\texchangeEvent.setEventDesc(\"Created_By_Conversion\");\n\t\t\texchangeEvent.setExchangeId(exchangeId);\n\t\t\texchangeEvent.setTimestamp(new Date());\n\n\t\t\tauditRepository.save(exchange);\n\t\t\tauditRepository.save(exchangeEvent);\n\t\t\tauditRepository.save(exchangeByService);\n\n\t\t\texchangeIdsDone.add(exchangeId);\n\n\t\t\tLOG.info(\"Creating exchange \" + exchangeId);\n\t\t}\n\n\t\tLOG.info(\"Finished exchange fix\");\n\t}\n\n\tprivate static UUID findServiceId(UUID batchId, Session session) {\n\n\t\tStatement stmt = new SimpleStatement(\"select resource_type, resource_id from ehr.resource_by_exchange_batch where batch_id = \" + batchId + \" LIMIT 1;\");\n\t\tResultSet rs = session.execute(stmt);\n\t\tif (rs.isExhausted()) {\n\t\t\tLOG.error(\"Failed to find resource_by_exchange_batch for batch_id \" + batchId);\n\t\t\treturn null;\n\t\t}\n\n\t\tRow row = rs.one();\n\t\tString resourceType = row.getString(0);\n\t\tUUID resourceId = row.get(1, UUID.class);\n\n\t\tstmt = new SimpleStatement(\"select service_id from ehr.resource_history where resource_type = '\" + resourceType + \"' and resource_id = \" + resourceId + \" LIMIT 1;\");\n\t\trs = session.execute(stmt);\n\t\tif (rs.isExhausted()) {\n\t\t\tLOG.error(\"Failed to find resource_history for resource_type \" + resourceType + \" and resource_id \" + resourceId);\n\t\t\treturn null;\n\t\t}\n\n\t\trow = rs.one();\n\t\tUUID serviceId = row.get(0, UUID.class);\n\t\treturn serviceId;\n\t}*/\n\n\t/*private static void fixExchangeEvents() {\n\n\t\tList events = new AuditRepository().getAllExchangeEvents();\n\t\tfor (ExchangeEvent event: events) {\n\t\t\tif (event.getEventDesc() != null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString eventDesc = \"\";\n\t\t\tint eventType = event.getEvent().intValue();\n\t\t\tswitch (eventType) {\n\t\t\t\tcase 1:\n\t\t\t\t\teventDesc = \"Receive\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\teventDesc = \"Validate\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\teventDesc = \"Transform_Start\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\teventDesc = \"Transform_End\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\teventDesc = \"Send\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\teventDesc = \"??? \" + eventType;\n\t\t\t}\n\n\t\t\tevent.setEventDesc(eventDesc);\n\t\t\tnew AuditRepository().save(null, event);\n\t\t}\n\n\t}*/\n\n\t/*private static void fixExchanges() {\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\n\t\tMap> existingOnes = new HashMap();\n\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\n\t\tList exchanges = auditRepository.getAllExchanges();\n\t\tfor (Exchange exchange: exchanges) {\n\n\t\t\tUUID exchangeUuid = exchange.getExchangeId();\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to read headers for exchange \" + exchangeUuid + \" and Json \" + headerJson);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t*//*String serviceId = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\tif (serviceId == null) {\n\t\t\t\tLOG.warn(\"No service ID found for exchange \" + exchange.getExchangeId());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tUUID serviceUuid = UUID.fromString(serviceId);\n\n\t\t\tSet exchangeIdsDone = existingOnes.get(serviceUuid);\n\t\t\tif (exchangeIdsDone == null) {\n\t\t\t\texchangeIdsDone = new HashSet<>();\n\n\t\t\t\tList exchangeByServices = auditRepository.getExchangesByService(serviceUuid, Integer.MAX_VALUE);\n\t\t\t\tfor (ExchangeByService exchangeByService: exchangeByServices) {\n\t\t\t\t\texchangeIdsDone.add(exchangeByService.getExchangeId());\n\t\t\t\t}\n\n\t\t\t\texistingOnes.put(serviceUuid, exchangeIdsDone);\n\t\t\t}\n\n\t\t\t//create the exchange by service entity\n\t\t\tif (!exchangeIdsDone.contains(exchangeUuid)) {\n\n\t\t\t\tDate timestamp = exchange.getTimestamp();\n\n\t\t\t\tExchangeByService newOne = new ExchangeByService();\n\t\t\t\tnewOne.setExchangeId(exchangeUuid);\n\t\t\t\tnewOne.setServiceId(serviceUuid);\n\t\t\t\tnewOne.setTimestamp(timestamp);\n\n\t\t\t\tauditRepository.save(newOne);\n\t\t\t}*//*\n\n\t\t\ttry {\n\t\t\t\theaders.remove(HeaderKeys.BatchIdsJson);\n\t\t\t\tString newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\texchange.setHeaders(newHeaderJson);\n\n\t\t\t\tauditRepository.save(exchange);\n\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tLOG.error(\"Failed to populate batch IDs for exchange \" + exchangeUuid, e);\n\t\t\t}\n\n\t\t\tif (!headers.containsKey(HeaderKeys.BatchIdsJson)) {\n\n\t\t\t\t//fix the batch IDs not being in the exchange\n\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeUuid);\n\t\t\t\tif (!batches.isEmpty()) {\n\n\t\t\t\t\tList batchUuids = batches\n\t\t\t\t\t\t\t.stream()\n\t\t\t\t\t\t\t.map(t -> t.getBatchId())\n\t\t\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t\t\ttry {\n\t\t\t\t\t\tString batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchUuids.toArray());\n\t\t\t\t\t\theaders.put(HeaderKeys.BatchIdsJson, batchUuidsStr);\n\t\t\t\t\t\tString newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\t\t\texchange.setHeaders(newHeaderJson);\n\n\t\t\t\t\t\tauditRepository.save(exchange, null);\n\n\t\t\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t\t\tLOG.error(\"Failed to populate batch IDs for exchange \" + exchangeUuid, e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t//}\n\t\t}\n\t}*/\n\n\t/*private static UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException {\n\n\t\tList endpoints = null;\n\t\ttry {\n\t\t\tendpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\n\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\n\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\tString endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString();\n\n\t\t\t\tLibraryRepository libraryRepository = new LibraryRepository();\n\t\t\t\tActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId);\n\t\t\t\tItem item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId());\n\t\t\t\tLibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent());\n\t\t\t\tSystem system = libraryItem.getSystem();\n\t\t\t\tfor (TechnicalInterface technicalInterface: system.getTechnicalInterface()) {\n\n\t\t\t\t\tif (endpointInterfaceId.equals(technicalInterface.getUuid())\n\t\t\t\t\t\t\t&& technicalInterface.getMessageFormat().equalsIgnoreCase(software)\n\t\t\t\t\t\t\t&& technicalInterface.getMessageFormatVersion().equalsIgnoreCase(messageVersion)) {\n\n\t\t\t\t\t\treturn endpointSystemId;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new PipelineException(\"Failed to process endpoints from service \" + service.getId());\n\t\t}\n\n\t\treturn null;\n\t}\n*/\n\t/*private static void addSystemIdToExchangeHeaders() throws Exception {\n\t\tLOG.info(\"populateExchangeBatchPatients\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\t\t//OrganisationRepository organisationRepository = new OrganisationRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT exchange_id FROM audit.exchange LIMIT 500;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\n\t\t\torg.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to read headers for exchange \" + exchangeId + \" and Json \" + headerJson);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" as no service UUID\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" as already got system UUID\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\n\t\t\t\t//work out service ID\n\t\t\t\tString serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid);\n\t\t\t\tUUID serviceId = UUID.fromString(serviceIdStr);\n\n\t\t\t\tString software = headers.get(HeaderKeys.SourceSystem);\n\t\t\t\tString version = headers.get(HeaderKeys.SystemVersion);\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tUUID systemUuid = findSystemId(service, software, version);\n\n\t\t\t\theaders.put(HeaderKeys.SenderSystemUuid, systemUuid.toString());\n\n\t\t\t\t//work out protocol IDs\n\t\t\t\ttry {\n\t\t\t\t\tString newProtocolIdsJson = DetermineRelevantProtocolIds.getProtocolIdsForPublisherService(serviceIdStr);\n\t\t\t\t\theaders.put(HeaderKeys.ProtocolIds, newProtocolIdsJson);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tLOG.error(\"Failed to recalculate protocols for \" + exchangeId + \": \" + ex.getMessage());\n\t\t\t\t}\n\n\t\t\t\t//save to DB\n\t\t\t\theaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers);\n\t\t\t\texchange.setHeaders(headerJson);\n\t\t\t\tauditRepository.save(exchange);\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Error with exchange \" + exchangeId, ex);\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished populateExchangeBatchPatients\");\n\t}*/\n\n\n\t/*private static void populateExchangeBatchPatients() throws Exception {\n\t\tLOG.info(\"populateExchangeBatchPatients\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\t//ServiceRepository serviceRepository = new ServiceRepository();\n\t\t//OrganisationRepository organisationRepository = new OrganisationRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT exchange_id FROM audit.exchange LIMIT 500;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID exchangeId = row.get(0, UUID.class);\n\n\t\t\torg.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId);\n\n\t\t\tString headerJson = exchange.getHeaders();\n\t\t\tHashMap headers = null;\n\t\t\ttry {\n\t\t\t\theaders = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.error(\"Failed to read headers for exchange \" + exchangeId + \" and Json \" + headerJson);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))\n\t\t\t\t\t|| Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) {\n\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" because no service or system in header\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tUUID serviceId = UUID.fromString(headers.get(HeaderKeys.SenderServiceUuid));\n\t\t\t\tUUID systemId = UUID.fromString(headers.get(HeaderKeys.SenderSystemUuid));\n\n\t\t\t\tList exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\tfor (ExchangeBatch exchangeBatch : exchangeBatches) {\n\n\t\t\t\t\tif (exchangeBatch.getEdsPatientId() != null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tUUID batchId = exchangeBatch.getBatchId();\n\t\t\t\t\tList resourceWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Patient.toString());\n\t\t\t\t\tif (resourceWrappers.isEmpty()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tList patientIds = new ArrayList<>();\n\t\t\t\t\tfor (ResourceByExchangeBatch resourceWrapper : resourceWrappers) {\n\t\t\t\t\t\tUUID patientId = resourceWrapper.getResourceId();\n\n\t\t\t\t\t\tif (resourceWrapper.getIsDeleted()) {\n\t\t\t\t\t\t\tdeleteEntirePatientRecord(patientId, serviceId, systemId, exchangeId, batchId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!patientIds.contains(patientId)) {\n\t\t\t\t\t\t\tpatientIds.add(patientId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (patientIds.size() != 1) {\n\t\t\t\t\t\tLOG.info(\"Skipping exchange \" + exchangeId + \" and batch \" + batchId + \" because found \" + patientIds.size() + \" patient IDs\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tUUID patientId = patientIds.get(0);\n\t\t\t\t\texchangeBatch.setEdsPatientId(patientId);\n\n\t\t\t\t\texchangeBatchRepository.save(exchangeBatch);\n\t\t\t\t}\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Error with exchange \" + exchangeId, ex);\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished populateExchangeBatchPatients\");\n\t}\n\n\tprivate static void deleteEntirePatientRecord(UUID patientId, UUID serviceId, UUID systemId, UUID exchangeId, UUID batchId) throws Exception {\n\n\t\tFhirStorageService storageService = new FhirStorageService(serviceId, systemId);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tList resourceWrappers = resourceRepository.getResourcesByPatient(serviceId, systemId, patientId);\n\t\tfor (ResourceByPatient resourceWrapper: resourceWrappers) {\n\t\t\tString json = resourceWrapper.getResourceData();\n\t\t\tResource resource = new JsonParser().parse(json);\n\n\t\t\tstorageService.exchangeBatchDelete(exchangeId, batchId, resource);\n\t\t}\n\n\n\t}*/\n\n\t/*private static void convertPatientSearch() {\n\t\tLOG.info(\"Converting Patient Search\");\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tfor (UUID systemId : findSystemIds(service)) {\n\n\t\t\t\t\tList resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.EpisodeOfCare.toString());\n\t\t\t\t\tfor (ResourceByService resourceWrapper: resourceWrappers) {\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tEpisodeOfCare episodeOfCare = (EpisodeOfCare) new JsonParser().parse(resourceWrapper.getResourceData());\n\t\t\t\t\t\t\tString patientId = ReferenceHelper.getReferenceId(episodeOfCare.getPatient());\n\n\t\t\t\t\t\t\tResourceHistory patientWrapper = resourceRepository.getCurrentVersion(ResourceType.Patient.toString(), UUID.fromString(patientId));\n\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(patientWrapper.getResourceData())) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tPatient patient = (Patient) new JsonParser().parse(patientWrapper.getResourceData());\n\n\t\t\t\t\t\t\tPatientSearchHelper.update(serviceId, systemId, patient);\n\t\t\t\t\t\t\tPatientSearchHelper.update(serviceId, systemId, episodeOfCare);\n\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tLOG.error(\"Failed on \" + resourceWrapper.getResourceType() + \" \" + resourceWrapper.getResourceId(), ex);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Converted Patient Search\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\n\t}*/\n\n\tprivate static List findSystemIds(Service service) throws Exception {\n\n\t\tList ret = new ArrayList<>();\n\n\t\tList endpoints = null;\n\t\ttry {\n\t\t\tendpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference>() {});\n\t\t\tfor (JsonServiceInterfaceEndpoint endpoint: endpoints) {\n\t\t\t\tUUID endpointSystemId = endpoint.getSystemUuid();\n\t\t\t\tret.add(endpointSystemId);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new Exception(\"Failed to process endpoints from service \" + service.getId());\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/*private static void convertPatientLink() {\n\t\tLOG.info(\"Converting Patient Link\");\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tfor (UUID systemId : findSystemIds(service)) {\n\n\t\t\t\t\tList resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.Patient.toString());\n\t\t\t\t\tfor (ResourceByService resourceWrapper: resourceWrappers) {\n\t\t\t\t\t\tif (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tPatient patient = (Patient)new JsonParser().parse(resourceWrapper.getResourceData());\n\t\t\t\t\t\t\tPatientLinkHelper.updatePersonId(patient);\n\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tLOG.error(\"Failed on \" + resourceWrapper.getResourceType() + \" \" + resourceWrapper.getResourceId(), ex);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Converted Patient Link\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixConfidentialPatients(String sharedStoragePath, UUID justThisService) {\n\t\tLOG.info(\"Fixing Confidential Patients using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tParserPool parserPool = new ParserPool();\n\t\tMappingManager mappingManager = CassandraConnector.getInstance().getMappingManager();\n\t\tMapper mapperResourceHistory = mappingManager.mapper(ResourceHistory.class);\n\t\tMapper mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class);\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\t\t\t\tMap resourcesFixed = new HashMap<>();\n\t\t\t\tMap> exchangeBatchesToPutInProtocolQueue = new HashMap<>();\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (systemIds.size() > 1) {\n\t\t\t\t\t\tthrow new Exception(\"Multiple system IDs for service \" + serviceId);\n\t\t\t\t\t}\n\t\t\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId);\n\n\t\t\t\t\tSet batchIdsToPutInProtocolQueue = new HashSet<>();\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tString dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f);\n\n\t\t\t\t\tEmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId);\n\t\t\t\t\tResourceFiler filer = new ResourceFiler(exchangeId, serviceId, systemId, null, null, 1);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers);\n\n\t\t\t\t\tProblemPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tObservationPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tDrugRecordPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tIssueRecordPreTransformer.transform(version, parsers, filer, helper);\n\t\t\t\t\tDiaryPreTransformer.transform(version, parsers, filer, helper);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient)parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class);\n\t\t\t\t\twhile (patientParser.nextRecord()) {\n\t\t\t\t\t\tif (patientParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !patientParser.getDeleted()) {\n\t\t\t\t\t\t\tPatientTransformer.createResource(patientParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpatientParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class);\n\t\t\t\t\twhile (consultationParser.nextRecord()) {\n\t\t\t\t\t\tif (consultationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !consultationParser.getDeleted()) {\n\t\t\t\t\t\t\tConsultationTransformer.createResource(consultationParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsultationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tif (observationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !observationParser.getDeleted()) {\n\t\t\t\t\t\t\tObservationTransformer.createResource(observationParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class);\n\t\t\t\t\twhile (diaryParser.nextRecord()) {\n\t\t\t\t\t\tif (diaryParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !diaryParser.getDeleted()) {\n\t\t\t\t\t\t\tDiaryTransformer.createResource(diaryParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdiaryParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class);\n\t\t\t\t\twhile (drugRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (drugRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !drugRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tDrugRecordTransformer.createResource(drugRecordParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdrugRecordParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class);\n\t\t\t\t\twhile (issueRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (issueRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !issueRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tIssueRecordTransformer.createResource(issueRecordParser, filer, helper, version);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tissueRecordParser.close();\n\n\t\t\t\t\tfiler.waitToFinish(); //just to close the thread pool, even though it's not been used\n\t\t\t\t\tList resources = filer.getNewResources();\n\t\t\t\t\tfor (Resource resource: resources) {\n\n\t\t\t\t\t\tString patientId = IdHelper.getPatientId(resource);\n\t\t\t\t\t\tUUID edsPatientId = UUID.fromString(patientId);\n\n\t\t\t\t\t\tResourceType resourceType = resource.getResourceType();\n\t\t\t\t\t\tUUID resourceId = UUID.fromString(resource.getId());\n\n\t\t\t\t\t\tboolean foundResourceInDbBatch = false;\n\n\t\t\t\t\t\tList batchIds = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\tif (batchIds != null) {\n\t\t\t\t\t\t\tfor (UUID batchId : batchIds) {\n\n\t\t\t\t\t\t\t\tList resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), resourceId);\n\t\t\t\t\t\t\t\tif (resourceByExchangeBatches.isEmpty()) {\n\t\t\t\t\t\t\t\t\t//if we've deleted data, this will be null\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfoundResourceInDbBatch = true;\n\n\t\t\t\t\t\t\t\tfor (ResourceByExchangeBatch resourceByExchangeBatch : resourceByExchangeBatches) {\n\n\t\t\t\t\t\t\t\t\tString json = resourceByExchangeBatch.getResourceData();\n\t\t\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(json)) {\n\t\t\t\t\t\t\t\t\t\tLOG.warn(\"JSON already in resource \" + resourceType + \" \" + resourceId);\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\tjson = parserPool.composeString(resource);\n\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setIsDeleted(false);\n\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setSchemaVersion(\"0.1\");\n\n\t\t\t\t\t\t\t\t\t\tLOG.info(\"Saved resource by batch \" + resourceType + \" \" + resourceId + \" in batch \" + batchId);\n\n\t\t\t\t\t\t\t\t\t\tUUID versionUuid = resourceByExchangeBatch.getVersion();\n\t\t\t\t\t\t\t\t\t\tResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(resourceId, resourceType.toString(), versionUuid);\n\t\t\t\t\t\t\t\t\t\tif (resourceHistory == null) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find resource history for \" + resourceType + \" \" + resourceId + \" and version \" + versionUuid);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setIsDeleted(false);\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json));\n\t\t\t\t\t\t\t\t\t\tresourceHistory.setSchemaVersion(\"0.1\");\n\n\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByExchangeBatch);\n\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceHistory);\n\t\t\t\t\t\t\t\t\t\tbatchIdsToPutInProtocolQueue.add(batchId);\n\n\t\t\t\t\t\t\t\t\t\tString key = resourceType.toString() + \":\" + resourceId;\n\t\t\t\t\t\t\t\t\t\tresourcesFixed.put(key, resourceHistory);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t//if a patient became confidential, we will have deleted all resources for that\n\t\t\t\t\t\t\t\t\t//patient, so we need to undo that too\n\t\t\t\t\t\t\t\t\t//to undelete WHOLE patient record\n\t\t\t\t\t\t\t\t\t//1. if THIS resource is a patient\n\t\t\t\t\t\t\t\t\t//2. get all other deletes from the same exchange batch\n\t\t\t\t\t\t\t\t\t//3. delete those from resource_by_exchange_batch (the deleted ones only)\n\t\t\t\t\t\t\t\t\t//4. delete same ones from resource_history\n\t\t\t\t\t\t\t\t\t//5. retrieve most recent resource_history\n\t\t\t\t\t\t\t\t\t//6. if not deleted, add to resources fixed\n\t\t\t\t\t\t\t\t\tif (resourceType == ResourceType.Patient) {\n\n\t\t\t\t\t\t\t\t\t\tList resourcesInSameBatch = resourceRepository.getResourcesForBatch(batchId);\n\t\t\t\t\t\t\t\t\t\tLOG.info(\"Undeleting \" + resourcesInSameBatch.size() + \" resources for batch \" + batchId);\n\t\t\t\t\t\t\t\t\t\tfor (ResourceByExchangeBatch resourceInSameBatch: resourcesInSameBatch) {\n\t\t\t\t\t\t\t\t\t\t\tif (!resourceInSameBatch.getIsDeleted()) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t//patient and episode resources will be restored by the above stuff, so don't try\n\t\t\t\t\t\t\t\t\t\t\t//to do it again\n\t\t\t\t\t\t\t\t\t\t\tif (resourceInSameBatch.getResourceType().equals(ResourceType.Patient.toString())\n\t\t\t\t\t\t\t\t\t\t\t\t\t|| resourceInSameBatch.getResourceType().equals(ResourceType.EpisodeOfCare.toString())) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(resourceInSameBatch.getResourceId(), resourceInSameBatch.getResourceType(), resourceInSameBatch.getVersion());\n\n\t\t\t\t\t\t\t\t\t\t\tmapperResourceByExchangeBatch.delete(resourceInSameBatch);\n\t\t\t\t\t\t\t\t\t\t\tmapperResourceHistory.delete(deletedResourceHistory);\n\t\t\t\t\t\t\t\t\t\t\tbatchIdsToPutInProtocolQueue.add(batchId);\n\n\t\t\t\t\t\t\t\t\t\t\t//check the most recent version of our resource, and if it's not deleted, add to the list to update the resource_by_service table\n\t\t\t\t\t\t\t\t\t\t\tResourceHistory mostRecentDeletedResourceHistory = resourceRepository.getCurrentVersion(resourceInSameBatch.getResourceType(), resourceInSameBatch.getResourceId());\n\t\t\t\t\t\t\t\t\t\t\tif (mostRecentDeletedResourceHistory != null\n\t\t\t\t\t\t\t\t\t\t\t\t\t&& !mostRecentDeletedResourceHistory.getIsDeleted()) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tString key2 = mostRecentDeletedResourceHistory.getResourceType().toString() + \":\" + mostRecentDeletedResourceHistory.getResourceId();\n\t\t\t\t\t\t\t\t\t\t\t\tresourcesFixed.put(key2, mostRecentDeletedResourceHistory);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//if we didn't find records in the DB to update, then\n\t\t\t\t\t\tif (!foundResourceInDbBatch) {\n\n\t\t\t\t\t\t\t//we can't generate a back-dated time UUID, but we need one so the resource_history\n\t\t\t\t\t\t\t//table is in order. To get a suitable time UUID, we just pull out the first exchange batch for our exchange,\n\t\t\t\t\t\t\t//and the batch ID is actually a time UUID that was allocated around the right time\n\t\t\t\t\t\t\tExchangeBatch firstBatch = exchangeBatchRepository.retrieveFirstForExchangeId(exchangeId);\n\n\t\t\t\t\t\t\t//if there was no batch for the exchange, then the exchange wasn't processed at all. So skip this exchange\n\t\t\t\t\t\t\t//and we'll pick up the same patient data in a following exchange\n\t\t\t\t\t\t\tif (firstBatch == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tUUID versionUuid = firstBatch.getBatchId();\n\n\t\t\t\t\t\t\t//find suitable batch ID\n\t\t\t\t\t\t\tUUID batchId = null;\n\t\t\t\t\t\t\tif (batchIds != null\n\t\t\t\t\t\t\t\t\t&& batchIds.size() > 0) {\n\t\t\t\t\t\t\t\tbatchId = batchIds.get(batchIds.size()-1);\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t//create new batch ID if not found\n\t\t\t\t\t\t\t\tExchangeBatch exchangeBatch = new ExchangeBatch();\n\t\t\t\t\t\t\t\texchangeBatch.setBatchId(UUIDs.timeBased());\n\t\t\t\t\t\t\t\texchangeBatch.setExchangeId(exchangeId);\n\t\t\t\t\t\t\t\texchangeBatch.setInsertedAt(new Date());\n\t\t\t\t\t\t\t\texchangeBatch.setEdsPatientId(edsPatientId);\n\t\t\t\t\t\t\t\texchangeBatchRepository.save(exchangeBatch);\n\n\t\t\t\t\t\t\t\tbatchId = exchangeBatch.getBatchId();\n\n\t\t\t\t\t\t\t\t//add to map for next resource\n\t\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbatchIds.add(batchId);\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(edsPatientId, batchIds);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString json = parserPool.composeString(resource);\n\n\t\t\t\t\t\t\tResourceHistory resourceHistory = new ResourceHistory();\n\t\t\t\t\t\t\tresourceHistory.setResourceId(resourceId);\n\t\t\t\t\t\t\tresourceHistory.setResourceType(resourceType.toString());\n\t\t\t\t\t\t\tresourceHistory.setVersion(versionUuid);\n\t\t\t\t\t\t\tresourceHistory.setCreatedAt(new Date());\n\t\t\t\t\t\t\tresourceHistory.setServiceId(serviceId);\n\t\t\t\t\t\t\tresourceHistory.setSystemId(systemId);\n\t\t\t\t\t\t\tresourceHistory.setIsDeleted(false);\n\t\t\t\t\t\t\tresourceHistory.setSchemaVersion(\"0.1\");\n\t\t\t\t\t\t\tresourceHistory.setResourceData(json);\n\t\t\t\t\t\t\tresourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json));\n\n\t\t\t\t\t\t\tResourceByExchangeBatch resourceByExchangeBatch = new ResourceByExchangeBatch();\n\t\t\t\t\t\t\tresourceByExchangeBatch.setBatchId(batchId);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setExchangeId(exchangeId);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceType(resourceType.toString());\n\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceId(resourceId);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setVersion(versionUuid);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setIsDeleted(false);\n\t\t\t\t\t\t\tresourceByExchangeBatch.setSchemaVersion(\"0.1\");\n\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceData(json);\n\n\t\t\t\t\t\t\tresourceRepository.save(resourceHistory);\n\t\t\t\t\t\t\tresourceRepository.save(resourceByExchangeBatch);\n\n\t\t\t\t\t\t\tbatchIdsToPutInProtocolQueue.add(batchId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!batchIdsToPutInProtocolQueue.isEmpty()) {\n\t\t\t\t\t\texchangeBatchesToPutInProtocolQueue.put(exchangeId, batchIdsToPutInProtocolQueue);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//update the resource_by_service table (and the resource_by_patient view)\n\t\t\t\tfor (ResourceHistory resourceHistory: resourcesFixed.values()) {\n\t\t\t\t\tUUID latestVersionUpdatedUuid = resourceHistory.getVersion();\n\n\t\t\t\t\tResourceHistory latestVersion = resourceRepository.getCurrentVersion(resourceHistory.getResourceType(), resourceHistory.getResourceId());\n\t\t\t\t\tUUID latestVersionUuid = latestVersion.getVersion();\n\n\t\t\t\t\t//if there have been subsequent updates to the resource, then skip it\n\t\t\t\t\tif (!latestVersionUuid.equals(latestVersionUpdatedUuid)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tResource resource = parserPool.parse(resourceHistory.getResourceData());\n\t\t\t\t\tResourceMetadata metadata = MetadataFactory.createMetadata(resource);\n\t\t\t\t\tUUID patientId = ((PatientCompartment)metadata).getPatientId();\n\n\t\t\t\t\tResourceByService resourceByService = new ResourceByService();\n\t\t\t\t\tresourceByService.setServiceId(resourceHistory.getServiceId());\n\t\t\t\t\tresourceByService.setSystemId(resourceHistory.getSystemId());\n\t\t\t\t\tresourceByService.setResourceType(resourceHistory.getResourceType());\n\t\t\t\t\tresourceByService.setResourceId(resourceHistory.getResourceId());\n\t\t\t\t\tresourceByService.setCurrentVersion(resourceHistory.getVersion());\n\t\t\t\t\tresourceByService.setUpdatedAt(resourceHistory.getCreatedAt());\n\t\t\t\t\tresourceByService.setPatientId(patientId);\n\t\t\t\t\tresourceByService.setSchemaVersion(resourceHistory.getSchemaVersion());\n\t\t\t\t\tresourceByService.setResourceMetadata(JsonSerializer.serialize(metadata));\n\t\t\t\t\tresourceByService.setResourceData(resourceHistory.getResourceData());\n\n\t\t\t\t\tresourceRepository.save(resourceByService);\n\n\t\t\t\t\t//call out to our patient search and person matching services\n\t\t\t\t\tif (resource instanceof Patient) {\n\t\t\t\t\t\tPatientLinkHelper.updatePersonId((Patient)resource);\n\t\t\t\t\t\tPatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (Patient)resource);\n\n\t\t\t\t\t} else if (resource instanceof EpisodeOfCare) {\n\t\t\t\t\t\tPatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (EpisodeOfCare)resource);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!exchangeBatchesToPutInProtocolQueue.isEmpty()) {\n\t\t\t\t\t//find the config for our protocol queue\n\t\t\t\t\tString configXml = ConfigManager.getConfiguration(\"inbound\", \"queuereader\");\n\n\t\t\t\t\t//the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary\n\t\t\t\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\t\t\t\t\tPipeline pipeline = configuration.getPipeline();\n\n\t\t\t\t\tPostMessageToExchangeConfig config = pipeline\n\t\t\t\t\t\t\t.getPipelineComponents()\n\t\t\t\t\t\t\t.stream()\n\t\t\t\t\t\t\t.filter(t -> t instanceof PostMessageToExchangeConfig)\n\t\t\t\t\t\t\t.map(t -> (PostMessageToExchangeConfig) t)\n\t\t\t\t\t\t\t.filter(t -> t.getExchange().equalsIgnoreCase(\"EdsProtocol\"))\n\t\t\t\t\t\t\t.collect(StreamExtension.singleOrNullCollector());\n\n\t\t\t\t\t//post to the protocol exchange\n\t\t\t\t\tfor (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) {\n\t\t\t\t\t\tSet batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId);\n\n\t\t\t\t\t\torg.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\t\tString batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds);\n\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString);\n\n\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(config);\n\t\t\t\t\t\tcomponent.process(exchange);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Confidential Patients\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixDeletedAppointments(String sharedStoragePath, boolean saveChanges, UUID justThisService) {\n\t\tLOG.info(\"Fixing Deleted Appointments using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tParserPool parserPool = new ParserPool();\n\t\tMappingManager mappingManager = CassandraConnector.getInstance().getMappingManager();\n\t\tMapper mapperResourceHistory = mappingManager.mapper(ResourceHistory.class);\n\t\tMapper mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class);\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (systemIds.size() > 1) {\n\t\t\t\t\t\tthrow new Exception(\"Multiple system IDs for service \" + serviceId);\n\t\t\t\t\t}\n\t\t\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId);\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch batch : batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class, dir, version, true, parsers);\n\n\t\t\t\t\t//find any deleted patients\n\t\t\t\t\tList deletedPatientUuids = new ArrayList<>();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class);\n\t\t\t\t\twhile (patientParser.nextRecord()) {\n\t\t\t\t\t\tif (patientParser.getDeleted()) {\n\t\t\t\t\t\t\t//find the EDS patient ID for this local guid\n\t\t\t\t\t\t\tString patientGuid = patientParser.getPatientGuid();\n\t\t\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid);\n\t\t\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find patient ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + ResourceType.Patient + \" local ID \" + patientGuid);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdeletedPatientUuids.add(edsPatientId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpatientParser.close();\n\n\t\t\t\t\t//go through the appts file to find properly deleted appt GUIDS\n\t\t\t\t\tList deletedApptUuids = new ArrayList<>();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.appointment.Slot apptParser = (org.endeavourhealth.transform.emis.csv.schema.appointment.Slot) parsers.get(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class);\n\t\t\t\t\twhile (apptParser.nextRecord()) {\n\t\t\t\t\t\tif (apptParser.getDeleted()) {\n\t\t\t\t\t\t\tString patientGuid = apptParser.getPatientGuid();\n\t\t\t\t\t\t\tString slotGuid = apptParser.getSlotGuid();\n\t\t\t\t\t\t\tif (!Strings.isNullOrEmpty(patientGuid)) {\n\t\t\t\t\t\t\t\tString uniqueLocalId = EmisCsvHelper.createUniqueId(patientGuid, slotGuid);\n\t\t\t\t\t\t\t\tUUID edsApptId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Appointment, uniqueLocalId);\n\t\t\t\t\t\t\t\tdeletedApptUuids.add(edsApptId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tapptParser.close();\n\n\t\t\t\t\tfor (UUID edsPatientId : deletedPatientUuids) {\n\n\t\t\t\t\t\tList batchIds = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t//if there are no batches for this patient, we'll be handling this data in another exchange\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (UUID batchId : batchIds) {\n\t\t\t\t\t\t\tList apptWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Appointment.toString());\n\t\t\t\t\t\t\tfor (ResourceByExchangeBatch apptWrapper : apptWrappers) {\n\n\t\t\t\t\t\t\t\t//ignore non-deleted appts\n\t\t\t\t\t\t\t\tif (!apptWrapper.getIsDeleted()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//if the appt was deleted legitamately, then skip it\n\t\t\t\t\t\t\t\tUUID apptId = apptWrapper.getResourceId();\n\t\t\t\t\t\t\t\tif (deletedApptUuids.contains(apptId)) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(apptWrapper.getResourceId(), apptWrapper.getResourceType(), apptWrapper.getVersion());\n\n\t\t\t\t\t\t\t\tif (saveChanges) {\n\t\t\t\t\t\t\t\t\tmapperResourceByExchangeBatch.delete(apptWrapper);\n\t\t\t\t\t\t\t\t\tmapperResourceHistory.delete(deletedResourceHistory);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tLOG.info(\"Un-deleted \" + apptWrapper.getResourceType() + \" \" + apptWrapper.getResourceId() + \" in batch \" + batchId + \" patient \" + edsPatientId);\n\n\t\t\t\t\t\t\t\t//now get the most recent instance of the appointment, and if it's NOT deleted, insert into the resource_by_service table\n\t\t\t\t\t\t\t\tResourceHistory mostRecentResourceHistory = resourceRepository.getCurrentVersion(apptWrapper.getResourceType(), apptWrapper.getResourceId());\n\t\t\t\t\t\t\t\tif (mostRecentResourceHistory != null\n\t\t\t\t\t\t\t\t\t\t&& !mostRecentResourceHistory.getIsDeleted()) {\n\n\t\t\t\t\t\t\t\t\tResource resource = parserPool.parse(mostRecentResourceHistory.getResourceData());\n\t\t\t\t\t\t\t\t\tResourceMetadata metadata = MetadataFactory.createMetadata(resource);\n\t\t\t\t\t\t\t\t\tUUID patientId = ((PatientCompartment) metadata).getPatientId();\n\n\t\t\t\t\t\t\t\t\tResourceByService resourceByService = new ResourceByService();\n\t\t\t\t\t\t\t\t\tresourceByService.setServiceId(mostRecentResourceHistory.getServiceId());\n\t\t\t\t\t\t\t\t\tresourceByService.setSystemId(mostRecentResourceHistory.getSystemId());\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceType(mostRecentResourceHistory.getResourceType());\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceId(mostRecentResourceHistory.getResourceId());\n\t\t\t\t\t\t\t\t\tresourceByService.setCurrentVersion(mostRecentResourceHistory.getVersion());\n\t\t\t\t\t\t\t\t\tresourceByService.setUpdatedAt(mostRecentResourceHistory.getCreatedAt());\n\t\t\t\t\t\t\t\t\tresourceByService.setPatientId(patientId);\n\t\t\t\t\t\t\t\t\tresourceByService.setSchemaVersion(mostRecentResourceHistory.getSchemaVersion());\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceMetadata(JsonSerializer.serialize(metadata));\n\t\t\t\t\t\t\t\t\tresourceByService.setResourceData(mostRecentResourceHistory.getResourceData());\n\n\t\t\t\t\t\t\t\t\tif (saveChanges) {\n\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByService);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tLOG.info(\"Restored \" + apptWrapper.getResourceType() + \" \" + apptWrapper.getResourceId() + \" to resource_by_service table\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Deleted Appointments Patients\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\n\t/*private static void fixReviews(String sharedStoragePath, UUID justThisService) {\n\t\tLOG.info(\"Fixing Reviews using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tParserPool parserPool = new ParserPool();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\t\t\t\tMap problemCodes = new HashMap<>();\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId + \" with \" + batches.size() + \" batches\");\n\t\t\t\t\tfor (ExchangeBatch batch: batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Problem problemParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class);\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\n\t\t\t\t\twhile (problemParser.nextRecord()) {\n\t\t\t\t\t\tString patientGuid = problemParser.getPatientGuid();\n\t\t\t\t\t\tString observationGuid = problemParser.getObservationGuid();\n\t\t\t\t\t\tString key = patientGuid + \":\" + observationGuid;\n\t\t\t\t\t\tif (!problemCodes.containsKey(key)) {\n\t\t\t\t\t\t\tproblemCodes.put(key, null);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tproblemParser.close();\n\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tString patientGuid = observationParser.getPatientGuid();\n\t\t\t\t\t\tString observationGuid = observationParser.getObservationGuid();\n\t\t\t\t\t\tString key = patientGuid + \":\" + observationGuid;\n\t\t\t\t\t\tif (problemCodes.containsKey(key)) {\n\t\t\t\t\t\t\tLong codeId = observationParser.getCodeId();\n\t\t\t\t\t\t\tif (codeId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tproblemCodes.put(key, codeId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\t\t\t\t\tLOG.info(\"Found \" + problemCodes.size() + \" problem codes so far\");\n\n\t\t\t\t\tString dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f);\n\n\t\t\t\t\tEmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId);\n\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tString problemGuid = observationParser.getProblemGuid();\n\t\t\t\t\t\tif (!Strings.isNullOrEmpty(problemGuid)) {\n\t\t\t\t\t\t\tString patientGuid = observationParser.getPatientGuid();\n\t\t\t\t\t\t\tLong codeId = observationParser.getCodeId();\n\t\t\t\t\t\t\tif (codeId == null) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString key = patientGuid + \":\" + problemGuid;\n\t\t\t\t\t\t\tLong problemCodeId = problemCodes.get(key);\n\t\t\t\t\t\t\tif (problemCodeId == null\n\t\t\t\t\t\t\t\t\t|| problemCodeId.longValue() != codeId.longValue()) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//if here, our code is the same as the problem, so it's a review\n\t\t\t\t\t\t\tString locallyUniqueId = patientGuid + \":\" + observationParser.getObservationGuid();\n\t\t\t\t\t\t\tResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, helper);\n\n\t\t\t\t\t\t\tfor (UUID systemId: systemIds) {\n\n\t\t\t\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid);\n\t\t\t\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find patient ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + ResourceType.Patient + \" local ID \" + patientGuid);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tUUID edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId);\n\t\t\t\t\t\t\t\tif (edsObservationId == null) {\n\n\t\t\t\t\t\t\t\t\t//try observations as diagnostic reports, because it could be one of those instead\n\t\t\t\t\t\t\t\t\tif (resourceType == ResourceType.Observation) {\n\t\t\t\t\t\t\t\t\t\tresourceType = ResourceType.DiagnosticReport;\n\t\t\t\t\t\t\t\t\t\tedsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (edsObservationId == null) {\n\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find observation ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + resourceType + \" local ID \" + locallyUniqueId);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\t\t//if there are no batches for this patient, we'll be handling this data in another exchange\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t//throw new Exception(\"Failed to find batch ID for patient \" + edsPatientId + \" in exchange \" + exchangeId + \" for resource \" + resourceType + \" \" + edsObservationId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor (UUID batchId: batchIds) {\n\n\t\t\t\t\t\t\t\t\tList resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), edsObservationId);\n\t\t\t\t\t\t\t\t\tif (resourceByExchangeBatches.isEmpty()) {\n\t\t\t\t\t\t\t\t\t\t//if we've deleted data, this will be null\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t//throw new Exception(\"No resources found for batch \" + batchId + \" resource type \" + resourceType + \" and resource id \" + edsObservationId);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tfor (ResourceByExchangeBatch resourceByExchangeBatch: resourceByExchangeBatches) {\n\n\t\t\t\t\t\t\t\t\t\tString json = resourceByExchangeBatch.getResourceData();\n\t\t\t\t\t\t\t\t\t\tif (Strings.isNullOrEmpty(json)) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"No JSON in resource \" + resourceType + \" \" + edsObservationId + \" in batch \" + batchId);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tResource resource = parserPool.parse(json);\n\t\t\t\t\t\t\t\t\t\tif (addReviewExtension((DomainResource)resource)) {\n\t\t\t\t\t\t\t\t\t\t\tjson = parserPool.composeString(resource);\n\t\t\t\t\t\t\t\t\t\t\tresourceByExchangeBatch.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\t\tLOG.info(\"Changed \" + resourceType + \" \" + edsObservationId + \" to have extension in batch \" + batchId);\n\n\t\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByExchangeBatch);\n\n\t\t\t\t\t\t\t\t\t\t\tUUID versionUuid = resourceByExchangeBatch.getVersion();\n\t\t\t\t\t\t\t\t\t\t\tResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(edsObservationId, resourceType.toString(), versionUuid);\n\t\t\t\t\t\t\t\t\t\t\tif (resourceHistory == null) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Exception(\"Failed to find resource history for \" + resourceType + \" \" + edsObservationId + \" and version \" + versionUuid);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\t\tresourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json));\n\t\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceHistory);\n\n\t\t\t\t\t\t\t\t\t\t\tResourceByService resourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType.toString(), edsObservationId);\n\t\t\t\t\t\t\t\t\t\t\tif (resourceByService != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tUUID serviceVersionUuid = resourceByService.getCurrentVersion();\n\t\t\t\t\t\t\t\t\t\t\t\tif (serviceVersionUuid.equals(versionUuid)) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tresourceByService.setResourceData(json);\n\t\t\t\t\t\t\t\t\t\t\t\t\tresourceRepository.save(resourceByService);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tLOG.info(\"\" + resourceType + \" \" + edsObservationId + \" already has extension\");\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//1. find out resource type originall saved from\n\t\t\t\t\t\t\t//2. retrieve from resource_by_exchange_batch\n\t\t\t\t\t\t\t//3. update resource in resource_by_exchange_batch\n\t\t\t\t\t\t\t//4. retrieve from resource_history\n\t\t\t\t\t\t\t//5. update resource_history\n\t\t\t\t\t\t\t//6. retrieve record from resource_by_service\n\t\t\t\t\t\t\t//7. if resource_by_service version UUID matches the resource_history updated, then update that too\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Fixing Reviews\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static boolean addReviewExtension(DomainResource resource) {\n\n\t\tif (ExtensionConverter.hasExtension(resource, FhirExtensionUri.IS_REVIEW)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tExtension extension = ExtensionConverter.createExtension(FhirExtensionUri.IS_REVIEW, new BooleanType(true));\n\t\tresource.addExtension(extension);\n\n\t\treturn true;\n\t}*/\n\n\n\t/*private static void runProtocolsForConfidentialPatients(String sharedStoragePath, UUID justThisService) {\n\t\tLOG.info(\"Running Protocols for Confidential Patients using path \" + sharedStoragePath + \" and service \" + justThisService);\n\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\n\t\ttry {\n\t\t\tIterable iterable = new ServiceRepository().getAll();\n\t\t\tfor (Service service : iterable) {\n\t\t\t\tUUID serviceId = service.getId();\n\n\t\t\t\tif (justThisService != null\n\t\t\t\t\t\t&& !service.getId().equals(justThisService)) {\n\t\t\t\t\tLOG.info(\"Skipping service \" + service.getName());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//once we match the servce, set this to null to do all other services\n\t\t\t\tjustThisService = null;\n\n\t\t\t\tLOG.info(\"Doing service \" + service.getName());\n\n\t\t\t\tList systemIds = findSystemIds(service);\n\n\n\t\t\t\tList interestingPatientGuids = new ArrayList<>();\n\t\t\t\tMap>> batchesPerPatientPerExchange = new HashMap<>();\n\n\t\t\t\tList exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId);\n\t\t\t\tfor (UUID exchangeId: exchangeIds) {\n\n\t\t\t\t\tExchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\tString software = exchange.getHeader(HeaderKeys.SourceSystem);\n\t\t\t\t\tif (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString body = exchange.getBody();\n\t\t\t\t\tString[] files = body.split(java.lang.System.lineSeparator());\n\n\t\t\t\t\tif (files.length == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(\"Doing Emis CSV exchange \" + exchangeId);\n\n\t\t\t\t\tMap> batchesPerPatient = new HashMap<>();\n\n\t\t\t\t\tList batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId);\n\t\t\t\t\tfor (ExchangeBatch batch : batches) {\n\t\t\t\t\t\tUUID patientId = batch.getEdsPatientId();\n\t\t\t\t\t\tif (patientId != null) {\n\t\t\t\t\t\t\tList batchIds = batchesPerPatient.get(patientId);\n\t\t\t\t\t\t\tif (batchIds == null) {\n\t\t\t\t\t\t\t\tbatchIds = new ArrayList<>();\n\t\t\t\t\t\t\t\tbatchesPerPatient.put(patientId, batchIds);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbatchIds.add(batch.getBatchId());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbatchesPerPatientPerExchange.put(exchangeId, batchesPerPatient);\n\n\t\t\t\t\tFile f = new File(sharedStoragePath, files[0]);\n\t\t\t\t\tFile dir = f.getParentFile();\n\n\t\t\t\t\tString version = EmisCsvToFhirTransformer.determineVersion(dir);\n\n\t\t\t\t\tMap parsers = new HashMap<>();\n\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers);\n\t\t\t\t\tEmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers);\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class);\n\t\t\t\t\twhile (patientParser.nextRecord()) {\n\t\t\t\t\t\tif (patientParser.getIsConfidential() || patientParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(patientParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpatientParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class);\n\t\t\t\t\twhile (consultationParser.nextRecord()) {\n\t\t\t\t\t\tif (consultationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !consultationParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(consultationParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsultationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class);\n\t\t\t\t\twhile (observationParser.nextRecord()) {\n\t\t\t\t\t\tif (observationParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !observationParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(observationParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobservationParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class);\n\t\t\t\t\twhile (diaryParser.nextRecord()) {\n\t\t\t\t\t\tif (diaryParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !diaryParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(diaryParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdiaryParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class);\n\t\t\t\t\twhile (drugRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (drugRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !drugRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(drugRecordParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdrugRecordParser.close();\n\n\t\t\t\t\torg.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class);\n\t\t\t\t\twhile (issueRecordParser.nextRecord()) {\n\t\t\t\t\t\tif (issueRecordParser.getIsConfidential()\n\t\t\t\t\t\t\t\t&& !issueRecordParser.getDeleted()) {\n\t\t\t\t\t\t\tinterestingPatientGuids.add(issueRecordParser.getPatientGuid());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tissueRecordParser.close();\n\t\t\t\t}\n\n\t\t\t\tMap> exchangeBatchesToPutInProtocolQueue = new HashMap<>();\n\n\t\t\t\tfor (String interestingPatientGuid: interestingPatientGuids) {\n\n\t\t\t\t\tif (systemIds.size() > 1) {\n\t\t\t\t\t\tthrow new Exception(\"Multiple system IDs for service \" + serviceId);\n\t\t\t\t\t}\n\t\t\t\t\tUUID systemId = systemIds.get(0);\n\n\t\t\t\t\tUUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, interestingPatientGuid);\n\t\t\t\t\tif (edsPatientId == null) {\n\t\t\t\t\t\tthrow new Exception(\"Failed to find patient ID for service \" + serviceId + \" system \" + systemId + \" resourceType \" + ResourceType.Patient + \" local ID \" + interestingPatientGuid);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (UUID exchangeId: batchesPerPatientPerExchange.keySet()) {\n\t\t\t\t\t\tMap> batchesPerPatient = batchesPerPatientPerExchange.get(exchangeId);\n\t\t\t\t\t\tList batches = batchesPerPatient.get(edsPatientId);\n\t\t\t\t\t\tif (batches != null) {\n\n\t\t\t\t\t\t\tSet batchesForExchange = exchangeBatchesToPutInProtocolQueue.get(exchangeId);\n\t\t\t\t\t\t\tif (batchesForExchange == null) {\n\t\t\t\t\t\t\t\tbatchesForExchange = new HashSet<>();\n\t\t\t\t\t\t\t\texchangeBatchesToPutInProtocolQueue.put(exchangeId, batchesForExchange);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbatchesForExchange.addAll(batches);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif (!exchangeBatchesToPutInProtocolQueue.isEmpty()) {\n\t\t\t\t\t//find the config for our protocol queue\n\t\t\t\t\tString configXml = ConfigManager.getConfiguration(\"inbound\", \"queuereader\");\n\n\t\t\t\t\t//the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary\n\t\t\t\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\t\t\t\t\tPipeline pipeline = configuration.getPipeline();\n\n\t\t\t\t\tPostMessageToExchangeConfig config = pipeline\n\t\t\t\t\t\t\t.getPipelineComponents()\n\t\t\t\t\t\t\t.stream()\n\t\t\t\t\t\t\t.filter(t -> t instanceof PostMessageToExchangeConfig)\n\t\t\t\t\t\t\t.map(t -> (PostMessageToExchangeConfig) t)\n\t\t\t\t\t\t\t.filter(t -> t.getExchange().equalsIgnoreCase(\"EdsProtocol\"))\n\t\t\t\t\t\t\t.collect(StreamExtension.singleOrNullCollector());\n\n\t\t\t\t\t//post to the protocol exchange\n\t\t\t\t\tfor (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) {\n\t\t\t\t\t\tSet batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId);\n\n\t\t\t\t\t\torg.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\t\t\tString batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds);\n\t\t\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString);\n\t\t\t\t\t\tLOG.info(\"Posting exchange \" + exchangeId + \" batch \" + batchIdString);\n\n\t\t\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(config);\n\t\t\t\t\t\tcomponent.process(exchange);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLOG.info(\"Finished Running Protocols for Confidential Patients\");\n\n\t\t} catch (Exception ex) {\n\t\t\tLOG.error(\"\", ex);\n\t\t}\n\t}*/\n\n\t/*private static void fixOrgs() {\n\n\t\tLOG.info(\"Posting orgs to protocol queue\");\n\n\t\tString[] orgIds = new String[]{\n\t\t\"332f31a2-7b28-47cb-af6f-18f65440d43d\",\n\t\t\"c893d66b-eb89-4657-9f53-94c5867e7ed9\"};\n\n\t\tExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository();\n\t\tResourceRepository resourceRepository = new ResourceRepository();\n\n\t\tMap> exchangeBatches = new HashMap<>();\n\n\t\tfor (String orgId: orgIds) {\n\n\t\t\tLOG.info(\"Doing org ID \" + orgId);\n\t\t\tUUID orgUuid = UUID.fromString(orgId);\n\n\t\t\ttry {\n\n\t\t\t\t//select batch_id from ehr.resource_by_exchange_batch where resource_type = 'Organization' and resource_id = 8f465517-729b-4ad9-b405-92b487047f19 LIMIT 1 ALLOW FILTERING;\n\t\t\t\tResourceByExchangeBatch resourceByExchangeBatch = resourceRepository.getFirstResourceByExchangeBatch(ResourceType.Organization.toString(), orgUuid);\n\t\t\t\tUUID batchId = resourceByExchangeBatch.getBatchId();\n\n\t\t\t\t//select exchange_id from ehr.exchange_batch where batch_id = 1a940e10-1535-11e7-a29d-a90b99186399 LIMIT 1 ALLOW FILTERING;\n\t\t\t\tExchangeBatch exchangeBatch = exchangeBatchRepository.retrieveFirstForBatchId(batchId);\n\t\t\t\tUUID exchangeId = exchangeBatch.getExchangeId();\n\n\t\t\t\tSet list = exchangeBatches.get(exchangeId);\n\t\t\t\tif (list == null) {\n\t\t\t\t\tlist = new HashSet<>();\n\t\t\t\t\texchangeBatches.put(exchangeId, list);\n\t\t\t\t}\n\t\t\t\tlist.add(batchId);\n\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"\", ex);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t//find the config for our protocol queue (which is in the inbound config)\n\t\t\tString configXml = ConfigManager.getConfiguration(\"inbound\", \"queuereader\");\n\n\t\t\t//the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary\n\t\t\tQueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml);\n\t\t\tPipeline pipeline = configuration.getPipeline();\n\n\t\t\tPostMessageToExchangeConfig config = pipeline\n\t\t\t\t\t.getPipelineComponents()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(t -> t instanceof PostMessageToExchangeConfig)\n\t\t\t\t\t.map(t -> (PostMessageToExchangeConfig) t)\n\t\t\t\t\t.filter(t -> t.getExchange().equalsIgnoreCase(\"EdsProtocol\"))\n\t\t\t\t\t.collect(StreamExtension.singleOrNullCollector());\n\n\t\t\t//post to the protocol exchange\n\t\t\tfor (UUID exchangeId : exchangeBatches.keySet()) {\n\t\t\t\tSet batchIds = exchangeBatches.get(exchangeId);\n\n\t\t\t\torg.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId);\n\n\t\t\t\tString batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds);\n\t\t\t\texchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString);\n\t\t\t\tLOG.info(\"Posting exchange \" + exchangeId + \" batch \" + batchIdString);\n\n\t\t\t\tPostMessageToExchange component = new PostMessageToExchange(config);\n\t\t\t\tcomponent.process(exchange);\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\n\t\t\tLOG.error(\"\", ex);\n\t\t\treturn;\n\t\t}\n\n\n\t\tLOG.info(\"Finished posting orgs to protocol queue\");\n\t}*/\n\n\t/*private static void findCodes() {\n\n\t\tLOG.info(\"Finding missing codes\");\n\n\t\tAuditRepository auditRepository = new AuditRepository();\n\t\tServiceRepository serviceRepository = new ServiceRepository();\n\n\t\tSession session = CassandraConnector.getInstance().getSession();\n\t\tStatement stmt = new SimpleStatement(\"SELECT service_id, system_id, exchange_id, version FROM audit.exchange_transform_audit ALLOW FILTERING;\");\n\t\tstmt.setFetchSize(100);\n\n\t\tResultSet rs = session.execute(stmt);\n\t\twhile (!rs.isExhausted()) {\n\t\t\tRow row = rs.one();\n\t\t\tUUID serviceId = row.get(0, UUID.class);\n\t\t\tUUID systemId = row.get(1, UUID.class);\n\t\t\tUUID exchangeId = row.get(2, UUID.class);\n\t\t\tUUID version = row.get(3, UUID.class);\n\n\t\t\tExchangeTransformAudit audit = auditRepository.getExchangeTransformAudit(serviceId, systemId, exchangeId, version);\n\t\t\tString xml = audit.getErrorXml();\n\t\t\tif (xml == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString codePrefix = \"Failed to find clinical code CodeableConcept for codeId \";\n\t\t\tint codeIndex = xml.indexOf(codePrefix);\n\t\t\tif (codeIndex > -1) {\n\t\t\t\tint startIndex = codeIndex + codePrefix.length();\n\t\t\t\tint tagEndIndex = xml.indexOf(\"<\", startIndex);\n\n\t\t\t\tString code = xml.substring(startIndex, tagEndIndex);\n\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tString name = service.getName();\n\n\t\t\t\tLOG.info(name + \" clinical code \" + code + \" from \" + audit.getStarted());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcodePrefix = \"Failed to find medication CodeableConcept for codeId \";\n\t\t\tcodeIndex = xml.indexOf(codePrefix);\n\t\t\tif (codeIndex > -1) {\n\t\t\t\tint startIndex = codeIndex + codePrefix.length();\n\t\t\t\tint tagEndIndex = xml.indexOf(\"<\", startIndex);\n\n\t\t\t\tString code = xml.substring(startIndex, tagEndIndex);\n\t\t\t\tService service = serviceRepository.getById(serviceId);\n\t\t\t\tString name = service.getName();\n\n\t\t\t\tLOG.info(name + \" drug code \" + code + \" from \" + audit.getStarted());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(\"Finished finding missing codes\");\n\t}*/\n\n\tprivate static void createTppSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) {\n\t\tLOG.info(\"Creating TPP Subset\");\n\n\t\ttry {\n\n\t\t\tSet personIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpersonIds.add(line);\n\t\t\t}\n\n\t\t\tFile sourceDir = new File(sourceDirPath);\n\t\t\tFile destDir = new File(destDirPath);\n\n\t\t\tif (!destDir.exists()) {\n\t\t\t\tdestDir.mkdirs();\n\t\t\t}\n\n\t\t\tcreateTppSubsetForFile(sourceDir, destDir, personIds);\n\n\t\t\tLOG.info(\"Finished Creating TPP Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\tprivate static void createTppSubsetForFile(File sourceDir, File destDir, Set personIds) throws Exception {\n\n\t\tFile[] files = sourceDir.listFiles();\n\t\tLOG.info(\"Found \" + files.length + \" files in \" + sourceDir);\n\n\t\tfor (File sourceFile: files) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\t//LOG.info(\"Doing dir \" + sourceFile);\n\t\t\t\tcreateTppSubsetForFile(sourceFile, destFile, personIds);\n\n\t\t\t} else {\n\n\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\tdestFile.delete();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Checking file \" + sourceFile);\n\n\t\t\t\t//skip any non-CSV file\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (!ext.equalsIgnoreCase(\"csv\")) {\n\t\t\t\t\tLOG.info(\"Skipping as not a CSV file\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\t\tCSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withHeader();\n\n\t\t\t\tCSVParser parser = new CSVParser(br, format);\n\n\t\t\t\tString filterColumn = null;\n\n\t\t\t\tMap headerMap = parser.getHeaderMap();\n\t\t\t\tif (headerMap.containsKey(\"IDPatient\")) {\n\t\t\t\t\tfilterColumn = \"IDPatient\";\n\n\t\t\t\t} else if (name.equalsIgnoreCase(\"SRPatient.csv\")) {\n\t\t\t\t\tfilterColumn = \"RowIdentifier\";\n\n\t\t\t\t} else {\n\t\t\t\t\t//if no patient column, just copy the file\n\t\t\t\t\tparser.close();\n\n\t\t\t\t\tLOG.info(\"Copying non-patient file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString[] columnHeaders = new String[headerMap.size()];\n\t\t\t\tIterator headerIterator = headerMap.keySet().iterator();\n\t\t\t\twhile (headerIterator.hasNext()) {\n\t\t\t\t\tString headerName = headerIterator.next();\n\t\t\t\t\tint headerIndex = headerMap.get(headerName);\n\t\t\t\t\tcolumnHeaders[headerIndex] = headerName;\n\t\t\t\t}\n\n\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\n\t\t\t\tCSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders));\n\n\t\t\t\tIterator csvIterator = parser.iterator();\n\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\tString patientId = csvRecord.get(filterColumn);\n\t\t\t\t\tif (personIds.contains(patientId)) {\n\n\t\t\t\t\t\tprinter.printRecord(csvRecord);\n\t\t\t\t\t\tprinter.flush();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparser.close();\n\t\t\t\tprinter.close();\n\n\t\t\t\t/*} else {\n\t\t\t\t\t//the 2.1 files are going to be a pain to split by patient, so just copy them over\n\t\t\t\t\tLOG.info(\"Copying 2.1 file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void createVisionSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) {\n\t\tLOG.info(\"Creating Vision Subset\");\n\n\t\ttry {\n\n\t\t\tSet personIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpersonIds.add(line);\n\t\t\t}\n\n\t\t\tFile sourceDir = new File(sourceDirPath);\n\t\t\tFile destDir = new File(destDirPath);\n\n\t\t\tif (!destDir.exists()) {\n\t\t\t\tdestDir.mkdirs();\n\t\t\t}\n\n\t\t\tcreateVisionSubsetForFile(sourceDir, destDir, personIds);\n\n\t\t\tLOG.info(\"Finished Creating Vision Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\tprivate static void createVisionSubsetForFile(File sourceDir, File destDir, Set personIds) throws Exception {\n\n\t\tFile[] files = sourceDir.listFiles();\n\t\tLOG.info(\"Found \" + files.length + \" files in \" + sourceDir);\n\n\t\tfor (File sourceFile: files) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\tcreateVisionSubsetForFile(sourceFile, destFile, personIds);\n\n\t\t\t} else {\n\n\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\tdestFile.delete();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Checking file \" + sourceFile);\n\n\t\t\t\t//skip any non-CSV file\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (!ext.equalsIgnoreCase(\"csv\")) {\n\t\t\t\t\tLOG.info(\"Skipping as not a CSV file\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\t\tCSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL);\n\n\t\t\t\tCSVParser parser = new CSVParser(br, format);\n\n\t\t\t\tint filterColumn = -1;\n\n\t\t\t\tif (name.contains(\"encounter_data\") || name.contains(\"journal_data\") ||\n\t\t\t\t\t\tname.contains(\"patient_data\") || name.contains(\"referral_data\")) {\n\n\t\t\t\t\tfilterColumn = 0;\n\t\t\t\t} else {\n\t\t\t\t\t//if no patient column, just copy the file\n\t\t\t\t\tparser.close();\n\n\t\t\t\t\tLOG.info(\"Copying non-patient file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\n\t\t\t\tCSVPrinter printer = new CSVPrinter(bw, format);\n\n\t\t\t\tIterator csvIterator = parser.iterator();\n\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\tString patientId = csvRecord.get(filterColumn);\n\t\t\t\t\tif (personIds.contains(patientId)) {\n\n\t\t\t\t\t\tprinter.printRecord(csvRecord);\n\t\t\t\t\t\tprinter.flush();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparser.close();\n\t\t\t\tprinter.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void createAdastraSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) {\n\t\tLOG.info(\"Creating Adastra Subset\");\n\n\t\ttry {\n\n\t\t\tSet caseIds = new HashSet<>();\n\t\t\tList lines = Files.readAllLines(new File(samplePatientsFile).toPath());\n\t\t\tfor (String line: lines) {\n\t\t\t\tline = line.trim();\n\n\t\t\t\t//ignore comments\n\t\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//adastra extract files are all keyed on caseId\n\t\t\t\tcaseIds.add(line);\n\t\t\t}\n\n\t\t\tFile sourceDir = new File(sourceDirPath);\n\t\t\tFile destDir = new File(destDirPath);\n\n\t\t\tif (!destDir.exists()) {\n\t\t\t\tdestDir.mkdirs();\n\t\t\t}\n\n\t\t\tcreateAdastraSubsetForFile(sourceDir, destDir, caseIds);\n\n\t\t\tLOG.info(\"Finished Creating Adastra Subset\");\n\n\t\t} catch (Throwable t) {\n\t\t\tLOG.error(\"\", t);\n\t\t}\n\t}\n\n\tprivate static void createAdastraSubsetForFile(File sourceDir, File destDir, Set caseIds) throws Exception {\n\n\t\tFile[] files = sourceDir.listFiles();\n\t\tLOG.info(\"Found \" + files.length + \" files in \" + sourceDir);\n\n\t\tfor (File sourceFile: files) {\n\n\t\t\tString name = sourceFile.getName();\n\t\t\tFile destFile = new File(destDir, name);\n\n\t\t\tif (sourceFile.isDirectory()) {\n\n\t\t\t\tif (!destFile.exists()) {\n\t\t\t\t\tdestFile.mkdirs();\n\t\t\t\t}\n\n\t\t\t\tcreateAdastraSubsetForFile(sourceFile, destFile, caseIds);\n\n\t\t\t} else {\n\n\t\t\t\tif (destFile.exists()) {\n\t\t\t\t\tdestFile.delete();\n\t\t\t\t}\n\n\t\t\t\tLOG.info(\"Checking file \" + sourceFile);\n\n\t\t\t\t//skip any non-CSV file\n\t\t\t\tString ext = FilenameUtils.getExtension(name);\n\t\t\t\tif (!ext.equalsIgnoreCase(\"csv\")) {\n\t\t\t\t\tLOG.info(\"Skipping as not a CSV file\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tFileReader fr = new FileReader(sourceFile);\n\t\t\t\tBufferedReader br = new BufferedReader(fr);\n\n\t\t\t\t//fully quote destination file to fix CRLF in columns\n\t\t\t\tCSVFormat format = CSVFormat.DEFAULT.withDelimiter('|');\n\n\t\t\t\tCSVParser parser = new CSVParser(br, format);\n\n\t\t\t\tint filterColumn = -1;\n\n\t\t\t\t//CaseRef column at 0\n\t\t\t\tif (name.contains(\"NOTES\") || name.contains(\"CASEQUESTIONS\") ||\n\t\t\t\t\t\tname.contains(\"OUTCOMES\") || name.contains(\"CONSULTATION\") ||\n\t\t\t\t\t\tname.contains(\"CLINICALCODES\") || name.contains(\"PRESCRIPTIONS\") ||\n\t\t\t\t\t\tname.contains(\"PATIENT\")) {\n\n\t\t\t\t\tfilterColumn = 0;\n\n\t\t\t\t} else if (name.contains(\"CASE\")) {\n\t\t\t\t\t//CaseRef column at 2\n\t\t\t\t\tfilterColumn = 2;\n\n\t\t\t\t} else if (name.contains(\"PROVIDER\")) {\n\t\t\t\t\t//CaseRef column at 7\n\t\t\t\t\tfilterColumn = 7;\n\n\t\t\t\t} else {\n\t\t\t\t\t//if no patient column, just copy the file\n\t\t\t\t\tparser.close();\n\n\t\t\t\t\tLOG.info(\"Copying non-patient file \" + sourceFile);\n\t\t\t\t\tcopyFile(sourceFile, destFile);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPrintWriter fw = new PrintWriter(destFile);\n\t\t\t\tBufferedWriter bw = new BufferedWriter(fw);\n\n\t\t\t\tCSVPrinter printer = new CSVPrinter(bw, format);\n\n\t\t\t\tIterator csvIterator = parser.iterator();\n\t\t\t\twhile (csvIterator.hasNext()) {\n\t\t\t\t\tCSVRecord csvRecord = csvIterator.next();\n\n\t\t\t\t\tString caseId = csvRecord.get(filterColumn);\n\t\t\t\t\tif (caseIds.contains(caseId)) {\n\n\t\t\t\t\t\tprinter.printRecord(csvRecord);\n\t\t\t\t\t\tprinter.flush();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparser.close();\n\t\t\t\tprinter.close();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*class ResourceFiler extends FhirResourceFiler {\n\tpublic ResourceFiler(UUID exchangeId, UUID serviceId, UUID systemId, TransformError transformError,\n\t\t\t\t\t\t\t List batchIdsCreated, int maxFilingThreads) {\n\t\tsuper(exchangeId, serviceId, systemId, transformError, batchIdsCreated, maxFilingThreads);\n\t}\n\n\tprivate List newResources = new ArrayList<>();\n\n\tpublic List getNewResources() {\n\t\treturn newResources;\n\t}\n\n\t@Override\n\tpublic void saveAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception {\n\t\tthrow new Exception(\"shouldn't be calling saveAdminResource\");\n\t}\n\n\t@Override\n\tpublic void deleteAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception {\n\t\tthrow new Exception(\"shouldn't be calling deleteAdminResource\");\n\t}\n\n\t@Override\n\tpublic void savePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception {\n\n\t\tfor (Resource resource: resources) {\n\t\t\tif (mapIds) {\n\t\t\t\tIdHelper.mapIds(getServiceId(), getSystemId(), resource);\n\t\t\t}\n\t\t\tnewResources.add(resource);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deletePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception {\n\t\tthrow new Exception(\"shouldn't be calling deletePatientResource\");\n\t}\n}*/\n"},"message":{"kind":"string","value":"New transform repo\n"},"old_file":{"kind":"string","value":"src/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java"},"subject":{"kind":"string","value":"New transform repo"}}},{"rowIdx":1251,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e54a591ddaf20f75f6e7037c98215247e7f73791"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient"},"new_contents":{"kind":"string","value":"package org.sagebionetworks.web.unitserver;\r\n\r\nimport static org.junit.Assert.*;\r\nimport static org.mockito.Matchers.*;\r\nimport static org.mockito.Mockito.*;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.*;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.io.UnsupportedEncodingException;\r\nimport java.net.MalformedURLException;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.Date;\r\nimport java.util.HashSet;\r\nimport java.util.LinkedList;\r\nimport java.util.List;\r\nimport java.util.NoSuchElementException;\r\nimport java.util.Set;\r\n\r\nimport javax.servlet.ServletConfig;\r\nimport javax.servlet.ServletContext;\r\nimport javax.servlet.ServletException;\r\n\r\nimport org.json.JSONArray;\r\nimport org.json.JSONException;\r\nimport org.json.JSONObject;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.mockito.ArgumentCaptor;\r\nimport org.mockito.Matchers;\r\nimport org.mockito.Mock;\r\nimport org.mockito.Mockito;\r\nimport org.mockito.MockitoAnnotations;\r\nimport org.sagebionetworks.client.SynapseClient;\r\nimport org.sagebionetworks.client.exceptions.SynapseBadRequestException;\r\nimport org.sagebionetworks.client.exceptions.SynapseException;\r\nimport org.sagebionetworks.client.exceptions.SynapseNotFoundException;\r\nimport org.sagebionetworks.evaluation.model.Evaluation;\r\nimport org.sagebionetworks.evaluation.model.EvaluationStatus;\r\nimport org.sagebionetworks.evaluation.model.UserEvaluationPermissions;\r\nimport org.sagebionetworks.reflection.model.PaginatedResults;\r\nimport org.sagebionetworks.repo.model.*;\r\n\r\nimport org.sagebionetworks.repo.model.auth.UserEntityPermissions;\r\nimport org.sagebionetworks.repo.model.doi.Doi;\r\nimport org.sagebionetworks.repo.model.doi.DoiStatus;\r\nimport org.sagebionetworks.repo.model.entity.query.SortDirection;\r\nimport org.sagebionetworks.repo.model.file.BatchFileHandleCopyRequest;\r\nimport org.sagebionetworks.repo.model.file.BatchFileHandleCopyResult;\r\nimport org.sagebionetworks.repo.model.file.CompleteAllChunksRequest;\r\nimport org.sagebionetworks.repo.model.file.ExternalFileHandle;\r\nimport org.sagebionetworks.repo.model.file.FileHandleCopyRequest;\r\nimport org.sagebionetworks.repo.model.file.FileHandleCopyResult;\r\nimport org.sagebionetworks.repo.model.file.FileHandleResults;\r\nimport org.sagebionetworks.repo.model.file.FileResultFailureCode;\r\nimport org.sagebionetworks.repo.model.file.S3FileHandle;\r\nimport org.sagebionetworks.repo.model.file.State;\r\nimport org.sagebionetworks.repo.model.file.UploadDaemonStatus;\r\nimport org.sagebionetworks.repo.model.file.UploadDestination;\r\nimport org.sagebionetworks.repo.model.message.MessageToUser;\r\nimport org.sagebionetworks.repo.model.message.NotificationSettingsSignedToken;\r\nimport org.sagebionetworks.repo.model.message.Settings;\r\nimport org.sagebionetworks.repo.model.principal.AddEmailInfo;\r\nimport org.sagebionetworks.repo.model.principal.PrincipalAliasRequest;\r\nimport org.sagebionetworks.repo.model.principal.PrincipalAliasResponse;\r\nimport org.sagebionetworks.repo.model.project.ExternalS3StorageLocationSetting;\r\nimport org.sagebionetworks.repo.model.project.ExternalStorageLocationSetting;\r\nimport org.sagebionetworks.repo.model.project.ProjectSetting;\r\nimport org.sagebionetworks.repo.model.project.ProjectSettingsType;\r\nimport org.sagebionetworks.repo.model.project.StorageLocationSetting;\r\nimport org.sagebionetworks.repo.model.project.UploadDestinationListSetting;\r\nimport org.sagebionetworks.repo.model.provenance.Activity;\r\nimport org.sagebionetworks.repo.model.quiz.PassingRecord;\r\nimport org.sagebionetworks.repo.model.quiz.Quiz;\r\nimport org.sagebionetworks.repo.model.quiz.QuizResponse;\r\nimport org.sagebionetworks.repo.model.table.ColumnChange;\r\nimport org.sagebionetworks.repo.model.table.ColumnModel;\r\nimport org.sagebionetworks.repo.model.table.ColumnType;\r\nimport org.sagebionetworks.repo.model.table.TableSchemaChangeRequest;\r\nimport org.sagebionetworks.repo.model.table.TableUpdateRequest;\r\nimport org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest;\r\nimport org.sagebionetworks.repo.model.table.ViewType;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;\r\nimport org.sagebionetworks.repo.model.wiki.WikiHeader;\r\nimport org.sagebionetworks.repo.model.wiki.WikiPage;\r\nimport org.sagebionetworks.schema.adapter.AdapterFactory;\r\nimport org.sagebionetworks.schema.adapter.JSONObjectAdapterException;\r\nimport org.sagebionetworks.schema.adapter.org.json.AdapterFactoryImpl;\r\nimport org.sagebionetworks.schema.adapter.org.json.EntityFactory;\r\nimport org.sagebionetworks.util.SerializationUtils;\r\nimport org.sagebionetworks.web.client.view.TeamRequestBundle;\r\nimport org.sagebionetworks.web.server.servlet.MarkdownCacheRequest;\r\nimport org.sagebionetworks.web.server.servlet.NotificationTokenType;\r\nimport org.sagebionetworks.web.server.servlet.ServiceUrlProvider;\r\nimport org.sagebionetworks.web.server.servlet.SynapseClientImpl;\r\nimport org.sagebionetworks.web.server.servlet.SynapseProvider;\r\nimport org.sagebionetworks.web.server.servlet.TokenProvider;\r\nimport org.sagebionetworks.web.shared.AccessRequirementUtils;\r\nimport org.sagebionetworks.web.shared.EntityBundlePlus;\r\nimport org.sagebionetworks.web.shared.OpenTeamInvitationBundle;\r\nimport org.sagebionetworks.web.shared.ProjectPagedResults;\r\nimport org.sagebionetworks.web.shared.TeamBundle;\r\nimport org.sagebionetworks.web.shared.TeamMemberBundle;\r\nimport org.sagebionetworks.web.shared.TeamMemberPagedResults;\r\nimport org.sagebionetworks.web.shared.WikiPageKey;\r\nimport org.sagebionetworks.web.shared.exceptions.BadRequestException;\r\nimport org.sagebionetworks.web.shared.exceptions.ConflictException;\r\nimport org.sagebionetworks.web.shared.exceptions.NotFoundException;\r\nimport org.sagebionetworks.web.shared.exceptions.RestServiceException;\r\nimport org.sagebionetworks.web.shared.exceptions.UnauthorizedException;\r\nimport org.sagebionetworks.web.shared.exceptions.UnknownErrorException;\r\nimport org.sagebionetworks.web.shared.users.AclUtils;\r\nimport org.sagebionetworks.web.shared.users.PermissionLevel;\r\n\r\nimport com.google.appengine.repackaged.com.google.common.base.Objects;\r\nimport com.google.common.cache.Cache;\r\n\r\n/**\r\n * Test for the SynapseClientImpl\r\n * \r\n * @author John\r\n * \r\n */\r\npublic class SynapseClientImplTest {\r\n\tprivate static final String BANNER_2 = \"Another Banner\";\r\n\tprivate static final String BANNER_1 = \"Banner 1\";\r\n\tpublic static final String TEST_HOME_PAGE_BASE = \"http://mysynapse.org/\";\r\n\tpublic static final String MY_USER_PROFILE_OWNER_ID = \"MyOwnerID\";\r\n\t\r\n\tSynapseProvider mockSynapseProvider;\r\n\tTokenProvider mockTokenProvider;\r\n\tServiceUrlProvider mockUrlProvider;\r\n\tSynapseClient mockSynapse;\r\n\tSynapseClientImpl synapseClient;\r\n\tString entityId = \"123\";\r\n\tString inviteeUserId = \"900\";\r\n\tUserProfile inviteeUserProfile;\r\n\tExampleEntity entity;\r\n\tAnnotations annos;\r\n\tUserEntityPermissions eup;\r\n\tUserEvaluationPermissions userEvaluationPermissions;\r\n\tList batchHeaderResults;\r\n\r\n\tString testFileName = \"testFileEntity.R\";\r\n\tEntityPath path;\r\n\torg.sagebionetworks.reflection.model.PaginatedResults pgugs;\r\n\torg.sagebionetworks.reflection.model.PaginatedResults pgups;\r\n\torg.sagebionetworks.reflection.model.PaginatedResults pguts;\r\n\tTeam teamA, teamZ;\r\n\tAccessControlList acl;\r\n\tWikiPage page;\r\n\tV2WikiPage v2Page;\r\n\tS3FileHandle handle;\r\n\tEvaluation mockEvaluation;\r\n\tUserSessionData mockUserSessionData;\r\n\tUserProfile mockUserProfile;\r\n\tMembershipInvtnSubmission testInvitation;\r\n\tPaginatedResults mockPaginatedMembershipRequest;\r\n\tActivity mockActivity;\r\n\r\n\tMessageToUser sentMessage;\r\n\tLong storageLocationId = 9090L;\r\n\tUserProfile testUserProfile;\r\n\tLong version = 1L;\r\n\t\r\n\t//Token testing\r\n\tNotificationSettingsSignedToken notificationSettingsToken;\r\n\tJoinTeamSignedToken joinTeamToken;\r\n\tString encodedJoinTeamToken, encodedNotificationSettingsToken;\r\n\t\r\n\t@Mock\r\n\tUserGroupHeaderResponsePage mockUserGroupHeaderResponsePage;\r\n\t@Mock\r\n\tUserGroupHeader mockUserGroupHeader;\r\n\t@Mock\r\n\tPrincipalAliasResponse mockPrincipalAliasResponse;\r\n\t@Mock\r\n\tColumnModel mockOldColumnModel;\r\n\t@Mock\r\n\tColumnModel mockNewColumnModel;\r\n\t@Mock\r\n\tColumnModel mockNewColumnModelAfterCreate;\r\n\t\r\n\t@Mock\r\n\tBatchFileHandleCopyResult mockBatchCopyResults;\r\n\t@Mock\r\n\tFileHandleCopyResult mockFileHandleCopyResult;\r\n\t@Mock\r\n\tFileEntity mockFileEntity;\r\n\t@Mock\r\n\tFileHandleCopyRequest mockFileHandleCopyRequest;\r\n\tList batchCopyResultsList;\r\n\t\r\n\t\r\n\tpublic static final String OLD_COLUMN_MODEL_ID = \"4444\";\r\n\tpublic static final String NEW_COLUMN_MODEL_ID = \"837837\";\r\n\tprivate static final String testUserId = \"myUserId\";\r\n\r\n\tprivate static final String EVAL_ID_1 = \"eval ID 1\";\r\n\tprivate static final String EVAL_ID_2 = \"eval ID 2\";\r\n\tprivate static AdapterFactory adapterFactory = new AdapterFactoryImpl();\r\n\tprivate TeamMembershipStatus membershipStatus;\r\n\r\n\t@Before\r\n\tpublic void before() throws SynapseException, JSONObjectAdapterException {\r\n\t\tMockitoAnnotations.initMocks(this);\r\n\t\tmockSynapse = Mockito.mock(SynapseClient.class);\r\n\t\tmockSynapseProvider = Mockito.mock(SynapseProvider.class);\r\n\t\tmockUrlProvider = Mockito.mock(ServiceUrlProvider.class);\r\n\t\twhen(mockSynapseProvider.createNewClient()).thenReturn(mockSynapse);\r\n\t\tmockTokenProvider = Mockito.mock(TokenProvider.class);\r\n\t\tmockPaginatedMembershipRequest = Mockito.mock(PaginatedResults.class);\r\n\t\tmockActivity = Mockito.mock(Activity.class);\r\n\t\twhen(mockPaginatedMembershipRequest.getTotalNumberOfResults()).thenReturn(3L);\r\n\t\tsynapseClient = new SynapseClientImpl();\r\n\t\tsynapseClient.setSynapseProvider(mockSynapseProvider);\r\n\t\tsynapseClient.setTokenProvider(mockTokenProvider);\r\n\t\tsynapseClient.setServiceUrlProvider(mockUrlProvider);\r\n\r\n\t\t// Setup the the entity\r\n\t\tentity = new ExampleEntity();\r\n\t\tentity.setId(entityId);\r\n\t\tentity.setEntityType(ExampleEntity.class.getName());\r\n\t\tentity.setModifiedBy(testUserId);\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getEntityById(entityId)).thenReturn(entity);\r\n\t\t// Setup the annotations\r\n\t\tannos = new Annotations();\r\n\t\tannos.setId(entityId);\r\n\t\tannos.addAnnotation(\"string\", \"a string value\");\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getAnnotations(entityId)).thenReturn(annos);\r\n\t\t// Setup the Permissions\r\n\t\teup = new UserEntityPermissions();\r\n\t\teup.setCanDelete(true);\r\n\t\teup.setCanView(false);\r\n\t\teup.setOwnerPrincipalId(999L);\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getUsersEntityPermissions(entityId)).thenReturn(eup);\r\n\r\n\t\t// user can change permissions on eval 2, but not on 1\r\n\t\tuserEvaluationPermissions = new UserEvaluationPermissions();\r\n\t\tuserEvaluationPermissions.setCanChangePermissions(false);\r\n\t\twhen(mockSynapse.getUserEvaluationPermissions(EVAL_ID_1)).thenReturn(\r\n\t\t\t\tuserEvaluationPermissions);\r\n\r\n\t\tuserEvaluationPermissions = new UserEvaluationPermissions();\r\n\t\tuserEvaluationPermissions.setCanChangePermissions(true);\r\n\t\twhen(mockSynapse.getUserEvaluationPermissions(EVAL_ID_2)).thenReturn(\r\n\t\t\t\tuserEvaluationPermissions);\r\n\t\twhen(mockOldColumnModel.getId()).thenReturn(OLD_COLUMN_MODEL_ID);\r\n\t\twhen(mockNewColumnModelAfterCreate.getId()).thenReturn(NEW_COLUMN_MODEL_ID);\r\n\t\t\r\n\t\t// Setup the path\r\n\t\tpath = new EntityPath();\r\n\t\tpath.setPath(new ArrayList());\r\n\t\tEntityHeader header = new EntityHeader();\r\n\t\theader.setId(entityId);\r\n\t\theader.setName(\"RomperRuuuu\");\r\n\t\tpath.getPath().add(header);\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getEntityPath(entityId)).thenReturn(path);\r\n\r\n\t\tpgugs = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tList ugs = new ArrayList();\r\n\t\tugs.add(new UserGroup());\r\n\t\tpgugs.setResults(ugs);\r\n\t\twhen(mockSynapse.getGroups(anyInt(), anyInt())).thenReturn(pgugs);\r\n\r\n\t\tpgups = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tList ups = new ArrayList();\r\n\t\tups.add(new UserProfile());\r\n\t\tpgups.setResults(ups);\r\n\t\twhen(mockSynapse.getUsers(anyInt(), anyInt())).thenReturn(pgups);\r\n\r\n\t\tpguts = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tList uts = new ArrayList();\r\n\t\tteamZ = new Team();\r\n\t\tteamZ.setId(\"1\");\r\n\t\tteamZ.setName(\"zygote\");\r\n\t\tuts.add(teamZ);\r\n\t\tteamA = new Team();\r\n\t\tteamA.setId(\"2\");\r\n\t\tteamA.setName(\"Amplitude\");\r\n\t\tuts.add(teamA);\r\n\t\tpguts.setResults(uts);\r\n\t\twhen(mockSynapse.getTeamsForUser(anyString(), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(pguts);\r\n\r\n\t\tacl = new AccessControlList();\r\n\t\tacl.setId(\"sys999\");\r\n\t\tSet ras = new HashSet();\r\n\t\tResourceAccess ra = new ResourceAccess();\r\n\t\tra.setPrincipalId(101L);\r\n\t\tra.setAccessType(AclUtils\r\n\t\t\t\t.getACCESS_TYPEs(PermissionLevel.CAN_ADMINISTER));\r\n\t\tacl.setResourceAccess(ras);\r\n\t\twhen(mockSynapse.getACL(anyString())).thenReturn(acl);\r\n\t\twhen(mockSynapse.createACL((AccessControlList) any())).thenReturn(acl);\r\n\t\twhen(mockSynapse.updateACL((AccessControlList) any())).thenReturn(acl);\r\n\t\twhen(mockSynapse.updateACL((AccessControlList) any(), eq(true)))\r\n\t\t\t\t.thenReturn(acl);\r\n\t\twhen(mockSynapse.updateACL((AccessControlList) any(), eq(false)))\r\n\t\t\t\t.thenReturn(acl);\r\n\t\twhen(mockSynapse.updateTeamACL(any(AccessControlList.class))).thenReturn(acl);\r\n\t\twhen(mockSynapse.getTeamACL(anyString())).thenReturn(acl);\r\n\r\n\t\tEntityHeader bene = new EntityHeader();\r\n\t\tbene.setId(\"syn999\");\r\n\t\twhen(mockSynapse.getEntityBenefactor(anyString())).thenReturn(bene);\r\n\r\n\t\torg.sagebionetworks.reflection.model.PaginatedResults batchHeaders = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tbatchHeaderResults = new ArrayList();\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\tEntityHeader h = new EntityHeader();\r\n\t\t\th.setId(\"syn\" + i);\r\n\t\t\tbatchHeaderResults.add(h);\r\n\t\t}\r\n\t\tbatchHeaders.setResults(batchHeaderResults);\r\n\t\twhen(mockSynapse.getEntityHeaderBatch(anyList())).thenReturn(\r\n\t\t\t\tbatchHeaders);\r\n\r\n\t\tList accessRequirements = new ArrayList();\r\n\t\taccessRequirements.add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD));\r\n\r\n\t\tint mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH\r\n\t\t\t\t| HAS_CHILDREN | ACCESS_REQUIREMENTS\r\n\t\t\t\t| UNMET_ACCESS_REQUIREMENTS;\r\n\t\tint emptyMask = 0;\r\n\t\tEntityBundle bundle = new EntityBundle();\r\n\t\tbundle.setEntity(entity);\r\n\t\tbundle.setAnnotations(annos);\r\n\t\tbundle.setPermissions(eup);\r\n\t\tbundle.setPath(path);\r\n\t\tbundle.setHasChildren(false);\r\n\t\tbundle.setAccessRequirements(accessRequirements);\r\n\t\tbundle.setUnmetAccessRequirements(accessRequirements);\r\n\t\tbundle.setBenefactorAcl(acl);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), Matchers.eq(mask)))\r\n\t\t\t\t.thenReturn(bundle);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), Matchers.eq(ENTITY | ANNOTATIONS | ROOT_WIKI_ID | FILE_HANDLES | PERMISSIONS | BENEFACTOR_ACL)))\r\n\t\t\t\t.thenReturn(bundle);\r\n\r\n\t\tEntityBundle emptyBundle = new EntityBundle();\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), Matchers.eq(emptyMask)))\r\n\t\t\t\t.thenReturn(emptyBundle);\r\n\r\n\t\twhen(mockSynapse.canAccess(\"syn101\", ACCESS_TYPE.READ))\r\n\t\t\t\t.thenReturn(true);\r\n\r\n\t\tpage = new WikiPage();\r\n\t\tpage.setId(\"testId\");\r\n\t\tpage.setMarkdown(\"my markdown\");\r\n\t\tpage.setParentWikiId(null);\r\n\t\tpage.setTitle(\"A Title\");\r\n\t\tv2Page = new V2WikiPage();\r\n\t\tv2Page.setId(\"v2TestId\");\r\n\t\tv2Page.setEtag(\"122333\");\r\n\t\thandle = new S3FileHandle();\r\n\t\thandle.setId(\"4422\");\r\n\t\thandle.setBucketName(\"bucket\");\r\n\t\thandle.setFileName(testFileName);\r\n\t\thandle.setKey(\"key\");\r\n\t\twhen(mockSynapse.getRawFileHandle(anyString())).thenReturn(handle);\r\n\t\torg.sagebionetworks.reflection.model.PaginatedResults ars = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tars.setTotalNumberOfResults(0);\r\n\t\tars.setResults(new ArrayList());\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getAccessRequirements(any(RestrictableObjectDescriptor.class)))\r\n\t\t\t\t.thenReturn(ars);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getUnmetAccessRequirements(\r\n\t\t\t\t\t\tany(RestrictableObjectDescriptor.class),\r\n\t\t\t\t\t\tany(ACCESS_TYPE.class))).thenReturn(ars);\r\n\t\tmockEvaluation = Mockito.mock(Evaluation.class);\r\n\t\twhen(mockEvaluation.getStatus()).thenReturn(EvaluationStatus.OPEN);\r\n\t\twhen(mockSynapse.getEvaluation(anyString())).thenReturn(mockEvaluation);\r\n\t\tmockUserSessionData = Mockito.mock(UserSessionData.class);\r\n\t\tmockUserProfile = Mockito.mock(UserProfile.class);\r\n\t\twhen(mockSynapse.getUserSessionData()).thenReturn(mockUserSessionData);\r\n\t\twhen(mockUserSessionData.getProfile()).thenReturn(mockUserProfile);\r\n\t\twhen(mockUserProfile.getOwnerId()).thenReturn(MY_USER_PROFILE_OWNER_ID);\r\n\t\twhen(mockSynapse.getMyProfile()).thenReturn(mockUserProfile);\r\n\t\tUploadDaemonStatus status = new UploadDaemonStatus();\r\n\t\tString fileHandleId = \"myFileHandleId\";\r\n\t\tstatus.setFileHandleId(fileHandleId);\r\n\t\tstatus.setState(State.COMPLETED);\r\n\t\twhen(mockSynapse.getCompleteUploadDaemonStatus(anyString()))\r\n\t\t\t\t.thenReturn(status);\r\n\r\n\t\tstatus = new UploadDaemonStatus();\r\n\t\tstatus.setState(State.PROCESSING);\r\n\t\tstatus.setPercentComplete(.05d);\r\n\t\twhen(mockSynapse.startUploadDeamon(any(CompleteAllChunksRequest.class)))\r\n\t\t\t\t.thenReturn(status);\r\n\r\n\t\tPaginatedResults openInvites = new PaginatedResults();\r\n\t\topenInvites.setTotalNumberOfResults(0);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipInvitations(anyString(),\r\n\t\t\t\t\t\tanyString(), anyLong(), anyLong())).thenReturn(\r\n\t\t\t\topenInvites);\r\n\r\n\t\tPaginatedResults openRequests = new PaginatedResults();\r\n\t\topenRequests.setTotalNumberOfResults(0);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipRequests(anyString(), anyString(),\r\n\t\t\t\t\t\tanyLong(), anyLong())).thenReturn(openRequests);\r\n\t\tmembershipStatus = new TeamMembershipStatus();\r\n\t\tmembershipStatus.setCanJoin(false);\r\n\t\tmembershipStatus.setHasOpenInvitation(false);\r\n\t\tmembershipStatus.setHasOpenRequest(false);\r\n\t\tmembershipStatus.setHasUnmetAccessRequirement(false);\r\n\t\tmembershipStatus.setIsMember(false);\r\n\t\tmembershipStatus.setMembershipApprovalRequired(false);\r\n\t\twhen(mockSynapse.getTeamMembershipStatus(anyString(), anyString()))\r\n\t\t\t\t.thenReturn(membershipStatus);\r\n\r\n\t\tsentMessage = new MessageToUser();\r\n\t\tsentMessage.setId(\"987\");\r\n\t\twhen(mockSynapse.sendMessage(any(MessageToUser.class))).thenReturn(sentMessage);\r\n\t\twhen(mockSynapse.sendMessage(any(MessageToUser.class), anyString())).thenReturn(sentMessage);\r\n\r\n\t\t// getMyProjects getUserProjects\r\n\t\tPaginatedResults headers = new PaginatedResults();\r\n\t\theaders.setTotalNumberOfResults(1100);\r\n\t\tList projectHeaders = new ArrayList();\r\n\t\tList userProfile = new ArrayList();\r\n\t\tprojectHeaders.add(new ProjectHeader());\r\n\t\theaders.setResults(projectHeaders);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getMyProjects(any(ProjectListType.class),\r\n\t\t\t\t\t\tany(ProjectListSortColumn.class),\r\n\t\t\t\t\t\tany(SortDirection.class), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(headers);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getProjectsFromUser(anyLong(),\r\n\t\t\t\t\t\tany(ProjectListSortColumn.class),\r\n\t\t\t\t\t\tany(SortDirection.class), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(headers);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getProjectsForTeam(anyLong(),\r\n\t\t\t\t\t\tany(ProjectListSortColumn.class),\r\n\t\t\t\t\t\tany(SortDirection.class), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(headers);\r\n\t\t\r\n\t\ttestUserProfile = new UserProfile();\r\n\t\ttestUserProfile.setUserName(\"Test User\");\r\n\t\twhen(mockSynapse.getUserProfile(eq(testUserId))).thenReturn(\r\n\t\t\t\ttestUserProfile);\r\n\t\t\r\n\t\tjoinTeamToken = new JoinTeamSignedToken();\r\n\t\tjoinTeamToken.setHmac(\"98765\");\r\n\t\tjoinTeamToken.setMemberId(\"1\");\r\n\t\tjoinTeamToken.setTeamId(\"2\");\r\n\t\tjoinTeamToken.setUserId(\"3\");\r\n\t\tencodedJoinTeamToken = SerializationUtils.serializeAndHexEncode(joinTeamToken);\r\n\t\t\r\n\t\tnotificationSettingsToken = new NotificationSettingsSignedToken();\r\n\t\tnotificationSettingsToken.setHmac(\"987654\");\r\n\t\tnotificationSettingsToken.setSettings(new Settings());\r\n\t\tnotificationSettingsToken.setUserId(\"4\");\r\n\t\tencodedNotificationSettingsToken = SerializationUtils.serializeAndHexEncode(notificationSettingsToken);\r\n\t\t\r\n\t\twhen(mockSynapse.copyFileHandles(any(BatchFileHandleCopyRequest.class))).thenReturn(mockBatchCopyResults);\r\n\t\tbatchCopyResultsList = new ArrayList();\r\n\t\twhen(mockBatchCopyResults.getCopyResults()).thenReturn(batchCopyResultsList);\r\n\t}\r\n\r\n\tprivate AccessRequirement createAccessRequirement(ACCESS_TYPE type) {\r\n\t\tTermsOfUseAccessRequirement accessRequirement = new TermsOfUseAccessRequirement();\r\n\t\taccessRequirement.setConcreteType(TermsOfUseAccessRequirement.class\r\n\t\t\t\t.getName());\r\n\t\tRestrictableObjectDescriptor descriptor = new RestrictableObjectDescriptor();\r\n\t\tdescriptor.setId(\"101\");\r\n\t\tdescriptor.setType(RestrictableObjectType.ENTITY);\r\n\t\taccessRequirement.setSubjectIds(Arrays\r\n\t\t\t\t.asList(new RestrictableObjectDescriptor[] { descriptor }));\r\n\t\taccessRequirement.setAccessType(type);\r\n\t\treturn accessRequirement;\r\n\t}\r\n\r\n\tprivate void setupTeamInvitations() throws SynapseException {\r\n\t\tArrayList testInvitations = new ArrayList();\r\n\t\ttestInvitation = new MembershipInvtnSubmission();\r\n\t\ttestInvitation.setId(\"628319\");\r\n\t\ttestInvitation.setInviteeId(inviteeUserId);\r\n\t\ttestInvitations.add(testInvitation);\r\n\t\tPaginatedResults paginatedInvitations = new PaginatedResults();\r\n\t\tpaginatedInvitations.setResults(testInvitations);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipInvitationSubmissions(anyString(),\r\n\t\t\t\t\t\tanyString(), anyLong(), anyLong())).thenReturn(\r\n\t\t\t\tpaginatedInvitations);\r\n\r\n\t\tinviteeUserProfile = new UserProfile();\r\n\t\tinviteeUserProfile.setUserName(\"Invitee User\");\r\n\t\tinviteeUserProfile.setOwnerId(inviteeUserId);\r\n\t\twhen(mockSynapse.getUserProfile(eq(inviteeUserId))).thenReturn(\r\n\t\t\t\tinviteeUserProfile);\r\n\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityBundleAll() throws RestServiceException {\r\n\t\t// Make sure we can get all parts of the bundel\r\n\t\tint mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH\r\n\t\t\t\t| HAS_CHILDREN | ACCESS_REQUIREMENTS\r\n\t\t\t\t| UNMET_ACCESS_REQUIREMENTS;\r\n\t\tEntityBundle bundle = synapseClient.getEntityBundle(entityId, mask);\r\n\t\tassertNotNull(bundle);\r\n\t\t// We should have all of the strings\r\n\t\tassertNotNull(bundle.getEntity());\r\n\t\tassertNotNull(bundle.getAnnotations());\r\n\t\tassertNotNull(bundle.getPath());\r\n\t\tassertNotNull(bundle.getPermissions());\r\n\t\tassertNotNull(bundle.getHasChildren());\r\n\t\tassertNotNull(bundle.getAccessRequirements());\r\n\t\tassertNotNull(bundle.getUnmetAccessRequirements());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityBundleNone() throws RestServiceException {\r\n\t\t// Make sure all are null\r\n\t\tint mask = 0x0;\r\n\t\tEntityBundle bundle = synapseClient.getEntityBundle(entityId, mask);\r\n\t\tassertNotNull(bundle);\r\n\t\t// We should have all of the strings\r\n\t\tassertNull(bundle.getEntity());\r\n\t\tassertNull(bundle.getAnnotations());\r\n\t\tassertNull(bundle.getPath());\r\n\t\tassertNull(bundle.getPermissions());\r\n\t\tassertNull(bundle.getHasChildren());\r\n\t\tassertNull(bundle.getAccessRequirements());\r\n\t\tassertNull(bundle.getUnmetAccessRequirements());\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testParseEntityFromJsonNoType()\r\n\t\t\tthrows JSONObjectAdapterException {\r\n\t\tExampleEntity example = new ExampleEntity();\r\n\t\texample.setName(\"some name\");\r\n\t\texample.setDescription(\"some description\");\r\n\t\t// do not set the type\r\n\t\tString json = EntityFactory.createJSONStringForEntity(example);\r\n\t\t// This will fail as the type is required\r\n\t\tsynapseClient.parseEntityFromJson(json);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testParseEntityFromJson() throws JSONObjectAdapterException {\r\n\t\tExampleEntity example = new ExampleEntity();\r\n\t\texample.setName(\"some name\");\r\n\t\texample.setDescription(\"some description\");\r\n\t\texample.setEntityType(ExampleEntity.class.getName());\r\n\t\tString json = EntityFactory.createJSONStringForEntity(example);\r\n\t\t// System.out.println(json);\r\n\t\t// Now make sure this can be read back\r\n\t\tExampleEntity clone = (ExampleEntity) synapseClient\r\n\t\t\t\t.parseEntityFromJson(json);\r\n\t\tassertEquals(example, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateOrUpdateEntityFalse()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setDescription(\"some description\");\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setDescription(\"some description\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(\"syn123\");\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.putEntity(in)).thenReturn(out);\r\n\t\tString result = synapseClient.createOrUpdateEntity(in, null, false);\r\n\t\tassertEquals(out.getId(), result);\r\n\t\tverify(mockSynapse).putEntity(in);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateOrUpdateEntityTrue()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setDescription(\"some description\");\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setDescription(\"some description\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(\"syn123\");\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.createEntity(in)).thenReturn(out);\r\n\t\tString result = synapseClient.createOrUpdateEntity(in, null, true);\r\n\t\tassertEquals(out.getId(), result);\r\n\t\tverify(mockSynapse).createEntity(in);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateOrUpdateEntityTrueWithAnnos()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setDescription(\"some description\");\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tAnnotations annos = new Annotations();\r\n\t\tannos.addAnnotation(\"someString\", \"one\");\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setDescription(\"some description\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(\"syn123\");\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.createEntity(in)).thenReturn(out);\r\n\t\tString result = synapseClient.createOrUpdateEntity(in, annos, true);\r\n\t\tassertEquals(out.getId(), result);\r\n\t\tverify(mockSynapse).createEntity(in);\r\n\t\tannos.setEtag(out.getEtag());\r\n\t\tannos.setId(out.getId());\r\n\t\tverify(mockSynapse).updateAnnotations(out.getId(), annos);\r\n\t}\r\n\r\n\t\r\n\r\n\t@Test\r\n\tpublic void testMoveEntity()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tString oldParentId = \"syn1\", newParentId = \"syn2\";\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setParentId(oldParentId);\r\n\t\tin.setId(entityId);\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(entityId);\r\n\t\tout.setParentId(newParentId);\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.putEntity(in)).thenReturn(out);\r\n\t\twhen(mockSynapse.getEntityById(entityId)).thenReturn(in);\r\n\t\tEntity result = synapseClient.moveEntity(entityId, newParentId);\r\n\t\tassertEquals(newParentId, result.getParentId());\r\n\t\tverify(mockSynapse).getEntityById(entityId);\r\n\t\tverify(mockSynapse).putEntity(any(Entity.class));\r\n\t}\r\n\t@Test\r\n\tpublic void testGetEntityBenefactorAcl() throws Exception {\r\n\t\tEntityBundle bundle = new EntityBundle();\r\n\t\tbundle.setBenefactorAcl(acl);\r\n\t\twhen(mockSynapse.getEntityBundle(\"syn101\", EntityBundle.BENEFACTOR_ACL))\r\n\t\t\t\t.thenReturn(bundle);\r\n\t\tAccessControlList clone = synapseClient\r\n\t\t\t\t.getEntityBenefactorAcl(\"syn101\");\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateAcl() throws Exception {\r\n\t\tAccessControlList clone = synapseClient.createAcl(acl);\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateAcl() throws Exception {\r\n\t\tAccessControlList clone = synapseClient.updateAcl(acl);\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateAclRecursive() throws Exception {\r\n\t\tAccessControlList clone = synapseClient.updateAcl(acl, true);\r\n\t\tassertEquals(acl, clone);\r\n\t\tverify(mockSynapse).updateACL(any(AccessControlList.class), eq(true));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testDeleteAcl() throws Exception {\r\n\t\tEntityBundle bundle = new EntityBundle();\r\n\t\tbundle.setBenefactorAcl(acl);\r\n\t\twhen(mockSynapse.getEntityBundle(\"syn101\", EntityBundle.BENEFACTOR_ACL))\r\n\t\t\t\t.thenReturn(bundle);\r\n\t\tAccessControlList clone = synapseClient.deleteAcl(\"syn101\");\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testHasAccess() throws Exception {\r\n\t\tassertTrue(synapseClient.hasAccess(\"syn101\", \"READ\"));\r\n\t}\r\n\r\n\r\n\t@Test\r\n\tpublic void testGetUserProfile() throws Exception {\r\n\t\t// verify call is directly calling the synapse client provider\r\n\t\tString testRepoUrl = \"http://mytestrepourl\";\r\n\t\twhen(mockUrlProvider.getRepositoryServiceUrl()).thenReturn(testRepoUrl);\r\n\t\tUserProfile userProfile = synapseClient.getUserProfile(testUserId);\r\n\t\tassertEquals(userProfile, testUserProfile);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetProjectById() throws Exception {\r\n\t\tString projectId = \"syn1029\";\r\n\t\tProject project = new Project();\r\n\t\tproject.setId(projectId);\r\n\t\twhen(mockSynapse.getEntityById(projectId)).thenReturn(project);\r\n\r\n\t\tProject actualProject = synapseClient.getProject(projectId);\r\n\t\tassertEquals(project, actualProject);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetJSONEntity() throws Exception {\r\n\r\n\t\tJSONObject json = EntityFactory.createJSONObjectForEntity(entity);\r\n\t\tMockito.when(mockSynapse.getEntity(anyString())).thenReturn(json);\r\n\r\n\t\tString testRepoUri = \"/testservice\";\r\n\r\n\t\tsynapseClient.getJSONEntity(testRepoUri);\r\n\t\t// verify that this call uses Synapse.getEntity(testRepoUri)\r\n\t\tverify(mockSynapse).getEntity(testRepoUri);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetWikiHeaderTree() throws Exception {\r\n\t\tPaginatedResults headerTreeResults = new PaginatedResults();\r\n\t\twhen(mockSynapse.getWikiHeaderTree(anyString(), any(ObjectType.class)))\r\n\t\t\t\t.thenReturn(headerTreeResults);\r\n\t\tsynapseClient.getWikiHeaderTree(\"testId\", ObjectType.ENTITY.toString());\r\n\t\tverify(mockSynapse).getWikiHeaderTree(anyString(),\r\n\t\t\t\teq(ObjectType.ENTITY));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetWikiAttachmentHandles() throws Exception {\r\n\t\tFileHandleResults testResults = new FileHandleResults();\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getWikiAttachmenthHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(testResults);\r\n\t\tsynapseClient.getWikiAttachmentHandles(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getWikiAttachmenthHandles(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testDeleteV2WikiPage() throws Exception {\r\n\t\tsynapseClient.deleteV2WikiPage(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).deleteV2WikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiPage() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.getV2WikiPage(new WikiPageKey(\"syn123\", ObjectType.ENTITY\r\n\t\t\t\t.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getV2WikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiPage(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(v2Page);\r\n\t\tsynapseClient.getVersionOfV2WikiPage(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).getVersionOfV2WikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateV2WikiPage() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.updateV2WikiPage(anyString(),\r\n\t\t\t\t\t\tany(ObjectType.class), any(V2WikiPage.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.updateV2WikiPage(\"testId\", ObjectType.ENTITY.toString(),\r\n\t\t\t\tv2Page);\r\n\t\tverify(mockSynapse).updateV2WikiPage(anyString(),\r\n\t\t\t\tany(ObjectType.class), any(V2WikiPage.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRestoreV2WikiPage() throws Exception {\r\n\t\tString wikiId = \"syn123\";\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.restoreV2WikiPage(anyString(),\r\n\t\t\t\t\t\tany(ObjectType.class), any(String.class), anyLong()))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.restoreV2WikiPage(\"ownerId\",\r\n\t\t\t\tObjectType.ENTITY.toString(), wikiId, new Long(2));\r\n\t\tverify(mockSynapse).restoreV2WikiPage(anyString(),\r\n\t\t\t\tany(ObjectType.class), any(String.class), anyLong());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiHeaderTree() throws Exception {\r\n\t\tPaginatedResults headerTreeResults = new PaginatedResults();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getV2WikiHeaderTree(anyString(),\r\n\t\t\t\t\t\tany(ObjectType.class))).thenReturn(headerTreeResults);\r\n\t\tsynapseClient.getV2WikiHeaderTree(\"testId\",\r\n\t\t\t\tObjectType.ENTITY.toString());\r\n\t\tverify(mockSynapse).getV2WikiHeaderTree(anyString(),\r\n\t\t\t\tany(ObjectType.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiOrderHint() throws Exception {\r\n\t\tV2WikiOrderHint orderHint = new V2WikiOrderHint();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2OrderHint(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(orderHint);\r\n\t\tsynapseClient.getV2WikiOrderHint(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getV2OrderHint(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateV2WikiOrderHint() throws Exception {\r\n\t\tV2WikiOrderHint orderHint = new V2WikiOrderHint();\r\n\t\twhen(mockSynapse.updateV2WikiOrderHint(any(V2WikiOrderHint.class)))\r\n\t\t\t\t.thenReturn(orderHint);\r\n\t\tsynapseClient.updateV2WikiOrderHint(orderHint);\r\n\t\tverify(mockSynapse).updateV2WikiOrderHint(any(V2WikiOrderHint.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiHistory() throws Exception {\r\n\t\tPaginatedResults historyResults = new PaginatedResults();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiHistory(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class), any(Long.class))).thenReturn(\r\n\t\t\t\thistoryResults);\r\n\t\tsynapseClient.getV2WikiHistory(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(10), new Long(0));\r\n\t\tverify(mockSynapse).getV2WikiHistory(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class), any(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiAttachmentHandles() throws Exception {\r\n\t\tFileHandleResults testResults = new FileHandleResults();\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiAttachmentHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(testResults);\r\n\t\tsynapseClient.getV2WikiAttachmentHandles(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getV2WikiAttachmentHandles(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiAttachmentHandles(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(testResults);\r\n\t\tsynapseClient.getVersionOfV2WikiAttachmentHandles(new WikiPageKey(\r\n\t\t\t\t\"syn123\", ObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).getVersionOfV2WikiAttachmentHandles(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testZipAndUpload() throws IOException, RestServiceException,\r\n\t\t\tJSONObjectAdapterException, SynapseException {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createFileHandle(any(File.class), any(String.class)))\r\n\t\t\t\t.thenReturn(handle);\r\n\t\tsynapseClient.zipAndUploadFile(\"markdown\", \"fileName\");\r\n\t\tverify(mockSynapse)\r\n\t\t\t\t.createFileHandle(any(File.class), any(String.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetMarkdown() throws IOException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tString someMarkDown = \"someMarkDown\";\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.downloadV2WikiMarkdown(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(someMarkDown);\r\n\t\tsynapseClient.getMarkdown(new WikiPageKey(\"syn123\", ObjectType.ENTITY\r\n\t\t\t\t.toString(), \"20\"));\r\n\t\tverify(mockSynapse).downloadV2WikiMarkdown(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.downloadVersionOfV2WikiMarkdown(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(someMarkDown);\r\n\t\tsynapseClient.getVersionOfMarkdown(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).downloadVersionOfV2WikiMarkdown(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateV2WikiPageWithV1() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.createWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\t\t\tany(WikiPage.class))).thenReturn(page);\r\n\t\tsynapseClient.createV2WikiPageWithV1(\"testId\",\r\n\t\t\t\tObjectType.ENTITY.toString(), page);\r\n\t\tverify(mockSynapse).createWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\tany(WikiPage.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateV2WikiPageWithV1() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.updateWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\t\t\tany(WikiPage.class))).thenReturn(page);\r\n\t\tsynapseClient.updateV2WikiPageWithV1(\"testId\",\r\n\t\t\t\tObjectType.ENTITY.toString(), page);\r\n\t\tverify(mockSynapse).updateWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\tany(WikiPage.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void getV2WikiPageAsV1() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getWikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.getV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getWikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t\t// asking for the same page twice should result in a cache hit, and it\r\n\t\t// should not ask for it from the synapse client\r\n\t\tsynapseClient.getV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse, Mockito.times(1)).getWikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getWikiPageForVersion(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiPage(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tanyLong())).thenReturn(v2Page);\r\n\t\tsynapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).getWikiPageForVersion(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t\t// asking for the same page twice should result in a cache hit, and it\r\n\t\t// should not ask for it from the synapse client\r\n\t\tsynapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse, Mockito.times(1)).getWikiPageForVersion(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\tprivate void resetUpdateExternalFileHandleMocks(String testId,\r\n\t\t\tFileEntity file, ExternalFileHandle handle)\r\n\t\t\tthrows SynapseException, JSONObjectAdapterException {\r\n\t\treset(mockSynapse);\r\n\t\twhen(mockSynapse.getEntityById(testId)).thenReturn(file);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createExternalFileHandle(any(ExternalFileHandle.class)))\r\n\t\t\t\t.thenReturn(handle);\r\n\t\twhen(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateExternalFileHandle() throws Exception {\r\n\t\t// verify call is directly calling the synapse client provider, and it\r\n\t\t// tries to rename the entity to the filename\r\n\t\tString myFileName = \"testFileName.csv\";\r\n\t\tString testUrl = \" http://mytesturl/\" + myFileName;\r\n\t\tString testId = \"myTestId\";\r\n\t\tString md5 = \"e10e3f4491440ce7b48edc97f03307bb\";\r\n\t\tLong fileSize=2048L;\r\n\t\tFileEntity file = new FileEntity();\r\n\t\tString originalFileEntityName = \"syn1223\";\r\n\t\tfile.setName(originalFileEntityName);\r\n\t\tfile.setId(testId);\r\n\t\tfile.setDataFileHandleId(\"handle1\");\r\n\t\tExternalFileHandle handle = new ExternalFileHandle();\r\n\t\thandle.setExternalURL(testUrl);\r\n\r\n\t\tresetUpdateExternalFileHandleMocks(testId, file, handle);\r\n\t\tsynapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId);\r\n\r\n\t\tverify(mockSynapse).getEntityById(testId);\r\n\t\t\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(ExternalFileHandle.class);\r\n\t\tverify(mockSynapse).createExternalFileHandle(captor.capture());\r\n\t\tExternalFileHandle capturedValue = captor.getValue();\r\n\t\tassertEquals(testUrl.trim(), capturedValue.getExternalURL());\r\n\t\tassertEquals(md5, capturedValue.getContentMd5());\r\n//\t\tassertEquals(fileSize, capturedValue.getContentSize());\r\n\t\t\r\n\t\tverify(mockSynapse).putEntity(any(FileEntity.class));\r\n\r\n\t\t// and if rename fails, verify all is well (but the FileEntity name is\r\n\t\t// not updated)\r\n\t\tresetUpdateExternalFileHandleMocks(testId, file, handle);\r\n\t\tfile.setName(originalFileEntityName);\r\n\t\t// first call should return file, second call to putEntity should throw\r\n\t\t// an exception\r\n\t\twhen(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file)\r\n\t\t\t\t.thenThrow(\r\n\t\t\t\t\t\tnew IllegalArgumentException(\r\n\t\t\t\t\t\t\t\t\"invalid name for some reason\"));\r\n\t\tsynapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId);\r\n\r\n\t\t// called createExternalFileHandle\r\n\t\tverify(mockSynapse).createExternalFileHandle(\r\n\t\t\t\tany(ExternalFileHandle.class));\r\n\t\t// and it should have called putEntity again\r\n\t\tverify(mockSynapse).putEntity(any(FileEntity.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateExternalFile() throws Exception {\r\n\t\t// test setting file handle name\r\n\t\tString parentEntityId = \"syn123333\";\r\n\t\tString externalUrl = \" sftp://foobar.edu/b/test.txt\";\r\n\t\tString fileName = \"testing.txt\";\r\n\t\tString md5 = \"e10e3f4491440ce7b48edc97f03307bb\";\r\n\t\tLong fileSize = 1024L;\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createExternalFileHandle(any(ExternalFileHandle.class)))\r\n\t\t\t\t.thenReturn(new ExternalFileHandle());\r\n\t\twhen(mockSynapse.createEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\tnew FileEntity());\r\n\t\tsynapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId);\r\n\t\tArgumentCaptor captor = ArgumentCaptor\r\n\t\t\t\t.forClass(ExternalFileHandle.class);\r\n\t\tverify(mockSynapse).createExternalFileHandle(captor.capture());\r\n\t\tExternalFileHandle handle = captor.getValue();\r\n\t\t// verify name is set\r\n\t\tassertEquals(fileName, handle.getFileName());\r\n\t\tassertEquals(externalUrl.trim(), handle.getExternalURL());\r\n\t\tassertEquals(storageLocationId, handle.getStorageLocationId());\r\n\t\tassertEquals(md5, handle.getContentMd5());\r\n//\t\tassertEquals(fileSize, handle.getContentSize());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testCreateExternalFileAutoname() throws Exception {\r\n\t\t// test setting file handle name\r\n\t\tString parentEntityId = \"syn123333\";\r\n\t\tString externalUrl = \"sftp://foobar.edu/b/test.txt\";\r\n\t\tString expectedAutoFilename = \"test.txt\";\r\n\t\tString fileName = null;\r\n\t\tString md5 = \"e10e3f4491440ce7b48edc97f03307bb\";\r\n\t\tLong fileSize = 1024L;\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createExternalFileHandle(any(ExternalFileHandle.class)))\r\n\t\t\t\t.thenReturn(new ExternalFileHandle());\r\n\t\twhen(mockSynapse.createEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\tnew FileEntity());\r\n\t\tsynapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId);\r\n\t\tArgumentCaptor captor = ArgumentCaptor\r\n\t\t\t\t.forClass(ExternalFileHandle.class);\r\n\t\tverify(mockSynapse).createExternalFileHandle(captor.capture());\r\n\t\tExternalFileHandle handle = captor.getValue();\r\n\t\t// verify name is set\r\n\t\tassertEquals(expectedAutoFilename, handle.getFileName());\r\n\t\tassertEquals(externalUrl, handle.getExternalURL());\r\n\t\tassertEquals(storageLocationId, handle.getStorageLocationId());\r\n\t\tassertEquals(md5, handle.getContentMd5());\r\n\t\t\r\n\t\t//also check the entity name\r\n\t\tArgumentCaptor entityCaptor = ArgumentCaptor.forClass(Entity.class);\r\n\t\tverify(mockSynapse).createEntity(entityCaptor.capture());\r\n\t\tassertEquals(expectedAutoFilename, entityCaptor.getValue().getName());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityDoi() throws Exception {\r\n\t\t// wiring test\r\n\t\tDoi testDoi = new Doi();\r\n\t\ttestDoi.setDoiStatus(DoiStatus.CREATED);\r\n\t\ttestDoi.setId(\"test doi id\");\r\n\t\ttestDoi.setCreatedBy(\"Test User\");\r\n\t\ttestDoi.setCreatedOn(new Date());\r\n\t\ttestDoi.setObjectId(\"syn1234\");\r\n\t\tMockito.when(mockSynapse.getEntityDoi(anyString(), anyLong()))\r\n\t\t\t\t.thenReturn(testDoi);\r\n\t\tsynapseClient.getEntityDoi(\"test entity id\", null);\r\n\t\tverify(mockSynapse).getEntityDoi(anyString(), anyLong());\r\n\t}\r\n\r\n\tprivate FileEntity getTestFileEntity() {\r\n\t\tFileEntity testFileEntity = new FileEntity();\r\n\t\ttestFileEntity.setId(\"5544\");\r\n\t\ttestFileEntity.setName(testFileName);\r\n\t\treturn testFileEntity;\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testGetEntityDoiNotFound() throws Exception {\r\n\t\t// wiring test\r\n\t\tMockito.when(mockSynapse.getEntityDoi(anyString(), anyLong()))\r\n\t\t\t\t.thenThrow(new SynapseNotFoundException());\r\n\t\tsynapseClient.getEntityDoi(\"test entity id\", null);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateDoi() throws Exception {\r\n\t\t// wiring test\r\n\t\tsynapseClient.createDoi(\"test entity id\", null);\r\n\t\tverify(mockSynapse).createEntityDoi(anyString(), anyLong());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetUploadDaemonStatus() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\tsynapseClient.getUploadDaemonStatus(\"daemonId\");\r\n\t\tverify(mockSynapse).getCompleteUploadDaemonStatus(anyString());\r\n\t}\r\n\r\n\t/**\r\n\t * Direct upload tests. Most of the methods are simple pass-throughs to the\r\n\t * Java Synapse client, but completeUpload has additional logic\r\n\t * \r\n\t * @throws JSONObjectAdapterException\r\n\t * @throws SynapseException\r\n\t * @throws RestServiceException\r\n\t */\r\n\t@Test\r\n\tpublic void testCompleteUpload() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\tFileEntity testFileEntity = getTestFileEntity();\r\n\t\twhen(mockSynapse.createEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\ttestFileEntity);\r\n\t\twhen(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\ttestFileEntity);\r\n\r\n\t\t// parent entity has no immediate children\r\n\t\tEntityIdList childEntities = new EntityIdList();\r\n\t\tchildEntities.setIdList(new ArrayList());\r\n\r\n\t\tsynapseClient.setFileEntityFileHandle(null, null, \"parentEntityId\");\r\n\r\n\t\t// it should have tried to create a new entity (since entity id was\r\n\t\t// null)\r\n\t\tverify(mockSynapse).createEntity(any(FileEntity.class));\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testGetFileEntityIdWithSameNameNotFound()\r\n\t\t\tthrows JSONObjectAdapterException, SynapseException,\r\n\t\t\tRestServiceException, JSONException {\r\n\t\tJSONObject queryResult = new JSONObject();\r\n\t\tqueryResult.put(\"totalNumberOfResults\", (long) 0);\r\n\t\twhen(mockSynapse.query(anyString())).thenReturn(queryResult); // TODO\r\n\r\n\t\tString fileEntityId = synapseClient.getFileEntityIdWithSameName(\r\n\t\t\t\ttestFileName, \"parentEntityId\");\r\n\t}\r\n\r\n\t@Test(expected = ConflictException.class)\r\n\tpublic void testGetFileEntityIdWithSameNameConflict()\r\n\t\t\tthrows JSONObjectAdapterException, SynapseException,\r\n\t\t\tRestServiceException, JSONException {\r\n\t\tFolder folder = new Folder();\r\n\t\tfolder.setName(testFileName);\r\n\t\tJSONObject queryResult = new JSONObject();\r\n\t\tJSONArray results = new JSONArray();\r\n\r\n\t\t// Set up results.\r\n\t\tJSONObject objectResult = EntityFactory\r\n\t\t\t\t.createJSONObjectForEntity(folder);\r\n\t\tJSONArray typeArray = new JSONArray();\r\n\t\ttypeArray.put(\"Folder\");\r\n\t\tobjectResult.put(\"entity.concreteType\", typeArray);\r\n\t\tresults.put(objectResult);\r\n\r\n\t\t// Set up query result.\r\n\t\tqueryResult.put(\"totalNumberOfResults\", (long) 1);\r\n\t\tqueryResult.put(\"results\", results);\r\n\r\n\t\t// Have results returned in query.\r\n\t\twhen(mockSynapse.query(anyString())).thenReturn(queryResult);\r\n\r\n\t\tString fileEntityId = synapseClient.getFileEntityIdWithSameName(\r\n\t\t\t\ttestFileName, \"parentEntityId\");\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetFileEntityIdWithSameNameFound() throws JSONException,\r\n\t\t\tJSONObjectAdapterException, SynapseException, RestServiceException {\r\n\t\tFileEntity file = getTestFileEntity();\r\n\t\tJSONObject queryResult = new JSONObject();\r\n\t\tJSONArray results = new JSONArray();\r\n\r\n\t\t// Set up results.\r\n\t\tJSONObject objectResult = EntityFactory.createJSONObjectForEntity(file);\r\n\t\tJSONArray typeArray = new JSONArray();\r\n\t\ttypeArray.put(FileEntity.class.getName());\r\n\t\tobjectResult.put(\"entity.concreteType\", typeArray);\r\n\t\tobjectResult.put(\"entity.id\", file.getId());\r\n\t\tresults.put(objectResult);\r\n\t\tqueryResult.put(\"totalNumberOfResults\", (long) 1);\r\n\t\tqueryResult.put(\"results\", results);\r\n\r\n\t\t// Have results returned in query.\r\n\t\twhen(mockSynapse.query(anyString())).thenReturn(queryResult);\r\n\r\n\t\tString fileEntityId = synapseClient.getFileEntityIdWithSameName(\r\n\t\t\t\ttestFileName, \"parentEntityId\");\r\n\t\tassertEquals(fileEntityId, file.getId());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInviteMemberOpenInvitations() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setHasOpenInvitation(true);\r\n\t\t// verify it does not create a new invitation since one is already open\r\n\t\tsynapseClient.inviteMember(\"123\", \"a team\", \"\", \"\");\r\n\t\tverify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(),\r\n\t\t\t\tanyString(), anyString(), anyString());\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipInvitation(\r\n\t\t\t\tany(MembershipInvtnSubmission.class), anyString(), anyString());\r\n\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRequestMemberOpenRequests() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setHasOpenRequest(true);\r\n\t\t// verify it does not create a new request since one is already open\r\n\t\tsynapseClient.requestMembership(\"123\", \"a team\", \"let me join\", TEST_HOME_PAGE_BASE, null);\r\n\t\tverify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(),\r\n\t\t\t\tanyString(), eq(TEST_HOME_PAGE_BASE+\"#!Team:\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class);\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), anyString(), anyString());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInviteMemberCanJoin() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setCanJoin(true);\r\n\t\tsynapseClient.inviteMember(\"123\", \"a team\", \"\", TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+\"#!Team:\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRequestMembershipCanJoin() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setCanJoin(true);\r\n\t\tsynapseClient.requestMembership(\"123\", \"a team\", \"\", TEST_HOME_PAGE_BASE, new Date());\r\n\t\tverify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+\"#!Team:\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInviteMember() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tsynapseClient.inviteMember(\"123\", \"a team\", \"\", TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).createMembershipInvitation(\r\n\t\t\t\tany(MembershipInvtnSubmission.class), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:JoinTeam/\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRequestMembership() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class);\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), anyString(), anyString());\r\n\t\tString teamId = \"a team\";\r\n\t\tString message= \"let me join\";\r\n\t\tDate expiresOn = null;\r\n\t\tsynapseClient.requestMembership(\"123\", teamId, message, TEST_HOME_PAGE_BASE, expiresOn);\r\n\t\tverify(mockSynapse).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:JoinTeam/\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t\tMembershipRqstSubmission request = captor.getValue();\r\n\t\tassertEquals(expiresOn, request.getExpiresOn());\r\n\t\tassertEquals(teamId, request.getTeamId());\r\n\t\tassertEquals(message, request.getMessage());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testRequestMembershipWithExpiresOn() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class);\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), anyString(), anyString());\r\n\t\tString teamId = \"a team\";\r\n\t\tString message= \"let me join\";\r\n\t\tDate expiresOn = new Date();\r\n\t\tsynapseClient.requestMembership(\"123\", teamId, message, TEST_HOME_PAGE_BASE, expiresOn);\r\n\t\tverify(mockSynapse).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:JoinTeam/\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t\tMembershipRqstSubmission request = captor.getValue();\r\n\t\tassertEquals(expiresOn, request.getExpiresOn());\r\n\t\tassertEquals(teamId, request.getTeamId());\r\n\t\tassertEquals(message, request.getMessage());\r\n\t}\r\n\r\n\r\n\t@Test\r\n\tpublic void testGetOpenRequestCountUnauthorized() throws SynapseException,\r\n\t\t\tRestServiceException {\r\n\t\t// is not an admin\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\ttestTeamMember.setIsAdmin(false);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\r\n\t\tLong count = synapseClient.getOpenRequestCount(\"myUserId\", \"myTeamId\");\r\n\t\t// should never ask for open request count\r\n\t\tverify(mockSynapse, Mockito.never()).getOpenMembershipRequests(\r\n\t\t\t\tanyString(), anyString(), anyLong(), anyLong());\r\n\t\tassertNull(count);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetOpenRequestCount() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\t// is admin\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\ttestTeamMember.setIsAdmin(true);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\r\n\t\tLong testCount = 42L;\r\n\t\tPaginatedResults testOpenRequests = new PaginatedResults();\r\n\t\ttestOpenRequests.setTotalNumberOfResults(testCount);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipRequests(anyString(), anyString(),\r\n\t\t\t\t\t\tanyLong(), anyLong())).thenReturn(testOpenRequests);\r\n\r\n\t\tLong count = synapseClient.getOpenRequestCount(\"myUserId\", \"myTeamId\");\r\n\r\n\t\tverify(mockSynapse, Mockito.times(1)).getOpenMembershipRequests(\r\n\t\t\t\tanyString(), anyString(), anyLong(), anyLong());\r\n\t\tassertEquals(testCount, count);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetOpenTeamInvitations() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tsetupTeamInvitations();\r\n\t\tint limit = 55;\r\n\t\tint offset = 2;\r\n\t\tString teamId = \"132\";\r\n\t\tList invitationBundles = synapseClient\r\n\t\t\t\t.getOpenTeamInvitations(teamId, limit, offset);\r\n\t\tverify(mockSynapse).getOpenMembershipInvitationSubmissions(eq(teamId),\r\n\t\t\t\tanyString(), eq((long) limit), eq((long) offset));\r\n\t\t// we set this up so that a single invite would be returned. Verify that\r\n\t\t// it is the one we're looking for\r\n\t\tassertEquals(1, invitationBundles.size());\r\n\t\tOpenTeamInvitationBundle invitationBundle = invitationBundles.get(0);\r\n\t\tassertEquals(inviteeUserProfile, invitationBundle.getUserProfile());\r\n\t\tassertEquals(testInvitation, invitationBundle.getMembershipInvtnSubmission());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetTeamBundle() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\t// set team member count\r\n\t\tLong testMemberCount = 111L;\r\n\t\tPaginatedResults allMembers = new PaginatedResults();\r\n\t\tallMembers.setTotalNumberOfResults(testMemberCount);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getTeamMembers(anyString(), anyString(), anyLong(),\r\n\t\t\t\t\t\tanyLong())).thenReturn(allMembers);\r\n\r\n\t\t// set team\r\n\t\tTeam team = new Team();\r\n\t\tteam.setId(\"test team id\");\r\n\t\twhen(mockSynapse.getTeam(anyString())).thenReturn(team);\r\n\t\t\r\n\t\t// is member\r\n\t\tTeamMembershipStatus membershipStatus = new TeamMembershipStatus();\r\n\t\tmembershipStatus.setIsMember(true);\r\n\t\twhen(mockSynapse.getTeamMembershipStatus(anyString(), anyString()))\r\n\t\t\t\t.thenReturn(membershipStatus);\r\n\t\t// is admin\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\tboolean isAdmin = true;\r\n\t\ttestTeamMember.setIsAdmin(isAdmin);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\r\n\t\t// make the call\r\n\t\tTeamBundle bundle = synapseClient.getTeamBundle(\"myUserId\", \"myTeamId\",\r\n\t\t\t\ttrue);\r\n\r\n\t\t// now verify round all values were returned in the bundle (based on the\r\n\t\t// mocked service calls)\r\n\t\tassertEquals(team, bundle.getTeam());\r\n\t\tassertEquals(membershipStatus, bundle.getTeamMembershipStatus());\r\n\t\tassertEquals(isAdmin, bundle.isUserAdmin());\r\n\t\tassertEquals(testMemberCount, bundle.getTotalMemberCount());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetTeamMembers() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\t// set team member count\r\n\t\tLong testMemberCount = 111L;\r\n\t\tPaginatedResults allMembers = new PaginatedResults();\r\n\t\tallMembers.setTotalNumberOfResults(testMemberCount);\r\n\t\tList members = new ArrayList();\r\n\r\n\t\tTeamMember member1 = new TeamMember();\r\n\t\tmember1.setIsAdmin(true);\r\n\t\tUserGroupHeader header1 = new UserGroupHeader();\r\n\t\tLong member1Id = 123L;\r\n\t\theader1.setOwnerId(member1Id + \"\");\r\n\t\tmember1.setMember(header1);\r\n\t\tmembers.add(member1);\r\n\r\n\t\tTeamMember member2 = new TeamMember();\r\n\t\tmember2.setIsAdmin(false);\r\n\t\tUserGroupHeader header2 = new UserGroupHeader();\r\n\t\tLong member2Id = 456L;\r\n\t\theader2.setOwnerId(member2Id + \"\");\r\n\t\tmember2.setMember(header2);\r\n\t\tmembers.add(member2);\r\n\r\n\t\tallMembers.setResults(members);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getTeamMembers(anyString(), anyString(), anyLong(),\r\n\t\t\t\t\t\tanyLong())).thenReturn(allMembers);\r\n\r\n\t\tList profiles = new ArrayList();\r\n\t\tUserProfile profile1 = new UserProfile();\r\n\t\tprofile1.setOwnerId(member1Id + \"\");\r\n\t\tUserProfile profile2 = new UserProfile();\r\n\t\tprofile2.setOwnerId(member2Id + \"\");\r\n\t\tprofiles.add(profile1);\r\n\t\tprofiles.add(profile2);\r\n\t\twhen(mockSynapse.listUserProfiles(anyList())).thenReturn(profiles);\r\n\r\n\t\t// make the call\r\n\t\tTeamMemberPagedResults results = synapseClient.getTeamMembers(\r\n\t\t\t\t\"myTeamId\", \"search term\", 100, 0);\r\n\r\n\t\t// verify it results in the two team member bundles that we expect\r\n\t\tList memberBundles = results.getResults();\r\n\t\tassertEquals(2, memberBundles.size());\r\n\t\tTeamMemberBundle bundle1 = memberBundles.get(0);\r\n\t\tassertTrue(bundle1.getIsTeamAdmin());\r\n\t\tassertEquals(profile1, bundle1.getUserProfile());\r\n\t\tTeamMemberBundle bundle2 = memberBundles.get(1);\r\n\t\tassertFalse(bundle2.getIsTeamAdmin());\r\n\t\tassertEquals(profile2, bundle2.getUserProfile());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testIsTeamMember() throws NumberFormatException, RestServiceException, SynapseException {\r\n\t\tsynapseClient.isTeamMember(entityId, Long.valueOf(teamA.getId()));\r\n\t\tverify(mockSynapse).getTeamMembershipStatus(teamA.getId(), entityId);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityHeaderBatch() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\tList headers = synapseClient\r\n\t\t\t\t.getEntityHeaderBatch(new ArrayList());\r\n\t\t// in the setup, we told the mockSynapse.getEntityHeaderBatch to return\r\n\t\t// batchHeaderResults\r\n\t\tfor (int i = 0; i < batchHeaderResults.size(); i++) {\r\n\t\t\tassertEquals(batchHeaderResults.get(i), headers.get(i));\r\n\t\t}\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSendMessage() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor arg = ArgumentCaptor\r\n\t\t\t\t.forClass(MessageToUser.class);\r\n\t\tSet recipients = new HashSet();\r\n\t\trecipients.add(\"333\");\r\n\t\tString subject = \"The Mathematics of Quantum Neutrino Fields\";\r\n\t\tString messageBody = \"Atoms are not to be trusted, they make up everything\";\r\n\t\tString hostPageBaseURL = \"http://localhost/Portal.html\";\r\n\t\tsynapseClient.sendMessage(recipients, subject, messageBody, hostPageBaseURL);\r\n\t\tverify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE));\r\n\t\tverify(mockSynapse).sendMessage(arg.capture());\r\n\t\tMessageToUser toSendMessage = arg.getValue();\r\n\t\tassertEquals(subject, toSendMessage.getSubject());\r\n\t\tassertEquals(recipients, toSendMessage.getRecipients());\r\n\t\tassertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testSendMessageToEntityOwner() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor arg = ArgumentCaptor\r\n\t\t\t\t.forClass(MessageToUser.class);\r\n\t\tArgumentCaptor entityIdCaptor = ArgumentCaptor\r\n\t\t\t\t.forClass(String.class);\r\n\t\t\r\n\t\tString subject = \"The Mathematics of Quantum Neutrino Fields\";\r\n\t\tString messageBody = \"Atoms are not to be trusted, they make up everything\";\r\n\t\tString hostPageBaseURL = \"http://localhost/Portal.html\";\r\n\t\tString entityId = \"syn98765\";\r\n\t\tsynapseClient.sendMessageToEntityOwner(entityId, subject, messageBody, hostPageBaseURL);\r\n\t\tverify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE));\r\n\t\tverify(mockSynapse).sendMessage(arg.capture(), entityIdCaptor.capture());\r\n\t\tMessageToUser toSendMessage = arg.getValue();\r\n\t\tassertEquals(subject, toSendMessage.getSubject());\r\n\t\tassertEquals(entityId, entityIdCaptor.getValue());\r\n\t\tassertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetCertifiedUserPassingRecord()\r\n\t\t\tthrows RestServiceException, SynapseException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\tPassingRecord passingRecord = new PassingRecord();\r\n\t\tpassingRecord.setPassed(true);\r\n\t\tpassingRecord.setQuizId(1238L);\r\n\t\tString passingRecordJson = passingRecord.writeToJSONObject(\r\n\t\t\t\tadapterFactory.createNew()).toJSONString();\r\n\t\twhen(mockSynapse.getCertifiedUserPassingRecord(anyString()))\r\n\t\t\t\t.thenReturn(passingRecord);\r\n\t\tString returnedPassingRecordJson = synapseClient\r\n\t\t\t\t.getCertifiedUserPassingRecord(\"123\");\r\n\t\tverify(mockSynapse).getCertifiedUserPassingRecord(anyString());\r\n\t\tassertEquals(passingRecordJson, returnedPassingRecordJson);\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testUserNeverAttemptedCertification()\r\n\t\t\tthrows RestServiceException, SynapseException {\r\n\t\twhen(mockSynapse.getCertifiedUserPassingRecord(anyString())).thenThrow(\r\n\t\t\t\tnew SynapseNotFoundException(\"PassingRecord not found\"));\r\n\t\tsynapseClient.getCertifiedUserPassingRecord(\"123\");\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testUserFailedCertification() throws RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tPassingRecord passingRecord = new PassingRecord();\r\n\t\tpassingRecord.setPassed(false);\r\n\t\tpassingRecord.setQuizId(1238L);\r\n\t\twhen(mockSynapse.getCertifiedUserPassingRecord(anyString()))\r\n\t\t\t\t.thenReturn(passingRecord);\r\n\t\tsynapseClient.getCertifiedUserPassingRecord(\"123\");\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetCertificationQuiz() throws RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\twhen(mockSynapse.getCertifiedUserTest()).thenReturn(new Quiz());\r\n\t\tsynapseClient.getCertificationQuiz();\r\n\t\tverify(mockSynapse).getCertifiedUserTest();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSubmitCertificationQuizResponse()\r\n\t\t\tthrows RestServiceException, SynapseException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\tPassingRecord mockPassingRecord = new PassingRecord();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.submitCertifiedUserTestResponse(any(QuizResponse.class)))\r\n\t\t\t\t.thenReturn(mockPassingRecord);\r\n\t\tQuizResponse myResponse = new QuizResponse();\r\n\t\tmyResponse.setId(837L);\r\n\t\tsynapseClient.submitCertificationQuizResponse(myResponse);\r\n\t\tverify(mockSynapse).submitCertifiedUserTestResponse(eq(myResponse));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testMarkdownCache() throws Exception {\r\n\t\tCache mockCache = Mockito\r\n\t\t\t\t.mock(Cache.class);\r\n\t\tsynapseClient.setMarkdownCache(mockCache);\r\n\t\tWikiPage page = new WikiPage();\r\n\t\twhen(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tWikiPage actualResult = synapseClient\r\n\t\t\t\t.getV2WikiPageAsV1(new WikiPageKey(entity.getId(),\r\n\t\t\t\t\t\tObjectType.ENTITY.toString(), \"12\"));\r\n\t\tassertEquals(page, actualResult);\r\n\t\tverify(mockCache).get(any(MarkdownCacheRequest.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testMarkdownCacheWithVersion() throws Exception {\r\n\t\tCache mockCache = Mockito\r\n\t\t\t\t.mock(Cache.class);\r\n\t\tsynapseClient.setMarkdownCache(mockCache);\r\n\t\tWikiPage page = new WikiPage();\r\n\t\twhen(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiPage(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tanyLong())).thenReturn(v2Page);\r\n\t\tWikiPage actualResult = synapseClient.getVersionOfV2WikiPageAsV1(\r\n\t\t\t\tnew WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(),\r\n\t\t\t\t\t\t\"12\"), 5L);\r\n\t\tassertEquals(page, actualResult);\r\n\t\tverify(mockCache).get(any(MarkdownCacheRequest.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testFilterAccessRequirements() throws Exception {\r\n\t\tList unfilteredAccessRequirements = new ArrayList();\r\n\t\tList filteredAccessRequirements;\r\n\t\t// filter empty list should not result in failure\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.UPDATE);\r\n\t\tassertTrue(filteredAccessRequirements.isEmpty());\r\n\r\n\t\tunfilteredAccessRequirements\r\n\t\t\t\t.add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD));\r\n\t\tunfilteredAccessRequirements\r\n\t\t\t\t.add(createAccessRequirement(ACCESS_TYPE.SUBMIT));\r\n\t\tunfilteredAccessRequirements\r\n\t\t\t\t.add(createAccessRequirement(ACCESS_TYPE.SUBMIT));\r\n\t\t// no requirements of type UPDATE\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.UPDATE);\r\n\t\tassertTrue(filteredAccessRequirements.isEmpty());\r\n\t\t// 1 download\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.DOWNLOAD);\r\n\t\tassertEquals(1, filteredAccessRequirements.size());\r\n\t\t// 2 submit\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.SUBMIT);\r\n\t\tassertEquals(2, filteredAccessRequirements.size());\r\n\r\n\t\t// finally, filter null list - result will be an empty list\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(null, ACCESS_TYPE.SUBMIT);\r\n\t\tassertNotNull(filteredAccessRequirements);\r\n\t\tassertTrue(filteredAccessRequirements.isEmpty());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityUnmetAccessRequirements() throws Exception {\r\n\t\t// verify it calls getUnmetAccessRequirements when unmet is true\r\n\t\tsynapseClient.getEntityAccessRequirements(entityId, true, null);\r\n\t\tverify(mockSynapse)\r\n\t\t\t\t.getUnmetAccessRequirements(\r\n\t\t\t\t\t\tany(RestrictableObjectDescriptor.class),\r\n\t\t\t\t\t\tany(ACCESS_TYPE.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetAllEntityAccessRequirements() throws Exception {\r\n\t\t// verify it calls getAccessRequirements when unmet is false\r\n\t\tsynapseClient.getEntityAccessRequirements(entityId, false, null);\r\n\t\tverify(mockSynapse).getAccessRequirements(\r\n\t\t\t\tany(RestrictableObjectDescriptor.class));\r\n\t}\r\n\r\n\t// pass through tests for email validation\r\n\r\n\t@Test\r\n\tpublic void testAdditionalEmailValidation() throws Exception {\r\n\t\tLong userId = 992843l;\r\n\t\tString emailAddress = \"test@test.com\";\r\n\t\tString callbackUrl = \"http://www.synapse.org/#!Account:\";\r\n\t\tsynapseClient.additionalEmailValidation(userId.toString(),\r\n\t\t\t\temailAddress, callbackUrl);\r\n\t\tverify(mockSynapse).additionalEmailValidation(eq(userId),\r\n\t\t\t\teq(emailAddress), eq(callbackUrl));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testAddEmail() throws Exception {\r\n\t\tString emailAddressToken = \"long synapse email token\";\r\n\t\tsynapseClient.addEmail(emailAddressToken);\r\n\t\tverify(mockSynapse).addEmail(any(AddEmailInfo.class), anyBoolean());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetNotificationEmail() throws Exception {\r\n\t\tsynapseClient.getNotificationEmail();\r\n\t\tverify(mockSynapse).getNotificationEmail();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSetNotificationEmail() throws Exception {\r\n\t\tString emailAddress = \"test@test.com\";\r\n\t\tsynapseClient.setNotificationEmail(emailAddress);\r\n\t\tverify(mockSynapse).setNotificationEmail(eq(emailAddress));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testLogErrorToRepositoryServices() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tString errorMessage = \"error has occurred\";\r\n\t\tString permutationStrongName=\"Chrome\";\r\n\t\tsynapseClient.logErrorToRepositoryServices(errorMessage, null, null, null, permutationStrongName);\r\n\t\tverify(mockSynapse).getMyProfile();\r\n\t\tverify(mockSynapse).logError(any(LogEntry.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testLogErrorToRepositoryServicesTruncation()\r\n\t\t\tthrows SynapseException, RestServiceException,\r\n\t\t\tJSONObjectAdapterException, ServletException {\r\n\t\tString exceptionMessage = \"This exception brought to you by Sage Bionetworks\";\r\n\t\tException e = new Exception(exceptionMessage, new IllegalArgumentException(new NullPointerException()));\r\n\t\tServletContext mockServletContext = Mockito.mock(ServletContext.class);\r\n\t\tServletConfig mockServletConfig = Mockito.mock(ServletConfig.class);\r\n\t\twhen(mockServletConfig.getServletContext()).thenReturn(mockServletContext);\r\n\t\tsynapseClient.init(mockServletConfig);\r\n\t\tString errorMessage = \"error has occurred\";\r\n\t\tString permutationStrongName=\"FF\";\r\n\t\tsynapseClient.logErrorToRepositoryServices(errorMessage, e.getClass().getSimpleName(), e.getMessage(), e.getStackTrace(), permutationStrongName);\r\n\t\tArgumentCaptor captor = ArgumentCaptor\r\n\t\t\t\t.forClass(LogEntry.class);\r\n\t\tverify(mockSynapse).logError(captor.capture());\r\n\t\tLogEntry logEntry = captor.getValue();\r\n\t\tassertTrue(logEntry.getLabel().length() < SynapseClientImpl.MAX_LOG_ENTRY_LABEL_SIZE + 100);\r\n\t\tassertTrue(logEntry.getMessage().contains(errorMessage));\r\n\t\tassertTrue(logEntry.getMessage().contains(MY_USER_PROFILE_OWNER_ID));\r\n\t\tassertTrue(logEntry.getMessage().contains(e.getClass().getSimpleName()));\r\n\t\tassertTrue(logEntry.getMessage().contains(exceptionMessage));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetMyProjects() throws Exception {\r\n\t\tint limit = 11;\r\n\t\tint offset = 20;\r\n\t\tProjectPagedResults results = synapseClient.getMyProjects(ProjectListType.MY_PROJECTS, limit, offset,\r\n\t\t\t\tProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC);\r\n\t\tverify(mockSynapse).getMyProjects(eq(ProjectListType.MY_PROJECTS),\r\n\t\t\t\teq(ProjectListSortColumn.LAST_ACTIVITY),\r\n\t\t\t\teq(SortDirection.DESC), eq(limit), eq(offset));\r\n\t\tverify(mockSynapse).listUserProfiles(anyList());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetUserProjects() throws Exception {\r\n\t\tint limit = 11;\r\n\t\tint offset = 20;\r\n\t\tLong userId = 133l;\r\n\t\tString userIdString = userId.toString();\r\n\t\tsynapseClient.getUserProjects(userIdString, limit, offset,\r\n\t\t\t\tProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC);\r\n\t\tverify(mockSynapse).getProjectsFromUser(eq(userId),\r\n\t\t\t\teq(ProjectListSortColumn.LAST_ACTIVITY),\r\n\t\t\t\teq(SortDirection.DESC), eq(limit), eq(offset));\r\n\t\tverify(mockSynapse).listUserProfiles(anyList());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetProjectsForTeam() throws Exception {\r\n\t\tint limit = 13;\r\n\t\tint offset = 40;\r\n\t\tLong teamId = 144l;\r\n\t\tString teamIdString = teamId.toString();\r\n\t\tsynapseClient.getProjectsForTeam(teamIdString, limit, offset,\r\n\t\t\t\tProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC);\r\n\t\tverify(mockSynapse).getProjectsForTeam(eq(teamId),\r\n\t\t\t\teq(ProjectListSortColumn.LAST_ACTIVITY),\r\n\t\t\t\teq(SortDirection.DESC), eq(limit), eq(offset));\r\n\t\tverify(mockSynapse).listUserProfiles(anyList());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSafeLongToInt() {\r\n\t\tint inRangeInt = 500;\r\n\t\tint after = SynapseClientImpl.safeLongToInt(inRangeInt);\r\n\t\tassertEquals(inRangeInt, after);\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testSafeLongToIntPositive() {\r\n\t\tlong testValue = Integer.MAX_VALUE;\r\n\t\ttestValue++;\r\n\t\tSynapseClientImpl.safeLongToInt(testValue);\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testSafeLongToIntNegative() {\r\n\t\tlong testValue = Integer.MIN_VALUE;\r\n\t\ttestValue--;\r\n\t\tSynapseClientImpl.safeLongToInt(testValue);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetHost() throws RestServiceException {\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"sfTp://mydomain.com/foo/bar\"));\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"http://mydomain.com/foo/bar\"));\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"http://mydomain.com\"));\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"sftp://mydomain.com:22/foo/bar\"));\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testGetHostNull() throws RestServiceException {\r\n\t\tsynapseClient.getHost(null);\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testGetHostEmpty() throws RestServiceException {\r\n\t\tsynapseClient.getHost(\"\");\r\n\t}\r\n\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testGetHostBadUrl() throws RestServiceException {\r\n\t\tsynapseClient.getHost(\"foobar\");\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetRootWikiId() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\torg.sagebionetworks.repo.model.dao.WikiPageKey key = new org.sagebionetworks.repo.model.dao.WikiPageKey();\r\n\t\tkey.setOwnerObjectId(\"1\");\r\n\t\tkey.setOwnerObjectType(ObjectType.ENTITY);\r\n\t\tString expectedId = \"123\";\r\n\t\tkey.setWikiPageId(expectedId);\r\n\t\twhen(mockSynapse.getRootWikiPageKey(anyString(), any(ObjectType.class)))\r\n\t\t\t\t.thenReturn(key);\r\n\r\n\t\tString actualId = synapseClient.getRootWikiId(\"1\",\r\n\t\t\t\tObjectType.ENTITY.toString());\r\n\t\tassertEquals(expectedId, actualId);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetFavorites() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\tPaginatedResults pagedResults = new PaginatedResults();\r\n\t\tList unsortedResults = new ArrayList();\r\n\t\tpagedResults.setResults(unsortedResults);\r\n\t\twhen(mockSynapse.getFavorites(anyInt(), anyInt())).thenReturn(\r\n\t\t\t\tpagedResults);\r\n\r\n\t\t// test empty favorites\r\n\t\tList actualList = synapseClient.getFavorites();\r\n\t\tassertTrue(actualList.isEmpty());\r\n\r\n\t\t// test a few unsorted favorites\r\n\t\tEntityHeader favZ = new EntityHeader();\r\n\t\tfavZ.setName(\"Z\");\r\n\t\tunsortedResults.add(favZ);\r\n\t\tEntityHeader favA = new EntityHeader();\r\n\t\tfavA.setName(\"A\");\r\n\t\tunsortedResults.add(favA);\r\n\t\tEntityHeader favQ = new EntityHeader();\r\n\t\tfavQ.setName(\"q\");\r\n\t\tunsortedResults.add(favQ);\r\n\r\n\t\tactualList = synapseClient.getFavorites();\r\n\t\tassertEquals(3, actualList.size());\r\n\t\tassertEquals(favA, actualList.get(0));\r\n\t\tassertEquals(favQ, actualList.get(1));\r\n\t\tassertEquals(favZ, actualList.get(2));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetTeamBundlesNotOwner() throws RestServiceException, SynapseException {\r\n\t\t// the paginated results were set up to return {teamZ, teamA}, but\r\n\t\t// servlet side we sort by name.\r\n\t\tList results = synapseClient.getTeamsForUser(\"abba\", false);\r\n\t\tverify(mockSynapse).getTeamsForUser(eq(\"abba\"), anyInt(), anyInt());\r\n\t\tassertEquals(2, results.size());\r\n\t\tassertEquals(teamA, results.get(0).getTeam());\r\n\t\tassertEquals(teamZ, results.get(1).getTeam());\r\n\t\tverify(mockSynapse, Mockito.never()).getOpenMembershipRequests(anyString(), anyString(),\r\n\t\t\t\tanyLong(), anyLong());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTeamBundlesOwner() throws RestServiceException, SynapseException {\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\ttestTeamMember.setIsAdmin(true);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\t\twhen(mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(mockPaginatedMembershipRequest);\r\n\t\t\r\n\t\tList results = synapseClient.getTeamsForUser(\"abba\", true);\r\n\t\tverify(mockSynapse).getTeamsForUser(eq(\"abba\"), anyInt(), anyInt());\r\n\t\tassertEquals(2, results.size());\r\n\t\tassertEquals(teamA, results.get(0).getTeam());\r\n\t\tassertEquals(teamZ, results.get(1).getTeam());\r\n\t\tLong reqCount1 = results.get(0).getRequestCount();\r\n\t\tLong reqCount2 = results.get(1).getRequestCount();\r\n\t\tassertEquals(new Long(3L), results.get(0).getRequestCount());\r\n\t\tassertEquals(new Long(3L), results.get(1).getRequestCount());\r\n\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenNull() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = null;\r\n\t\tsynapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenEmpty() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = \"\";\r\n\t\tsynapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenUnrecognized() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = \"InvalidTokenType\";\r\n\t\tsynapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testHandleSignedTokenJoinTeam() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.JoinTeam.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t\tsynapseClient.handleSignedToken(token,TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).addTeamMember(joinTeamToken, TEST_HOME_PAGE_BASE+\"#!Team:\", TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\");\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenInvalidJoinTeam() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.JoinTeam.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, \"invalid token\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testHandleSignedTokenNotificationSettings() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.Settings.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedNotificationSettingsToken);\r\n\t\tsynapseClient.handleSignedToken(token, TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).updateNotificationSettings(notificationSettingsToken);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenInvalidNotificationSettings() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.Settings.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, \"invalid token\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetOrCreateActivityForEntityVersionGet() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenReturn(new Activity());\r\n\t\tsynapseClient.getOrCreateActivityForEntityVersion(entityId, version);\r\n\t\tverify(mockSynapse).getActivityForEntityVersion(entityId, version);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetOrCreateActivityForEntityVersionCreate() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new SynapseNotFoundException());\r\n\t\twhen(mockSynapse.createActivity(any(Activity.class))).thenReturn(mockActivity);\r\n\t\tsynapseClient.getOrCreateActivityForEntityVersion(entityId, version);\r\n\t\tverify(mockSynapse).getActivityForEntityVersion(entityId, version);\r\n\t\tverify(mockSynapse).createActivity(any(Activity.class));\r\n\t\tverify(mockSynapse).putEntity(mockSynapse.getEntityById(entityId), mockActivity.getId());\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testGetOrCreateActivityForEntityVersionFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new Exception());\r\n\t\tsynapseClient.getOrCreateActivityForEntityVersion(entityId, version);\r\n\t}\r\n\t\r\n\tprivate void setupGetMyLocationSettings() throws SynapseException, RestServiceException{\r\n\t\tList existingStorageLocations = new ArrayList();\r\n\t\tStorageLocationSetting storageLocation = new ExternalS3StorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(1L);\r\n\t\tstorageLocation.setBanner(BANNER_1);\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\tstorageLocation = new ExternalStorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(2L);\r\n\t\tstorageLocation.setBanner(BANNER_2);\r\n\t\t((ExternalStorageLocationSetting)storageLocation).setUrl(\"sftp://www.jayhodgson.com\");\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\tstorageLocation = new ExternalStorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(3L);\r\n\t\tstorageLocation.setBanner(BANNER_1);\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\tstorageLocation = new ExternalStorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(4L);\r\n\t\tstorageLocation.setBanner(null);\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\twhen(mockSynapse.getMyStorageLocationSettings()).thenReturn(existingStorageLocations);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetMyLocationSettingBanners() throws SynapseException, RestServiceException {\r\n\t\tsetupGetMyLocationSettings();\r\n\t\tList banners = synapseClient.getMyLocationSettingBanners();\r\n\t\tverify(mockSynapse).getMyStorageLocationSettings();\r\n\t\t//should be 2 (only returns unique values)\r\n\t\tassertEquals(2, banners.size());\r\n\t\tassertTrue(banners.contains(BANNER_1));\r\n\t\tassertTrue(banners.contains(BANNER_2));\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testGetMyLocationSettingBannersFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getMyStorageLocationSettings()).thenThrow(new Exception());\r\n\t\tsynapseClient.getMyLocationSettingBanners();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSettingNullSetting() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null);\r\n\t\tassertNull(synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSettingNullUploadDestination() throws SynapseException, RestServiceException {\r\n\t\tassertNull(synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSettingDefaultUploadDestination() throws SynapseException, RestServiceException {\r\n\t\tUploadDestination setting = Mockito.mock(UploadDestination.class);\r\n\t\tString defaultStorageId = synapseClient.getSynapseProperties().get(SynapseClientImpl.DEFAULT_STORAGE_ID_PROPERTY_KEY);\r\n\t\twhen(setting.getStorageLocationId()).thenReturn(Long.parseLong(defaultStorageId));\r\n\t\twhen(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting);\r\n\t\tStorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class);\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting);\r\n\t\t\r\n\t\tassertNull(synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSetting() throws SynapseException, RestServiceException {\r\n\t\tUploadDestination setting = Mockito.mock(UploadDestination.class);\r\n\t\twhen(setting.getStorageLocationId()).thenReturn(42L);\r\n\t\twhen(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting);\r\n\t\tStorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class);\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting);\r\n\t\tassertEquals(mockStorageLocationSetting, synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testGetStorageLocationSettingFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception());\r\n\t\tsynapseClient.getStorageLocationSetting(entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testCreateStorageLocationSettingFoundStorageAndProjectSetting() throws SynapseException, RestServiceException {\r\n\t\tsetupGetMyLocationSettings();\r\n\t\t\r\n\t\tUploadDestinationListSetting projectSetting = new UploadDestinationListSetting();\r\n\t\tprojectSetting.setLocations(Collections.EMPTY_LIST);\r\n\t\twhen(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(projectSetting);\r\n\t\t\r\n\t\t//test the case when it finds a duplicate storage location.\r\n\t\tExternalStorageLocationSetting setting = new ExternalStorageLocationSetting();\r\n\t\tsetting.setBanner(BANNER_2);\r\n\t\tsetting.setUrl(\"sftp://www.jayhodgson.com\");\r\n\t\t\r\n\t\tsynapseClient.createStorageLocationSetting(entityId, setting);\r\n\t\t//should have found the duplicate storage location, so this is never called\r\n\t\tverify(mockSynapse, Mockito.never()).createStorageLocationSetting(any(StorageLocationSetting.class));\r\n\t\t//verify updates project setting, and the new location list is a single value (id of existing storage location)\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(ProjectSetting.class);\r\n\t\tverify(mockSynapse).updateProjectSetting(captor.capture());\r\n\t\tUploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue();\r\n\t\tList locations = updatedProjectSetting.getLocations();\r\n\t\tassertEquals(new Long(2), locations.get(0));\r\n\t}\r\n\t\r\n\r\n\t@Test\r\n\tpublic void testCreateStorageLocationSettingNewStorageAndProjectSetting() throws SynapseException, RestServiceException {\r\n\t\tsetupGetMyLocationSettings();\r\n\t\twhen(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null);\r\n\t\t\r\n\t\t//test the case when it does not find duplicate storage location setting.\r\n\t\tExternalStorageLocationSetting setting = new ExternalStorageLocationSetting();\r\n\t\tsetting.setBanner(BANNER_2);\r\n\t\tsetting.setUrl(\"sftp://www.google.com\");\r\n\t\t\r\n\t\tLong newStorageLocationId = 1007L;\r\n\t\tExternalStorageLocationSetting createdSetting = new ExternalStorageLocationSetting();\r\n\t\tcreatedSetting.setStorageLocationId(newStorageLocationId);\r\n\t\t\r\n\t\twhen(mockSynapse.createStorageLocationSetting(any(StorageLocationSetting.class))).thenReturn(createdSetting);\r\n\t\t\r\n\t\tsynapseClient.createStorageLocationSetting(entityId, setting);\r\n\t\t//should not have found a duplicate storage location, so this should be called\r\n\t\tverify(mockSynapse).createStorageLocationSetting(any(StorageLocationSetting.class));\r\n\t\t//verify creates new project setting, and the new location list is a single value (id of the new storage location)\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(ProjectSetting.class);\r\n\t\tverify(mockSynapse).createProjectSetting(captor.capture());\r\n\t\tUploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue();\r\n\t\tList locations = updatedProjectSetting.getLocations();\r\n\t\tassertEquals(newStorageLocationId, locations.get(0));\r\n\t\tassertEquals(ProjectSettingsType.upload, updatedProjectSetting.getSettingsType());\r\n\t\tassertEquals(entityId, updatedProjectSetting.getProjectId());\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testCreateStorageLocationSettingFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception());\r\n\t\tsynapseClient.createStorageLocationSetting(entityId, new ExternalStorageLocationSetting());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testUpdateTeamAcl() throws SynapseException, RestServiceException {\r\n\t\tAccessControlList returnedAcl = synapseClient.updateTeamAcl(acl);\r\n\t\tverify(mockSynapse).updateTeamACL(acl);\r\n\t\tassertEquals(acl, returnedAcl);\r\n\t}\r\n\t@Test\r\n\tpublic void testGetTeamAcl() throws SynapseException, RestServiceException {\r\n\t\tString teamId = \"14\";\r\n\t\tAccessControlList returnedAcl = synapseClient.getTeamAcl(teamId);\r\n\t\tverify(mockSynapse).getTeamACL(teamId);\r\n\t\tassertEquals(acl, returnedAcl);\r\n\t}\r\n\t\r\n\tprivate void setupVersionedEntityBundle(String entityId, Long latestVersionNumber) throws SynapseException {\r\n\t\tEntityBundle eb = new EntityBundle();\r\n\t\tEntity file = new FileEntity();\r\n\t\teb.setEntity(file);\r\n\t\teb.getEntity().setId(entityId);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), anyLong(), anyInt())).thenReturn(eb);\r\n\t\tPaginatedResults versionInfoPaginatedResults = new PaginatedResults();\r\n\t\tList versionInfoList = new LinkedList();\r\n\t\tVersionInfo versionInfo = new VersionInfo();\r\n\t\tversionInfo.setVersionNumber(latestVersionNumber);\r\n\t\tversionInfoList.add(versionInfo);\r\n\t\tversionInfoPaginatedResults.setResults(versionInfoList);\r\n\t\twhen(mockSynapse.getEntityVersions(anyString(), anyInt(), anyInt())).thenReturn(versionInfoPaginatedResults);\r\n\t\twhen(mockSynapse.getEntityById(anyString())).thenReturn(file);\r\n\t}\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForVersionVersionable() throws RestServiceException, SynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tLong targetVersionNumber = 1L;\r\n\t\tLong latestVersionNumber = 2L;\r\n\t\tsetupVersionedEntityBundle(entityId, latestVersionNumber);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1);\r\n\t\tassertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber);\r\n\t\tverify(mockSynapse).getEntityBundle(anyString(), eq(targetVersionNumber), anyInt());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForNullVersionVersionable() throws RestServiceException, SynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tLong targetVersionNumber = null;\r\n\t\tLong latestVersionNumber = 2L;\r\n\t\tsetupVersionedEntityBundle(entityId, latestVersionNumber);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1);\r\n\t\tassertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber);\r\n\t\tverify(mockSynapse).getEntityBundle(anyString(), anyInt());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForVersionLatestVersion() throws RestServiceException, SynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tLong targetVersionNumber = 2L;\r\n\t\tLong latestVersionNumber = 2L;\r\n\t\tsetupVersionedEntityBundle(entityId, latestVersionNumber);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1);\r\n\t\tassertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber);\r\n\t\tverify(mockSynapse).getEntityBundle(anyString(), anyInt());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForVersionNonVersionable() throws RestServiceException, SynapseException {\r\n\t\tEntityBundle eb = new EntityBundle();\r\n\t\teb.setEntity(new Folder());\r\n\t\teb.getEntity().setId(\"syn123\");\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(\"syn123\", 123L, 1);\r\n\t\tassertNull(returnedEntityBundle.getLatestVersionNumber());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), \"syn123\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetUserIdFromUsername() throws UnsupportedEncodingException, SynapseException, RestServiceException {\r\n\t\t//find the user id based on user name\r\n\t\tLong targetUserId = 4L;\r\n\t\twhen(mockPrincipalAliasResponse.getPrincipalId()).thenReturn(targetUserId);\r\n\t\twhen(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenReturn(mockPrincipalAliasResponse);\r\n\t\tString userId = synapseClient.getUserIdFromUsername(\"luke\");\r\n\t\tassertEquals(targetUserId.toString(), userId);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testGetUserIdFromUsernameBackendError() throws UnsupportedEncodingException, SynapseException, RestServiceException {\r\n\t\t//test error from backend\r\n\t\twhen(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenThrow(new SynapseBadRequestException());\r\n\t\tsynapseClient.getUserIdFromUsername(\"bad-request\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTableUpdateTransactionRequestNoChange() throws RestServiceException, SynapseException {\r\n\t\tString tableId = \"syn93939\";\r\n\t\t\r\n\t\tList oldColumnModels = Collections.singletonList(mockOldColumnModel);\r\n\t\twhen(mockSynapse.createColumnModels(anyList())).thenReturn(oldColumnModels);\r\n\t\twhen(mockSynapse.getColumnModelsForTableEntity(tableId)).thenReturn(oldColumnModels);\r\n\t\tassertEquals(0, synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, oldColumnModels).getChanges().size());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTableUpdateTransactionRequestNewColumn() throws RestServiceException, SynapseException {\r\n\t\tString tableId = \"syn93939\";\r\n\t\tList oldColumnModels = new ArrayList();\r\n\t\twhen(mockSynapse.createColumnModels(anyList())).thenReturn(Collections.singletonList(mockNewColumnModelAfterCreate));\r\n\t\tList newColumnModels = Collections.singletonList(mockNewColumnModel);\r\n\t\tTableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, newColumnModels);\r\n\t\tverify(mockSynapse).createColumnModels(anyList());\r\n\t\tassertEquals(tableId, request.getEntityId());\r\n\t\tList tableUpdates = request.getChanges();\r\n\t\tassertEquals(1, tableUpdates.size());\r\n\t\tTableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0);\r\n\t\tList changes = schemaChange.getChanges();\r\n\t\tassertEquals(1, changes.size());\r\n\t\tColumnChange columnChange = changes.get(0);\r\n\t\tassertNull(columnChange.getOldColumnId());\r\n\t\tassertEquals(NEW_COLUMN_MODEL_ID, columnChange.getNewColumnId());\r\n\t}\r\n\t\r\n\tprivate ColumnModel getColumnModel(String id, ColumnType columnType) {\r\n\t\tColumnModel cm = new ColumnModel();\r\n\t\tcm.setId(id);\r\n\t\tcm.setColumnType(columnType);\r\n\t\treturn cm;\r\n\t}\r\n\t\r\n\tprivate ColumnChange getColumnChange(String oldColumnId, List changes) {\r\n\t\tfor (ColumnChange columnChange : changes) {\r\n\t\t\tif (Objects.equal(oldColumnId, columnChange.getOldColumnId())) {\r\n\t\t\t\treturn columnChange;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new NoSuchElementException();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTableUpdateTransactionRequestFullTest() throws RestServiceException, SynapseException {\r\n\t\t//In this test, we will change a column, delete a column, and add a column (with appropriately mocked responses)\r\n\t\t// Modify colA, delete colB, no change to colC, and add colD\r\n\t\tColumnModel colA, colB, colC, colD, colAModified, colAAfterSave, colDAfterSave;\r\n\t\tString tableId = \"syn93939\";\r\n\t\tcolA = getColumnModel(\"1\", ColumnType.STRING);\r\n\t\tcolB = getColumnModel(\"2\", ColumnType.STRING);\r\n\t\tcolC = getColumnModel(\"3\", ColumnType.STRING);\r\n\t\tcolD = getColumnModel(null, ColumnType.STRING);\r\n\t\tcolAModified = getColumnModel(\"1\", ColumnType.INTEGER);\r\n\t\tcolAAfterSave = getColumnModel(\"4\", ColumnType.INTEGER);\r\n\t\tcolDAfterSave = getColumnModel(\"5\", ColumnType.STRING);\r\n\t\t\r\n\t\tList oldSchema = Arrays.asList(colA, colB, colC);\r\n\t\tList proposedNewSchema = Arrays.asList(colAModified, colC, colD);\r\n\t\tList newSchemaAfterUpdate = Arrays.asList(colAAfterSave, colC, colDAfterSave);\r\n\t\twhen(mockSynapse.createColumnModels(anyList())).thenReturn(newSchemaAfterUpdate);\r\n\t\t\r\n\t\tTableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldSchema, proposedNewSchema);\r\n\t\tverify(mockSynapse).createColumnModels(anyList());\r\n\t\tassertEquals(tableId, request.getEntityId());\r\n\t\tList tableUpdates = request.getChanges();\r\n\t\tassertEquals(1, tableUpdates.size());\r\n\t\tTableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0);\r\n\t\t\r\n\t\t//changes should consist of a create, an update, and a delete\r\n\t\tList changes = schemaChange.getChanges();\r\n\t\tassertEquals(3, changes.size());\r\n\t\t\r\n\t\t// colB should be deleted\r\n\t\tColumnChange columnChange = getColumnChange(\"2\", changes);\r\n\t\tassertNull(columnChange.getNewColumnId());\r\n\t\t// colA should be modified\r\n\t\tcolumnChange = getColumnChange(\"1\", changes);\r\n\t\tassertEquals(\"4\", columnChange.getNewColumnId());\r\n\t\t// colD should be new\r\n\t\tcolumnChange = getColumnChange(null, changes);\r\n\t\tassertEquals(\"5\", columnChange.getNewColumnId());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetDefaultColumnsForView() throws RestServiceException, SynapseException{\r\n\t\tColumnModel colA, colB;\r\n\t\tcolA = getColumnModel(\"1\", ColumnType.STRING);\r\n\t\tcolB = getColumnModel(\"2\", ColumnType.STRING);\r\n\t\t\r\n\t\tList defaultColumns = Arrays.asList(colA, colB);\r\n\t\twhen(mockSynapse.getDefaultColumnsForView(any(ViewType.class))).thenReturn(defaultColumns);\r\n\t\tList returnedColumns = synapseClient.getDefaultColumnsForView(ViewType.file);\r\n\t\t\r\n\t\tassertEquals(2, returnedColumns.size());\r\n\t\tassertNull(returnedColumns.get(0).getId());\r\n\t\tassertNull(returnedColumns.get(1).getId());\r\n\t}\r\n\t\r\n\r\n\t@Test(expected = UnknownErrorException.class)\r\n\tpublic void testUpdateFileEntityWrongResponseSize() throws RestServiceException, SynapseException {\r\n\t\tsynapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest);\r\n\t}\r\n\t\r\n\t@Test(expected = UnknownErrorException.class)\r\n\tpublic void testUpdateFileEntityWrongResponseSizeTooMany() throws RestServiceException, SynapseException {\r\n\t\tbatchCopyResultsList.add(mockFileHandleCopyResult);\r\n\t\tbatchCopyResultsList.add(mockFileHandleCopyResult);\r\n\t\tsynapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testUpdateFileEntity() throws RestServiceException, SynapseException {\r\n\t\tbatchCopyResultsList.add(mockFileHandleCopyResult);\r\n\t\twhen(mockFileHandleCopyResult.getFailureCode()).thenReturn(null);\r\n\t\twhen(mockFileHandleCopyResult.getNewFileHandle()).thenReturn(handle);\r\n\t\t\r\n\t\tsynapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest);\r\n\t\t\r\n\t\tverify(mockSynapse).copyFileHandles(isA(BatchFileHandleCopyRequest.class));\r\n\t\tverify(mockFileEntity).setDataFileHandleId(handle.getId());\r\n\t\tverify(mockSynapse).putEntity(mockFileEntity);\r\n\t}\r\n\t\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testUpdateFileEntityNotFound() throws RestServiceException, SynapseException {\r\n\t\tbatchCopyResultsList.add(mockFileHandleCopyResult);\r\n\t\twhen(mockFileHandleCopyResult.getFailureCode()).thenReturn(FileResultFailureCode.NOT_FOUND);\r\n\t\tsynapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest);\r\n\t}\r\n\t\r\n\t@Test(expected = UnauthorizedException.class)\r\n\tpublic void testUpdateFileEntityUnauthorized() throws RestServiceException, SynapseException {\r\n\t\tbatchCopyResultsList.add(mockFileHandleCopyResult);\r\n\t\twhen(mockFileHandleCopyResult.getFailureCode()).thenReturn(FileResultFailureCode.UNAUTHORIZED);\r\n\t\tsynapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest);\r\n\t}\r\n}\r\n"},"new_file":{"kind":"string","value":"src/test/java/org/sagebionetworks/web/unitserver/SynapseClientImplTest.java"},"old_contents":{"kind":"string","value":"package org.sagebionetworks.web.unitserver;\r\n\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertFalse;\r\nimport static org.junit.Assert.assertNotNull;\r\nimport static org.junit.Assert.assertNull;\r\nimport static org.junit.Assert.assertTrue;\r\nimport static org.mockito.Matchers.any;\r\nimport static org.mockito.Matchers.anyBoolean;\r\nimport static org.mockito.Matchers.anyInt;\r\nimport static org.mockito.Matchers.anyList;\r\nimport static org.mockito.Matchers.anyLong;\r\nimport static org.mockito.Matchers.anyString;\r\nimport static org.mockito.Matchers.eq;\r\nimport static org.mockito.Mockito.reset;\r\nimport static org.mockito.Mockito.verify;\r\nimport static org.mockito.Mockito.when;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.ACCESS_REQUIREMENTS;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.ANNOTATIONS;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.BENEFACTOR_ACL;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.ENTITY;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.ENTITY_PATH;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.FILE_HANDLES;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.HAS_CHILDREN;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.PERMISSIONS;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.ROOT_WIKI_ID;\r\nimport static org.sagebionetworks.repo.model.EntityBundle.UNMET_ACCESS_REQUIREMENTS;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.io.UnsupportedEncodingException;\r\nimport java.net.MalformedURLException;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.Date;\r\nimport java.util.HashSet;\r\nimport java.util.LinkedList;\r\nimport java.util.List;\r\nimport java.util.NoSuchElementException;\r\nimport java.util.Set;\r\n\r\nimport javax.servlet.ServletConfig;\r\nimport javax.servlet.ServletContext;\r\nimport javax.servlet.ServletException;\r\n\r\nimport org.json.JSONArray;\r\nimport org.json.JSONException;\r\nimport org.json.JSONObject;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.mockito.ArgumentCaptor;\r\nimport org.mockito.Matchers;\r\nimport org.mockito.Mock;\r\nimport org.mockito.Mockito;\r\nimport org.mockito.MockitoAnnotations;\r\nimport org.sagebionetworks.client.SynapseClient;\r\nimport org.sagebionetworks.client.exceptions.SynapseBadRequestException;\r\nimport org.sagebionetworks.client.exceptions.SynapseException;\r\nimport org.sagebionetworks.client.exceptions.SynapseNotFoundException;\r\nimport org.sagebionetworks.evaluation.model.Evaluation;\r\nimport org.sagebionetworks.evaluation.model.EvaluationStatus;\r\nimport org.sagebionetworks.evaluation.model.UserEvaluationPermissions;\r\nimport org.sagebionetworks.reflection.model.PaginatedResults;\r\nimport org.sagebionetworks.repo.model.ACCESS_TYPE;\r\nimport org.sagebionetworks.repo.model.AccessControlList;\r\nimport org.sagebionetworks.repo.model.AccessRequirement;\r\nimport org.sagebionetworks.repo.model.Annotations;\r\nimport org.sagebionetworks.repo.model.Entity;\r\nimport org.sagebionetworks.repo.model.EntityBundle;\r\nimport org.sagebionetworks.repo.model.EntityHeader;\r\nimport org.sagebionetworks.repo.model.EntityIdList;\r\nimport org.sagebionetworks.repo.model.EntityPath;\r\nimport org.sagebionetworks.repo.model.ExampleEntity;\r\nimport org.sagebionetworks.repo.model.FileEntity;\r\nimport org.sagebionetworks.repo.model.Folder;\r\nimport org.sagebionetworks.repo.model.JoinTeamSignedToken;\r\nimport org.sagebionetworks.repo.model.LogEntry;\r\nimport org.sagebionetworks.repo.model.MembershipInvitation;\r\nimport org.sagebionetworks.repo.model.MembershipInvtnSubmission;\r\nimport org.sagebionetworks.repo.model.MembershipRequest;\r\nimport org.sagebionetworks.repo.model.MembershipRqstSubmission;\r\nimport org.sagebionetworks.repo.model.ObjectType;\r\nimport org.sagebionetworks.repo.model.Project;\r\nimport org.sagebionetworks.repo.model.ProjectHeader;\r\nimport org.sagebionetworks.repo.model.ProjectListSortColumn;\r\nimport org.sagebionetworks.repo.model.ProjectListType;\r\nimport org.sagebionetworks.repo.model.ResourceAccess;\r\nimport org.sagebionetworks.repo.model.RestrictableObjectDescriptor;\r\nimport org.sagebionetworks.repo.model.RestrictableObjectType;\r\nimport org.sagebionetworks.repo.model.SignedTokenInterface;\r\nimport org.sagebionetworks.repo.model.Team;\r\nimport org.sagebionetworks.repo.model.TeamMember;\r\nimport org.sagebionetworks.repo.model.TeamMembershipStatus;\r\nimport org.sagebionetworks.repo.model.TermsOfUseAccessRequirement;\r\nimport org.sagebionetworks.repo.model.UserGroup;\r\nimport org.sagebionetworks.repo.model.UserGroupHeader;\r\nimport org.sagebionetworks.repo.model.UserGroupHeaderResponsePage;\r\nimport org.sagebionetworks.repo.model.UserProfile;\r\nimport org.sagebionetworks.repo.model.UserSessionData;\r\nimport org.sagebionetworks.repo.model.VersionInfo;\r\nimport org.sagebionetworks.repo.model.auth.UserEntityPermissions;\r\nimport org.sagebionetworks.repo.model.doi.Doi;\r\nimport org.sagebionetworks.repo.model.doi.DoiStatus;\r\nimport org.sagebionetworks.repo.model.entity.query.SortDirection;\r\nimport org.sagebionetworks.repo.model.file.CompleteAllChunksRequest;\r\nimport org.sagebionetworks.repo.model.file.ExternalFileHandle;\r\nimport org.sagebionetworks.repo.model.file.FileHandleResults;\r\nimport org.sagebionetworks.repo.model.file.S3FileHandle;\r\nimport org.sagebionetworks.repo.model.file.State;\r\nimport org.sagebionetworks.repo.model.file.UploadDaemonStatus;\r\nimport org.sagebionetworks.repo.model.file.UploadDestination;\r\nimport org.sagebionetworks.repo.model.message.MessageToUser;\r\nimport org.sagebionetworks.repo.model.message.NotificationSettingsSignedToken;\r\nimport org.sagebionetworks.repo.model.message.Settings;\r\nimport org.sagebionetworks.repo.model.principal.AddEmailInfo;\r\nimport org.sagebionetworks.repo.model.principal.PrincipalAliasRequest;\r\nimport org.sagebionetworks.repo.model.principal.PrincipalAliasResponse;\r\nimport org.sagebionetworks.repo.model.project.ExternalS3StorageLocationSetting;\r\nimport org.sagebionetworks.repo.model.project.ExternalStorageLocationSetting;\r\nimport org.sagebionetworks.repo.model.project.ProjectSetting;\r\nimport org.sagebionetworks.repo.model.project.ProjectSettingsType;\r\nimport org.sagebionetworks.repo.model.project.StorageLocationSetting;\r\nimport org.sagebionetworks.repo.model.project.UploadDestinationListSetting;\r\nimport org.sagebionetworks.repo.model.provenance.Activity;\r\nimport org.sagebionetworks.repo.model.quiz.PassingRecord;\r\nimport org.sagebionetworks.repo.model.quiz.Quiz;\r\nimport org.sagebionetworks.repo.model.quiz.QuizResponse;\r\nimport org.sagebionetworks.repo.model.table.ColumnChange;\r\nimport org.sagebionetworks.repo.model.table.ColumnModel;\r\nimport org.sagebionetworks.repo.model.table.ColumnType;\r\nimport org.sagebionetworks.repo.model.table.TableSchemaChangeRequest;\r\nimport org.sagebionetworks.repo.model.table.TableUpdateRequest;\r\nimport org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest;\r\nimport org.sagebionetworks.repo.model.table.ViewType;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint;\r\nimport org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;\r\nimport org.sagebionetworks.repo.model.wiki.WikiHeader;\r\nimport org.sagebionetworks.repo.model.wiki.WikiPage;\r\nimport org.sagebionetworks.schema.adapter.AdapterFactory;\r\nimport org.sagebionetworks.schema.adapter.JSONObjectAdapterException;\r\nimport org.sagebionetworks.schema.adapter.org.json.AdapterFactoryImpl;\r\nimport org.sagebionetworks.schema.adapter.org.json.EntityFactory;\r\nimport org.sagebionetworks.util.SerializationUtils;\r\nimport org.sagebionetworks.web.client.view.TeamRequestBundle;\r\nimport org.sagebionetworks.web.server.servlet.MarkdownCacheRequest;\r\nimport org.sagebionetworks.web.server.servlet.NotificationTokenType;\r\nimport org.sagebionetworks.web.server.servlet.ServiceUrlProvider;\r\nimport org.sagebionetworks.web.server.servlet.SynapseClientImpl;\r\nimport org.sagebionetworks.web.server.servlet.SynapseProvider;\r\nimport org.sagebionetworks.web.server.servlet.TokenProvider;\r\nimport org.sagebionetworks.web.shared.AccessRequirementUtils;\r\nimport org.sagebionetworks.web.shared.EntityBundlePlus;\r\nimport org.sagebionetworks.web.shared.OpenTeamInvitationBundle;\r\nimport org.sagebionetworks.web.shared.ProjectPagedResults;\r\nimport org.sagebionetworks.web.shared.TeamBundle;\r\nimport org.sagebionetworks.web.shared.TeamMemberBundle;\r\nimport org.sagebionetworks.web.shared.TeamMemberPagedResults;\r\nimport org.sagebionetworks.web.shared.WikiPageKey;\r\nimport org.sagebionetworks.web.shared.exceptions.BadRequestException;\r\nimport org.sagebionetworks.web.shared.exceptions.ConflictException;\r\nimport org.sagebionetworks.web.shared.exceptions.NotFoundException;\r\nimport org.sagebionetworks.web.shared.exceptions.RestServiceException;\r\nimport org.sagebionetworks.web.shared.users.AclUtils;\r\nimport org.sagebionetworks.web.shared.users.PermissionLevel;\r\n\r\nimport com.google.appengine.repackaged.com.google.common.base.Objects;\r\nimport com.google.common.cache.Cache;\r\n\r\n/**\r\n * Test for the SynapseClientImpl\r\n * \r\n * @author John\r\n * \r\n */\r\npublic class SynapseClientImplTest {\r\n\tprivate static final String BANNER_2 = \"Another Banner\";\r\n\tprivate static final String BANNER_1 = \"Banner 1\";\r\n\tpublic static final String TEST_HOME_PAGE_BASE = \"http://mysynapse.org/\";\r\n\tpublic static final String MY_USER_PROFILE_OWNER_ID = \"MyOwnerID\";\r\n\t\r\n\tSynapseProvider mockSynapseProvider;\r\n\tTokenProvider mockTokenProvider;\r\n\tServiceUrlProvider mockUrlProvider;\r\n\tSynapseClient mockSynapse;\r\n\tSynapseClientImpl synapseClient;\r\n\tString entityId = \"123\";\r\n\tString inviteeUserId = \"900\";\r\n\tUserProfile inviteeUserProfile;\r\n\tExampleEntity entity;\r\n\tAnnotations annos;\r\n\tUserEntityPermissions eup;\r\n\tUserEvaluationPermissions userEvaluationPermissions;\r\n\tList batchHeaderResults;\r\n\r\n\tString testFileName = \"testFileEntity.R\";\r\n\tEntityPath path;\r\n\torg.sagebionetworks.reflection.model.PaginatedResults pgugs;\r\n\torg.sagebionetworks.reflection.model.PaginatedResults pgups;\r\n\torg.sagebionetworks.reflection.model.PaginatedResults pguts;\r\n\tTeam teamA, teamZ;\r\n\tAccessControlList acl;\r\n\tWikiPage page;\r\n\tV2WikiPage v2Page;\r\n\tS3FileHandle handle;\r\n\tEvaluation mockEvaluation;\r\n\tUserSessionData mockUserSessionData;\r\n\tUserProfile mockUserProfile;\r\n\tMembershipInvtnSubmission testInvitation;\r\n\tPaginatedResults mockPaginatedMembershipRequest;\r\n\tActivity mockActivity;\r\n\r\n\tMessageToUser sentMessage;\r\n\tLong storageLocationId = 9090L;\r\n\tUserProfile testUserProfile;\r\n\tLong version = 1L;\r\n\t\r\n\t//Token testing\r\n\tNotificationSettingsSignedToken notificationSettingsToken;\r\n\tJoinTeamSignedToken joinTeamToken;\r\n\tString encodedJoinTeamToken, encodedNotificationSettingsToken;\r\n\t\r\n\t@Mock\r\n\tUserGroupHeaderResponsePage mockUserGroupHeaderResponsePage;\r\n\t@Mock\r\n\tUserGroupHeader mockUserGroupHeader;\r\n\t@Mock\r\n\tPrincipalAliasResponse mockPrincipalAliasResponse;\r\n\t@Mock\r\n\tColumnModel mockOldColumnModel;\r\n\t@Mock\r\n\tColumnModel mockNewColumnModel;\r\n\t@Mock\r\n\tColumnModel mockNewColumnModelAfterCreate;\r\n\tpublic static final String OLD_COLUMN_MODEL_ID = \"4444\";\r\n\tpublic static final String NEW_COLUMN_MODEL_ID = \"837837\";\r\n\tprivate static final String testUserId = \"myUserId\";\r\n\r\n\tprivate static final String EVAL_ID_1 = \"eval ID 1\";\r\n\tprivate static final String EVAL_ID_2 = \"eval ID 2\";\r\n\tprivate static AdapterFactory adapterFactory = new AdapterFactoryImpl();\r\n\tprivate TeamMembershipStatus membershipStatus;\r\n\r\n\t@Before\r\n\tpublic void before() throws SynapseException, JSONObjectAdapterException {\r\n\t\tMockitoAnnotations.initMocks(this);\r\n\t\tmockSynapse = Mockito.mock(SynapseClient.class);\r\n\t\tmockSynapseProvider = Mockito.mock(SynapseProvider.class);\r\n\t\tmockUrlProvider = Mockito.mock(ServiceUrlProvider.class);\r\n\t\twhen(mockSynapseProvider.createNewClient()).thenReturn(mockSynapse);\r\n\t\tmockTokenProvider = Mockito.mock(TokenProvider.class);\r\n\t\tmockPaginatedMembershipRequest = Mockito.mock(PaginatedResults.class);\r\n\t\tmockActivity = Mockito.mock(Activity.class);\r\n\t\twhen(mockPaginatedMembershipRequest.getTotalNumberOfResults()).thenReturn(3L);\r\n\t\tsynapseClient = new SynapseClientImpl();\r\n\t\tsynapseClient.setSynapseProvider(mockSynapseProvider);\r\n\t\tsynapseClient.setTokenProvider(mockTokenProvider);\r\n\t\tsynapseClient.setServiceUrlProvider(mockUrlProvider);\r\n\r\n\t\t// Setup the the entity\r\n\t\tentity = new ExampleEntity();\r\n\t\tentity.setId(entityId);\r\n\t\tentity.setEntityType(ExampleEntity.class.getName());\r\n\t\tentity.setModifiedBy(testUserId);\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getEntityById(entityId)).thenReturn(entity);\r\n\t\t// Setup the annotations\r\n\t\tannos = new Annotations();\r\n\t\tannos.setId(entityId);\r\n\t\tannos.addAnnotation(\"string\", \"a string value\");\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getAnnotations(entityId)).thenReturn(annos);\r\n\t\t// Setup the Permissions\r\n\t\teup = new UserEntityPermissions();\r\n\t\teup.setCanDelete(true);\r\n\t\teup.setCanView(false);\r\n\t\teup.setOwnerPrincipalId(999L);\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getUsersEntityPermissions(entityId)).thenReturn(eup);\r\n\r\n\t\t// user can change permissions on eval 2, but not on 1\r\n\t\tuserEvaluationPermissions = new UserEvaluationPermissions();\r\n\t\tuserEvaluationPermissions.setCanChangePermissions(false);\r\n\t\twhen(mockSynapse.getUserEvaluationPermissions(EVAL_ID_1)).thenReturn(\r\n\t\t\t\tuserEvaluationPermissions);\r\n\r\n\t\tuserEvaluationPermissions = new UserEvaluationPermissions();\r\n\t\tuserEvaluationPermissions.setCanChangePermissions(true);\r\n\t\twhen(mockSynapse.getUserEvaluationPermissions(EVAL_ID_2)).thenReturn(\r\n\t\t\t\tuserEvaluationPermissions);\r\n\t\twhen(mockOldColumnModel.getId()).thenReturn(OLD_COLUMN_MODEL_ID);\r\n\t\twhen(mockNewColumnModelAfterCreate.getId()).thenReturn(NEW_COLUMN_MODEL_ID);\r\n\t\t\r\n\t\t// Setup the path\r\n\t\tpath = new EntityPath();\r\n\t\tpath.setPath(new ArrayList());\r\n\t\tEntityHeader header = new EntityHeader();\r\n\t\theader.setId(entityId);\r\n\t\theader.setName(\"RomperRuuuu\");\r\n\t\tpath.getPath().add(header);\r\n\t\t// the mock synapse should return this object\r\n\t\twhen(mockSynapse.getEntityPath(entityId)).thenReturn(path);\r\n\r\n\t\tpgugs = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tList ugs = new ArrayList();\r\n\t\tugs.add(new UserGroup());\r\n\t\tpgugs.setResults(ugs);\r\n\t\twhen(mockSynapse.getGroups(anyInt(), anyInt())).thenReturn(pgugs);\r\n\r\n\t\tpgups = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tList ups = new ArrayList();\r\n\t\tups.add(new UserProfile());\r\n\t\tpgups.setResults(ups);\r\n\t\twhen(mockSynapse.getUsers(anyInt(), anyInt())).thenReturn(pgups);\r\n\r\n\t\tpguts = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tList uts = new ArrayList();\r\n\t\tteamZ = new Team();\r\n\t\tteamZ.setId(\"1\");\r\n\t\tteamZ.setName(\"zygote\");\r\n\t\tuts.add(teamZ);\r\n\t\tteamA = new Team();\r\n\t\tteamA.setId(\"2\");\r\n\t\tteamA.setName(\"Amplitude\");\r\n\t\tuts.add(teamA);\r\n\t\tpguts.setResults(uts);\r\n\t\twhen(mockSynapse.getTeamsForUser(anyString(), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(pguts);\r\n\r\n\t\tacl = new AccessControlList();\r\n\t\tacl.setId(\"sys999\");\r\n\t\tSet ras = new HashSet();\r\n\t\tResourceAccess ra = new ResourceAccess();\r\n\t\tra.setPrincipalId(101L);\r\n\t\tra.setAccessType(AclUtils\r\n\t\t\t\t.getACCESS_TYPEs(PermissionLevel.CAN_ADMINISTER));\r\n\t\tacl.setResourceAccess(ras);\r\n\t\twhen(mockSynapse.getACL(anyString())).thenReturn(acl);\r\n\t\twhen(mockSynapse.createACL((AccessControlList) any())).thenReturn(acl);\r\n\t\twhen(mockSynapse.updateACL((AccessControlList) any())).thenReturn(acl);\r\n\t\twhen(mockSynapse.updateACL((AccessControlList) any(), eq(true)))\r\n\t\t\t\t.thenReturn(acl);\r\n\t\twhen(mockSynapse.updateACL((AccessControlList) any(), eq(false)))\r\n\t\t\t\t.thenReturn(acl);\r\n\t\twhen(mockSynapse.updateTeamACL(any(AccessControlList.class))).thenReturn(acl);\r\n\t\twhen(mockSynapse.getTeamACL(anyString())).thenReturn(acl);\r\n\r\n\t\tEntityHeader bene = new EntityHeader();\r\n\t\tbene.setId(\"syn999\");\r\n\t\twhen(mockSynapse.getEntityBenefactor(anyString())).thenReturn(bene);\r\n\r\n\t\torg.sagebionetworks.reflection.model.PaginatedResults batchHeaders = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tbatchHeaderResults = new ArrayList();\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\tEntityHeader h = new EntityHeader();\r\n\t\t\th.setId(\"syn\" + i);\r\n\t\t\tbatchHeaderResults.add(h);\r\n\t\t}\r\n\t\tbatchHeaders.setResults(batchHeaderResults);\r\n\t\twhen(mockSynapse.getEntityHeaderBatch(anyList())).thenReturn(\r\n\t\t\t\tbatchHeaders);\r\n\r\n\t\tList accessRequirements = new ArrayList();\r\n\t\taccessRequirements.add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD));\r\n\r\n\t\tint mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH\r\n\t\t\t\t| HAS_CHILDREN | ACCESS_REQUIREMENTS\r\n\t\t\t\t| UNMET_ACCESS_REQUIREMENTS;\r\n\t\tint emptyMask = 0;\r\n\t\tEntityBundle bundle = new EntityBundle();\r\n\t\tbundle.setEntity(entity);\r\n\t\tbundle.setAnnotations(annos);\r\n\t\tbundle.setPermissions(eup);\r\n\t\tbundle.setPath(path);\r\n\t\tbundle.setHasChildren(false);\r\n\t\tbundle.setAccessRequirements(accessRequirements);\r\n\t\tbundle.setUnmetAccessRequirements(accessRequirements);\r\n\t\tbundle.setBenefactorAcl(acl);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), Matchers.eq(mask)))\r\n\t\t\t\t.thenReturn(bundle);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), Matchers.eq(ENTITY | ANNOTATIONS | ROOT_WIKI_ID | FILE_HANDLES | PERMISSIONS | BENEFACTOR_ACL)))\r\n\t\t\t\t.thenReturn(bundle);\r\n\r\n\t\tEntityBundle emptyBundle = new EntityBundle();\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), Matchers.eq(emptyMask)))\r\n\t\t\t\t.thenReturn(emptyBundle);\r\n\r\n\t\twhen(mockSynapse.canAccess(\"syn101\", ACCESS_TYPE.READ))\r\n\t\t\t\t.thenReturn(true);\r\n\r\n\t\tpage = new WikiPage();\r\n\t\tpage.setId(\"testId\");\r\n\t\tpage.setMarkdown(\"my markdown\");\r\n\t\tpage.setParentWikiId(null);\r\n\t\tpage.setTitle(\"A Title\");\r\n\t\tv2Page = new V2WikiPage();\r\n\t\tv2Page.setId(\"v2TestId\");\r\n\t\tv2Page.setEtag(\"122333\");\r\n\t\thandle = new S3FileHandle();\r\n\t\thandle.setId(\"4422\");\r\n\t\thandle.setBucketName(\"bucket\");\r\n\t\thandle.setFileName(testFileName);\r\n\t\thandle.setKey(\"key\");\r\n\t\twhen(mockSynapse.getRawFileHandle(anyString())).thenReturn(handle);\r\n\t\torg.sagebionetworks.reflection.model.PaginatedResults ars = new org.sagebionetworks.reflection.model.PaginatedResults();\r\n\t\tars.setTotalNumberOfResults(0);\r\n\t\tars.setResults(new ArrayList());\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getAccessRequirements(any(RestrictableObjectDescriptor.class)))\r\n\t\t\t\t.thenReturn(ars);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getUnmetAccessRequirements(\r\n\t\t\t\t\t\tany(RestrictableObjectDescriptor.class),\r\n\t\t\t\t\t\tany(ACCESS_TYPE.class))).thenReturn(ars);\r\n\t\tmockEvaluation = Mockito.mock(Evaluation.class);\r\n\t\twhen(mockEvaluation.getStatus()).thenReturn(EvaluationStatus.OPEN);\r\n\t\twhen(mockSynapse.getEvaluation(anyString())).thenReturn(mockEvaluation);\r\n\t\tmockUserSessionData = Mockito.mock(UserSessionData.class);\r\n\t\tmockUserProfile = Mockito.mock(UserProfile.class);\r\n\t\twhen(mockSynapse.getUserSessionData()).thenReturn(mockUserSessionData);\r\n\t\twhen(mockUserSessionData.getProfile()).thenReturn(mockUserProfile);\r\n\t\twhen(mockUserProfile.getOwnerId()).thenReturn(MY_USER_PROFILE_OWNER_ID);\r\n\t\twhen(mockSynapse.getMyProfile()).thenReturn(mockUserProfile);\r\n\t\tUploadDaemonStatus status = new UploadDaemonStatus();\r\n\t\tString fileHandleId = \"myFileHandleId\";\r\n\t\tstatus.setFileHandleId(fileHandleId);\r\n\t\tstatus.setState(State.COMPLETED);\r\n\t\twhen(mockSynapse.getCompleteUploadDaemonStatus(anyString()))\r\n\t\t\t\t.thenReturn(status);\r\n\r\n\t\tstatus = new UploadDaemonStatus();\r\n\t\tstatus.setState(State.PROCESSING);\r\n\t\tstatus.setPercentComplete(.05d);\r\n\t\twhen(mockSynapse.startUploadDeamon(any(CompleteAllChunksRequest.class)))\r\n\t\t\t\t.thenReturn(status);\r\n\r\n\t\tPaginatedResults openInvites = new PaginatedResults();\r\n\t\topenInvites.setTotalNumberOfResults(0);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipInvitations(anyString(),\r\n\t\t\t\t\t\tanyString(), anyLong(), anyLong())).thenReturn(\r\n\t\t\t\topenInvites);\r\n\r\n\t\tPaginatedResults openRequests = new PaginatedResults();\r\n\t\topenRequests.setTotalNumberOfResults(0);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipRequests(anyString(), anyString(),\r\n\t\t\t\t\t\tanyLong(), anyLong())).thenReturn(openRequests);\r\n\t\tmembershipStatus = new TeamMembershipStatus();\r\n\t\tmembershipStatus.setCanJoin(false);\r\n\t\tmembershipStatus.setHasOpenInvitation(false);\r\n\t\tmembershipStatus.setHasOpenRequest(false);\r\n\t\tmembershipStatus.setHasUnmetAccessRequirement(false);\r\n\t\tmembershipStatus.setIsMember(false);\r\n\t\tmembershipStatus.setMembershipApprovalRequired(false);\r\n\t\twhen(mockSynapse.getTeamMembershipStatus(anyString(), anyString()))\r\n\t\t\t\t.thenReturn(membershipStatus);\r\n\r\n\t\tsentMessage = new MessageToUser();\r\n\t\tsentMessage.setId(\"987\");\r\n\t\twhen(mockSynapse.sendMessage(any(MessageToUser.class))).thenReturn(sentMessage);\r\n\t\twhen(mockSynapse.sendMessage(any(MessageToUser.class), anyString())).thenReturn(sentMessage);\r\n\r\n\t\t// getMyProjects getUserProjects\r\n\t\tPaginatedResults headers = new PaginatedResults();\r\n\t\theaders.setTotalNumberOfResults(1100);\r\n\t\tList projectHeaders = new ArrayList();\r\n\t\tList userProfile = new ArrayList();\r\n\t\tprojectHeaders.add(new ProjectHeader());\r\n\t\theaders.setResults(projectHeaders);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getMyProjects(any(ProjectListType.class),\r\n\t\t\t\t\t\tany(ProjectListSortColumn.class),\r\n\t\t\t\t\t\tany(SortDirection.class), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(headers);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getProjectsFromUser(anyLong(),\r\n\t\t\t\t\t\tany(ProjectListSortColumn.class),\r\n\t\t\t\t\t\tany(SortDirection.class), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(headers);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getProjectsForTeam(anyLong(),\r\n\t\t\t\t\t\tany(ProjectListSortColumn.class),\r\n\t\t\t\t\t\tany(SortDirection.class), anyInt(), anyInt()))\r\n\t\t\t\t.thenReturn(headers);\r\n\t\t\r\n\t\ttestUserProfile = new UserProfile();\r\n\t\ttestUserProfile.setUserName(\"Test User\");\r\n\t\twhen(mockSynapse.getUserProfile(eq(testUserId))).thenReturn(\r\n\t\t\t\ttestUserProfile);\r\n\t\t\r\n\t\tjoinTeamToken = new JoinTeamSignedToken();\r\n\t\tjoinTeamToken.setHmac(\"98765\");\r\n\t\tjoinTeamToken.setMemberId(\"1\");\r\n\t\tjoinTeamToken.setTeamId(\"2\");\r\n\t\tjoinTeamToken.setUserId(\"3\");\r\n\t\tencodedJoinTeamToken = SerializationUtils.serializeAndHexEncode(joinTeamToken);\r\n\t\t\r\n\t\tnotificationSettingsToken = new NotificationSettingsSignedToken();\r\n\t\tnotificationSettingsToken.setHmac(\"987654\");\r\n\t\tnotificationSettingsToken.setSettings(new Settings());\r\n\t\tnotificationSettingsToken.setUserId(\"4\");\r\n\t\tencodedNotificationSettingsToken = SerializationUtils.serializeAndHexEncode(notificationSettingsToken);\t\t\r\n\t}\r\n\r\n\tprivate AccessRequirement createAccessRequirement(ACCESS_TYPE type) {\r\n\t\tTermsOfUseAccessRequirement accessRequirement = new TermsOfUseAccessRequirement();\r\n\t\taccessRequirement.setConcreteType(TermsOfUseAccessRequirement.class\r\n\t\t\t\t.getName());\r\n\t\tRestrictableObjectDescriptor descriptor = new RestrictableObjectDescriptor();\r\n\t\tdescriptor.setId(\"101\");\r\n\t\tdescriptor.setType(RestrictableObjectType.ENTITY);\r\n\t\taccessRequirement.setSubjectIds(Arrays\r\n\t\t\t\t.asList(new RestrictableObjectDescriptor[] { descriptor }));\r\n\t\taccessRequirement.setAccessType(type);\r\n\t\treturn accessRequirement;\r\n\t}\r\n\r\n\tprivate void setupTeamInvitations() throws SynapseException {\r\n\t\tArrayList testInvitations = new ArrayList();\r\n\t\ttestInvitation = new MembershipInvtnSubmission();\r\n\t\ttestInvitation.setId(\"628319\");\r\n\t\ttestInvitation.setInviteeId(inviteeUserId);\r\n\t\ttestInvitations.add(testInvitation);\r\n\t\tPaginatedResults paginatedInvitations = new PaginatedResults();\r\n\t\tpaginatedInvitations.setResults(testInvitations);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipInvitationSubmissions(anyString(),\r\n\t\t\t\t\t\tanyString(), anyLong(), anyLong())).thenReturn(\r\n\t\t\t\tpaginatedInvitations);\r\n\r\n\t\tinviteeUserProfile = new UserProfile();\r\n\t\tinviteeUserProfile.setUserName(\"Invitee User\");\r\n\t\tinviteeUserProfile.setOwnerId(inviteeUserId);\r\n\t\twhen(mockSynapse.getUserProfile(eq(inviteeUserId))).thenReturn(\r\n\t\t\t\tinviteeUserProfile);\r\n\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityBundleAll() throws RestServiceException {\r\n\t\t// Make sure we can get all parts of the bundel\r\n\t\tint mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH\r\n\t\t\t\t| HAS_CHILDREN | ACCESS_REQUIREMENTS\r\n\t\t\t\t| UNMET_ACCESS_REQUIREMENTS;\r\n\t\tEntityBundle bundle = synapseClient.getEntityBundle(entityId, mask);\r\n\t\tassertNotNull(bundle);\r\n\t\t// We should have all of the strings\r\n\t\tassertNotNull(bundle.getEntity());\r\n\t\tassertNotNull(bundle.getAnnotations());\r\n\t\tassertNotNull(bundle.getPath());\r\n\t\tassertNotNull(bundle.getPermissions());\r\n\t\tassertNotNull(bundle.getHasChildren());\r\n\t\tassertNotNull(bundle.getAccessRequirements());\r\n\t\tassertNotNull(bundle.getUnmetAccessRequirements());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityBundleNone() throws RestServiceException {\r\n\t\t// Make sure all are null\r\n\t\tint mask = 0x0;\r\n\t\tEntityBundle bundle = synapseClient.getEntityBundle(entityId, mask);\r\n\t\tassertNotNull(bundle);\r\n\t\t// We should have all of the strings\r\n\t\tassertNull(bundle.getEntity());\r\n\t\tassertNull(bundle.getAnnotations());\r\n\t\tassertNull(bundle.getPath());\r\n\t\tassertNull(bundle.getPermissions());\r\n\t\tassertNull(bundle.getHasChildren());\r\n\t\tassertNull(bundle.getAccessRequirements());\r\n\t\tassertNull(bundle.getUnmetAccessRequirements());\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testParseEntityFromJsonNoType()\r\n\t\t\tthrows JSONObjectAdapterException {\r\n\t\tExampleEntity example = new ExampleEntity();\r\n\t\texample.setName(\"some name\");\r\n\t\texample.setDescription(\"some description\");\r\n\t\t// do not set the type\r\n\t\tString json = EntityFactory.createJSONStringForEntity(example);\r\n\t\t// This will fail as the type is required\r\n\t\tsynapseClient.parseEntityFromJson(json);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testParseEntityFromJson() throws JSONObjectAdapterException {\r\n\t\tExampleEntity example = new ExampleEntity();\r\n\t\texample.setName(\"some name\");\r\n\t\texample.setDescription(\"some description\");\r\n\t\texample.setEntityType(ExampleEntity.class.getName());\r\n\t\tString json = EntityFactory.createJSONStringForEntity(example);\r\n\t\t// System.out.println(json);\r\n\t\t// Now make sure this can be read back\r\n\t\tExampleEntity clone = (ExampleEntity) synapseClient\r\n\t\t\t\t.parseEntityFromJson(json);\r\n\t\tassertEquals(example, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateOrUpdateEntityFalse()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setDescription(\"some description\");\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setDescription(\"some description\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(\"syn123\");\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.putEntity(in)).thenReturn(out);\r\n\t\tString result = synapseClient.createOrUpdateEntity(in, null, false);\r\n\t\tassertEquals(out.getId(), result);\r\n\t\tverify(mockSynapse).putEntity(in);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateOrUpdateEntityTrue()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setDescription(\"some description\");\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setDescription(\"some description\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(\"syn123\");\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.createEntity(in)).thenReturn(out);\r\n\t\tString result = synapseClient.createOrUpdateEntity(in, null, true);\r\n\t\tassertEquals(out.getId(), result);\r\n\t\tverify(mockSynapse).createEntity(in);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateOrUpdateEntityTrueWithAnnos()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setDescription(\"some description\");\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tAnnotations annos = new Annotations();\r\n\t\tannos.addAnnotation(\"someString\", \"one\");\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setDescription(\"some description\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(\"syn123\");\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.createEntity(in)).thenReturn(out);\r\n\t\tString result = synapseClient.createOrUpdateEntity(in, annos, true);\r\n\t\tassertEquals(out.getId(), result);\r\n\t\tverify(mockSynapse).createEntity(in);\r\n\t\tannos.setEtag(out.getEtag());\r\n\t\tannos.setId(out.getId());\r\n\t\tverify(mockSynapse).updateAnnotations(out.getId(), annos);\r\n\t}\r\n\r\n\t\r\n\r\n\t@Test\r\n\tpublic void testMoveEntity()\r\n\t\t\tthrows JSONObjectAdapterException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tString oldParentId = \"syn1\", newParentId = \"syn2\";\r\n\t\tExampleEntity in = new ExampleEntity();\r\n\t\tin.setName(\"some name\");\r\n\t\tin.setParentId(oldParentId);\r\n\t\tin.setId(entityId);\r\n\t\tin.setEntityType(ExampleEntity.class.getName());\r\n\r\n\t\tExampleEntity out = new ExampleEntity();\r\n\t\tout.setName(\"some name\");\r\n\t\tout.setEntityType(ExampleEntity.class.getName());\r\n\t\tout.setId(entityId);\r\n\t\tout.setParentId(newParentId);\r\n\t\tout.setEtag(\"45\");\r\n\r\n\t\t// when in comes in then return out.\r\n\t\twhen(mockSynapse.putEntity(in)).thenReturn(out);\r\n\t\twhen(mockSynapse.getEntityById(entityId)).thenReturn(in);\r\n\t\tEntity result = synapseClient.moveEntity(entityId, newParentId);\r\n\t\tassertEquals(newParentId, result.getParentId());\r\n\t\tverify(mockSynapse).getEntityById(entityId);\r\n\t\tverify(mockSynapse).putEntity(any(Entity.class));\r\n\t}\r\n\t@Test\r\n\tpublic void testGetEntityBenefactorAcl() throws Exception {\r\n\t\tEntityBundle bundle = new EntityBundle();\r\n\t\tbundle.setBenefactorAcl(acl);\r\n\t\twhen(mockSynapse.getEntityBundle(\"syn101\", EntityBundle.BENEFACTOR_ACL))\r\n\t\t\t\t.thenReturn(bundle);\r\n\t\tAccessControlList clone = synapseClient\r\n\t\t\t\t.getEntityBenefactorAcl(\"syn101\");\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateAcl() throws Exception {\r\n\t\tAccessControlList clone = synapseClient.createAcl(acl);\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateAcl() throws Exception {\r\n\t\tAccessControlList clone = synapseClient.updateAcl(acl);\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateAclRecursive() throws Exception {\r\n\t\tAccessControlList clone = synapseClient.updateAcl(acl, true);\r\n\t\tassertEquals(acl, clone);\r\n\t\tverify(mockSynapse).updateACL(any(AccessControlList.class), eq(true));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testDeleteAcl() throws Exception {\r\n\t\tEntityBundle bundle = new EntityBundle();\r\n\t\tbundle.setBenefactorAcl(acl);\r\n\t\twhen(mockSynapse.getEntityBundle(\"syn101\", EntityBundle.BENEFACTOR_ACL))\r\n\t\t\t\t.thenReturn(bundle);\r\n\t\tAccessControlList clone = synapseClient.deleteAcl(\"syn101\");\r\n\t\tassertEquals(acl, clone);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testHasAccess() throws Exception {\r\n\t\tassertTrue(synapseClient.hasAccess(\"syn101\", \"READ\"));\r\n\t}\r\n\r\n\r\n\t@Test\r\n\tpublic void testGetUserProfile() throws Exception {\r\n\t\t// verify call is directly calling the synapse client provider\r\n\t\tString testRepoUrl = \"http://mytestrepourl\";\r\n\t\twhen(mockUrlProvider.getRepositoryServiceUrl()).thenReturn(testRepoUrl);\r\n\t\tUserProfile userProfile = synapseClient.getUserProfile(testUserId);\r\n\t\tassertEquals(userProfile, testUserProfile);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetProjectById() throws Exception {\r\n\t\tString projectId = \"syn1029\";\r\n\t\tProject project = new Project();\r\n\t\tproject.setId(projectId);\r\n\t\twhen(mockSynapse.getEntityById(projectId)).thenReturn(project);\r\n\r\n\t\tProject actualProject = synapseClient.getProject(projectId);\r\n\t\tassertEquals(project, actualProject);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetJSONEntity() throws Exception {\r\n\r\n\t\tJSONObject json = EntityFactory.createJSONObjectForEntity(entity);\r\n\t\tMockito.when(mockSynapse.getEntity(anyString())).thenReturn(json);\r\n\r\n\t\tString testRepoUri = \"/testservice\";\r\n\r\n\t\tsynapseClient.getJSONEntity(testRepoUri);\r\n\t\t// verify that this call uses Synapse.getEntity(testRepoUri)\r\n\t\tverify(mockSynapse).getEntity(testRepoUri);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetWikiHeaderTree() throws Exception {\r\n\t\tPaginatedResults headerTreeResults = new PaginatedResults();\r\n\t\twhen(mockSynapse.getWikiHeaderTree(anyString(), any(ObjectType.class)))\r\n\t\t\t\t.thenReturn(headerTreeResults);\r\n\t\tsynapseClient.getWikiHeaderTree(\"testId\", ObjectType.ENTITY.toString());\r\n\t\tverify(mockSynapse).getWikiHeaderTree(anyString(),\r\n\t\t\t\teq(ObjectType.ENTITY));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetWikiAttachmentHandles() throws Exception {\r\n\t\tFileHandleResults testResults = new FileHandleResults();\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getWikiAttachmenthHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(testResults);\r\n\t\tsynapseClient.getWikiAttachmentHandles(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getWikiAttachmenthHandles(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testDeleteV2WikiPage() throws Exception {\r\n\t\tsynapseClient.deleteV2WikiPage(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).deleteV2WikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiPage() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.getV2WikiPage(new WikiPageKey(\"syn123\", ObjectType.ENTITY\r\n\t\t\t\t.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getV2WikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiPage(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(v2Page);\r\n\t\tsynapseClient.getVersionOfV2WikiPage(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).getVersionOfV2WikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateV2WikiPage() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.updateV2WikiPage(anyString(),\r\n\t\t\t\t\t\tany(ObjectType.class), any(V2WikiPage.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.updateV2WikiPage(\"testId\", ObjectType.ENTITY.toString(),\r\n\t\t\t\tv2Page);\r\n\t\tverify(mockSynapse).updateV2WikiPage(anyString(),\r\n\t\t\t\tany(ObjectType.class), any(V2WikiPage.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRestoreV2WikiPage() throws Exception {\r\n\t\tString wikiId = \"syn123\";\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.restoreV2WikiPage(anyString(),\r\n\t\t\t\t\t\tany(ObjectType.class), any(String.class), anyLong()))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.restoreV2WikiPage(\"ownerId\",\r\n\t\t\t\tObjectType.ENTITY.toString(), wikiId, new Long(2));\r\n\t\tverify(mockSynapse).restoreV2WikiPage(anyString(),\r\n\t\t\t\tany(ObjectType.class), any(String.class), anyLong());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiHeaderTree() throws Exception {\r\n\t\tPaginatedResults headerTreeResults = new PaginatedResults();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getV2WikiHeaderTree(anyString(),\r\n\t\t\t\t\t\tany(ObjectType.class))).thenReturn(headerTreeResults);\r\n\t\tsynapseClient.getV2WikiHeaderTree(\"testId\",\r\n\t\t\t\tObjectType.ENTITY.toString());\r\n\t\tverify(mockSynapse).getV2WikiHeaderTree(anyString(),\r\n\t\t\t\tany(ObjectType.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiOrderHint() throws Exception {\r\n\t\tV2WikiOrderHint orderHint = new V2WikiOrderHint();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2OrderHint(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(orderHint);\r\n\t\tsynapseClient.getV2WikiOrderHint(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getV2OrderHint(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateV2WikiOrderHint() throws Exception {\r\n\t\tV2WikiOrderHint orderHint = new V2WikiOrderHint();\r\n\t\twhen(mockSynapse.updateV2WikiOrderHint(any(V2WikiOrderHint.class)))\r\n\t\t\t\t.thenReturn(orderHint);\r\n\t\tsynapseClient.updateV2WikiOrderHint(orderHint);\r\n\t\tverify(mockSynapse).updateV2WikiOrderHint(any(V2WikiOrderHint.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiHistory() throws Exception {\r\n\t\tPaginatedResults historyResults = new PaginatedResults();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiHistory(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class), any(Long.class))).thenReturn(\r\n\t\t\t\thistoryResults);\r\n\t\tsynapseClient.getV2WikiHistory(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(10), new Long(0));\r\n\t\tverify(mockSynapse).getV2WikiHistory(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class), any(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetV2WikiAttachmentHandles() throws Exception {\r\n\t\tFileHandleResults testResults = new FileHandleResults();\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiAttachmentHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(testResults);\r\n\t\tsynapseClient.getV2WikiAttachmentHandles(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getV2WikiAttachmentHandles(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiAttachmentHandles(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(testResults);\r\n\t\tsynapseClient.getVersionOfV2WikiAttachmentHandles(new WikiPageKey(\r\n\t\t\t\t\"syn123\", ObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).getVersionOfV2WikiAttachmentHandles(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testZipAndUpload() throws IOException, RestServiceException,\r\n\t\t\tJSONObjectAdapterException, SynapseException {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createFileHandle(any(File.class), any(String.class)))\r\n\t\t\t\t.thenReturn(handle);\r\n\t\tsynapseClient.zipAndUploadFile(\"markdown\", \"fileName\");\r\n\t\tverify(mockSynapse)\r\n\t\t\t\t.createFileHandle(any(File.class), any(String.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetMarkdown() throws IOException, RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tString someMarkDown = \"someMarkDown\";\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.downloadV2WikiMarkdown(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(someMarkDown);\r\n\t\tsynapseClient.getMarkdown(new WikiPageKey(\"syn123\", ObjectType.ENTITY\r\n\t\t\t\t.toString(), \"20\"));\r\n\t\tverify(mockSynapse).downloadV2WikiMarkdown(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.downloadVersionOfV2WikiMarkdown(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(someMarkDown);\r\n\t\tsynapseClient.getVersionOfMarkdown(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).downloadVersionOfV2WikiMarkdown(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateV2WikiPageWithV1() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.createWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\t\t\tany(WikiPage.class))).thenReturn(page);\r\n\t\tsynapseClient.createV2WikiPageWithV1(\"testId\",\r\n\t\t\t\tObjectType.ENTITY.toString(), page);\r\n\t\tverify(mockSynapse).createWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\tany(WikiPage.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateV2WikiPageWithV1() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse.updateWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\t\t\tany(WikiPage.class))).thenReturn(page);\r\n\t\tsynapseClient.updateV2WikiPageWithV1(\"testId\",\r\n\t\t\t\tObjectType.ENTITY.toString(), page);\r\n\t\tverify(mockSynapse).updateWikiPage(anyString(), any(ObjectType.class),\r\n\t\t\t\tany(WikiPage.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void getV2WikiPageAsV1() throws Exception {\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getWikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tsynapseClient.getV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse).getWikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\t\t// asking for the same page twice should result in a cache hit, and it\r\n\t\t// should not ask for it from the synapse client\r\n\t\tsynapseClient.getV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"));\r\n\t\tverify(mockSynapse, Mockito.times(1)).getWikiPage(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class));\r\n\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getWikiPageForVersion(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tany(Long.class))).thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiPage(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tanyLong())).thenReturn(v2Page);\r\n\t\tsynapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse).getWikiPageForVersion(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t\t// asking for the same page twice should result in a cache hit, and it\r\n\t\t// should not ask for it from the synapse client\r\n\t\tsynapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey(\"syn123\",\r\n\t\t\t\tObjectType.ENTITY.toString(), \"20\"), new Long(0));\r\n\t\tverify(mockSynapse, Mockito.times(1)).getWikiPageForVersion(\r\n\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\tany(Long.class));\r\n\t}\r\n\r\n\tprivate void resetUpdateExternalFileHandleMocks(String testId,\r\n\t\t\tFileEntity file, ExternalFileHandle handle)\r\n\t\t\tthrows SynapseException, JSONObjectAdapterException {\r\n\t\treset(mockSynapse);\r\n\t\twhen(mockSynapse.getEntityById(testId)).thenReturn(file);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createExternalFileHandle(any(ExternalFileHandle.class)))\r\n\t\t\t\t.thenReturn(handle);\r\n\t\twhen(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testUpdateExternalFileHandle() throws Exception {\r\n\t\t// verify call is directly calling the synapse client provider, and it\r\n\t\t// tries to rename the entity to the filename\r\n\t\tString myFileName = \"testFileName.csv\";\r\n\t\tString testUrl = \" http://mytesturl/\" + myFileName;\r\n\t\tString testId = \"myTestId\";\r\n\t\tString md5 = \"e10e3f4491440ce7b48edc97f03307bb\";\r\n\t\tLong fileSize=2048L;\r\n\t\tFileEntity file = new FileEntity();\r\n\t\tString originalFileEntityName = \"syn1223\";\r\n\t\tfile.setName(originalFileEntityName);\r\n\t\tfile.setId(testId);\r\n\t\tfile.setDataFileHandleId(\"handle1\");\r\n\t\tExternalFileHandle handle = new ExternalFileHandle();\r\n\t\thandle.setExternalURL(testUrl);\r\n\r\n\t\tresetUpdateExternalFileHandleMocks(testId, file, handle);\r\n\t\tsynapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId);\r\n\r\n\t\tverify(mockSynapse).getEntityById(testId);\r\n\t\t\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(ExternalFileHandle.class);\r\n\t\tverify(mockSynapse).createExternalFileHandle(captor.capture());\r\n\t\tExternalFileHandle capturedValue = captor.getValue();\r\n\t\tassertEquals(testUrl.trim(), capturedValue.getExternalURL());\r\n\t\tassertEquals(md5, capturedValue.getContentMd5());\r\n//\t\tassertEquals(fileSize, capturedValue.getContentSize());\r\n\t\t\r\n\t\tverify(mockSynapse).putEntity(any(FileEntity.class));\r\n\r\n\t\t// and if rename fails, verify all is well (but the FileEntity name is\r\n\t\t// not updated)\r\n\t\tresetUpdateExternalFileHandleMocks(testId, file, handle);\r\n\t\tfile.setName(originalFileEntityName);\r\n\t\t// first call should return file, second call to putEntity should throw\r\n\t\t// an exception\r\n\t\twhen(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file)\r\n\t\t\t\t.thenThrow(\r\n\t\t\t\t\t\tnew IllegalArgumentException(\r\n\t\t\t\t\t\t\t\t\"invalid name for some reason\"));\r\n\t\tsynapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId);\r\n\r\n\t\t// called createExternalFileHandle\r\n\t\tverify(mockSynapse).createExternalFileHandle(\r\n\t\t\t\tany(ExternalFileHandle.class));\r\n\t\t// and it should have called putEntity again\r\n\t\tverify(mockSynapse).putEntity(any(FileEntity.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateExternalFile() throws Exception {\r\n\t\t// test setting file handle name\r\n\t\tString parentEntityId = \"syn123333\";\r\n\t\tString externalUrl = \" sftp://foobar.edu/b/test.txt\";\r\n\t\tString fileName = \"testing.txt\";\r\n\t\tString md5 = \"e10e3f4491440ce7b48edc97f03307bb\";\r\n\t\tLong fileSize = 1024L;\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createExternalFileHandle(any(ExternalFileHandle.class)))\r\n\t\t\t\t.thenReturn(new ExternalFileHandle());\r\n\t\twhen(mockSynapse.createEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\tnew FileEntity());\r\n\t\tsynapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId);\r\n\t\tArgumentCaptor captor = ArgumentCaptor\r\n\t\t\t\t.forClass(ExternalFileHandle.class);\r\n\t\tverify(mockSynapse).createExternalFileHandle(captor.capture());\r\n\t\tExternalFileHandle handle = captor.getValue();\r\n\t\t// verify name is set\r\n\t\tassertEquals(fileName, handle.getFileName());\r\n\t\tassertEquals(externalUrl.trim(), handle.getExternalURL());\r\n\t\tassertEquals(storageLocationId, handle.getStorageLocationId());\r\n\t\tassertEquals(md5, handle.getContentMd5());\r\n//\t\tassertEquals(fileSize, handle.getContentSize());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testCreateExternalFileAutoname() throws Exception {\r\n\t\t// test setting file handle name\r\n\t\tString parentEntityId = \"syn123333\";\r\n\t\tString externalUrl = \"sftp://foobar.edu/b/test.txt\";\r\n\t\tString expectedAutoFilename = \"test.txt\";\r\n\t\tString fileName = null;\r\n\t\tString md5 = \"e10e3f4491440ce7b48edc97f03307bb\";\r\n\t\tLong fileSize = 1024L;\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.createExternalFileHandle(any(ExternalFileHandle.class)))\r\n\t\t\t\t.thenReturn(new ExternalFileHandle());\r\n\t\twhen(mockSynapse.createEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\tnew FileEntity());\r\n\t\tsynapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId);\r\n\t\tArgumentCaptor captor = ArgumentCaptor\r\n\t\t\t\t.forClass(ExternalFileHandle.class);\r\n\t\tverify(mockSynapse).createExternalFileHandle(captor.capture());\r\n\t\tExternalFileHandle handle = captor.getValue();\r\n\t\t// verify name is set\r\n\t\tassertEquals(expectedAutoFilename, handle.getFileName());\r\n\t\tassertEquals(externalUrl, handle.getExternalURL());\r\n\t\tassertEquals(storageLocationId, handle.getStorageLocationId());\r\n\t\tassertEquals(md5, handle.getContentMd5());\r\n\t\t\r\n\t\t//also check the entity name\r\n\t\tArgumentCaptor entityCaptor = ArgumentCaptor.forClass(Entity.class);\r\n\t\tverify(mockSynapse).createEntity(entityCaptor.capture());\r\n\t\tassertEquals(expectedAutoFilename, entityCaptor.getValue().getName());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityDoi() throws Exception {\r\n\t\t// wiring test\r\n\t\tDoi testDoi = new Doi();\r\n\t\ttestDoi.setDoiStatus(DoiStatus.CREATED);\r\n\t\ttestDoi.setId(\"test doi id\");\r\n\t\ttestDoi.setCreatedBy(\"Test User\");\r\n\t\ttestDoi.setCreatedOn(new Date());\r\n\t\ttestDoi.setObjectId(\"syn1234\");\r\n\t\tMockito.when(mockSynapse.getEntityDoi(anyString(), anyLong()))\r\n\t\t\t\t.thenReturn(testDoi);\r\n\t\tsynapseClient.getEntityDoi(\"test entity id\", null);\r\n\t\tverify(mockSynapse).getEntityDoi(anyString(), anyLong());\r\n\t}\r\n\r\n\tprivate FileEntity getTestFileEntity() {\r\n\t\tFileEntity testFileEntity = new FileEntity();\r\n\t\ttestFileEntity.setId(\"5544\");\r\n\t\ttestFileEntity.setName(testFileName);\r\n\t\treturn testFileEntity;\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testGetEntityDoiNotFound() throws Exception {\r\n\t\t// wiring test\r\n\t\tMockito.when(mockSynapse.getEntityDoi(anyString(), anyLong()))\r\n\t\t\t\t.thenThrow(new SynapseNotFoundException());\r\n\t\tsynapseClient.getEntityDoi(\"test entity id\", null);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCreateDoi() throws Exception {\r\n\t\t// wiring test\r\n\t\tsynapseClient.createDoi(\"test entity id\", null);\r\n\t\tverify(mockSynapse).createEntityDoi(anyString(), anyLong());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetUploadDaemonStatus() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\tsynapseClient.getUploadDaemonStatus(\"daemonId\");\r\n\t\tverify(mockSynapse).getCompleteUploadDaemonStatus(anyString());\r\n\t}\r\n\r\n\t/**\r\n\t * Direct upload tests. Most of the methods are simple pass-throughs to the\r\n\t * Java Synapse client, but completeUpload has additional logic\r\n\t * \r\n\t * @throws JSONObjectAdapterException\r\n\t * @throws SynapseException\r\n\t * @throws RestServiceException\r\n\t */\r\n\t@Test\r\n\tpublic void testCompleteUpload() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\tFileEntity testFileEntity = getTestFileEntity();\r\n\t\twhen(mockSynapse.createEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\ttestFileEntity);\r\n\t\twhen(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(\r\n\t\t\t\ttestFileEntity);\r\n\r\n\t\t// parent entity has no immediate children\r\n\t\tEntityIdList childEntities = new EntityIdList();\r\n\t\tchildEntities.setIdList(new ArrayList());\r\n\r\n\t\tsynapseClient.setFileEntityFileHandle(null, null, \"parentEntityId\");\r\n\r\n\t\t// it should have tried to create a new entity (since entity id was\r\n\t\t// null)\r\n\t\tverify(mockSynapse).createEntity(any(FileEntity.class));\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testGetFileEntityIdWithSameNameNotFound()\r\n\t\t\tthrows JSONObjectAdapterException, SynapseException,\r\n\t\t\tRestServiceException, JSONException {\r\n\t\tJSONObject queryResult = new JSONObject();\r\n\t\tqueryResult.put(\"totalNumberOfResults\", (long) 0);\r\n\t\twhen(mockSynapse.query(anyString())).thenReturn(queryResult); // TODO\r\n\r\n\t\tString fileEntityId = synapseClient.getFileEntityIdWithSameName(\r\n\t\t\t\ttestFileName, \"parentEntityId\");\r\n\t}\r\n\r\n\t@Test(expected = ConflictException.class)\r\n\tpublic void testGetFileEntityIdWithSameNameConflict()\r\n\t\t\tthrows JSONObjectAdapterException, SynapseException,\r\n\t\t\tRestServiceException, JSONException {\r\n\t\tFolder folder = new Folder();\r\n\t\tfolder.setName(testFileName);\r\n\t\tJSONObject queryResult = new JSONObject();\r\n\t\tJSONArray results = new JSONArray();\r\n\r\n\t\t// Set up results.\r\n\t\tJSONObject objectResult = EntityFactory\r\n\t\t\t\t.createJSONObjectForEntity(folder);\r\n\t\tJSONArray typeArray = new JSONArray();\r\n\t\ttypeArray.put(\"Folder\");\r\n\t\tobjectResult.put(\"entity.concreteType\", typeArray);\r\n\t\tresults.put(objectResult);\r\n\r\n\t\t// Set up query result.\r\n\t\tqueryResult.put(\"totalNumberOfResults\", (long) 1);\r\n\t\tqueryResult.put(\"results\", results);\r\n\r\n\t\t// Have results returned in query.\r\n\t\twhen(mockSynapse.query(anyString())).thenReturn(queryResult);\r\n\r\n\t\tString fileEntityId = synapseClient.getFileEntityIdWithSameName(\r\n\t\t\t\ttestFileName, \"parentEntityId\");\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetFileEntityIdWithSameNameFound() throws JSONException,\r\n\t\t\tJSONObjectAdapterException, SynapseException, RestServiceException {\r\n\t\tFileEntity file = getTestFileEntity();\r\n\t\tJSONObject queryResult = new JSONObject();\r\n\t\tJSONArray results = new JSONArray();\r\n\r\n\t\t// Set up results.\r\n\t\tJSONObject objectResult = EntityFactory.createJSONObjectForEntity(file);\r\n\t\tJSONArray typeArray = new JSONArray();\r\n\t\ttypeArray.put(FileEntity.class.getName());\r\n\t\tobjectResult.put(\"entity.concreteType\", typeArray);\r\n\t\tobjectResult.put(\"entity.id\", file.getId());\r\n\t\tresults.put(objectResult);\r\n\t\tqueryResult.put(\"totalNumberOfResults\", (long) 1);\r\n\t\tqueryResult.put(\"results\", results);\r\n\r\n\t\t// Have results returned in query.\r\n\t\twhen(mockSynapse.query(anyString())).thenReturn(queryResult);\r\n\r\n\t\tString fileEntityId = synapseClient.getFileEntityIdWithSameName(\r\n\t\t\t\ttestFileName, \"parentEntityId\");\r\n\t\tassertEquals(fileEntityId, file.getId());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInviteMemberOpenInvitations() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setHasOpenInvitation(true);\r\n\t\t// verify it does not create a new invitation since one is already open\r\n\t\tsynapseClient.inviteMember(\"123\", \"a team\", \"\", \"\");\r\n\t\tverify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(),\r\n\t\t\t\tanyString(), anyString(), anyString());\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipInvitation(\r\n\t\t\t\tany(MembershipInvtnSubmission.class), anyString(), anyString());\r\n\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRequestMemberOpenRequests() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setHasOpenRequest(true);\r\n\t\t// verify it does not create a new request since one is already open\r\n\t\tsynapseClient.requestMembership(\"123\", \"a team\", \"let me join\", TEST_HOME_PAGE_BASE, null);\r\n\t\tverify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(),\r\n\t\t\t\tanyString(), eq(TEST_HOME_PAGE_BASE+\"#!Team:\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class);\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), anyString(), anyString());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInviteMemberCanJoin() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setCanJoin(true);\r\n\t\tsynapseClient.inviteMember(\"123\", \"a team\", \"\", TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+\"#!Team:\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRequestMembershipCanJoin() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tmembershipStatus.setCanJoin(true);\r\n\t\tsynapseClient.requestMembership(\"123\", \"a team\", \"\", TEST_HOME_PAGE_BASE, new Date());\r\n\t\tverify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+\"#!Team:\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInviteMember() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tsynapseClient.inviteMember(\"123\", \"a team\", \"\", TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).createMembershipInvitation(\r\n\t\t\t\tany(MembershipInvtnSubmission.class), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:JoinTeam/\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testRequestMembership() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class);\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), anyString(), anyString());\r\n\t\tString teamId = \"a team\";\r\n\t\tString message= \"let me join\";\r\n\t\tDate expiresOn = null;\r\n\t\tsynapseClient.requestMembership(\"123\", teamId, message, TEST_HOME_PAGE_BASE, expiresOn);\r\n\t\tverify(mockSynapse).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:JoinTeam/\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t\tMembershipRqstSubmission request = captor.getValue();\r\n\t\tassertEquals(expiresOn, request.getExpiresOn());\r\n\t\tassertEquals(teamId, request.getTeamId());\r\n\t\tassertEquals(message, request.getMessage());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testRequestMembershipWithExpiresOn() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class);\r\n\t\tverify(mockSynapse, Mockito.times(0)).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), anyString(), anyString());\r\n\t\tString teamId = \"a team\";\r\n\t\tString message= \"let me join\";\r\n\t\tDate expiresOn = new Date();\r\n\t\tsynapseClient.requestMembership(\"123\", teamId, message, TEST_HOME_PAGE_BASE, expiresOn);\r\n\t\tverify(mockSynapse).createMembershipRequest(\r\n\t\t\t\tcaptor.capture(), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:JoinTeam/\"), eq(TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\"));\r\n\t\tMembershipRqstSubmission request = captor.getValue();\r\n\t\tassertEquals(expiresOn, request.getExpiresOn());\r\n\t\tassertEquals(teamId, request.getTeamId());\r\n\t\tassertEquals(message, request.getMessage());\r\n\t}\r\n\r\n\r\n\t@Test\r\n\tpublic void testGetOpenRequestCountUnauthorized() throws SynapseException,\r\n\t\t\tRestServiceException {\r\n\t\t// is not an admin\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\ttestTeamMember.setIsAdmin(false);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\r\n\t\tLong count = synapseClient.getOpenRequestCount(\"myUserId\", \"myTeamId\");\r\n\t\t// should never ask for open request count\r\n\t\tverify(mockSynapse, Mockito.never()).getOpenMembershipRequests(\r\n\t\t\t\tanyString(), anyString(), anyLong(), anyLong());\r\n\t\tassertNull(count);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetOpenRequestCount() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\t// is admin\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\ttestTeamMember.setIsAdmin(true);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\r\n\t\tLong testCount = 42L;\r\n\t\tPaginatedResults testOpenRequests = new PaginatedResults();\r\n\t\ttestOpenRequests.setTotalNumberOfResults(testCount);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getOpenMembershipRequests(anyString(), anyString(),\r\n\t\t\t\t\t\tanyLong(), anyLong())).thenReturn(testOpenRequests);\r\n\r\n\t\tLong count = synapseClient.getOpenRequestCount(\"myUserId\", \"myTeamId\");\r\n\r\n\t\tverify(mockSynapse, Mockito.times(1)).getOpenMembershipRequests(\r\n\t\t\t\tanyString(), anyString(), anyLong(), anyLong());\r\n\t\tassertEquals(testCount, count);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetOpenTeamInvitations() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tsetupTeamInvitations();\r\n\t\tint limit = 55;\r\n\t\tint offset = 2;\r\n\t\tString teamId = \"132\";\r\n\t\tList invitationBundles = synapseClient\r\n\t\t\t\t.getOpenTeamInvitations(teamId, limit, offset);\r\n\t\tverify(mockSynapse).getOpenMembershipInvitationSubmissions(eq(teamId),\r\n\t\t\t\tanyString(), eq((long) limit), eq((long) offset));\r\n\t\t// we set this up so that a single invite would be returned. Verify that\r\n\t\t// it is the one we're looking for\r\n\t\tassertEquals(1, invitationBundles.size());\r\n\t\tOpenTeamInvitationBundle invitationBundle = invitationBundles.get(0);\r\n\t\tassertEquals(inviteeUserProfile, invitationBundle.getUserProfile());\r\n\t\tassertEquals(testInvitation, invitationBundle.getMembershipInvtnSubmission());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetTeamBundle() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\t// set team member count\r\n\t\tLong testMemberCount = 111L;\r\n\t\tPaginatedResults allMembers = new PaginatedResults();\r\n\t\tallMembers.setTotalNumberOfResults(testMemberCount);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getTeamMembers(anyString(), anyString(), anyLong(),\r\n\t\t\t\t\t\tanyLong())).thenReturn(allMembers);\r\n\r\n\t\t// set team\r\n\t\tTeam team = new Team();\r\n\t\tteam.setId(\"test team id\");\r\n\t\twhen(mockSynapse.getTeam(anyString())).thenReturn(team);\r\n\t\t\r\n\t\t// is member\r\n\t\tTeamMembershipStatus membershipStatus = new TeamMembershipStatus();\r\n\t\tmembershipStatus.setIsMember(true);\r\n\t\twhen(mockSynapse.getTeamMembershipStatus(anyString(), anyString()))\r\n\t\t\t\t.thenReturn(membershipStatus);\r\n\t\t// is admin\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\tboolean isAdmin = true;\r\n\t\ttestTeamMember.setIsAdmin(isAdmin);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\r\n\t\t// make the call\r\n\t\tTeamBundle bundle = synapseClient.getTeamBundle(\"myUserId\", \"myTeamId\",\r\n\t\t\t\ttrue);\r\n\r\n\t\t// now verify round all values were returned in the bundle (based on the\r\n\t\t// mocked service calls)\r\n\t\tassertEquals(team, bundle.getTeam());\r\n\t\tassertEquals(membershipStatus, bundle.getTeamMembershipStatus());\r\n\t\tassertEquals(isAdmin, bundle.isUserAdmin());\r\n\t\tassertEquals(testMemberCount, bundle.getTotalMemberCount());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetTeamMembers() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\t// set team member count\r\n\t\tLong testMemberCount = 111L;\r\n\t\tPaginatedResults allMembers = new PaginatedResults();\r\n\t\tallMembers.setTotalNumberOfResults(testMemberCount);\r\n\t\tList members = new ArrayList();\r\n\r\n\t\tTeamMember member1 = new TeamMember();\r\n\t\tmember1.setIsAdmin(true);\r\n\t\tUserGroupHeader header1 = new UserGroupHeader();\r\n\t\tLong member1Id = 123L;\r\n\t\theader1.setOwnerId(member1Id + \"\");\r\n\t\tmember1.setMember(header1);\r\n\t\tmembers.add(member1);\r\n\r\n\t\tTeamMember member2 = new TeamMember();\r\n\t\tmember2.setIsAdmin(false);\r\n\t\tUserGroupHeader header2 = new UserGroupHeader();\r\n\t\tLong member2Id = 456L;\r\n\t\theader2.setOwnerId(member2Id + \"\");\r\n\t\tmember2.setMember(header2);\r\n\t\tmembers.add(member2);\r\n\r\n\t\tallMembers.setResults(members);\r\n\t\twhen(\r\n\t\t\t\tmockSynapse.getTeamMembers(anyString(), anyString(), anyLong(),\r\n\t\t\t\t\t\tanyLong())).thenReturn(allMembers);\r\n\r\n\t\tList profiles = new ArrayList();\r\n\t\tUserProfile profile1 = new UserProfile();\r\n\t\tprofile1.setOwnerId(member1Id + \"\");\r\n\t\tUserProfile profile2 = new UserProfile();\r\n\t\tprofile2.setOwnerId(member2Id + \"\");\r\n\t\tprofiles.add(profile1);\r\n\t\tprofiles.add(profile2);\r\n\t\twhen(mockSynapse.listUserProfiles(anyList())).thenReturn(profiles);\r\n\r\n\t\t// make the call\r\n\t\tTeamMemberPagedResults results = synapseClient.getTeamMembers(\r\n\t\t\t\t\"myTeamId\", \"search term\", 100, 0);\r\n\r\n\t\t// verify it results in the two team member bundles that we expect\r\n\t\tList memberBundles = results.getResults();\r\n\t\tassertEquals(2, memberBundles.size());\r\n\t\tTeamMemberBundle bundle1 = memberBundles.get(0);\r\n\t\tassertTrue(bundle1.getIsTeamAdmin());\r\n\t\tassertEquals(profile1, bundle1.getUserProfile());\r\n\t\tTeamMemberBundle bundle2 = memberBundles.get(1);\r\n\t\tassertFalse(bundle2.getIsTeamAdmin());\r\n\t\tassertEquals(profile2, bundle2.getUserProfile());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testIsTeamMember() throws NumberFormatException, RestServiceException, SynapseException {\r\n\t\tsynapseClient.isTeamMember(entityId, Long.valueOf(teamA.getId()));\r\n\t\tverify(mockSynapse).getTeamMembershipStatus(teamA.getId(), entityId);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityHeaderBatch() throws SynapseException,\r\n\t\t\tRestServiceException, MalformedURLException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\tList headers = synapseClient\r\n\t\t\t\t.getEntityHeaderBatch(new ArrayList());\r\n\t\t// in the setup, we told the mockSynapse.getEntityHeaderBatch to return\r\n\t\t// batchHeaderResults\r\n\t\tfor (int i = 0; i < batchHeaderResults.size(); i++) {\r\n\t\t\tassertEquals(batchHeaderResults.get(i), headers.get(i));\r\n\t\t}\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSendMessage() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor arg = ArgumentCaptor\r\n\t\t\t\t.forClass(MessageToUser.class);\r\n\t\tSet recipients = new HashSet();\r\n\t\trecipients.add(\"333\");\r\n\t\tString subject = \"The Mathematics of Quantum Neutrino Fields\";\r\n\t\tString messageBody = \"Atoms are not to be trusted, they make up everything\";\r\n\t\tString hostPageBaseURL = \"http://localhost/Portal.html\";\r\n\t\tsynapseClient.sendMessage(recipients, subject, messageBody, hostPageBaseURL);\r\n\t\tverify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE));\r\n\t\tverify(mockSynapse).sendMessage(arg.capture());\r\n\t\tMessageToUser toSendMessage = arg.getValue();\r\n\t\tassertEquals(subject, toSendMessage.getSubject());\r\n\t\tassertEquals(recipients, toSendMessage.getRecipients());\r\n\t\tassertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testSendMessageToEntityOwner() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tArgumentCaptor arg = ArgumentCaptor\r\n\t\t\t\t.forClass(MessageToUser.class);\r\n\t\tArgumentCaptor entityIdCaptor = ArgumentCaptor\r\n\t\t\t\t.forClass(String.class);\r\n\t\t\r\n\t\tString subject = \"The Mathematics of Quantum Neutrino Fields\";\r\n\t\tString messageBody = \"Atoms are not to be trusted, they make up everything\";\r\n\t\tString hostPageBaseURL = \"http://localhost/Portal.html\";\r\n\t\tString entityId = \"syn98765\";\r\n\t\tsynapseClient.sendMessageToEntityOwner(entityId, subject, messageBody, hostPageBaseURL);\r\n\t\tverify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE));\r\n\t\tverify(mockSynapse).sendMessage(arg.capture(), entityIdCaptor.capture());\r\n\t\tMessageToUser toSendMessage = arg.getValue();\r\n\t\tassertEquals(subject, toSendMessage.getSubject());\r\n\t\tassertEquals(entityId, entityIdCaptor.getValue());\r\n\t\tassertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetCertifiedUserPassingRecord()\r\n\t\t\tthrows RestServiceException, SynapseException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\tPassingRecord passingRecord = new PassingRecord();\r\n\t\tpassingRecord.setPassed(true);\r\n\t\tpassingRecord.setQuizId(1238L);\r\n\t\tString passingRecordJson = passingRecord.writeToJSONObject(\r\n\t\t\t\tadapterFactory.createNew()).toJSONString();\r\n\t\twhen(mockSynapse.getCertifiedUserPassingRecord(anyString()))\r\n\t\t\t\t.thenReturn(passingRecord);\r\n\t\tString returnedPassingRecordJson = synapseClient\r\n\t\t\t\t.getCertifiedUserPassingRecord(\"123\");\r\n\t\tverify(mockSynapse).getCertifiedUserPassingRecord(anyString());\r\n\t\tassertEquals(passingRecordJson, returnedPassingRecordJson);\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testUserNeverAttemptedCertification()\r\n\t\t\tthrows RestServiceException, SynapseException {\r\n\t\twhen(mockSynapse.getCertifiedUserPassingRecord(anyString())).thenThrow(\r\n\t\t\t\tnew SynapseNotFoundException(\"PassingRecord not found\"));\r\n\t\tsynapseClient.getCertifiedUserPassingRecord(\"123\");\r\n\t}\r\n\r\n\t@Test(expected = NotFoundException.class)\r\n\tpublic void testUserFailedCertification() throws RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\tPassingRecord passingRecord = new PassingRecord();\r\n\t\tpassingRecord.setPassed(false);\r\n\t\tpassingRecord.setQuizId(1238L);\r\n\t\twhen(mockSynapse.getCertifiedUserPassingRecord(anyString()))\r\n\t\t\t\t.thenReturn(passingRecord);\r\n\t\tsynapseClient.getCertifiedUserPassingRecord(\"123\");\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetCertificationQuiz() throws RestServiceException,\r\n\t\t\tSynapseException {\r\n\t\twhen(mockSynapse.getCertifiedUserTest()).thenReturn(new Quiz());\r\n\t\tsynapseClient.getCertificationQuiz();\r\n\t\tverify(mockSynapse).getCertifiedUserTest();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSubmitCertificationQuizResponse()\r\n\t\t\tthrows RestServiceException, SynapseException,\r\n\t\t\tJSONObjectAdapterException {\r\n\t\tPassingRecord mockPassingRecord = new PassingRecord();\r\n\t\twhen(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.submitCertifiedUserTestResponse(any(QuizResponse.class)))\r\n\t\t\t\t.thenReturn(mockPassingRecord);\r\n\t\tQuizResponse myResponse = new QuizResponse();\r\n\t\tmyResponse.setId(837L);\r\n\t\tsynapseClient.submitCertificationQuizResponse(myResponse);\r\n\t\tverify(mockSynapse).submitCertifiedUserTestResponse(eq(myResponse));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testMarkdownCache() throws Exception {\r\n\t\tCache mockCache = Mockito\r\n\t\t\t\t.mock(Cache.class);\r\n\t\tsynapseClient.setMarkdownCache(mockCache);\r\n\t\tWikiPage page = new WikiPage();\r\n\t\twhen(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)))\r\n\t\t\t\t.thenReturn(v2Page);\r\n\t\tWikiPage actualResult = synapseClient\r\n\t\t\t\t.getV2WikiPageAsV1(new WikiPageKey(entity.getId(),\r\n\t\t\t\t\t\tObjectType.ENTITY.toString(), \"12\"));\r\n\t\tassertEquals(page, actualResult);\r\n\t\tverify(mockCache).get(any(MarkdownCacheRequest.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testMarkdownCacheWithVersion() throws Exception {\r\n\t\tCache mockCache = Mockito\r\n\t\t\t\t.mock(Cache.class);\r\n\t\tsynapseClient.setMarkdownCache(mockCache);\r\n\t\tWikiPage page = new WikiPage();\r\n\t\twhen(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page);\r\n\t\tMockito.when(\r\n\t\t\t\tmockSynapse\r\n\t\t\t\t\t\t.getVersionOfV2WikiPage(\r\n\t\t\t\t\t\t\t\tany(org.sagebionetworks.repo.model.dao.WikiPageKey.class),\r\n\t\t\t\t\t\t\t\tanyLong())).thenReturn(v2Page);\r\n\t\tWikiPage actualResult = synapseClient.getVersionOfV2WikiPageAsV1(\r\n\t\t\t\tnew WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(),\r\n\t\t\t\t\t\t\"12\"), 5L);\r\n\t\tassertEquals(page, actualResult);\r\n\t\tverify(mockCache).get(any(MarkdownCacheRequest.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testFilterAccessRequirements() throws Exception {\r\n\t\tList unfilteredAccessRequirements = new ArrayList();\r\n\t\tList filteredAccessRequirements;\r\n\t\t// filter empty list should not result in failure\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.UPDATE);\r\n\t\tassertTrue(filteredAccessRequirements.isEmpty());\r\n\r\n\t\tunfilteredAccessRequirements\r\n\t\t\t\t.add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD));\r\n\t\tunfilteredAccessRequirements\r\n\t\t\t\t.add(createAccessRequirement(ACCESS_TYPE.SUBMIT));\r\n\t\tunfilteredAccessRequirements\r\n\t\t\t\t.add(createAccessRequirement(ACCESS_TYPE.SUBMIT));\r\n\t\t// no requirements of type UPDATE\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.UPDATE);\r\n\t\tassertTrue(filteredAccessRequirements.isEmpty());\r\n\t\t// 1 download\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.DOWNLOAD);\r\n\t\tassertEquals(1, filteredAccessRequirements.size());\r\n\t\t// 2 submit\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(unfilteredAccessRequirements,\r\n\t\t\t\t\t\tACCESS_TYPE.SUBMIT);\r\n\t\tassertEquals(2, filteredAccessRequirements.size());\r\n\r\n\t\t// finally, filter null list - result will be an empty list\r\n\t\tfilteredAccessRequirements = AccessRequirementUtils\r\n\t\t\t\t.filterAccessRequirements(null, ACCESS_TYPE.SUBMIT);\r\n\t\tassertNotNull(filteredAccessRequirements);\r\n\t\tassertTrue(filteredAccessRequirements.isEmpty());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetEntityUnmetAccessRequirements() throws Exception {\r\n\t\t// verify it calls getUnmetAccessRequirements when unmet is true\r\n\t\tsynapseClient.getEntityAccessRequirements(entityId, true, null);\r\n\t\tverify(mockSynapse)\r\n\t\t\t\t.getUnmetAccessRequirements(\r\n\t\t\t\t\t\tany(RestrictableObjectDescriptor.class),\r\n\t\t\t\t\t\tany(ACCESS_TYPE.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetAllEntityAccessRequirements() throws Exception {\r\n\t\t// verify it calls getAccessRequirements when unmet is false\r\n\t\tsynapseClient.getEntityAccessRequirements(entityId, false, null);\r\n\t\tverify(mockSynapse).getAccessRequirements(\r\n\t\t\t\tany(RestrictableObjectDescriptor.class));\r\n\t}\r\n\r\n\t// pass through tests for email validation\r\n\r\n\t@Test\r\n\tpublic void testAdditionalEmailValidation() throws Exception {\r\n\t\tLong userId = 992843l;\r\n\t\tString emailAddress = \"test@test.com\";\r\n\t\tString callbackUrl = \"http://www.synapse.org/#!Account:\";\r\n\t\tsynapseClient.additionalEmailValidation(userId.toString(),\r\n\t\t\t\temailAddress, callbackUrl);\r\n\t\tverify(mockSynapse).additionalEmailValidation(eq(userId),\r\n\t\t\t\teq(emailAddress), eq(callbackUrl));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testAddEmail() throws Exception {\r\n\t\tString emailAddressToken = \"long synapse email token\";\r\n\t\tsynapseClient.addEmail(emailAddressToken);\r\n\t\tverify(mockSynapse).addEmail(any(AddEmailInfo.class), anyBoolean());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetNotificationEmail() throws Exception {\r\n\t\tsynapseClient.getNotificationEmail();\r\n\t\tverify(mockSynapse).getNotificationEmail();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSetNotificationEmail() throws Exception {\r\n\t\tString emailAddress = \"test@test.com\";\r\n\t\tsynapseClient.setNotificationEmail(emailAddress);\r\n\t\tverify(mockSynapse).setNotificationEmail(eq(emailAddress));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testLogErrorToRepositoryServices() throws SynapseException,\r\n\t\t\tRestServiceException, JSONObjectAdapterException {\r\n\t\tString errorMessage = \"error has occurred\";\r\n\t\tString permutationStrongName=\"Chrome\";\r\n\t\tsynapseClient.logErrorToRepositoryServices(errorMessage, null, null, null, permutationStrongName);\r\n\t\tverify(mockSynapse).getMyProfile();\r\n\t\tverify(mockSynapse).logError(any(LogEntry.class));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testLogErrorToRepositoryServicesTruncation()\r\n\t\t\tthrows SynapseException, RestServiceException,\r\n\t\t\tJSONObjectAdapterException, ServletException {\r\n\t\tString exceptionMessage = \"This exception brought to you by Sage Bionetworks\";\r\n\t\tException e = new Exception(exceptionMessage, new IllegalArgumentException(new NullPointerException()));\r\n\t\tServletContext mockServletContext = Mockito.mock(ServletContext.class);\r\n\t\tServletConfig mockServletConfig = Mockito.mock(ServletConfig.class);\r\n\t\twhen(mockServletConfig.getServletContext()).thenReturn(mockServletContext);\r\n\t\tsynapseClient.init(mockServletConfig);\r\n\t\tString errorMessage = \"error has occurred\";\r\n\t\tString permutationStrongName=\"FF\";\r\n\t\tsynapseClient.logErrorToRepositoryServices(errorMessage, e.getClass().getSimpleName(), e.getMessage(), e.getStackTrace(), permutationStrongName);\r\n\t\tArgumentCaptor captor = ArgumentCaptor\r\n\t\t\t\t.forClass(LogEntry.class);\r\n\t\tverify(mockSynapse).logError(captor.capture());\r\n\t\tLogEntry logEntry = captor.getValue();\r\n\t\tassertTrue(logEntry.getLabel().length() < SynapseClientImpl.MAX_LOG_ENTRY_LABEL_SIZE + 100);\r\n\t\tassertTrue(logEntry.getMessage().contains(errorMessage));\r\n\t\tassertTrue(logEntry.getMessage().contains(MY_USER_PROFILE_OWNER_ID));\r\n\t\tassertTrue(logEntry.getMessage().contains(e.getClass().getSimpleName()));\r\n\t\tassertTrue(logEntry.getMessage().contains(exceptionMessage));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetMyProjects() throws Exception {\r\n\t\tint limit = 11;\r\n\t\tint offset = 20;\r\n\t\tProjectPagedResults results = synapseClient.getMyProjects(ProjectListType.MY_PROJECTS, limit, offset,\r\n\t\t\t\tProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC);\r\n\t\tverify(mockSynapse).getMyProjects(eq(ProjectListType.MY_PROJECTS),\r\n\t\t\t\teq(ProjectListSortColumn.LAST_ACTIVITY),\r\n\t\t\t\teq(SortDirection.DESC), eq(limit), eq(offset));\r\n\t\tverify(mockSynapse).listUserProfiles(anyList());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetUserProjects() throws Exception {\r\n\t\tint limit = 11;\r\n\t\tint offset = 20;\r\n\t\tLong userId = 133l;\r\n\t\tString userIdString = userId.toString();\r\n\t\tsynapseClient.getUserProjects(userIdString, limit, offset,\r\n\t\t\t\tProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC);\r\n\t\tverify(mockSynapse).getProjectsFromUser(eq(userId),\r\n\t\t\t\teq(ProjectListSortColumn.LAST_ACTIVITY),\r\n\t\t\t\teq(SortDirection.DESC), eq(limit), eq(offset));\r\n\t\tverify(mockSynapse).listUserProfiles(anyList());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetProjectsForTeam() throws Exception {\r\n\t\tint limit = 13;\r\n\t\tint offset = 40;\r\n\t\tLong teamId = 144l;\r\n\t\tString teamIdString = teamId.toString();\r\n\t\tsynapseClient.getProjectsForTeam(teamIdString, limit, offset,\r\n\t\t\t\tProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC);\r\n\t\tverify(mockSynapse).getProjectsForTeam(eq(teamId),\r\n\t\t\t\teq(ProjectListSortColumn.LAST_ACTIVITY),\r\n\t\t\t\teq(SortDirection.DESC), eq(limit), eq(offset));\r\n\t\tverify(mockSynapse).listUserProfiles(anyList());\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testSafeLongToInt() {\r\n\t\tint inRangeInt = 500;\r\n\t\tint after = SynapseClientImpl.safeLongToInt(inRangeInt);\r\n\t\tassertEquals(inRangeInt, after);\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testSafeLongToIntPositive() {\r\n\t\tlong testValue = Integer.MAX_VALUE;\r\n\t\ttestValue++;\r\n\t\tSynapseClientImpl.safeLongToInt(testValue);\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testSafeLongToIntNegative() {\r\n\t\tlong testValue = Integer.MIN_VALUE;\r\n\t\ttestValue--;\r\n\t\tSynapseClientImpl.safeLongToInt(testValue);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetHost() throws RestServiceException {\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"sfTp://mydomain.com/foo/bar\"));\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"http://mydomain.com/foo/bar\"));\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"http://mydomain.com\"));\r\n\t\tassertEquals(\"mydomain.com\",\r\n\t\t\t\tsynapseClient.getHost(\"sftp://mydomain.com:22/foo/bar\"));\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testGetHostNull() throws RestServiceException {\r\n\t\tsynapseClient.getHost(null);\r\n\t}\r\n\r\n\t@Test(expected = IllegalArgumentException.class)\r\n\tpublic void testGetHostEmpty() throws RestServiceException {\r\n\t\tsynapseClient.getHost(\"\");\r\n\t}\r\n\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testGetHostBadUrl() throws RestServiceException {\r\n\t\tsynapseClient.getHost(\"foobar\");\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetRootWikiId() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\torg.sagebionetworks.repo.model.dao.WikiPageKey key = new org.sagebionetworks.repo.model.dao.WikiPageKey();\r\n\t\tkey.setOwnerObjectId(\"1\");\r\n\t\tkey.setOwnerObjectType(ObjectType.ENTITY);\r\n\t\tString expectedId = \"123\";\r\n\t\tkey.setWikiPageId(expectedId);\r\n\t\twhen(mockSynapse.getRootWikiPageKey(anyString(), any(ObjectType.class)))\r\n\t\t\t\t.thenReturn(key);\r\n\r\n\t\tString actualId = synapseClient.getRootWikiId(\"1\",\r\n\t\t\t\tObjectType.ENTITY.toString());\r\n\t\tassertEquals(expectedId, actualId);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetFavorites() throws JSONObjectAdapterException,\r\n\t\t\tSynapseException, RestServiceException {\r\n\t\tPaginatedResults pagedResults = new PaginatedResults();\r\n\t\tList unsortedResults = new ArrayList();\r\n\t\tpagedResults.setResults(unsortedResults);\r\n\t\twhen(mockSynapse.getFavorites(anyInt(), anyInt())).thenReturn(\r\n\t\t\t\tpagedResults);\r\n\r\n\t\t// test empty favorites\r\n\t\tList actualList = synapseClient.getFavorites();\r\n\t\tassertTrue(actualList.isEmpty());\r\n\r\n\t\t// test a few unsorted favorites\r\n\t\tEntityHeader favZ = new EntityHeader();\r\n\t\tfavZ.setName(\"Z\");\r\n\t\tunsortedResults.add(favZ);\r\n\t\tEntityHeader favA = new EntityHeader();\r\n\t\tfavA.setName(\"A\");\r\n\t\tunsortedResults.add(favA);\r\n\t\tEntityHeader favQ = new EntityHeader();\r\n\t\tfavQ.setName(\"q\");\r\n\t\tunsortedResults.add(favQ);\r\n\r\n\t\tactualList = synapseClient.getFavorites();\r\n\t\tassertEquals(3, actualList.size());\r\n\t\tassertEquals(favA, actualList.get(0));\r\n\t\tassertEquals(favQ, actualList.get(1));\r\n\t\tassertEquals(favZ, actualList.get(2));\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testGetTeamBundlesNotOwner() throws RestServiceException, SynapseException {\r\n\t\t// the paginated results were set up to return {teamZ, teamA}, but\r\n\t\t// servlet side we sort by name.\r\n\t\tList results = synapseClient.getTeamsForUser(\"abba\", false);\r\n\t\tverify(mockSynapse).getTeamsForUser(eq(\"abba\"), anyInt(), anyInt());\r\n\t\tassertEquals(2, results.size());\r\n\t\tassertEquals(teamA, results.get(0).getTeam());\r\n\t\tassertEquals(teamZ, results.get(1).getTeam());\r\n\t\tverify(mockSynapse, Mockito.never()).getOpenMembershipRequests(anyString(), anyString(),\r\n\t\t\t\tanyLong(), anyLong());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTeamBundlesOwner() throws RestServiceException, SynapseException {\r\n\t\tTeamMember testTeamMember = new TeamMember();\r\n\t\ttestTeamMember.setIsAdmin(true);\r\n\t\twhen(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn(\r\n\t\t\t\ttestTeamMember);\r\n\t\twhen(mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(mockPaginatedMembershipRequest);\r\n\t\t\r\n\t\tList results = synapseClient.getTeamsForUser(\"abba\", true);\r\n\t\tverify(mockSynapse).getTeamsForUser(eq(\"abba\"), anyInt(), anyInt());\r\n\t\tassertEquals(2, results.size());\r\n\t\tassertEquals(teamA, results.get(0).getTeam());\r\n\t\tassertEquals(teamZ, results.get(1).getTeam());\r\n\t\tLong reqCount1 = results.get(0).getRequestCount();\r\n\t\tLong reqCount2 = results.get(1).getRequestCount();\r\n\t\tassertEquals(new Long(3L), results.get(0).getRequestCount());\r\n\t\tassertEquals(new Long(3L), results.get(1).getRequestCount());\r\n\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenNull() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = null;\r\n\t\tsynapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenEmpty() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = \"\";\r\n\t\tsynapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenUnrecognized() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = \"InvalidTokenType\";\r\n\t\tsynapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testHandleSignedTokenJoinTeam() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.JoinTeam.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken);\r\n\t\tsynapseClient.handleSignedToken(token,TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).addTeamMember(joinTeamToken, TEST_HOME_PAGE_BASE+\"#!Team:\", TEST_HOME_PAGE_BASE+\"#!SignedToken:Settings/\");\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenInvalidJoinTeam() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.JoinTeam.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, \"invalid token\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testHandleSignedTokenNotificationSettings() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.Settings.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedNotificationSettingsToken);\r\n\t\tsynapseClient.handleSignedToken(token, TEST_HOME_PAGE_BASE);\r\n\t\tverify(mockSynapse).updateNotificationSettings(notificationSettingsToken);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testHandleSignedTokenInvalidNotificationSettings() throws RestServiceException, SynapseException{\r\n\t\tString tokenTypeName = NotificationTokenType.Settings.name();\r\n\t\tSignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, \"invalid token\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetOrCreateActivityForEntityVersionGet() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenReturn(new Activity());\r\n\t\tsynapseClient.getOrCreateActivityForEntityVersion(entityId, version);\r\n\t\tverify(mockSynapse).getActivityForEntityVersion(entityId, version);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetOrCreateActivityForEntityVersionCreate() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new SynapseNotFoundException());\r\n\t\twhen(mockSynapse.createActivity(any(Activity.class))).thenReturn(mockActivity);\r\n\t\tsynapseClient.getOrCreateActivityForEntityVersion(entityId, version);\r\n\t\tverify(mockSynapse).getActivityForEntityVersion(entityId, version);\r\n\t\tverify(mockSynapse).createActivity(any(Activity.class));\r\n\t\tverify(mockSynapse).putEntity(mockSynapse.getEntityById(entityId), mockActivity.getId());\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testGetOrCreateActivityForEntityVersionFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new Exception());\r\n\t\tsynapseClient.getOrCreateActivityForEntityVersion(entityId, version);\r\n\t}\r\n\t\r\n\tprivate void setupGetMyLocationSettings() throws SynapseException, RestServiceException{\r\n\t\tList existingStorageLocations = new ArrayList();\r\n\t\tStorageLocationSetting storageLocation = new ExternalS3StorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(1L);\r\n\t\tstorageLocation.setBanner(BANNER_1);\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\tstorageLocation = new ExternalStorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(2L);\r\n\t\tstorageLocation.setBanner(BANNER_2);\r\n\t\t((ExternalStorageLocationSetting)storageLocation).setUrl(\"sftp://www.jayhodgson.com\");\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\tstorageLocation = new ExternalStorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(3L);\r\n\t\tstorageLocation.setBanner(BANNER_1);\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\tstorageLocation = new ExternalStorageLocationSetting();\r\n\t\tstorageLocation.setStorageLocationId(4L);\r\n\t\tstorageLocation.setBanner(null);\r\n\t\texistingStorageLocations.add(storageLocation);\r\n\t\t\r\n\t\twhen(mockSynapse.getMyStorageLocationSettings()).thenReturn(existingStorageLocations);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetMyLocationSettingBanners() throws SynapseException, RestServiceException {\r\n\t\tsetupGetMyLocationSettings();\r\n\t\tList banners = synapseClient.getMyLocationSettingBanners();\r\n\t\tverify(mockSynapse).getMyStorageLocationSettings();\r\n\t\t//should be 2 (only returns unique values)\r\n\t\tassertEquals(2, banners.size());\r\n\t\tassertTrue(banners.contains(BANNER_1));\r\n\t\tassertTrue(banners.contains(BANNER_2));\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testGetMyLocationSettingBannersFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getMyStorageLocationSettings()).thenThrow(new Exception());\r\n\t\tsynapseClient.getMyLocationSettingBanners();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSettingNullSetting() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null);\r\n\t\tassertNull(synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSettingNullUploadDestination() throws SynapseException, RestServiceException {\r\n\t\tassertNull(synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSettingDefaultUploadDestination() throws SynapseException, RestServiceException {\r\n\t\tUploadDestination setting = Mockito.mock(UploadDestination.class);\r\n\t\tString defaultStorageId = synapseClient.getSynapseProperties().get(SynapseClientImpl.DEFAULT_STORAGE_ID_PROPERTY_KEY);\r\n\t\twhen(setting.getStorageLocationId()).thenReturn(Long.parseLong(defaultStorageId));\r\n\t\twhen(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting);\r\n\t\tStorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class);\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting);\r\n\t\t\r\n\t\tassertNull(synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetStorageLocationSetting() throws SynapseException, RestServiceException {\r\n\t\tUploadDestination setting = Mockito.mock(UploadDestination.class);\r\n\t\twhen(setting.getStorageLocationId()).thenReturn(42L);\r\n\t\twhen(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting);\r\n\t\tStorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class);\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting);\r\n\t\tassertEquals(mockStorageLocationSetting, synapseClient.getStorageLocationSetting(entityId));\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testGetStorageLocationSettingFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception());\r\n\t\tsynapseClient.getStorageLocationSetting(entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testCreateStorageLocationSettingFoundStorageAndProjectSetting() throws SynapseException, RestServiceException {\r\n\t\tsetupGetMyLocationSettings();\r\n\t\t\r\n\t\tUploadDestinationListSetting projectSetting = new UploadDestinationListSetting();\r\n\t\tprojectSetting.setLocations(Collections.EMPTY_LIST);\r\n\t\twhen(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(projectSetting);\r\n\t\t\r\n\t\t//test the case when it finds a duplicate storage location.\r\n\t\tExternalStorageLocationSetting setting = new ExternalStorageLocationSetting();\r\n\t\tsetting.setBanner(BANNER_2);\r\n\t\tsetting.setUrl(\"sftp://www.jayhodgson.com\");\r\n\t\t\r\n\t\tsynapseClient.createStorageLocationSetting(entityId, setting);\r\n\t\t//should have found the duplicate storage location, so this is never called\r\n\t\tverify(mockSynapse, Mockito.never()).createStorageLocationSetting(any(StorageLocationSetting.class));\r\n\t\t//verify updates project setting, and the new location list is a single value (id of existing storage location)\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(ProjectSetting.class);\r\n\t\tverify(mockSynapse).updateProjectSetting(captor.capture());\r\n\t\tUploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue();\r\n\t\tList locations = updatedProjectSetting.getLocations();\r\n\t\tassertEquals(new Long(2), locations.get(0));\r\n\t}\r\n\t\r\n\r\n\t@Test\r\n\tpublic void testCreateStorageLocationSettingNewStorageAndProjectSetting() throws SynapseException, RestServiceException {\r\n\t\tsetupGetMyLocationSettings();\r\n\t\twhen(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null);\r\n\t\t\r\n\t\t//test the case when it does not find duplicate storage location setting.\r\n\t\tExternalStorageLocationSetting setting = new ExternalStorageLocationSetting();\r\n\t\tsetting.setBanner(BANNER_2);\r\n\t\tsetting.setUrl(\"sftp://www.google.com\");\r\n\t\t\r\n\t\tLong newStorageLocationId = 1007L;\r\n\t\tExternalStorageLocationSetting createdSetting = new ExternalStorageLocationSetting();\r\n\t\tcreatedSetting.setStorageLocationId(newStorageLocationId);\r\n\t\t\r\n\t\twhen(mockSynapse.createStorageLocationSetting(any(StorageLocationSetting.class))).thenReturn(createdSetting);\r\n\t\t\r\n\t\tsynapseClient.createStorageLocationSetting(entityId, setting);\r\n\t\t//should not have found a duplicate storage location, so this should be called\r\n\t\tverify(mockSynapse).createStorageLocationSetting(any(StorageLocationSetting.class));\r\n\t\t//verify creates new project setting, and the new location list is a single value (id of the new storage location)\r\n\t\tArgumentCaptor captor = ArgumentCaptor.forClass(ProjectSetting.class);\r\n\t\tverify(mockSynapse).createProjectSetting(captor.capture());\r\n\t\tUploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue();\r\n\t\tList locations = updatedProjectSetting.getLocations();\r\n\t\tassertEquals(newStorageLocationId, locations.get(0));\r\n\t\tassertEquals(ProjectSettingsType.upload, updatedProjectSetting.getSettingsType());\r\n\t\tassertEquals(entityId, updatedProjectSetting.getProjectId());\r\n\t}\r\n\t\r\n\t@Test(expected = Exception.class)\r\n\tpublic void testCreateStorageLocationSettingFailure() throws SynapseException, RestServiceException {\r\n\t\twhen(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception());\r\n\t\tsynapseClient.createStorageLocationSetting(entityId, new ExternalStorageLocationSetting());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testUpdateTeamAcl() throws SynapseException, RestServiceException {\r\n\t\tAccessControlList returnedAcl = synapseClient.updateTeamAcl(acl);\r\n\t\tverify(mockSynapse).updateTeamACL(acl);\r\n\t\tassertEquals(acl, returnedAcl);\r\n\t}\r\n\t@Test\r\n\tpublic void testGetTeamAcl() throws SynapseException, RestServiceException {\r\n\t\tString teamId = \"14\";\r\n\t\tAccessControlList returnedAcl = synapseClient.getTeamAcl(teamId);\r\n\t\tverify(mockSynapse).getTeamACL(teamId);\r\n\t\tassertEquals(acl, returnedAcl);\r\n\t}\r\n\t\r\n\tprivate void setupVersionedEntityBundle(String entityId, Long latestVersionNumber) throws SynapseException {\r\n\t\tEntityBundle eb = new EntityBundle();\r\n\t\tEntity file = new FileEntity();\r\n\t\teb.setEntity(file);\r\n\t\teb.getEntity().setId(entityId);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb);\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), anyLong(), anyInt())).thenReturn(eb);\r\n\t\tPaginatedResults versionInfoPaginatedResults = new PaginatedResults();\r\n\t\tList versionInfoList = new LinkedList();\r\n\t\tVersionInfo versionInfo = new VersionInfo();\r\n\t\tversionInfo.setVersionNumber(latestVersionNumber);\r\n\t\tversionInfoList.add(versionInfo);\r\n\t\tversionInfoPaginatedResults.setResults(versionInfoList);\r\n\t\twhen(mockSynapse.getEntityVersions(anyString(), anyInt(), anyInt())).thenReturn(versionInfoPaginatedResults);\r\n\t\twhen(mockSynapse.getEntityById(anyString())).thenReturn(file);\r\n\t}\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForVersionVersionable() throws RestServiceException, SynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tLong targetVersionNumber = 1L;\r\n\t\tLong latestVersionNumber = 2L;\r\n\t\tsetupVersionedEntityBundle(entityId, latestVersionNumber);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1);\r\n\t\tassertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber);\r\n\t\tverify(mockSynapse).getEntityBundle(anyString(), eq(targetVersionNumber), anyInt());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForNullVersionVersionable() throws RestServiceException, SynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tLong targetVersionNumber = null;\r\n\t\tLong latestVersionNumber = 2L;\r\n\t\tsetupVersionedEntityBundle(entityId, latestVersionNumber);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1);\r\n\t\tassertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber);\r\n\t\tverify(mockSynapse).getEntityBundle(anyString(), anyInt());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForVersionLatestVersion() throws RestServiceException, SynapseException {\r\n\t\tString entityId = \"syn123\";\r\n\t\tLong targetVersionNumber = 2L;\r\n\t\tLong latestVersionNumber = 2L;\r\n\t\tsetupVersionedEntityBundle(entityId, latestVersionNumber);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1);\r\n\t\tassertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber);\r\n\t\tverify(mockSynapse).getEntityBundle(anyString(), anyInt());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetEntityBundlePlusForVersionNonVersionable() throws RestServiceException, SynapseException {\r\n\t\tEntityBundle eb = new EntityBundle();\r\n\t\teb.setEntity(new Folder());\r\n\t\teb.getEntity().setId(\"syn123\");\r\n\t\twhen(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb);\r\n\t\tEntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(\"syn123\", 123L, 1);\r\n\t\tassertNull(returnedEntityBundle.getLatestVersionNumber());\r\n\t\tassertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), \"syn123\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetUserIdFromUsername() throws UnsupportedEncodingException, SynapseException, RestServiceException {\r\n\t\t//find the user id based on user name\r\n\t\tLong targetUserId = 4L;\r\n\t\twhen(mockPrincipalAliasResponse.getPrincipalId()).thenReturn(targetUserId);\r\n\t\twhen(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenReturn(mockPrincipalAliasResponse);\r\n\t\tString userId = synapseClient.getUserIdFromUsername(\"luke\");\r\n\t\tassertEquals(targetUserId.toString(), userId);\r\n\t}\r\n\t\r\n\t@Test(expected = BadRequestException.class)\r\n\tpublic void testGetUserIdFromUsernameBackendError() throws UnsupportedEncodingException, SynapseException, RestServiceException {\r\n\t\t//test error from backend\r\n\t\twhen(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenThrow(new SynapseBadRequestException());\r\n\t\tsynapseClient.getUserIdFromUsername(\"bad-request\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTableUpdateTransactionRequestNoChange() throws RestServiceException, SynapseException {\r\n\t\tString tableId = \"syn93939\";\r\n\t\t\r\n\t\tList oldColumnModels = Collections.singletonList(mockOldColumnModel);\r\n\t\twhen(mockSynapse.createColumnModels(anyList())).thenReturn(oldColumnModels);\r\n\t\twhen(mockSynapse.getColumnModelsForTableEntity(tableId)).thenReturn(oldColumnModels);\r\n\t\tassertEquals(0, synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, oldColumnModels).getChanges().size());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTableUpdateTransactionRequestNewColumn() throws RestServiceException, SynapseException {\r\n\t\tString tableId = \"syn93939\";\r\n\t\tList oldColumnModels = new ArrayList();\r\n\t\twhen(mockSynapse.createColumnModels(anyList())).thenReturn(Collections.singletonList(mockNewColumnModelAfterCreate));\r\n\t\tList newColumnModels = Collections.singletonList(mockNewColumnModel);\r\n\t\tTableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, newColumnModels);\r\n\t\tverify(mockSynapse).createColumnModels(anyList());\r\n\t\tassertEquals(tableId, request.getEntityId());\r\n\t\tList tableUpdates = request.getChanges();\r\n\t\tassertEquals(1, tableUpdates.size());\r\n\t\tTableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0);\r\n\t\tList changes = schemaChange.getChanges();\r\n\t\tassertEquals(1, changes.size());\r\n\t\tColumnChange columnChange = changes.get(0);\r\n\t\tassertNull(columnChange.getOldColumnId());\r\n\t\tassertEquals(NEW_COLUMN_MODEL_ID, columnChange.getNewColumnId());\r\n\t}\r\n\t\r\n\tprivate ColumnModel getColumnModel(String id, ColumnType columnType) {\r\n\t\tColumnModel cm = new ColumnModel();\r\n\t\tcm.setId(id);\r\n\t\tcm.setColumnType(columnType);\r\n\t\treturn cm;\r\n\t}\r\n\t\r\n\tprivate ColumnChange getColumnChange(String oldColumnId, List changes) {\r\n\t\tfor (ColumnChange columnChange : changes) {\r\n\t\t\tif (Objects.equal(oldColumnId, columnChange.getOldColumnId())) {\r\n\t\t\t\treturn columnChange;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new NoSuchElementException();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetTableUpdateTransactionRequestFullTest() throws RestServiceException, SynapseException {\r\n\t\t//In this test, we will change a column, delete a column, and add a column (with appropriately mocked responses)\r\n\t\t// Modify colA, delete colB, no change to colC, and add colD\r\n\t\tColumnModel colA, colB, colC, colD, colAModified, colAAfterSave, colDAfterSave;\r\n\t\tString tableId = \"syn93939\";\r\n\t\tcolA = getColumnModel(\"1\", ColumnType.STRING);\r\n\t\tcolB = getColumnModel(\"2\", ColumnType.STRING);\r\n\t\tcolC = getColumnModel(\"3\", ColumnType.STRING);\r\n\t\tcolD = getColumnModel(null, ColumnType.STRING);\r\n\t\tcolAModified = getColumnModel(\"1\", ColumnType.INTEGER);\r\n\t\tcolAAfterSave = getColumnModel(\"4\", ColumnType.INTEGER);\r\n\t\tcolDAfterSave = getColumnModel(\"5\", ColumnType.STRING);\r\n\t\t\r\n\t\tList oldSchema = Arrays.asList(colA, colB, colC);\r\n\t\tList proposedNewSchema = Arrays.asList(colAModified, colC, colD);\r\n\t\tList newSchemaAfterUpdate = Arrays.asList(colAAfterSave, colC, colDAfterSave);\r\n\t\twhen(mockSynapse.createColumnModels(anyList())).thenReturn(newSchemaAfterUpdate);\r\n\t\t\r\n\t\tTableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldSchema, proposedNewSchema);\r\n\t\tverify(mockSynapse).createColumnModels(anyList());\r\n\t\tassertEquals(tableId, request.getEntityId());\r\n\t\tList tableUpdates = request.getChanges();\r\n\t\tassertEquals(1, tableUpdates.size());\r\n\t\tTableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0);\r\n\t\t\r\n\t\t//changes should consist of a create, an update, and a delete\r\n\t\tList changes = schemaChange.getChanges();\r\n\t\tassertEquals(3, changes.size());\r\n\t\t\r\n\t\t// colB should be deleted\r\n\t\tColumnChange columnChange = getColumnChange(\"2\", changes);\r\n\t\tassertNull(columnChange.getNewColumnId());\r\n\t\t// colA should be modified\r\n\t\tcolumnChange = getColumnChange(\"1\", changes);\r\n\t\tassertEquals(\"4\", columnChange.getNewColumnId());\r\n\t\t// colD should be new\r\n\t\tcolumnChange = getColumnChange(null, changes);\r\n\t\tassertEquals(\"5\", columnChange.getNewColumnId());\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGetDefaultColumnsForView() throws RestServiceException, SynapseException{\r\n\t\tColumnModel colA, colB;\r\n\t\tcolA = getColumnModel(\"1\", ColumnType.STRING);\r\n\t\tcolB = getColumnModel(\"2\", ColumnType.STRING);\r\n\t\t\r\n\t\tList defaultColumns = Arrays.asList(colA, colB);\r\n\t\twhen(mockSynapse.getDefaultColumnsForView(any(ViewType.class))).thenReturn(defaultColumns);\r\n\t\tList returnedColumns = synapseClient.getDefaultColumnsForView(ViewType.file);\r\n\t\t\r\n\t\tassertEquals(2, returnedColumns.size());\r\n\t\tassertNull(returnedColumns.get(0).getId());\r\n\t\tassertNull(returnedColumns.get(1).getId());\r\n\t}\r\n}\r\n"},"message":{"kind":"string","value":"test updateFileEntity with a file entity and file handle copy request\n"},"old_file":{"kind":"string","value":"src/test/java/org/sagebionetworks/web/unitserver/SynapseClientImplTest.java"},"subject":{"kind":"string","value":"test updateFileEntity with a file entity and file handle copy request"}}},{"rowIdx":1252,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"7ed9583ef706f5b7940dc524c1f77edeaf608351"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"statsbiblioteket/doms-ingesters,statsbiblioteket/doms-ingesters"},"new_contents":{"kind":"string","value":"/*\n * $Id$\n * $Revision$\n * $Date$\n * $Author$\n *\n * The DOMS project.\n * Copyright (C) 2007-2010 The State and University Library\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage dk.statsbiblioteket.doms.ingesters.radiotv;\n\nimport dk.statsbiblioteket.doms.client.DomsWSClient;\nimport dk.statsbiblioteket.doms.client.DomsWSClientImpl;\nimport dk.statsbiblioteket.doms.client.exceptions.NoObjectFound;\nimport dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed;\nimport dk.statsbiblioteket.doms.client.exceptions.XMLParseException;\nimport dk.statsbiblioteket.doms.client.relations.LiteralRelation;\nimport dk.statsbiblioteket.doms.client.relations.Relation;\nimport dk.statsbiblioteket.doms.client.utils.FileInfo;\nimport dk.statsbiblioteket.util.xml.DOM;\nimport dk.statsbiblioteket.util.xml.XPathSelector;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.validation.Schema;\nimport javax.xml.xpath.XPathExpressionException;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\n\n/** On added xml files with radio/tv metadata, add objects to DOMS describing these files. */\npublic class RadioTVMetadataProcessor implements HotFolderScannerClient {\n\n private static final String RITZAU_ORIGINALS_ELEMENT = \"//program/originals/ritzau_original\";\n private static final String GALLUP_ORIGINALS_ELEMENT = \"//program/originals/gallup_original\";\n private static final String HAS_METAFILE_RELATION_TYPE\n = \"http://doms.statsbiblioteket.dk/relations/default/0/1/#hasShard\";\n private static final String CONSISTS_OF_RELATION_TYPE\n = \"http://doms.statsbiblioteket.dk/relations/default/0/1/#consistsOf\";\n private static final String RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT\n = \"//program/pbcore/pbc:PBCoreDescriptionDocument\";\n private static final String RECORDING_FILES_FILE_ELEMENT = \"//program/program_recording_files/file\";\n private static final String FILE_URL_ELEMENT = \"file_url\";\n private static final String FILE_NAME_ELEMENT = \"file_name\";\n private static final String FORMAT_URI_ELEMENT = \"format_uri\";\n private static final String MD5_SUM_ELEMENT = \"md5_sum\";\n\n private static final String PROGRAM_TEMPLATE_PID = \"doms:Template_Program\";\n private static final String PROGRAM_PBCORE_DS_ID = \"PBCORE\";\n private static final String RITZAU_ORIGINAL_DS_ID = \"RITZAU_ORIGINAL\";\n private static final String GALLUP_ORIGINAL_DS_ID = \"GALLUP_ORIGINAL\";\n private static final String META_FILE_TEMPLATE_PID = \"doms:Template_Shard\";\n private static final String META_FILE_METADATA_DS_ID = \"SHARD_METADATA\";\n private static final String RADIO_TV_FILE_TEMPLATE_PID = \"doms:Template_RadioTVFile\";\n\n private static final int MAX_FAIL_COUNT = 10;\n\n private static final XPathSelector XPATH_SELECTOR = DOM\n .createXPathSelector(\"pbc\", \"http://www.pbcore.org/PBCore/PBCoreNamespace.html\");\n private static final String COMMENT = \"Ingest of Radio/TV data\";\n private static final String FAILED_COMMENT = COMMENT + \": Something failed, rolling back\";\n private int exceptionCount = 0;\n\n /** Folder to move failed files to. */\n private final File failedFilesFolder;\n /** Folder to move processed files to. */\n private final File processedFilesFolder;\n\n /** Document builder that fails on XML files not conforming to the preingest schema. */\n private final DocumentBuilder preingestFilesBuilder;\n /** Document builder that does not require a specific schema. */\n private final DocumentBuilder unSchemaedBuilder;\n /** Client for communicating with DOMS. */\n private final DomsWSClient domsClient;\n\n\n /**\n * Initialise the processor.\n *\n * @param domsLoginInfo Information used for contacting DOMS.\n * @param failedFilesFolder Folder to move failed files to.\n * @param processedFilesFolder Folder to move processed files to.\n * @param preIngestFileSchema Schema for Raio/TV metadata to process.\n */\n public RadioTVMetadataProcessor(DOMSLoginInfo domsLoginInfo, File failedFilesFolder, File processedFilesFolder,\n Schema preIngestFileSchema) {\n this.failedFilesFolder = failedFilesFolder;\n this.processedFilesFolder = processedFilesFolder;\n this.domsClient = new DomsWSClientImpl();\n this.domsClient.setCredentials(domsLoginInfo.getDomsWSAPIUrl(), domsLoginInfo.getLogin(),\n domsLoginInfo.getPassword());\n\n DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilderFactory unschemaedFactory = DocumentBuilderFactory.newInstance();\n documentBuilderFactory.setSchema(preIngestFileSchema);\n documentBuilderFactory.setNamespaceAware(true);\n try {\n preingestFilesBuilder = documentBuilderFactory.newDocumentBuilder();\n unSchemaedBuilder = unschemaedFactory.newDocumentBuilder();\n } catch (ParserConfigurationException pce) {\n pce.printStackTrace();\n fatalException();\n throw new RuntimeException();// will never be reached, but no matter\n }\n\n ErrorHandler documentErrorHandler = new org.xml.sax.ErrorHandler() {\n\n @Override\n public void warning(SAXParseException exception) throws SAXException {\n throw exception;\n }\n\n @Override\n public void fatalError(SAXParseException exception) throws SAXException {\n throw exception;\n }\n\n @Override\n public void error(SAXParseException exception) throws SAXException {\n throw exception;\n }\n };\n preingestFilesBuilder.setErrorHandler(documentErrorHandler);\n\n }\n\n /**\n * Will parse the metadata and add relevant objects to DOMS.\n * @param addedFile Full path to the new file.\n */\n @Override\n public void fileAdded(File addedFile) {\n List pidsToPublish = new ArrayList();\n //This method acts as fault barrier\n try {\n Document radioTVMetadata = preingestFilesBuilder.parse(addedFile);\n createRecord(radioTVMetadata, addedFile, pidsToPublish);\n } catch (Exception e) {\n // Handle anything unanticipated.\n failed(addedFile, pidsToPublish);\n e.printStackTrace();\n incrementFailedTries();\n }\n }\n\n @Override\n public void fileDeleted(File deletedFile) {\n // Not relevant.\n }\n\n /**\n * Acts exactly as fileAdded.\n * @param modifiedFile Full path to the modified file.\n */\n @Override\n public void fileModified(File modifiedFile) {\n fileAdded(modifiedFile);\n }\n\n /**\n * Create objects in DOMS for given program metadata. On success, the originating file will be moved to the folder\n * for processed files. On failure, a file in the folder of failed files will contain the pids that were not\n * published.\n *\n * @param radioTVMetadata The Metadata for the program.\n * @param addedFile The file containing the program metadata\n * @param pidsToPublish Initially empty list of pids to update with pids collected during process, to be published\n * in the end.\n *\n * @throws IOException On io trouble communicating.\n * @throws ServerOperationFailed On trouble updating DOMS.\n * @throws URISyntaxException Should never happen. Means shard URI generated is invalid.\n * @throws XPathExpressionException Should never happen. Means program is broken with wrong XPath exception.\n * @throws XMLParseException On trouble parsing XML.\n */\n private void createRecord(Document radioTVMetadata, File addedFile, List pidsToPublish)\n throws IOException, ServerOperationFailed, URISyntaxException, XPathExpressionException, XMLParseException {\n // Check if program is already in DOMS\n String originalPid;\n try {\n originalPid = alreadyExistsInRepo(radioTVMetadata);\n } catch (NoObjectFound noObjectFound) {\n originalPid = null;\n }\n\n // Find or create files containing this program\n // TODO: Fill out metadata for file\n List filePIDs = ingestFiles(radioTVMetadata);\n pidsToPublish.addAll(filePIDs);\n writePIDs(failedFilesFolder, addedFile, pidsToPublish);\n\n // Create or update shard for this program\n // TODO: Fill out datastreams in program instead\n String shardPid = null;\n if (originalPid != null) { //program already exists\n shardPid = getShardPidFromProgram(originalPid);\n }\n String metaFilePID = ingestMetaFile(radioTVMetadata, filePIDs, shardPid);\n pidsToPublish.add(metaFilePID);\n writePIDs(failedFilesFolder, addedFile, pidsToPublish);\n\n // Create or update program object for this program\n // TODO: May require some updates?\n String programPID = ingestProgram(radioTVMetadata, metaFilePID, originalPid);\n pidsToPublish.add(programPID);\n File allWrittenPIDs = writePIDs(failedFilesFolder, addedFile, pidsToPublish);\n\n // Publish the objects created in the process\n domsClient.publishObjects(COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()]));\n\n // The ingest was successful, if we make it here...\n // Move the processed file to the finished files folder.\n moveFile(addedFile, processedFilesFolder);\n\n // And it is now safe to delete the \"in progress\" PID file.\n allWrittenPIDs.delete();\n\n }\n\n /**\n * Lookup a program in DOMS.\n * If program exists, returns the PID of the program. Otherwise throws exception {@link NoObjectFound}.\n *\n * @param radioTVMetadata The document containing the program metadata.\n * @return PID of program, if found.\n *\n * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath.\n * @throws ServerOperationFailed Could not communicate with DOMS.\n * @throws NoObjectFound The program was not found in DOMS.\n */\n private String alreadyExistsInRepo(Document radioTVMetadata)\n throws XPathExpressionException, ServerOperationFailed, NoObjectFound {\n String oldId = getOldIdentifier(radioTVMetadata);\n List pids = domsClient.getPidFromOldIdentifier(oldId);\n if (!pids.isEmpty()) {\n return pids.get(0);\n }\n throw new NoObjectFound(\"No object found\");\n }\n\n /**\n * Find old identifier in program metadata, and use them for looking up programs in DOMS.\n *\n * @param radioTVMetadata The document containing the program metadata.\n * @return Old indentifier found.\n * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath.\n */\n private String getOldIdentifier(Document radioTVMetadata) throws XPathExpressionException {\n // TODO Should support TVMeter identifiers as well, and return a list!\n Node radioTVPBCoreElement = XPATH_SELECTOR\n .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT);\n\n Node oldPIDNode = XPATH_SELECTOR\n .selectNode(radioTVPBCoreElement, \"pbc:pbcoreIdentifier[pbc:identifierSource=\\\"id\\\"]/pbc:identifier\");\n\n if (oldPIDNode != null && !oldPIDNode.getTextContent().isEmpty()) {\n return oldPIDNode.getTextContent();\n } else {\n return null;\n }\n }\n\n /**\n * queries the list of relations in the program, and extracts the shard-pid from these\n *\n * @param pid the program object pid\n * @return the shard pid, or null if none found\n *\n * @throws ServerOperationFailed if something failed\n */\n private String getShardPidFromProgram(String pid) throws ServerOperationFailed {\n List shardrelations = domsClient.listObjectRelations(pid, HAS_METAFILE_RELATION_TYPE);\n return shardrelations.size() > 0 ? shardrelations.get(0).getSubjectPid() : null;\n }\n\n /**\n * Iteratively (over)write the pid the InProcessPIDs file\n * associated with the preIngestFile.\n *\n * @param outputDirectory absolute path to the directory where the PID file must be\n * written.\n * @param preIngestFile The file containing the Metadata for a program.\n * @param PIDs A list of PIDs to write.\n * @return The File which the PIDs were written to.\n *\n * @throws IOException thrown if the file cannot be written to.\n */\n private File writePIDs(File outputDirectory, File preIngestFile, List PIDs) throws IOException {\n final File pidFile = new File(outputDirectory, preIngestFile.getName() + \".InProcessPIDs\");\n\n if (!pidFile.exists()) {\n pidFile.createNewFile();\n }\n\n if (pidFile.canWrite()) {\n final PrintWriter writer = new PrintWriter(pidFile);\n for (String currentPID : PIDs) {\n writer.println(currentPID);\n }\n writer.flush();\n writer.close();\n return pidFile;\n } else {\n throw new IOException(\"Cannot write file \" + pidFile.getAbsolutePath());\n }\n }\n\n /**\n * Move the failed pre-ingest file to the \"failedFilesFolder\" folder and\n * rename the in-progress PID list file to a failed PID list file, also\n * stored in the \"failedFilesFolder\" folder.\n *

\n * This method should be called before \"pulling the plug\".\n *\n * @param addedFile The file attempted to have added to the doms\n * @param pidsToPublish The failed PIDs\n */\n private void failed(File addedFile, List pidsToPublish) {\n try {\n moveFile(addedFile, failedFilesFolder);\n\n // Rename the in-progress PIDs to failed PIDs.\n writeFailedPIDs(addedFile);\n domsClient.deleteObjects(FAILED_COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()]));\n } catch (Exception exception) {\n // If this bail-out error handling fails, then nothing can save\n // us...\n exception.printStackTrace(System.err);\n }\n }\n\n /**\n * Ingests or update a program object\n *\n *\n * @param radioTVMetadata Bibliographical metadata about the program.\n * @param metafilePID PID to the metafile which represents the program data.\n * @param existingPid the existing pid of the program object, or null if it does not exist\n * @return PID of the newly created program object, created by the DOMS.\n *\n * @throws ServerOperationFailed if creation or manipulation of the program object fails.\n * @throws XPathExpressionException should never happen. Means error in program with invalid XPath.\n * @throws XMLParseException if any errors were encountered while processing the\n * radioTVMetadata XML document.\n */\n private String ingestProgram(Document radioTVMetadata, String metafilePID, String existingPid)\n throws ServerOperationFailed, XPathExpressionException, XMLParseException {\n\n // First, fetch the PBCore metadata document node from the pre-ingest\n // document.\n\n Node radioTVPBCoreElement = XPATH_SELECTOR\n .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT);\n\n // Extract the ritzauID from the pre-ingest file.\n List listOfOldPIDs = new ArrayList();\n String oldId = getOldIdentifier(radioTVMetadata);\n if (oldId != null) {\n listOfOldPIDs.add(oldId);\n }\n\n String programObjectPID;\n if (existingPid == null) {//not Exist\n // Create a program object in the DOMS and update the PBCore metadata\n // datastream with the PBCore metadata from the pre-ingest file.\n programObjectPID = domsClient.createObjectFromTemplate(PROGRAM_TEMPLATE_PID, listOfOldPIDs, COMMENT);\n // Create relations to the metafile/shard\n domsClient.addObjectRelation(programObjectPID, HAS_METAFILE_RELATION_TYPE, metafilePID, COMMENT);\n\n } else { //Exists\n domsClient.unpublishObjects(COMMENT, existingPid);\n programObjectPID = existingPid;\n }\n\n final Document pbCoreDataStreamDocument = createPBCoreDocForDoms(radioTVPBCoreElement);\n domsClient.updateDataStream(programObjectPID, PROGRAM_PBCORE_DS_ID, pbCoreDataStreamDocument, COMMENT);\n\n // Get the program title from the PBCore metadata and use that as the\n // object label for this program object.\n Node titleNode = XPATH_SELECTOR\n .selectNode(radioTVPBCoreElement, \"pbc:pbcoreTitle[pbc:titleType=\\\"titel\\\"]/pbc:title\");\n final String programTitle = titleNode.getTextContent();\n domsClient.setObjectLabel(programObjectPID, programTitle, COMMENT);\n\n // Get the Ritzau metadata from the pre-ingest document and add it to\n // the Ritzau metadata data stream of the program object.\n final Document ritzauOriginalDocument = createRitzauDocument(radioTVMetadata);\n domsClient.updateDataStream(programObjectPID, RITZAU_ORIGINAL_DS_ID, ritzauOriginalDocument, COMMENT);\n\n // Add the Gallup metadata\n Document gallupOriginalDocument = createGallupDocument(radioTVMetadata);\n domsClient.updateDataStream(programObjectPID, GALLUP_ORIGINAL_DS_ID, gallupOriginalDocument, COMMENT);\n\n return programObjectPID;\n }\n\n /**\n * Utility method to create the Ritzau document to ingest\n *\n * @param radioTVMetadata Bibliographical metadata about the program.\n * @return A document containing the Ritzau metadata.\n */\n private Document createRitzauDocument(Document radioTVMetadata) {\n final Node ritzauPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, RITZAU_ORIGINALS_ELEMENT);\n\n // Build a Ritzau data document for the Ritzau data stream in the\n // program object.\n final Document ritzauOriginalDocument = unSchemaedBuilder.newDocument();\n final Element ritzauOriginalRootElement = ritzauOriginalDocument.createElement(\"ritzau_original\");\n\n ritzauOriginalRootElement.setAttribute(\"xmlns\", \"http://doms.statsbiblioteket.dk/types/ritzau_original/0/1/#\");\n ritzauOriginalDocument.appendChild(ritzauOriginalRootElement);\n\n ritzauOriginalRootElement.setTextContent(ritzauPreingestElement.getTextContent());\n return ritzauOriginalDocument;\n }\n\n /**\n * Utility method to create the Gallup document to ingest\n *\n * @param radioTVMetadata Bibliographical metadata about the program.\n * @return A document containing the Gallup metadata\n */\n private Document createGallupDocument(Node radioTVMetadata) {\n final Node gallupPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, GALLUP_ORIGINALS_ELEMENT);\n\n final Document gallupOriginalDocument = unSchemaedBuilder.newDocument();\n\n final Element gallupOriginalRootElement = gallupOriginalDocument.createElement(\"gallup_original\");\n\n gallupOriginalRootElement.setAttribute(\"xmlns\", \"http://doms.statsbiblioteket.dk/types/gallup_original/0/1/#\");\n\n gallupOriginalRootElement.setTextContent(gallupPreingestElement.getTextContent());\n\n gallupOriginalDocument.appendChild(gallupOriginalRootElement);\n return gallupOriginalDocument;\n }\n\n /**\n * Utility method to create the PBCore document to ingest\n *\n * @param radioTVPBCoreElement Element containing PBCore.\n * @return A document containing the PBCore metadata\n */\n private Document createPBCoreDocForDoms(Node radioTVPBCoreElement) {\n final Document pbCoreDataStreamDocument = unSchemaedBuilder.newDocument();\n\n // Import the PBCore metadata from the pre-ingest document and use it as\n // the contents for the PBCore metadata data stream of the program\n // object.\n final Node newPBCoreElement = pbCoreDataStreamDocument.importNode(radioTVPBCoreElement, true);\n\n pbCoreDataStreamDocument.appendChild(newPBCoreElement);\n return pbCoreDataStreamDocument;\n }\n\n /**\n * Ingest a metafile (aka. shard) object which represents the program data\n * (i.e. video and/or audio). A metafile may consist of data chunks from\n * multiple physical files identified by the PIDs in the\n * filePIDs list. The metadata provided by\n * radioTVMetadata contains, among other things, information\n * about location and duration of the chunks of data from the physical files\n * which constitutes the contents of the metafile.\n *

\n * TODO: Consider cleaning up/consolidating the exceptions\n *\n * @param radioTVMetadata Metadata about location and duration of the relevant data\n * chunks from the physical files.\n * @param filePIDs List of PIDs for the physical files containing the data\n * represented by this metafile.\n * @param metaFilePID The PID of the object, if it exists already. Otherwise null\n * @return PID of the newly created metafile object, created by the DOMS.\n *\n * @throws ServerOperationFailed if creation or manipulation of the metafile object fails.\n * @throws IOException if io exceptions occur while communicating.\n * @throws XPathExpressionException should never happen. Means error in program with invalid XPath.\n * @throws URISyntaxException if shard URL could not be generated\n * @throws XMLParseException if any errors were encountered while processing the\n * radioTVMetadata XML document.\n */\n private String ingestMetaFile(Document radioTVMetadata, List filePIDs, String metaFilePID)\n throws ServerOperationFailed, IOException, XPathExpressionException, URISyntaxException, XMLParseException {\n\n if (metaFilePID == null) {\n // Create a file object from the file object template.\n metaFilePID = domsClient.createObjectFromTemplate(META_FILE_TEMPLATE_PID, COMMENT);\n // TODO: Do something about this.\n final FileInfo fileInfo = new FileInfo(\"shard/\" + metaFilePID,\n new URL(\"http://www.statsbiblioteket.dk/doms/shard/\" + metaFilePID),\n \"\", new URI(\"info:pronom/fmt/199\"));\n\n domsClient.addFileToFileObject(metaFilePID, fileInfo, COMMENT);\n\n } else {\n domsClient.unpublishObjects(COMMENT, metaFilePID);\n }\n\n final Document metadataDataStreamDocument = unSchemaedBuilder.newDocument();\n\n final Element metadataDataStreamRootElement = metadataDataStreamDocument.createElement(\"shard_metadata\");\n\n metadataDataStreamDocument.appendChild(metadataDataStreamRootElement);\n\n // Add all the \"file\" elements from the radio-tv metadata document.\n // TODO: Note that this is just a first-shot implementation until a\n // proper metadata format has been defined.\n final NodeList recordingFileElements = XPATH_SELECTOR\n .selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT);\n\n for (int fileElementIdx = 0; fileElementIdx < recordingFileElements.getLength(); fileElementIdx++) {\n\n final Node currentRecordingFile = recordingFileElements.item(fileElementIdx);\n\n // Append to the end of the list of child nodes.\n final Node newMetadataElement = metadataDataStreamDocument.importNode(currentRecordingFile, true);\n\n metadataDataStreamRootElement.appendChild(newMetadataElement);\n }\n\n domsClient.updateDataStream(metaFilePID, META_FILE_METADATA_DS_ID, metadataDataStreamDocument, COMMENT);\n\n List relations = domsClient.listObjectRelations(metaFilePID, CONSISTS_OF_RELATION_TYPE);\n HashSet existingRels = new HashSet();\n for (Relation relation : relations) {\n if (!filePIDs.contains(relation.getSubjectPid())) {\n domsClient.removeObjectRelation((LiteralRelation) relation, COMMENT);\n } else {\n existingRels.add(relation.getSubjectPid());\n }\n }\n for (String filePID : filePIDs) {\n if (!existingRels.contains(filePID)) {\n domsClient.addObjectRelation(metaFilePID, CONSISTS_OF_RELATION_TYPE, filePID, COMMENT);\n\n }\n }\n\n return metaFilePID;\n }\n\n /**\n * Ingest any missing file objects into the DOMS and return a list of PIDs\n * for all the DOMS file objects corresponding to the files listed in the\n * radioTVMetadata document.\n *\n * @param radioTVMetadata Metadata XML document containing the file information.\n * @return A List of PIDs of the radio-tv file objects created\n * by the DOMS.\n *\n * @throws XPathExpressionException if any errors were encountered while processing the\n * radioTVMetadata XML document.\n * @throws MalformedURLException if a file element contains an invalid URL.\n * @throws ServerOperationFailed if creation and retrieval of a radio-tv file object fails.\n * @throws URISyntaxException if the format URI for the file is invalid.\n */\n private List ingestFiles(Document radioTVMetadata)\n throws XPathExpressionException, MalformedURLException, ServerOperationFailed, URISyntaxException {\n\n // Get the recording files XML element and process the file information.\n final NodeList recordingFiles = XPATH_SELECTOR.selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT);\n\n // Ensure that the DOMS contains a file object for each recording file\n // element in the radio-tv XML document.\n final List fileObjectPIDs = new ArrayList();\n for (int nodeIndex = 0; nodeIndex < recordingFiles.getLength(); nodeIndex++) {\n\n final Node currentFileNode = recordingFiles.item(nodeIndex);\n\n final Node fileURLNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_URL_ELEMENT);\n final String fileURLString = fileURLNode.getTextContent();\n final URL fileURL = new URL(fileURLString);\n\n String fileObjectPID;\n try {\n fileObjectPID = domsClient.getFileObjectPID(fileURL);\n } catch (NoObjectFound nof) {\n // The DOMS contains no file object for this file URL.\n // Create a new one now.\n final Node fileNameNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_NAME_ELEMENT);\n\n final String fileName = fileNameNode.getTextContent();\n\n final Node formatURINode = XPATH_SELECTOR.selectNode(currentFileNode, FORMAT_URI_ELEMENT);\n\n final URI formatURI = new URI(formatURINode.getTextContent());\n\n final Node md5SumNode = XPATH_SELECTOR.selectNode(currentFileNode, MD5_SUM_ELEMENT);\n\n // The MD5 check sum is optional. Just leave it empty if the\n // pre-ingest file does not provide it.\n String md5String = \"\";\n if (md5SumNode != null) {\n md5String = md5SumNode.getTextContent();\n }\n\n final FileInfo fileInfo = new FileInfo(fileName, fileURL, md5String, formatURI);\n\n fileObjectPID = domsClient.createFileObject(RADIO_TV_FILE_TEMPLATE_PID, fileInfo, COMMENT);\n }\n fileObjectPIDs.add(fileObjectPID);\n }\n return fileObjectPIDs;\n }\n\n /**\n * Move fileToMove to the folder specified by\n * destinationFolder.\n *\n * @param fileToMove Path to the file to move to destinationFolder.\n * @param destinationFolder Path of the destination folder to move the file to.\n */\n private void moveFile(File fileToMove, File destinationFolder) {\n fileToMove.renameTo(new File(destinationFolder.getAbsolutePath(), fileToMove.getName()));\n }\n\n /**\n * Rename the file with a list of PIDs in progress and never published to a file with a list of failed PIDs.\n * @param failedMetadataFile The originating file.\n *\n */\n private void writeFailedPIDs(File failedMetadataFile) {\n final File activePIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + \".InProcessPIDs\");\n final File failedPIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + \".failedPIDs\");\n activePIDsFile.renameTo(failedPIDsFile);\n }\n\n /**\n * ends all attempts to ingest from the current list of file descriptions in\n * the pre-ingest file Violent exit needed \"system.exit()\n */\n private void fatalException() {\n System.exit(-1);\n }\n\n /** The number of tries is incremented by one.\n * If this exceeds the maximum number of allowed failures, */\n private void incrementFailedTries() {\n exceptionCount += 1;\n if (exceptionCount >= MAX_FAIL_COUNT) {\n System.err.println(\"Too many errors (\" + exceptionCount + \") in ingest. Exiting.\");\n fatalException();\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"radio-tv/src/main/java/dk/statsbiblioteket/doms/ingesters/radiotv/RadioTVMetadataProcessor.java"},"old_contents":{"kind":"string","value":"/*\n * $Id$\n * $Revision$\n * $Date$\n * $Author$\n *\n * The DOMS project.\n * Copyright (C) 2007-2010 The State and University Library\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage dk.statsbiblioteket.doms.ingesters.radiotv;\n\nimport dk.statsbiblioteket.doms.client.DomsWSClient;\nimport dk.statsbiblioteket.doms.client.DomsWSClientImpl;\nimport dk.statsbiblioteket.doms.client.exceptions.NoObjectFound;\nimport dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed;\nimport dk.statsbiblioteket.doms.client.exceptions.XMLParseException;\nimport dk.statsbiblioteket.doms.client.relations.LiteralRelation;\nimport dk.statsbiblioteket.doms.client.relations.Relation;\nimport dk.statsbiblioteket.doms.client.utils.FileInfo;\nimport dk.statsbiblioteket.util.xml.DOM;\nimport dk.statsbiblioteket.util.xml.XPathSelector;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.ErrorHandler;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.validation.Schema;\nimport javax.xml.xpath.XPathExpressionException;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\n\n/** On added xml files with radio/tv metadata, add objects to DOMS describing these files. */\npublic class RadioTVMetadataProcessor implements HotFolderScannerClient {\n\n private static final String RITZAU_ORIGINALS_ELEMENT = \"//program/originals/ritzau_original\";\n private static final String GALLUP_ORIGINALS_ELEMENT = \"//program/originals/gallup_original\";\n private static final String HAS_METAFILE_RELATION_TYPE\n = \"http://doms.statsbiblioteket.dk/relations/default/0/1/#hasShard\";\n private static final String CONSISTS_OF_RELATION_TYPE\n = \"http://doms.statsbiblioteket.dk/relations/default/0/1/#consistsOf\";\n private static final String RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT\n = \"//program/pbcore/pbc:PBCoreDescriptionDocument\";\n private static final String RECORDING_FILES_FILE_ELEMENT = \"//program/program_recording_files/file\";\n private static final String FILE_URL_ELEMENT = \"file_url\";\n private static final String FILE_NAME_ELEMENT = \"file_name\";\n private static final String FORMAT_URI_ELEMENT = \"format_uri\";\n private static final String MD5_SUM_ELEMENT = \"md5_sum\";\n\n private static final String PROGRAM_TEMPLATE_PID = \"doms:Template_Program\";\n private static final String PROGRAM_PBCORE_DS_ID = \"PBCORE\";\n private static final String RITZAU_ORIGINAL_DS_ID = \"RITZAU_ORIGINAL\";\n private static final String GALLUP_ORIGINAL_DS_ID = \"GALLUP_ORIGINAL\";\n private static final String META_FILE_TEMPLATE_PID = \"doms:Template_Shard\";\n private static final String META_FILE_METADATA_DS_ID = \"SHARD_METADATA\";\n private static final String RADIO_TV_FILE_TEMPLATE_PID = \"doms:Template_RadioTVFile\";\n\n private static final int MAX_FAIL_COUNT = 3;\n\n private static final XPathSelector XPATH_SELECTOR = DOM\n .createXPathSelector(\"pbc\", \"http://www.pbcore.org/PBCore/PBCoreNamespace.html\");\n private static final String COMMENT = \"Ingest of Radio/TV data\";\n private static final String FAILED_COMMENT = COMMENT + \": Something failed, rolling back\";\n private int exceptionCount = 0;\n\n /** Folder to move failed files to. */\n private final File failedFilesFolder;\n /** Folder to move processed files to. */\n private final File processedFilesFolder;\n\n /** Document builder that fails on XML files not conforming to the preingest schema. */\n private final DocumentBuilder preingestFilesBuilder;\n /** Document builder that does not require a specific schema. */\n private final DocumentBuilder unSchemaedBuilder;\n /** Client for communicating with DOMS. */\n private final DomsWSClient domsClient;\n\n\n /**\n * Initialise the processor.\n *\n * @param domsLoginInfo Information used for contacting DOMS.\n * @param failedFilesFolder Folder to move failed files to.\n * @param processedFilesFolder Folder to move processed files to.\n * @param preIngestFileSchema Schema for Raio/TV metadata to process.\n */\n public RadioTVMetadataProcessor(DOMSLoginInfo domsLoginInfo, File failedFilesFolder, File processedFilesFolder,\n Schema preIngestFileSchema) {\n this.failedFilesFolder = failedFilesFolder;\n this.processedFilesFolder = processedFilesFolder;\n this.domsClient = new DomsWSClientImpl();\n this.domsClient.setCredentials(domsLoginInfo.getDomsWSAPIUrl(), domsLoginInfo.getLogin(),\n domsLoginInfo.getPassword());\n\n DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilderFactory unschemaedFactory = DocumentBuilderFactory.newInstance();\n documentBuilderFactory.setSchema(preIngestFileSchema);\n documentBuilderFactory.setNamespaceAware(true);\n try {\n preingestFilesBuilder = documentBuilderFactory.newDocumentBuilder();\n unSchemaedBuilder = unschemaedFactory.newDocumentBuilder();\n } catch (ParserConfigurationException pce) {\n pce.printStackTrace();\n fatalException();\n throw new RuntimeException();// will never be reached, but no matter\n }\n\n ErrorHandler documentErrorHandler = new org.xml.sax.ErrorHandler() {\n\n @Override\n public void warning(SAXParseException exception) throws SAXException {\n throw exception;\n }\n\n @Override\n public void fatalError(SAXParseException exception) throws SAXException {\n throw exception;\n }\n\n @Override\n public void error(SAXParseException exception) throws SAXException {\n throw exception;\n }\n };\n preingestFilesBuilder.setErrorHandler(documentErrorHandler);\n\n }\n\n /**\n * Will parse the metadata and add relevant objects to DOMS.\n * @param addedFile Full path to the new file.\n */\n @Override\n public void fileAdded(File addedFile) {\n List pidsToPublish = new ArrayList();\n //This method acts as fault barrier\n try {\n Document radioTVMetadata = preingestFilesBuilder.parse(addedFile);\n createRecord(radioTVMetadata, addedFile, pidsToPublish);\n } catch (Exception e) {\n // Handle anything unanticipated.\n failed(addedFile, pidsToPublish);\n e.printStackTrace();\n incrementFailedTries();\n }\n }\n\n @Override\n public void fileDeleted(File deletedFile) {\n // Not relevant.\n }\n\n /**\n * Acts exactly as fileAdded.\n * @param modifiedFile Full path to the modified file.\n */\n @Override\n public void fileModified(File modifiedFile) {\n fileAdded(modifiedFile);\n }\n\n /**\n * Create objects in DOMS for given program metadata. On success, the originating file will be moved to the folder\n * for processed files. On failure, a file in the folder of failed files will contain the pids that were not\n * published.\n *\n * @param radioTVMetadata The Metadata for the program.\n * @param addedFile The file containing the program metadata\n * @param pidsToPublish Initially empty list of pids to update with pids collected during process, to be published\n * in the end.\n *\n * @throws IOException On io trouble communicating.\n * @throws ServerOperationFailed On trouble updating DOMS.\n * @throws URISyntaxException Should never happen. Means shard URI generated is invalid.\n * @throws XPathExpressionException Should never happen. Means program is broken with wrong XPath exception.\n * @throws XMLParseException On trouble parsing XML.\n */\n private void createRecord(Document radioTVMetadata, File addedFile, List pidsToPublish)\n throws IOException, ServerOperationFailed, URISyntaxException, XPathExpressionException, XMLParseException {\n // Check if program is already in DOMS\n String originalPid;\n try {\n originalPid = alreadyExistsInRepo(radioTVMetadata);\n } catch (NoObjectFound noObjectFound) {\n originalPid = null;\n }\n\n // Find or create files containing this program\n // TODO: Fill out metadata for file\n List filePIDs = ingestFiles(radioTVMetadata);\n pidsToPublish.addAll(filePIDs);\n writePIDs(failedFilesFolder, addedFile, pidsToPublish);\n\n // Create or update shard for this program\n // TODO: Fill out datastreams in program instead\n String shardPid = null;\n if (originalPid != null) { //program already exists\n shardPid = getShardPidFromProgram(originalPid);\n }\n String metaFilePID = ingestMetaFile(radioTVMetadata, filePIDs, shardPid);\n pidsToPublish.add(metaFilePID);\n writePIDs(failedFilesFolder, addedFile, pidsToPublish);\n\n // Create or update program object for this program\n // TODO: May require some updates?\n String programPID = ingestProgram(radioTVMetadata, metaFilePID, originalPid);\n pidsToPublish.add(programPID);\n File allWrittenPIDs = writePIDs(failedFilesFolder, addedFile, pidsToPublish);\n\n // Publish the objects created in the process\n domsClient.publishObjects(COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()]));\n\n // The ingest was successful, if we make it here...\n // Move the processed file to the finished files folder.\n moveFile(addedFile, processedFilesFolder);\n\n // And it is now safe to delete the \"in progress\" PID file.\n allWrittenPIDs.delete();\n\n }\n\n /**\n * Lookup a program in DOMS.\n * If program exists, returns the PID of the program. Otherwise throws exception {@link NoObjectFound}.\n *\n * @param radioTVMetadata The document containing the program metadata.\n * @return PID of program, if found.\n *\n * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath.\n * @throws ServerOperationFailed Could not communicate with DOMS.\n * @throws NoObjectFound The program was not found in DOMS.\n */\n private String alreadyExistsInRepo(Document radioTVMetadata)\n throws XPathExpressionException, ServerOperationFailed, NoObjectFound {\n String oldId = getOldIdentifier(radioTVMetadata);\n List pids = domsClient.getPidFromOldIdentifier(oldId);\n if (!pids.isEmpty()) {\n return pids.get(0);\n }\n throw new NoObjectFound(\"No object found\");\n }\n\n /**\n * Find old identifier in program metadata, and use them for looking up programs in DOMS.\n *\n * @param radioTVMetadata The document containing the program metadata.\n * @return Old indentifier found.\n * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath.\n */\n private String getOldIdentifier(Document radioTVMetadata) throws XPathExpressionException {\n // TODO Should support TVMeter identifiers as well, and return a list!\n Node radioTVPBCoreElement = XPATH_SELECTOR\n .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT);\n\n Node oldPIDNode = XPATH_SELECTOR\n .selectNode(radioTVPBCoreElement, \"pbc:pbcoreIdentifier[pbc:identifierSource=\\\"id\\\"]/pbc:identifier\");\n\n if (oldPIDNode != null && !oldPIDNode.getTextContent().isEmpty()) {\n return oldPIDNode.getTextContent();\n } else {\n return null;\n }\n }\n\n /**\n * queries the list of relations in the program, and extracts the shard-pid from these\n *\n * @param pid the program object pid\n * @return the shard pid, or null if none found\n *\n * @throws ServerOperationFailed if something failed\n */\n private String getShardPidFromProgram(String pid) throws ServerOperationFailed {\n List shardrelations = domsClient.listObjectRelations(pid, HAS_METAFILE_RELATION_TYPE);\n return shardrelations.size() > 0 ? shardrelations.get(0).getSubjectPid() : null;\n }\n\n /**\n * Iteratively (over)write the pid the InProcessPIDs file\n * associated with the preIngestFile.\n *\n * @param outputDirectory absolute path to the directory where the PID file must be\n * written.\n * @param preIngestFile The file containing the Metadata for a program.\n * @param PIDs A list of PIDs to write.\n * @return The File which the PIDs were written to.\n *\n * @throws IOException thrown if the file cannot be written to.\n */\n private File writePIDs(File outputDirectory, File preIngestFile, List PIDs) throws IOException {\n final File pidFile = new File(outputDirectory, preIngestFile.getName() + \".InProcessPIDs\");\n\n if (!pidFile.exists()) {\n pidFile.createNewFile();\n }\n\n if (pidFile.canWrite()) {\n final PrintWriter writer = new PrintWriter(pidFile);\n for (String currentPID : PIDs) {\n writer.println(currentPID);\n }\n writer.flush();\n writer.close();\n return pidFile;\n } else {\n throw new IOException(\"Cannot write file \" + pidFile.getAbsolutePath());\n }\n }\n\n /**\n * Move the failed pre-ingest file to the \"failedFilesFolder\" folder and\n * rename the in-progress PID list file to a failed PID list file, also\n * stored in the \"failedFilesFolder\" folder.\n *

\n * This method should be called before \"pulling the plug\".\n *\n * @param addedFile The file attempted to have added to the doms\n * @param pidsToPublish The failed PIDs\n */\n private void failed(File addedFile, List pidsToPublish) {\n try {\n moveFile(addedFile, failedFilesFolder);\n\n // Rename the in-progress PIDs to failed PIDs.\n writeFailedPIDs(addedFile);\n domsClient.deleteObjects(FAILED_COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()]));\n } catch (Exception exception) {\n // If this bail-out error handling fails, then nothing can save\n // us...\n exception.printStackTrace(System.err);\n }\n }\n\n /**\n * Ingests or update a program object\n *\n *\n * @param radioTVMetadata Bibliographical metadata about the program.\n * @param metafilePID PID to the metafile which represents the program data.\n * @param existingPid the existing pid of the program object, or null if it does not exist\n * @return PID of the newly created program object, created by the DOMS.\n *\n * @throws ServerOperationFailed if creation or manipulation of the program object fails.\n * @throws XPathExpressionException should never happen. Means error in program with invalid XPath.\n * @throws XMLParseException if any errors were encountered while processing the\n * radioTVMetadata XML document.\n */\n private String ingestProgram(Document radioTVMetadata, String metafilePID, String existingPid)\n throws ServerOperationFailed, XPathExpressionException, XMLParseException {\n\n // First, fetch the PBCore metadata document node from the pre-ingest\n // document.\n\n Node radioTVPBCoreElement = XPATH_SELECTOR\n .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT);\n\n // Extract the ritzauID from the pre-ingest file.\n List listOfOldPIDs = new ArrayList();\n String oldId = getOldIdentifier(radioTVMetadata);\n if (oldId != null) {\n listOfOldPIDs.add(oldId);\n }\n\n String programObjectPID;\n if (existingPid == null) {//not Exist\n // Create a program object in the DOMS and update the PBCore metadata\n // datastream with the PBCore metadata from the pre-ingest file.\n programObjectPID = domsClient.createObjectFromTemplate(PROGRAM_TEMPLATE_PID, listOfOldPIDs, COMMENT);\n // Create relations to the metafile/shard\n domsClient.addObjectRelation(programObjectPID, HAS_METAFILE_RELATION_TYPE, metafilePID, COMMENT);\n\n } else { //Exists\n domsClient.unpublishObjects(COMMENT, existingPid);\n programObjectPID = existingPid;\n }\n\n final Document pbCoreDataStreamDocument = createPBCoreDocForDoms(radioTVPBCoreElement);\n domsClient.updateDataStream(programObjectPID, PROGRAM_PBCORE_DS_ID, pbCoreDataStreamDocument, COMMENT);\n\n // Get the program title from the PBCore metadata and use that as the\n // object label for this program object.\n Node titleNode = XPATH_SELECTOR\n .selectNode(radioTVPBCoreElement, \"pbc:pbcoreTitle[pbc:titleType=\\\"titel\\\"]/pbc:title\");\n final String programTitle = titleNode.getTextContent();\n domsClient.setObjectLabel(programObjectPID, programTitle, COMMENT);\n\n // Get the Ritzau metadata from the pre-ingest document and add it to\n // the Ritzau metadata data stream of the program object.\n final Document ritzauOriginalDocument = createRitzauDocument(radioTVMetadata);\n domsClient.updateDataStream(programObjectPID, RITZAU_ORIGINAL_DS_ID, ritzauOriginalDocument, COMMENT);\n\n // Add the Gallup metadata\n Document gallupOriginalDocument = createGallupDocument(radioTVMetadata);\n domsClient.updateDataStream(programObjectPID, GALLUP_ORIGINAL_DS_ID, gallupOriginalDocument, COMMENT);\n\n return programObjectPID;\n }\n\n /**\n * Utility method to create the Ritzau document to ingest\n *\n * @param radioTVMetadata Bibliographical metadata about the program.\n * @return A document containing the Ritzau metadata.\n */\n private Document createRitzauDocument(Document radioTVMetadata) {\n final Node ritzauPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, RITZAU_ORIGINALS_ELEMENT);\n\n // Build a Ritzau data document for the Ritzau data stream in the\n // program object.\n final Document ritzauOriginalDocument = unSchemaedBuilder.newDocument();\n final Element ritzauOriginalRootElement = ritzauOriginalDocument.createElement(\"ritzau_original\");\n\n ritzauOriginalRootElement.setAttribute(\"xmlns\", \"http://doms.statsbiblioteket.dk/types/ritzau_original/0/1/#\");\n ritzauOriginalDocument.appendChild(ritzauOriginalRootElement);\n\n ritzauOriginalRootElement.setTextContent(ritzauPreingestElement.getTextContent());\n return ritzauOriginalDocument;\n }\n\n /**\n * Utility method to create the Gallup document to ingest\n *\n * @param radioTVMetadata Bibliographical metadata about the program.\n * @return A document containing the Gallup metadata\n */\n private Document createGallupDocument(Node radioTVMetadata) {\n final Node gallupPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, GALLUP_ORIGINALS_ELEMENT);\n\n final Document gallupOriginalDocument = unSchemaedBuilder.newDocument();\n\n final Element gallupOriginalRootElement = gallupOriginalDocument.createElement(\"gallup_original\");\n\n gallupOriginalRootElement.setAttribute(\"xmlns\", \"http://doms.statsbiblioteket.dk/types/gallup_original/0/1/#\");\n\n gallupOriginalRootElement.setTextContent(gallupPreingestElement.getTextContent());\n\n gallupOriginalDocument.appendChild(gallupOriginalRootElement);\n return gallupOriginalDocument;\n }\n\n /**\n * Utility method to create the PBCore document to ingest\n *\n * @param radioTVPBCoreElement Element containing PBCore.\n * @return A document containing the PBCore metadata\n */\n private Document createPBCoreDocForDoms(Node radioTVPBCoreElement) {\n final Document pbCoreDataStreamDocument = unSchemaedBuilder.newDocument();\n\n // Import the PBCore metadata from the pre-ingest document and use it as\n // the contents for the PBCore metadata data stream of the program\n // object.\n final Node newPBCoreElement = pbCoreDataStreamDocument.importNode(radioTVPBCoreElement, true);\n\n pbCoreDataStreamDocument.appendChild(newPBCoreElement);\n return pbCoreDataStreamDocument;\n }\n\n /**\n * Ingest a metafile (aka. shard) object which represents the program data\n * (i.e. video and/or audio). A metafile may consist of data chunks from\n * multiple physical files identified by the PIDs in the\n * filePIDs list. The metadata provided by\n * radioTVMetadata contains, among other things, information\n * about location and duration of the chunks of data from the physical files\n * which constitutes the contents of the metafile.\n *

\n * TODO: Consider cleaning up/consolidating the exceptions\n *\n * @param radioTVMetadata Metadata about location and duration of the relevant data\n * chunks from the physical files.\n * @param filePIDs List of PIDs for the physical files containing the data\n * represented by this metafile.\n * @param metaFilePID The PID of the object, if it exists already. Otherwise null\n * @return PID of the newly created metafile object, created by the DOMS.\n *\n * @throws ServerOperationFailed if creation or manipulation of the metafile object fails.\n * @throws IOException if io exceptions occur while communicating.\n * @throws XPathExpressionException should never happen. Means error in program with invalid XPath.\n * @throws URISyntaxException if shard URL could not be generated\n * @throws XMLParseException if any errors were encountered while processing the\n * radioTVMetadata XML document.\n */\n private String ingestMetaFile(Document radioTVMetadata, List filePIDs, String metaFilePID)\n throws ServerOperationFailed, IOException, XPathExpressionException, URISyntaxException, XMLParseException {\n\n if (metaFilePID == null) {\n // Create a file object from the file object template.\n metaFilePID = domsClient.createObjectFromTemplate(META_FILE_TEMPLATE_PID, COMMENT);\n // TODO: Do something about this.\n final FileInfo fileInfo = new FileInfo(\"shard/\" + metaFilePID,\n new URL(\"http://www.statsbiblioteket.dk/doms/shard/\" + metaFilePID),\n \"\", new URI(\"info:pronom/fmt/199\"));\n\n domsClient.addFileToFileObject(metaFilePID, fileInfo, COMMENT);\n\n } else {\n domsClient.unpublishObjects(COMMENT, metaFilePID);\n }\n\n final Document metadataDataStreamDocument = unSchemaedBuilder.newDocument();\n\n final Element metadataDataStreamRootElement = metadataDataStreamDocument.createElement(\"shard_metadata\");\n\n metadataDataStreamDocument.appendChild(metadataDataStreamRootElement);\n\n // Add all the \"file\" elements from the radio-tv metadata document.\n // TODO: Note that this is just a first-shot implementation until a\n // proper metadata format has been defined.\n final NodeList recordingFileElements = XPATH_SELECTOR\n .selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT);\n\n for (int fileElementIdx = 0; fileElementIdx < recordingFileElements.getLength(); fileElementIdx++) {\n\n final Node currentRecordingFile = recordingFileElements.item(fileElementIdx);\n\n // Append to the end of the list of child nodes.\n final Node newMetadataElement = metadataDataStreamDocument.importNode(currentRecordingFile, true);\n\n metadataDataStreamRootElement.appendChild(newMetadataElement);\n }\n\n domsClient.updateDataStream(metaFilePID, META_FILE_METADATA_DS_ID, metadataDataStreamDocument, COMMENT);\n\n List relations = domsClient.listObjectRelations(metaFilePID, CONSISTS_OF_RELATION_TYPE);\n HashSet existingRels = new HashSet();\n for (Relation relation : relations) {\n if (!filePIDs.contains(relation.getSubjectPid())) {\n domsClient.removeObjectRelation((LiteralRelation) relation, COMMENT);\n } else {\n existingRels.add(relation.getSubjectPid());\n }\n }\n for (String filePID : filePIDs) {\n if (!existingRels.contains(filePID)) {\n domsClient.addObjectRelation(metaFilePID, CONSISTS_OF_RELATION_TYPE, filePID, COMMENT);\n\n }\n }\n\n return metaFilePID;\n }\n\n /**\n * Ingest any missing file objects into the DOMS and return a list of PIDs\n * for all the DOMS file objects corresponding to the files listed in the\n * radioTVMetadata document.\n *\n * @param radioTVMetadata Metadata XML document containing the file information.\n * @return A List of PIDs of the radio-tv file objects created\n * by the DOMS.\n *\n * @throws XPathExpressionException if any errors were encountered while processing the\n * radioTVMetadata XML document.\n * @throws MalformedURLException if a file element contains an invalid URL.\n * @throws ServerOperationFailed if creation and retrieval of a radio-tv file object fails.\n * @throws URISyntaxException if the format URI for the file is invalid.\n */\n private List ingestFiles(Document radioTVMetadata)\n throws XPathExpressionException, MalformedURLException, ServerOperationFailed, URISyntaxException {\n\n // Get the recording files XML element and process the file information.\n final NodeList recordingFiles = XPATH_SELECTOR.selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT);\n\n // Ensure that the DOMS contains a file object for each recording file\n // element in the radio-tv XML document.\n final List fileObjectPIDs = new ArrayList();\n for (int nodeIndex = 0; nodeIndex < recordingFiles.getLength(); nodeIndex++) {\n\n final Node currentFileNode = recordingFiles.item(nodeIndex);\n\n final Node fileURLNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_URL_ELEMENT);\n final String fileURLString = fileURLNode.getTextContent();\n final URL fileURL = new URL(fileURLString);\n\n String fileObjectPID;\n try {\n fileObjectPID = domsClient.getFileObjectPID(fileURL);\n } catch (NoObjectFound nof) {\n // The DOMS contains no file object for this file URL.\n // Create a new one now.\n final Node fileNameNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_NAME_ELEMENT);\n\n final String fileName = fileNameNode.getTextContent();\n\n final Node formatURINode = XPATH_SELECTOR.selectNode(currentFileNode, FORMAT_URI_ELEMENT);\n\n final URI formatURI = new URI(formatURINode.getTextContent());\n\n final Node md5SumNode = XPATH_SELECTOR.selectNode(currentFileNode, MD5_SUM_ELEMENT);\n\n // The MD5 check sum is optional. Just leave it empty if the\n // pre-ingest file does not provide it.\n String md5String = \"\";\n if (md5SumNode != null) {\n md5String = md5SumNode.getTextContent();\n }\n\n final FileInfo fileInfo = new FileInfo(fileName, fileURL, md5String, formatURI);\n\n fileObjectPID = domsClient.createFileObject(RADIO_TV_FILE_TEMPLATE_PID, fileInfo, COMMENT);\n }\n fileObjectPIDs.add(fileObjectPID);\n }\n return fileObjectPIDs;\n }\n\n /**\n * Move fileToMove to the folder specified by\n * destinationFolder.\n *\n * @param fileToMove Path to the file to move to destinationFolder.\n * @param destinationFolder Path of the destination folder to move the file to.\n */\n private void moveFile(File fileToMove, File destinationFolder) {\n fileToMove.renameTo(new File(destinationFolder.getAbsolutePath(), fileToMove.getName()));\n }\n\n /**\n * Rename the file with a list of PIDs in progress and never published to a file with a list of failed PIDs.\n * @param failedMetadataFile The originating file.\n *\n */\n private void writeFailedPIDs(File failedMetadataFile) {\n final File activePIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + \".InProcessPIDs\");\n final File failedPIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + \".failedPIDs\");\n activePIDsFile.renameTo(failedPIDsFile);\n }\n\n /**\n * ends all attempts to ingest from the current list of file descriptions in\n * the pre-ingest file Violent exit needed \"system.exit()\n */\n private void fatalException() {\n System.exit(-1);\n }\n\n /** The number of tries is incremented by one.\n * If this exceeds the maximum number of allowed failures, */\n private void incrementFailedTries() {\n exceptionCount += 1;\n if (exceptionCount >= MAX_FAIL_COUNT) {\n System.err.println(\"Too many errors (\" + exceptionCount + \") in ingest. Exiting.\");\n fatalException();\n }\n }\n\n}\n"},"message":{"kind":"string","value":"Increased allowed number of failures during ingest\n"},"old_file":{"kind":"string","value":"radio-tv/src/main/java/dk/statsbiblioteket/doms/ingesters/radiotv/RadioTVMetadataProcessor.java"},"subject":{"kind":"string","value":"Increased allowed number of failures during ingest"}}},{"rowIdx":1253,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"fffdcc380d44af3e763d989c8567c2a52d530da0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"PavelGirkalo/java_pft,PavelGirkalo/java_pft"},"new_contents":{"kind":"string","value":"package ru.stqa.pft.addressbook.generators;\n\nimport com.beust.jcommander.JCommander;\nimport com.beust.jcommander.Parameter;\nimport com.beust.jcommander.ParameterException;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.thoughtworks.xstream.XStream;\nimport ru.stqa.pft.addressbook.model.ContactData;\n\nimport java.io.File;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ContactDataGenetator {\n\n @Parameter(names = \"-c\", description = \"Contact count\")\n public int count;\n\n @Parameter(names = \"-f\", description = \"Target contact file\")\n public String file;\n\n @Parameter(names = \"-d\", description = \"Data format\")\n public String format;\n\n public static void main(String[] args) throws IOException {\n ContactDataGenetator genetator = new ContactDataGenetator();\n JCommander jCommander = new JCommander(genetator);\n try {\n jCommander.parse(args);\n } catch (ParameterException ex) {\n jCommander.usage();\n return;\n }\n genetator.run();\n\n }\n\n private void run() throws IOException {\n List contacts = generateContacts(count);\n if (format.equals(\"csv\")) {\n saveAsCsv(contacts, new File(file));\n } else if (format.equals(\"xml\")) {\n saveAsXml(contacts, new File(file));\n } else if (format.equals(\"json\")) {\n saveAsJson(contacts, new File(file));\n } else {\n System.out.println(\"Unrecognized format \" + format);\n }\n }\n\n private void saveAsJson(List contacts, File file) throws IOException {\n Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();\n String json = gson.toJson(contacts);\n Writer writer = new FileWriter(file);\n writer.write(json);\n writer.close();\n }\n\n private void saveAsXml(List contacts, File file) throws IOException {\n XStream xstream = new XStream();\n xstream.processAnnotations(ContactData.class);\n //xstream.alias(\"group\", GroupData.class);\n String xml = xstream.toXML(contacts);\n Writer writer = new FileWriter(file);\n writer.write(xml);\n writer.close();\n }\n\n private void saveAsCsv(List contacts, File file) throws IOException {\n System.out.println(new File(\".\").getAbsolutePath());\n Writer writer = new FileWriter(file);\n for (ContactData contact : contacts) {\n writer.write(String.format(\"%s;%s;%s;%s;%s\\n\", contact.getFirstname(), contact.getLastname(), contact.getAddress(), contact.getEmail(), contact.getMobile()));\n }\n writer.close();\n\n }\n\n private List generateContacts(int count) {\n List contacts = new ArrayList();\n for (int i = 0; i contacts = generateContacts(count);\n if (format.equals(\"csv\")) {\n saveAsCsv(contacts, new File(file));\n } else if (format.equals(\"xml\")) {\n saveAsXml(contacts, new File(file));\n } else if (format.equals(\"json\")) {\n saveAsJson(contacts, new File(file));\n } else {\n System.out.println(\"Unrecognized format \" + format);\n }\n }\n\n private void saveAsJson(List contacts, File file) throws IOException {\n Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();\n String json = gson.toJson(contacts);\n Writer writer = new FileWriter(file);\n writer.write(json);\n writer.close();\n }\n\n private void saveAsXml(List contacts, File file) throws IOException {\n XStream xstream = new XStream();\n xstream.processAnnotations(ContactData.class);\n //xstream.alias(\"group\", GroupData.class);\n String xml = xstream.toXML(contacts);\n Writer writer = new FileWriter(file);\n writer.write(xml);\n writer.close();\n }\n\n private void saveAsCsv(List contacts, File file) throws IOException {\n System.out.println(new File(\".\").getAbsolutePath());\n Writer writer = new FileWriter(file);\n for (ContactData contact : contacts) {\n writer.write(String.format(\"%s;%s;%s;%s;%s\\n\", contact.getFirstname(), contact.getLastname(), contact.getAddress(), contact.getEmail(), contact.getMobile()));\n }\n writer.close();\n\n }\n\n private List generateContacts(int count) {\n List contacts = new ArrayList();\n for (int i = 0; i joshua.ryan@asu.edu\n *\n * This class is basically just a conveinceince class for abstracting the creation of\n * PDF's from assessments\n * \n */\npublic class PDFAssessmentBean implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate static Log log = LogFactory.getLog(PDFAssessmentBean.class);\n\n\tprivate static ResourceBundle printMessages = ResourceBundle.getBundle(\"org.sakaiproject.tool.assessment.bundle.PrintMessages\");\n\n\tprivate static ResourceBundle authorMessages = ResourceBundle.getBundle(\"org.sakaiproject.tool.assessment.bundle.AuthorMessages\");\n\n\tprivate static ResourceBundle commonMessages = ResourceBundle.getBundle(\"org.sakaiproject.tool.assessment.bundle.CommonMessages\");\n\n\tprivate String intro = \"\";\n\n\tprivate String title = \"\";\n\n\tprivate ArrayList parts = null;\n\n\tprivate ArrayList deliveryParts = null;\n\n\tprivate int baseFontSize = 5;\n\n\tprivate String actionString = \"\";\n\n\tpublic PDFAssessmentBean() {\n\t\tif (log.isInfoEnabled())\n\t\t\tlog.info(\"Starting PDFAssessementBean with session scope\");\n\n\t}\n\n\n\t/**\n\t * Gets the pdf assessments intro\n\t * @return assessment intor in html\n\t */\n\tpublic String getIntro() {\n\t\treturn intro;\n\t}\n\n\t/**\n\t * sets the pdf assessments intro\n\t * @param intro in html\n\t */\n\tpublic void setIntro(String intro) {\n\t\tthis.intro = FormattedText.unEscapeHtml(intro);\n\t}\n\n\t/**\n\t * gets the delivery bean parts of the assessment\n\t * @return\n\t */\n\tpublic ArrayList getDeliveryParts() { \n\t\treturn deliveryParts;\n\t}\n\n\t/**\n\t * gets the parts of the assessment\n\t * @return\n\t */\n\tpublic ArrayList getParts() { \n\t\treturn parts;\n\t}\n\n\t/**\n\t * gets what should be the full set of html chunks for an assessment\n\t * @return\n\t */\n\tpublic ArrayList getHtmlChunks() {\n\t\treturn parts;\n\t}\n\n\t/**\n\t * sets the delivery parts\n\t * @param deliveryParts\n\t */\n\tpublic void setDeliveryParts(ArrayList deliveryParts) {\n\t\tArrayList parts = new ArrayList();\n\t\tint numberQuestion = 1;\n\t\tfor (int i=0; i 1) \n\t\t\t\tpdfPart.setIntro(\"

\" + authorMessages.getString(\"p\") + \" \" + (i+1) + \": \" + section.getTitle() + \"

\");\n\t\t\tArrayList pdfItems = new ArrayList();\n\n\t\t\t//for each item in a section we add a blank pdfItem to the pdfPart\n\t\t\tfor (int j = 0; j < items.size(); j++) {\n\t\t\t\tPDFItemBean pdfItem = new PDFItemBean();\n\n\t\t\t\tItemContentsBean item = (ItemContentsBean) items.get(j);\n\n\t\t\t\tString legacy = \"

\" + item.getNumber() +\"

\";\n\t\t\t\tpdfItem.setItemId(item.getItemData().getItemId());\n\n\t\t\t\tString content = \"
\" + item.getItemData().getText() + \"
\";\n\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING)) {\n\t\t\t\t\tcontent += printMessages.getString(\"time_allowed_seconds\") + \": \" + item.getItemData().getDuration();\n\t\t\t\t\tcontent += \"
\" + printMessages.getString(\"number_of_tries\") + \": \" + item.getItemData().getTriesAllowed();\n\t\t\t\t\tcontent += \"
\";\n\t\t\t\t}\n\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) {\n\t\t\t\t\tcontent += printMessages.getString(\"upload_instruction\") + \"
\";\n\n\t\t\t\t\tcontent += printMessages.getString(\"file\") + \": \";\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tcontent += \"
\";\n\t\t\t\t}\n\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) {\n\n\t\t\t\t\tArrayList question = item.getItemData().getItemTextArraySorted();\n\t\t\t\t\tfor (int k=0; k\";\n\t\t\t\t\t\tfor (int t=0; t\" + getContentAnswer(item, answer, printSetting) + \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontent += \"\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) {\n\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tArrayList question = item.getMatchingArray();\n\t\t\t\t\tfor (int k=0; k\";\n\t\t\t\t\t\tcontent += \"\";\n\t\t\t\t\t}\n\t\t\t\t\tcontent += \"
\";\n\t\t\t\t\t\tcontent += matching.getText();\n\t\t\t\t\t\tcontent += \"\";\t\t \n\t\t\t\t\t\tcontent += answer + \"
\";\n\t\t\t\t}\n\t\t\t\tif (printSetting.getShowKeys().booleanValue() || printSetting.getShowKeysFeedback().booleanValue()) {\n\t\t\t\t\tcontent += \"
\" + getContentQuestion(item, printSetting);\n\t\t\t\t}\n\n\t\t\t\tpdfItem.setContent(content);\n\n\t\t\t\tif (legacy != null) {\n\t\t\t\t\tpdfItem.setMeta(legacy); \n\t\t\t\t}\n\n\t\t\t\tpdfItems.add(pdfItem);\n\t\t\t}\n\n\t\t\tpdfPart.setQuestions(pdfItems);\n\t\t\tpdfPart.setResources(resources);\n\t\t\tif (resources.size() > 0)\n\t\t\t\tpdfPart.setHasResources(new Boolean(true));\n\t\t\tpdfParts.add(pdfPart);\n\n\t\t}\n\n\t\t//set the new colleciton of PDF beans to be the contents of the pdfassessment\n\t\tsetParts(pdfParts);\n\n\t\tsetTitle(deliveryBean.getAssessmentTitle());\n\n\t\treturn \"print\";\n\t}\n\n\tprivate String getContentAnswer(ItemContentsBean item, PublishedAnswer answer, PrintSettingsBean printSetting) {\n\t\tString content = \"\";\n\n\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) ||\n\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) ||\n\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) ||\n\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)) {\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT))\n\t\t\t\tcontent += \"\";\n\t\t\telse\n\t\t\t\tcontent += \"\";\n\t\t\tcontent += \"\";\n\t\t\tif (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)) \n\t\t\t\tcontent += answer.getLabel() + \". \";\n\t\t\tcontent += answer.getText();\n\t\t\tcontent += \"\";\n\t\t\tcontent += \"\";\n\t\t\tif (printSetting.getShowKeysFeedback()) {\n\t\t\t\tcontent += \"
\" + commonMessages.getString(\"feedback\") + \": \";\n\t\t\t\tif (answer.getGeneralAnswerFeedback() != null && !answer.getGeneralAnswerFeedback().equals(\"\"))\n\t\t\t\t\tcontent += answer.getGeneralAnswerFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t\tcontent += \"
\";\n\t\t\t}\n\t\t\tcontent += \"\";\n\t\t}\n\n\t\tif (item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) {\n\t\t\tcontent += \"\";\n\t\t\tcontent += \"\";\n\t\t\tcontent += answer.getText();\n\t\t\tcontent += \"\";\n\t\t}\n\n\t\treturn content;\n\t}\n\n\tprivate String getContentQuestion(ItemContentsBean item, PrintSettingsBean printSetting) {\n\t\tString content = \"
\";\n\n\t\tcontent += printMessages.getString(\"answer_point\") + \": \" + item.getItemData().getScore();\n\t\tcontent += \" \" + authorMessages.getString(\"points_lower_case\");\n\n\t\tif (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) &&\n\t\t\t\t!item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) &&\n\t\t\t\t!item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) {\n\n\t\t\tcontent += \"
\";\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION))\n\t\t\t\tcontent += printMessages.getString(\"answer_model\") + \": \";\n\t\t\telse\n\t\t\t\tcontent += printMessages.getString(\"answer_key\") + \": \";\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || \n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MATCHING))\n\t\t\t\tcontent += item.getKey();\n\t\t\telse if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION)) {\n\t\t\t\tif (item.getKey() != null && !item.getKey().equals(\"\"))\n\t\t\t\t\tcontent += item.getKey();\n\t\t\t\telse\n\t\t\t\t\tcontent += \"--------\";\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontent += item.getItemData().getAnswerKey();\n\t\t}\n\n\t\tif (printSetting.getShowKeysFeedback().booleanValue()) {\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) {\n\n\t\t\t\tcontent += \"
\";\n\t\t\t\tcontent += commonMessages.getString(\"feedback\") + \": \";\n\t\t\t\tif (item.getItemData().getGeneralItemFeedback() != null && !item.getItemData().getGeneralItemFeedback().equals(\"\"))\n\t\t\t\t\tcontent += item.getItemData().getGeneralItemFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t}\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MATCHING)) {\n\n\t\t\t\tcontent += \"
\";\n\t\t\t\tcontent += printMessages.getString(\"correct_feedback\") + \": \";\n\t\t\t\tif (item.getItemData().getCorrectItemFeedback() != null && !item.getItemData().getCorrectItemFeedback().equals(\"\"))\n\t\t\t\t\tcontent += item.getItemData().getCorrectItemFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t\tcontent += \"
\" + printMessages.getString(\"incorrect_feedback\") + \": \";\n\t\t\t\tif (item.getItemData().getInCorrectItemFeedback() != null && !item.getItemData().getInCorrectItemFeedback().equals(\"\"))\n\t\t\t\t\tcontent += item.getItemData().getInCorrectItemFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t}\n\n\t\t}\n\n\t\treturn content + \"
\";\n\t}\n\n\tpublic void getPDFAttachment() {\n\t\tprepDocumentPDF();\n\t\tByteArrayOutputStream pdf = getStream();\n\n\t\tFacesContext faces = FacesContext.getCurrentInstance();\n\t\tHttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse();\n\n\t\tresponse.reset();\n\t\tresponse.setHeader(\"Pragma\", \"public\"); \n\t\tresponse.setHeader(\"Cache-Control\", \"public, must-revalidate, post-check=0, pre-check=0, max-age=0\"); \n\n\t\tresponse.setContentType(\"application/pdf\");\n\t\tresponse.setHeader(\"Content-disposition\", \"attachment; filename=\" + genName()); \n\t\tresponse.setContentLength(pdf.toByteArray().length);\n\t\tOutputStream out = null;\n\t\ttry {\n\t\t\tout = response.getOutputStream();\n\t\t\tout.write(pdf.toByteArray());\n\t\t\tout.flush();\n\t\t} \n\t\tcatch (IOException e) {\n\t\t\tlog.error(e);\n\t\t\te.printStackTrace();\n\t\t} \n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tif (out != null) \n\t\t\t\t\tout.close();\n\t\t\t} \n\t\t\tcatch (IOException e) {\n\t\t\t\tlog.error(e);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tfaces.responseComplete();\n\t}\n\n\t/**\n\t * Converts all nice new school html into old school\n\t * font tagged up html that HTMLWorker will actually\n\t * parse right\n\t * \n\t * @param input\n\t */\n\tprivate String oldschoolIfy(String input) {\n\n\t\tif (log.isDebugEnabled())\n\t\t\tlog.debug(\"starting oldschoolify with: \" + input);\n\t\tinput = input.replaceAll(\"\", \"\");\n\n\t\treturn input;\n\t}\n\n\t/**\n\t * Turns a string into a StringReader with out the fuss of an IOException\n\t * \n\t * @param input\n\t * @return StringReader\n\t */\n\tprivate Reader safeReader(String input) {\n\t\tStringReader output = null;\n\t\tif (input == null) {\n\t\t\tinput = \"\";\n\t\t}\n\t\telse {\n\t\t\tinput = oldschoolIfy(input);\n\t\t}\n\n\t\ttry {\n\t\t\toutput = new StringReader(input + \"
\");\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\tlog.error(\"could not get StringReader for String \" + input + \" due to : \" + e);\n\t\t}\n\t\treturn output;\n\t}\n\n\tpublic ByteArrayOutputStream getStream() {\n\n\t\tByteArrayOutputStream output = new ByteArrayOutputStream();\n\n\t\ttry {\n\n\t\t\tif (log.isInfoEnabled())\n\t\t\t\tlog.info(\"starting PDF generation\" );\n\n\t\t\tDocument document = new Document(PageSize.A4, 20, 20, 20, 20);\n\t\t\tPdfWriter docWriter = PdfWriter.getInstance(document, output);\n\n\t\t\tdocument.open();\n\t\t\tdocument.resetPageCount();\n\n\t\t\tHTMLWorker worker = new HTMLWorker(document);\n\n\t\t\tHashMap props = worker.getInterfaceProps();\n\t\t\tif (props == null) {\n\t\t\t\tprops = new HashMap();\n\t\t\t}\n\n\t\t\tfloat prevs = 0;\n\n\t\t\tprops.put(\"img_baseurl\", ServerConfigurationService.getServerUrl());\n\t\t\tworker.setInterfaceProps(props);\n\n\t\t\t//TODO make a real style sheet\n\t\t\tStyleSheet style = null;\n\n\t\t\tString head = printMessages.getString(\"print_name_form\");\n\t\t\thead += \"
\";\n\t\t\thead += printMessages.getString(\"print_score_form\");\n\t\t\thead += \"

\";\n\t\t\thead += \"

\" + title + \"


\";\n\t\t\thead += intro + \"
\";\n\t\t\t//head = head.replaceAll(\"[ \\t\\n\\f\\r]+\", \" \");\n\n\t\t\t//parse out the elements from the html\n\t\t\tArrayList elementBuffer = HTMLWorker.parseToList(safeReader(head), style, props);\n\t\t\tfloat[] singleWidth = {1f};\n\t\t\tPdfPTable single = new PdfPTable(singleWidth);\n\t\t\tsingle.setWidthPercentage(100f);\n\t\t\tPdfPCell cell = new PdfPCell();\n\t\t\tcell.setBorderWidth(0);\n\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) { \n\t\t\t\tcell.addElement((Element)elementBuffer.get(k)); \n\t\t\t}\n\t\t\tsingle.addCell(cell);\n\n\t\t\tprevs += single.getTotalHeight() % document.getPageSize().height();\n\t\t\t//TODO do we want a new page here ... thus giving the cover page look?\n\n\t\t\tdocument.add(single);\n\t\t\tdocument.add(Chunk.NEWLINE);\n\n\t\t\t//extract the html and parse it into pdf\n\t\t\tArrayList parts = getHtmlChunks();\n\t\t\tfor (int i = 0; i < parts.size(); i++) {\n\t\t\t\t//add new page to start each new part\n\t\t\t\tif (i > 0) {\n\t\t\t\t\tdocument.newPage();\n\t\t\t\t}\n\n\t\t\t\tPDFPartBean pBean = (PDFPartBean) parts.get(i);\n\t\t\t\tif (pBean.getIntro() != null && !\"\".equals(pBean.getIntro())) {\n\t\t\t\t\telementBuffer = HTMLWorker.parseToList(safeReader(pBean.getIntro()), style, props);\n\t\t\t\t\tsingle = new PdfPTable(singleWidth);\n\t\t\t\t\tsingle.setWidthPercentage(100f);\n\t\t\t\t\tcell = new PdfPCell();\n\t\t\t\t\tcell.setBorderWidth(0);\n\t\t\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) { \n\t\t\t\t\t\tcell.addElement((Element)elementBuffer.get(k)); \n\t\t\t\t\t}\n\t\t\t\t\tsingle.addCell(cell);\n\n\t\t\t\t\tprevs += single.getTotalHeight() % document.getPageSize().height();\n\t\t\t\t\tdocument.add(single);\n\t\t\t\t} \n\n\t\t\t\tArrayList items = pBean.getQuestions();\n\n\t\t\t\tfor (int j = 0; j < items.size(); j++) {\n\t\t\t\t\tPDFItemBean iBean = (PDFItemBean) items.get(j);\n\n\t\t\t\t\tfloat[] widths = {0.1f, 0.9f};\n\t\t\t\t\tPdfPTable table = new PdfPTable(widths);\n\t\t\t\t\ttable.setWidthPercentage(100f);\n\t\t\t\t\tPdfPCell leftCell = new PdfPCell();\n\t\t\t\t\tPdfPCell rightCell = new PdfPCell();\n\t\t\t\t\tleftCell.setBorderWidth(0);\n\t\t\t\t\tleftCell.setPadding(0);\n\t\t\t\t\tleftCell.setLeading(0.00f, 0.00f);\n\t\t\t\t\tleftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);\n\t\t\t\t\tleftCell.setVerticalAlignment(Element.ALIGN_TOP);\n\t\t\t\t\trightCell.setBorderWidth(0);\n\t\t\t\t\telementBuffer = HTMLWorker.parseToList(safeReader(iBean.getMeta()), style, props);\n\t\t\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) {\n\t\t\t\t\t\tElement element = (Element)elementBuffer.get(k);\n\t\t\t\t\t\tif (element instanceof Paragraph) {\n\t\t\t\t\t\t\tParagraph p = (Paragraph)element;\n\t\t\t\t\t\t\tp.getFont().setColor(Color.GRAY);\n\t\t\t\t\t\t\tp.setAlignment(Paragraph.ALIGN_CENTER);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tleftCell.addElement(element);\n\t\t\t\t\t}\n\n\t\t\t\t\ttable.addCell(leftCell);\n\n\t\t\t\t\telementBuffer = HTMLWorker.parseToList(safeReader(iBean.getContent()), style, props);\n\t\t\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) {\n\t\t\t\t\t\tElement element = (Element)elementBuffer.get(k);\n\n\t\t\t\t\t\trightCell.addElement(element);\n\t\t\t\t\t}\n\t\t\t\t\ttable.addCell(rightCell);\n\n\t\t\t\t\tif (table.getTotalHeight() + prevs > document.getPageSize().height())\n\t\t\t\t\t\tdocument.newPage();\n\n\t\t\t\t\tdocument.add(table);\n\t\t\t\t\tdocument.add(Chunk.NEWLINE);\n\n\t\t\t\t\t//TODO add PDFTable and a collumn\n\n\t\t\t\t\t//worker.parse(safeReader(iBean.getMeta()));\n\t\t\t\t\t//TODO column break\n\t\t\t\t\t//worker.parse(safeReader(iBean.getContent()));\n\t\t\t\t\t//TODO end column and table\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdocument.close();\n\t\t\tdocWriter.close();\n\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(\"document: \" + e.getMessage());\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tpublic String getBaseFontSize() {\n\t\treturn \"\" + baseFontSize;\n\t}\n\n\tpublic void setBaseFontSize(String baseFontSize) {\n\t\tthis.baseFontSize = Integer.parseInt(baseFontSize);\n\t}\n\n\n\t/**\n\t * @return the actionString\n\t */\n\tpublic String getActionString() {\n\t\treturn actionString;\n\t}\n\n\n\t/**\n\t * @param actionString the actionString to set\n\t */\n\tpublic void setActionString(String actionString) {\n\t\tthis.actionString = actionString;\n\t}\n\n\tpublic String getSizeDeliveryParts() {\n\n\t\treturn \"\" + deliveryParts.size();\n\t}\n\n\tpublic String getTotalQuestions() {\n\n\t\tint items = 0;\n\t\tfor (int i=0; ijoshua.ryan@asu.edu\n *\n * This class is basically just a conveinceince class for abstracting the creation of\n * PDF's from assessments\n * \n */\npublic class PDFAssessmentBean implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate static Log log = LogFactory.getLog(PDFAssessmentBean.class);\n\n\tprivate static ResourceBundle printMessages = ResourceBundle.getBundle(\"org.sakaiproject.tool.assessment.bundle.PrintMessages\");\n\n\tprivate static ResourceBundle authorMessages = ResourceBundle.getBundle(\"org.sakaiproject.tool.assessment.bundle.AuthorMessages\");\n\n\tprivate String intro = \"\";\n\n\tprivate String title = \"\";\n\n\tprivate ArrayList parts = null;\n\n\tprivate ArrayList deliveryParts = null;\n\n\tprivate int baseFontSize = 5;\n\n\tprivate String actionString = \"\";\n\n\tpublic PDFAssessmentBean() {\n\t\tif (log.isInfoEnabled())\n\t\t\tlog.info(\"Starting PDFAssessementBean with session scope\");\n\n\t}\n\n\n\t/**\n\t * Gets the pdf assessments intro\n\t * @return assessment intor in html\n\t */\n\tpublic String getIntro() {\n\t\treturn intro;\n\t}\n\n\t/**\n\t * sets the pdf assessments intro\n\t * @param intro in html\n\t */\n\tpublic void setIntro(String intro) {\n\t\tthis.intro = FormattedText.unEscapeHtml(intro);\n\t}\n\n\t/**\n\t * gets the delivery bean parts of the assessment\n\t * @return\n\t */\n\tpublic ArrayList getDeliveryParts() { \n\t\treturn deliveryParts;\n\t}\n\n\t/**\n\t * gets the parts of the assessment\n\t * @return\n\t */\n\tpublic ArrayList getParts() { \n\t\treturn parts;\n\t}\n\n\t/**\n\t * gets what should be the full set of html chunks for an assessment\n\t * @return\n\t */\n\tpublic ArrayList getHtmlChunks() {\n\t\treturn parts;\n\t}\n\n\t/**\n\t * sets the delivery parts\n\t * @param deliveryParts\n\t */\n\tpublic void setDeliveryParts(ArrayList deliveryParts) {\n\t\tArrayList parts = new ArrayList();\n\t\tint numberQuestion = 1;\n\t\tfor (int i=0; i 1) \n\t\t\t\tpdfPart.setIntro(\"

\" + authorMessages.getString(\"p\") + \" \" + (i+1) + \": \" + section.getTitle() + \"

\");\n\t\t\tArrayList pdfItems = new ArrayList();\n\n\t\t\t//for each item in a section we add a blank pdfItem to the pdfPart\n\t\t\tfor (int j = 0; j < items.size(); j++) {\n\t\t\t\tPDFItemBean pdfItem = new PDFItemBean();\n\n\t\t\t\tItemContentsBean item = (ItemContentsBean) items.get(j);\n\n\t\t\t\tString legacy = \"

\" + item.getNumber() +\"

\";\n\t\t\t\tpdfItem.setItemId(item.getItemData().getItemId());\n\n\t\t\t\tString content = \"
\" + item.getItemData().getText() + \"
\";\n\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING)) {\n\t\t\t\t\tcontent += printMessages.getString(\"time_allowed_seconds\") + \": \" + item.getItemData().getDuration();\n\t\t\t\t\tcontent += \"
\" + printMessages.getString(\"number_of_tries\") + \": \" + item.getItemData().getTriesAllowed();\n\t\t\t\t\tcontent += \"
\";\n\t\t\t\t}\n\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) {\n\t\t\t\t\tcontent += printMessages.getString(\"upload_instruction\") + \"
\";\n\n\t\t\t\t\tcontent += printMessages.getString(\"file\") + \": \";\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tcontent += \"
\";\n\t\t\t\t}\n\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) ||\n\t\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) {\n\n\t\t\t\t\tArrayList question = item.getItemData().getItemTextArraySorted();\n\t\t\t\t\tfor (int k=0; k\";\n\t\t\t\t\t\tfor (int t=0; t\" + getContentAnswer(item, answer, printSetting) + \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontent += \"\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) {\n\n\t\t\t\t\tcontent += \"\";\n\t\t\t\t\tArrayList question = item.getMatchingArray();\n\t\t\t\t\tfor (int k=0; k\";\n\t\t\t\t\t\tcontent += \"\";\n\t\t\t\t\t}\n\t\t\t\t\tcontent += \"
\";\n\t\t\t\t\t\tcontent += matching.getText();\n\t\t\t\t\t\tcontent += \"\";\t\t \n\t\t\t\t\t\tcontent += answer + \"
\";\n\t\t\t\t}\n\t\t\t\tif (printSetting.getShowKeys().booleanValue() || printSetting.getShowKeysFeedback().booleanValue()) {\n\t\t\t\t\tcontent += \"
\" + getContentQuestion(item, printSetting);\n\t\t\t\t}\n\n\t\t\t\tpdfItem.setContent(content);\n\n\t\t\t\tif (legacy != null) {\n\t\t\t\t\tpdfItem.setMeta(legacy); \n\t\t\t\t}\n\n\t\t\t\tpdfItems.add(pdfItem);\n\t\t\t}\n\n\t\t\tpdfPart.setQuestions(pdfItems);\n\t\t\tpdfPart.setResources(resources);\n\t\t\tif (resources.size() > 0)\n\t\t\t\tpdfPart.setHasResources(new Boolean(true));\n\t\t\tpdfParts.add(pdfPart);\n\n\t\t}\n\n\t\t//set the new colleciton of PDF beans to be the contents of the pdfassessment\n\t\tsetParts(pdfParts);\n\n\t\tsetTitle(deliveryBean.getAssessmentTitle());\n\n\t\treturn \"print\";\n\t}\n\n\tprivate String getContentAnswer(ItemContentsBean item, PublishedAnswer answer, PrintSettingsBean printSetting) {\n\t\tString content = \"\";\n\n\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) ||\n\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) ||\n\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) ||\n\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)) {\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT))\n\t\t\t\tcontent += \"\";\n\t\t\telse\n\t\t\t\tcontent += \"\";\n\t\t\tcontent += \"\";\n\t\t\tif (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)) \n\t\t\t\tcontent += answer.getLabel() + \". \";\n\t\t\tcontent += answer.getText();\n\t\t\tcontent += \"\";\n\t\t\tcontent += \"\";\n\t\t\tif (printSetting.getShowKeysFeedback()) {\n\t\t\t\tcontent += \"
\" + printMessages.getString(\"feedback\") + \": \";\n\t\t\t\tif (answer.getGeneralAnswerFeedback() != null && !answer.getGeneralAnswerFeedback().equals(\"\"))\n\t\t\t\t\tcontent += answer.getGeneralAnswerFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t\tcontent += \"
\";\n\t\t\t}\n\t\t\tcontent += \"\";\n\t\t}\n\n\t\tif (item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) {\n\t\t\tcontent += \"\";\n\t\t\tcontent += \"\";\n\t\t\tcontent += answer.getText();\n\t\t\tcontent += \"\";\n\t\t}\n\n\t\treturn content;\n\t}\n\n\tprivate String getContentQuestion(ItemContentsBean item, PrintSettingsBean printSetting) {\n\t\tString content = \"
\";\n\n\t\tcontent += printMessages.getString(\"answer_point\") + \": \" + item.getItemData().getScore();\n\t\tcontent += \" \" + authorMessages.getString(\"points_lower_case\");\n\n\t\tif (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) &&\n\t\t\t\t!item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) &&\n\t\t\t\t!item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) {\n\n\t\t\tcontent += \"
\";\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION))\n\t\t\t\tcontent += printMessages.getString(\"answer_model\") + \": \";\n\t\t\telse\n\t\t\t\tcontent += printMessages.getString(\"answer_key\") + \": \";\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || \n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MATCHING))\n\t\t\t\tcontent += item.getKey();\n\t\t\telse if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION)) {\n\t\t\t\tif (item.getKey() != null && !item.getKey().equals(\"\"))\n\t\t\t\t\tcontent += item.getKey();\n\t\t\t\telse\n\t\t\t\t\tcontent += \"--------\";\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontent += item.getItemData().getAnswerKey();\n\t\t}\n\n\t\tif (printSetting.getShowKeysFeedback().booleanValue()) {\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) {\n\n\t\t\t\tcontent += \"
\";\n\t\t\t\tcontent += printMessages.getString(\"feedback\") + \": \";\n\t\t\t\tif (item.getItemData().getGeneralItemFeedback() != null && !item.getItemData().getGeneralItemFeedback().equals(\"\"))\n\t\t\t\t\tcontent += item.getItemData().getGeneralItemFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t}\n\n\t\t\tif (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) ||\n\t\t\t\t\titem.getItemData().getTypeId().equals(TypeIfc.MATCHING)) {\n\n\t\t\t\tcontent += \"
\";\n\t\t\t\tcontent += printMessages.getString(\"correct_feedback\") + \": \";\n\t\t\t\tif (item.getItemData().getCorrectItemFeedback() != null && !item.getItemData().getCorrectItemFeedback().equals(\"\"))\n\t\t\t\t\tcontent += item.getItemData().getCorrectItemFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t\tcontent += \"
\" + printMessages.getString(\"incorrect_feedback\") + \": \";\n\t\t\t\tif (item.getItemData().getInCorrectItemFeedback() != null && !item.getItemData().getInCorrectItemFeedback().equals(\"\"))\n\t\t\t\t\tcontent += item.getItemData().getInCorrectItemFeedback();\n\t\t\t\telse \n\t\t\t\t\tcontent += \"--------\";\n\t\t\t}\n\n\t\t}\n\n\t\treturn content + \"
\";\n\t}\n\n\tpublic void getPDFAttachment() {\n\t\tprepDocumentPDF();\n\t\tByteArrayOutputStream pdf = getStream();\n\n\t\tFacesContext faces = FacesContext.getCurrentInstance();\n\t\tHttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse();\n\n\t\tresponse.reset();\n\t\tresponse.setHeader(\"Pragma\", \"public\"); \n\t\tresponse.setHeader(\"Cache-Control\", \"public, must-revalidate, post-check=0, pre-check=0, max-age=0\"); \n\n\t\tresponse.setContentType(\"application/pdf\");\n\t\tresponse.setHeader(\"Content-disposition\", \"attachment; filename=\" + genName()); \n\t\tresponse.setContentLength(pdf.toByteArray().length);\n\t\tOutputStream out = null;\n\t\ttry {\n\t\t\tout = response.getOutputStream();\n\t\t\tout.write(pdf.toByteArray());\n\t\t\tout.flush();\n\t\t} \n\t\tcatch (IOException e) {\n\t\t\tlog.error(e);\n\t\t\te.printStackTrace();\n\t\t} \n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tif (out != null) \n\t\t\t\t\tout.close();\n\t\t\t} \n\t\t\tcatch (IOException e) {\n\t\t\t\tlog.error(e);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tfaces.responseComplete();\n\t}\n\n\t/**\n\t * Converts all nice new school html into old school\n\t * font tagged up html that HTMLWorker will actually\n\t * parse right\n\t * \n\t * @param input\n\t */\n\tprivate String oldschoolIfy(String input) {\n\n\t\tif (log.isDebugEnabled())\n\t\t\tlog.debug(\"starting oldschoolify with: \" + input);\n\t\tinput = input.replaceAll(\"\", \"\");\n\n\t\treturn input;\n\t}\n\n\t/**\n\t * Turns a string into a StringReader with out the fuss of an IOException\n\t * \n\t * @param input\n\t * @return StringReader\n\t */\n\tprivate Reader safeReader(String input) {\n\t\tStringReader output = null;\n\t\tif (input == null) {\n\t\t\tinput = \"\";\n\t\t}\n\t\telse {\n\t\t\tinput = oldschoolIfy(input);\n\t\t}\n\n\t\ttry {\n\t\t\toutput = new StringReader(input + \"
\");\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\tlog.error(\"could not get StringReader for String \" + input + \" due to : \" + e);\n\t\t}\n\t\treturn output;\n\t}\n\n\tpublic ByteArrayOutputStream getStream() {\n\n\t\tByteArrayOutputStream output = new ByteArrayOutputStream();\n\n\t\ttry {\n\n\t\t\tif (log.isInfoEnabled())\n\t\t\t\tlog.info(\"starting PDF generation\" );\n\n\t\t\tDocument document = new Document(PageSize.A4, 20, 20, 20, 20);\n\t\t\tPdfWriter docWriter = PdfWriter.getInstance(document, output);\n\n\t\t\tdocument.open();\n\t\t\tdocument.resetPageCount();\n\n\t\t\tHTMLWorker worker = new HTMLWorker(document);\n\n\t\t\tHashMap props = worker.getInterfaceProps();\n\t\t\tif (props == null) {\n\t\t\t\tprops = new HashMap();\n\t\t\t}\n\n\t\t\tfloat prevs = 0;\n\n\t\t\tprops.put(\"img_baseurl\", ServerConfigurationService.getServerUrl());\n\t\t\tworker.setInterfaceProps(props);\n\n\t\t\t//TODO make a real style sheet\n\t\t\tStyleSheet style = null;\n\n\t\t\tString head = printMessages.getString(\"print_name_form\");\n\t\t\thead += \"
\";\n\t\t\thead += printMessages.getString(\"print_score_form\");\n\t\t\thead += \"

\";\n\t\t\thead += \"

\" + title + \"


\";\n\t\t\thead += intro + \"
\";\n\t\t\t//head = head.replaceAll(\"[ \\t\\n\\f\\r]+\", \" \");\n\n\t\t\t//parse out the elements from the html\n\t\t\tArrayList elementBuffer = HTMLWorker.parseToList(safeReader(head), style, props);\n\t\t\tfloat[] singleWidth = {1f};\n\t\t\tPdfPTable single = new PdfPTable(singleWidth);\n\t\t\tsingle.setWidthPercentage(100f);\n\t\t\tPdfPCell cell = new PdfPCell();\n\t\t\tcell.setBorderWidth(0);\n\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) { \n\t\t\t\tcell.addElement((Element)elementBuffer.get(k)); \n\t\t\t}\n\t\t\tsingle.addCell(cell);\n\n\t\t\tprevs += single.getTotalHeight() % document.getPageSize().height();\n\t\t\t//TODO do we want a new page here ... thus giving the cover page look?\n\n\t\t\tdocument.add(single);\n\t\t\tdocument.add(Chunk.NEWLINE);\n\n\t\t\t//extract the html and parse it into pdf\n\t\t\tArrayList parts = getHtmlChunks();\n\t\t\tfor (int i = 0; i < parts.size(); i++) {\n\t\t\t\t//add new page to start each new part\n\t\t\t\tif (i > 0) {\n\t\t\t\t\tdocument.newPage();\n\t\t\t\t}\n\n\t\t\t\tPDFPartBean pBean = (PDFPartBean) parts.get(i);\n\t\t\t\tif (pBean.getIntro() != null && !\"\".equals(pBean.getIntro())) {\n\t\t\t\t\telementBuffer = HTMLWorker.parseToList(safeReader(pBean.getIntro()), style, props);\n\t\t\t\t\tsingle = new PdfPTable(singleWidth);\n\t\t\t\t\tsingle.setWidthPercentage(100f);\n\t\t\t\t\tcell = new PdfPCell();\n\t\t\t\t\tcell.setBorderWidth(0);\n\t\t\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) { \n\t\t\t\t\t\tcell.addElement((Element)elementBuffer.get(k)); \n\t\t\t\t\t}\n\t\t\t\t\tsingle.addCell(cell);\n\n\t\t\t\t\tprevs += single.getTotalHeight() % document.getPageSize().height();\n\t\t\t\t\tdocument.add(single);\n\t\t\t\t} \n\n\t\t\t\tArrayList items = pBean.getQuestions();\n\n\t\t\t\tfor (int j = 0; j < items.size(); j++) {\n\t\t\t\t\tPDFItemBean iBean = (PDFItemBean) items.get(j);\n\n\t\t\t\t\tfloat[] widths = {0.1f, 0.9f};\n\t\t\t\t\tPdfPTable table = new PdfPTable(widths);\n\t\t\t\t\ttable.setWidthPercentage(100f);\n\t\t\t\t\tPdfPCell leftCell = new PdfPCell();\n\t\t\t\t\tPdfPCell rightCell = new PdfPCell();\n\t\t\t\t\tleftCell.setBorderWidth(0);\n\t\t\t\t\tleftCell.setPadding(0);\n\t\t\t\t\tleftCell.setLeading(0.00f, 0.00f);\n\t\t\t\t\tleftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);\n\t\t\t\t\tleftCell.setVerticalAlignment(Element.ALIGN_TOP);\n\t\t\t\t\trightCell.setBorderWidth(0);\n\t\t\t\t\telementBuffer = HTMLWorker.parseToList(safeReader(iBean.getMeta()), style, props);\n\t\t\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) {\n\t\t\t\t\t\tElement element = (Element)elementBuffer.get(k);\n\t\t\t\t\t\tif (element instanceof Paragraph) {\n\t\t\t\t\t\t\tParagraph p = (Paragraph)element;\n\t\t\t\t\t\t\tp.getFont().setColor(Color.GRAY);\n\t\t\t\t\t\t\tp.setAlignment(Paragraph.ALIGN_CENTER);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tleftCell.addElement(element);\n\t\t\t\t\t}\n\n\t\t\t\t\ttable.addCell(leftCell);\n\n\t\t\t\t\telementBuffer = HTMLWorker.parseToList(safeReader(iBean.getContent()), style, props);\n\t\t\t\t\tfor (int k = 0; k < elementBuffer.size(); k++) {\n\t\t\t\t\t\tElement element = (Element)elementBuffer.get(k);\n\n\t\t\t\t\t\trightCell.addElement(element);\n\t\t\t\t\t}\n\t\t\t\t\ttable.addCell(rightCell);\n\n\t\t\t\t\tif (table.getTotalHeight() + prevs > document.getPageSize().height())\n\t\t\t\t\t\tdocument.newPage();\n\n\t\t\t\t\tdocument.add(table);\n\t\t\t\t\tdocument.add(Chunk.NEWLINE);\n\n\t\t\t\t\t//TODO add PDFTable and a collumn\n\n\t\t\t\t\t//worker.parse(safeReader(iBean.getMeta()));\n\t\t\t\t\t//TODO column break\n\t\t\t\t\t//worker.parse(safeReader(iBean.getContent()));\n\t\t\t\t\t//TODO end column and table\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdocument.close();\n\t\t\tdocWriter.close();\n\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(\"document: \" + e.getMessage());\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tpublic String getBaseFontSize() {\n\t\treturn \"\" + baseFontSize;\n\t}\n\n\tpublic void setBaseFontSize(String baseFontSize) {\n\t\tthis.baseFontSize = Integer.parseInt(baseFontSize);\n\t}\n\n\n\t/**\n\t * @return the actionString\n\t */\n\tpublic String getActionString() {\n\t\treturn actionString;\n\t}\n\n\n\t/**\n\t * @param actionString the actionString to set\n\t */\n\tpublic void setActionString(String actionString) {\n\t\tthis.actionString = actionString;\n\t}\n\n\tpublic String getSizeDeliveryParts() {\n\n\t\treturn \"\" + deliveryParts.size();\n\t}\n\n\tpublic String getTotalQuestions() {\n\n\t\tint items = 0;\n\t\tfor (int i=0; i volatileVertices;\n private final ConcurrentLRUCache cache;\n\n public LRUVertexCache(int capacity) {\n volatileVertices = new NonBlockingHashMapLong();\n cache = new ConcurrentLRUCache(capacity * 2, // upper is double capacity\n capacity + capacity / 3, // lower is capacity + 1/3\n capacity, // acceptable watermark is capacity\n 100, true, false, // 100 items initial size + use only one thread for items cleanup\n new ConcurrentLRUCache.EvictionListener() {\n @Override\n public void evictedEntry(Long vertexId, InternalVertex vertex) {\n if (vertexId == null || vertex == null)\n return;\n\n if (vertex.hasAddedRelations()) {\n volatileVertices.putIfAbsent(vertexId, vertex);\n }\n }\n });\n\n cache.setAlive(true); //need counters to its actually LRU\n }\n\n @Override\n public boolean contains(long id) {\n Long vertexId = id;\n return cache.containsKey(vertexId) || volatileVertices.containsKey(vertexId);\n }\n\n @Override\n public InternalVertex get(long id, final Retriever retriever) {\n final Long vertexId = id;\n\n InternalVertex vertex = cache.get(vertexId);\n\n if (vertex == null) {\n InternalVertex newVertex = volatileVertices.get(vertexId);\n\n if (newVertex == null) {\n newVertex = retriever.get(vertexId);\n }\n\n vertex = cache.putIfAbsent(vertexId, newVertex);\n if (vertex == null)\n vertex = newVertex;\n }\n\n return vertex;\n }\n\n @Override\n public void add(InternalVertex vertex, long id) {\n Preconditions.checkNotNull(vertex);\n Preconditions.checkArgument(id != 0);\n\n Long vertexId = id;\n\n cache.put(vertexId, vertex);\n\n if (vertex.isNew() || vertex.hasAddedRelations())\n volatileVertices.put(vertexId, vertex);\n }\n\n @Override\n public List getAllNew() {\n List vertices = new ArrayList(10);\n for (InternalVertex v : volatileVertices.values()) {\n if (v.isNew())\n vertices.add(v);\n }\n return vertices;\n }\n\n\n @Override\n public synchronized void close() {\n volatileVertices.clear();\n cache.destroy();\n }\n}\n"},"new_file":{"kind":"string","value":"titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/vertexcache/LRUVertexCache.java"},"old_contents":{"kind":"string","value":"package com.thinkaurelius.titan.graphdb.transaction.vertexcache;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.google.common.base.Preconditions;\nimport com.thinkaurelius.titan.graphdb.internal.InternalVertex;\nimport com.thinkaurelius.titan.graphdb.util.ConcurrentLRUCache;\nimport com.thinkaurelius.titan.util.datastructures.Retriever;\nimport org.cliffc.high_scale_lib.NonBlockingHashMapLong;\n\npublic class LRUVertexCache implements VertexCache {\n private final NonBlockingHashMapLong volatileVertices;\n private final ConcurrentLRUCache cache;\n\n public LRUVertexCache(int capacity) {\n volatileVertices = new NonBlockingHashMapLong();\n cache = new ConcurrentLRUCache(capacity * 2, // upper is double capacity\n capacity + capacity / 3, // lower is capacity + 1/3\n capacity, // acceptable watermark is capacity\n 100, true, false, // 100 items initial size + use only one thread for items cleanup\n new ConcurrentLRUCache.EvictionListener() {\n @Override\n public void evictedEntry(Long vertexId, InternalVertex vertex) {\n if (vertexId == null || vertex == null)\n return;\n\n if (vertex.hasAddedRelations()) {\n volatileVertices.putIfAbsent(vertexId, vertex);\n }\n }\n });\n\n cache.setAlive(true); //need counters to its actually LRU\n }\n\n @Override\n public boolean contains(long id) {\n Long vertexId = id;\n return cache.containsKey(vertexId) || volatileVertices.containsKey(vertexId);\n }\n\n @Override\n public InternalVertex get(long id, final Retriever retriever) {\n final Long vertexId = id;\n\n InternalVertex vertex = cache.get(vertexId);\n\n if (vertex == null) {\n vertex = volatileVertices.get(vertexId);\n\n if (vertex == null) {\n InternalVertex newVertex = retriever.get(vertexId);\n\n vertex = cache.putIfAbsent(vertexId, vertex);\n if (vertex == null)\n vertex = newVertex;\n }\n }\n\n return vertex;\n }\n\n @Override\n public void add(InternalVertex vertex, long id) {\n Preconditions.checkNotNull(vertex);\n Preconditions.checkArgument(id != 0);\n\n Long vertexId = id;\n\n cache.put(vertexId, vertex);\n\n if (vertex.isNew() || vertex.hasAddedRelations())\n volatileVertices.put(vertexId, vertex);\n }\n\n @Override\n public List getAllNew() {\n List vertices = new ArrayList(10);\n for (InternalVertex v : volatileVertices.values()) {\n if (v.isNew())\n vertices.add(v);\n }\n return vertices;\n }\n\n\n @Override\n public synchronized void close() {\n volatileVertices.clear();\n cache.destroy();\n }\n}\n"},"message":{"kind":"string","value":"fix VertexLRUCache get to actually cache non-existing vertices\n"},"old_file":{"kind":"string","value":"titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/vertexcache/LRUVertexCache.java"},"subject":{"kind":"string","value":"fix VertexLRUCache get to actually cache non-existing vertices"}}},{"rowIdx":1257,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"779614dd629fd8d5815d4e087b3b8ee9c19c654e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak"},"new_contents":{"kind":"string","value":"package com.sequenceiq.cloudbreak.service.identitymapping;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.stereotype.Component;\n\nimport com.sequenceiq.cloudbreak.cloud.IdentityService;\nimport com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors;\nimport com.sequenceiq.cloudbreak.cloud.model.Platform;\nimport com.sequenceiq.cloudbreak.cloud.model.Variant;\nimport com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException;\nimport com.sequenceiq.cloudbreak.converter.spi.CredentialToCloudCredentialConverter;\nimport com.sequenceiq.cloudbreak.dto.credential.Credential;\n\n@Component\npublic class GcpMockAccountMappingService {\n\n private static final String FIXED_SERVICE_ACCOUNT_ROLE = \"mock-idbroker-admin-role@${projectId}.iam.gserviceaccount.com\";\n\n private static final Map MOCK_IDBROKER_USER_MAPPINGS = AccountMappingSubject.ALL_SPECIAL_USERS\n .stream()\n .map(user -> Map.entry(user, FIXED_SERVICE_ACCOUNT_ROLE))\n .collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue));\n\n private final CloudPlatformConnectors cloudPlatformConnectors;\n\n private final CredentialToCloudCredentialConverter credentialConverter;\n\n public GcpMockAccountMappingService(CloudPlatformConnectors cloudPlatformConnectors, CredentialToCloudCredentialConverter credentialConverter) {\n this.cloudPlatformConnectors = cloudPlatformConnectors;\n this.credentialConverter = credentialConverter;\n }\n\n public Map getGroupMappings(String region, Credential credential, String adminGroupName) {\n String projectId = getProjectId(region, credential);\n if (StringUtils.isNotEmpty(adminGroupName)) {\n return replaceProjectName(getGroupMappings(adminGroupName), projectId);\n } else {\n throw new CloudbreakServiceException(String.format(\"Failed to get group mappings because of missing adminGroupName for getProjectId: %s\",\n projectId));\n }\n }\n\n public Map getUserMappings(String region, Credential credential) {\n String projectName = getProjectId(region, credential);\n return replaceProjectName(MOCK_IDBROKER_USER_MAPPINGS, projectName);\n }\n\n private String getProjectId(String region, Credential credential) {\n IdentityService identityService = getIdentityService(credential.cloudPlatform());\n return identityService.getAccountId(region, credentialConverter.convert(credential));\n }\n\n private IdentityService getIdentityService(String platform) {\n return cloudPlatformConnectors.get(Platform.platform(platform), Variant.variant(platform)).identityService();\n }\n\n private Map replaceProjectName(Map mappings, String projectId) {\n return mappings.entrySet()\n .stream()\n .map(e -> Map.entry(e.getKey(), e.getValue().replace(\"${projectId}\", projectId)))\n .collect(Collectors.toMap(Entry::getKey, Entry::getValue));\n }\n\n private Map getGroupMappings(String adminGroupName) {\n return Map.ofEntries(\n Map.entry(adminGroupName, FIXED_SERVICE_ACCOUNT_ROLE)\n );\n }\n\n}\n"},"new_file":{"kind":"string","value":"core/src/main/java/com/sequenceiq/cloudbreak/service/identitymapping/GcpMockAccountMappingService.java"},"old_contents":{"kind":"string","value":"package com.sequenceiq.cloudbreak.service.identitymapping;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.stereotype.Component;\n\nimport com.sequenceiq.cloudbreak.cloud.IdentityService;\nimport com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors;\nimport com.sequenceiq.cloudbreak.cloud.model.Platform;\nimport com.sequenceiq.cloudbreak.cloud.model.Variant;\nimport com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException;\nimport com.sequenceiq.cloudbreak.converter.spi.CredentialToCloudCredentialConverter;\nimport com.sequenceiq.cloudbreak.dto.credential.Credential;\n\n@Component\npublic class GcpMockAccountMappingService {\n\n private static final String FIXED_SERVICE_ACCOUNT_ROLE = \" mock-idbroker-admin-role@${projectId}.iam.gserviceaccount.com\";\n\n private static final Map MOCK_IDBROKER_USER_MAPPINGS = AccountMappingSubject.ALL_SPECIAL_USERS\n .stream()\n .map(user -> Map.entry(user, FIXED_SERVICE_ACCOUNT_ROLE))\n .collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue));\n\n private final CloudPlatformConnectors cloudPlatformConnectors;\n\n private final CredentialToCloudCredentialConverter credentialConverter;\n\n public GcpMockAccountMappingService(CloudPlatformConnectors cloudPlatformConnectors, CredentialToCloudCredentialConverter credentialConverter) {\n this.cloudPlatformConnectors = cloudPlatformConnectors;\n this.credentialConverter = credentialConverter;\n }\n\n public Map getGroupMappings(String region, Credential credential, String adminGroupName) {\n String projectId = getProjectId(region, credential);\n if (StringUtils.isNotEmpty(adminGroupName)) {\n return replaceProjectName(getGroupMappings(adminGroupName), projectId);\n } else {\n throw new CloudbreakServiceException(String.format(\"Failed to get group mappings because of missing adminGroupName for getProjectId: %s\",\n projectId));\n }\n }\n\n public Map getUserMappings(String region, Credential credential) {\n String projectName = getProjectId(region, credential);\n return replaceProjectName(MOCK_IDBROKER_USER_MAPPINGS, projectName);\n }\n\n private String getProjectId(String region, Credential credential) {\n IdentityService identityService = getIdentityService(credential.cloudPlatform());\n return identityService.getAccountId(region, credentialConverter.convert(credential));\n }\n\n private IdentityService getIdentityService(String platform) {\n return cloudPlatformConnectors.get(Platform.platform(platform), Variant.variant(platform)).identityService();\n }\n\n private Map replaceProjectName(Map mappings, String projectId) {\n return mappings.entrySet()\n .stream()\n .map(e -> Map.entry(e.getKey(), e.getValue().replace(\"${projectId}\", projectId)))\n .collect(Collectors.toMap(Entry::getKey, Entry::getValue));\n }\n\n private Map getGroupMappings(String adminGroupName) {\n return Map.ofEntries(\n Map.entry(adminGroupName, FIXED_SERVICE_ACCOUNT_ROLE)\n );\n }\n\n}\n"},"message":{"kind":"string","value":"CB-9250 fixing the current GCP mock idbroker role string to work correctly. This was testede with e2e cloud storage integration.\n"},"old_file":{"kind":"string","value":"core/src/main/java/com/sequenceiq/cloudbreak/service/identitymapping/GcpMockAccountMappingService.java"},"subject":{"kind":"string","value":"CB-9250 fixing the current GCP mock idbroker role string to work correctly. This was testede with e2e cloud storage integration."}}},{"rowIdx":1258,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"0c28ed51f4be7d8a178024d7b46bbcd11f05038b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"kalatestimine/titan,nvoron23/titan,jankotek/titan,anuragkh/titan,elkingtonmcb/titan,ThiagoGarciaAlves/titan,kangkot/titan,qiuqiyuan/titan,evanv/titan,fengshao0907/titan,xlcupid/titan,jamestyack/titan,fengshao0907/titan,mwpnava/titan,wangbf/titan,kalatestimine/titan,jamestyack/titan,mwpnava/titan,elkingtonmcb/titan,nvoron23/titan,tomersagi/titan,kangkot/titan,mwpnava/titan,kangkot/titan,hortonworks/titan,kalatestimine/titan,anuragkh/titan,kalatestimine/titan,xlcupid/titan,jankotek/titan,wangbf/titan,nvoron23/titan,ThiagoGarciaAlves/titan,evanv/titan,jamestyack/titan,fengshao0907/titan,elkingtonmcb/titan,tomersagi/titan,anuragkh/titan,evanv/titan,elkingtonmcb/titan,kalatestimine/titan,ThiagoGarciaAlves/titan,hortonworks/titan,fengshao0907/titan,qiuqiyuan/titan,mwpnava/titan,xlcupid/titan,hortonworks/titan,kangkot/titan,hortonworks/titan,jamestyack/titan,jankotek/titan,tomersagi/titan,wangbf/titan,mwpnava/titan,wangbf/titan,xlcupid/titan,xlcupid/titan,evanv/titan,wangbf/titan,anuragkh/titan,fengshao0907/titan,elkingtonmcb/titan,qiuqiyuan/titan,anuragkh/titan,ThiagoGarciaAlves/titan,kangkot/titan,jamestyack/titan,nvoron23/titan,jankotek/titan,qiuqiyuan/titan,tomersagi/titan,jankotek/titan,hortonworks/titan,tomersagi/titan,ThiagoGarciaAlves/titan,evanv/titan,qiuqiyuan/titan"},"new_contents":{"kind":"string","value":"package com.thinkaurelius.titan.hadoop;\n\nimport com.google.common.base.Preconditions;\nimport com.thinkaurelius.titan.hadoop.compat.HadoopCompatLoader;\nimport com.thinkaurelius.titan.hadoop.compat.HadoopCompiler;\nimport com.thinkaurelius.titan.hadoop.config.TitanHadoopConfiguration;\nimport com.thinkaurelius.titan.hadoop.formats.EdgeCopyMapReduce;\nimport com.thinkaurelius.titan.hadoop.formats.MapReduceFormat;\nimport com.thinkaurelius.titan.hadoop.mapreduce.IdentityMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.BackFilterMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.CyclicPathFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.DuplicateFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.FilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.IntervalFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.PropertyFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitEdgesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitVerticesMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.GroupCountMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.LinkMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ScriptMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.SideEffectMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ValueGroupCountMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesVerticesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.OrderMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.PathMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMapMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.TransformMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VertexMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesEdgesMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesVerticesMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.util.CountMapReduce;\nimport com.tinkerpop.blueprints.Compare;\nimport com.tinkerpop.blueprints.Direction;\nimport com.tinkerpop.blueprints.Edge;\nimport com.tinkerpop.blueprints.Element;\nimport com.tinkerpop.blueprints.Vertex;\nimport com.tinkerpop.pipes.transform.TransformPipe;\nimport com.tinkerpop.pipes.util.structures.Pair;\n\nimport org.apache.hadoop.io.BooleanWritable;\nimport org.apache.hadoop.io.DoubleWritable;\nimport org.apache.hadoop.io.FloatWritable;\nimport org.apache.hadoop.io.IntWritable;\nimport org.apache.hadoop.io.LongWritable;\nimport org.apache.hadoop.io.NullWritable;\nimport org.apache.hadoop.io.Text;\nimport org.apache.hadoop.io.WritableComparable;\nimport org.apache.hadoop.util.ToolRunner;\nimport org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.script.ScriptEngine;\nimport javax.script.ScriptException;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static com.tinkerpop.blueprints.Direction.*;\n\n\n/**\n * A HadoopPipeline defines a breadth-first traversal through a property graph representation.\n * Gremlin/Hadoop compiles down to a HadoopPipeline which is ultimately a series of MapReduce jobs.\n *\n * @author Marko A. Rodriguez (http://markorodriguez.com)\n */\npublic class HadoopPipeline {\n\n private static final Logger log =\n LoggerFactory.getLogger(HadoopPipeline.class);\n\n // used to validate closure parse tree\n protected static final ScriptEngine engine = new GroovyScriptEngineImpl();\n public static final String PIPELINE_IS_LOCKED = \"No more steps are possible as pipeline is locked\";\n\n protected final HadoopCompiler compiler;\n protected final HadoopGraph graph;\n protected final State state;\n\n protected final List stringRepresentation = new ArrayList();\n\n private Compare convert(final com.tinkerpop.gremlin.Tokens.T compare) {\n if (compare.equals(com.tinkerpop.gremlin.Tokens.T.eq))\n return Compare.EQUAL;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.neq))\n return Compare.NOT_EQUAL;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gt))\n return Compare.GREATER_THAN;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gte))\n return Compare.GREATER_THAN_EQUAL;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.lt))\n return Compare.LESS_THAN;\n else\n return Compare.LESS_THAN_EQUAL;\n }\n\n protected class State {\n private Class elementType;\n private String propertyKey;\n private Class propertyType;\n private int step = -1;\n private boolean locked = false;\n private Map namedSteps = new HashMap();\n\n public State set(Class elementType) {\n if (!elementType.equals(Vertex.class) && !elementType.equals(Edge.class))\n throw new IllegalArgumentException(\"The element class type must be either Vertex or Edge\");\n\n this.elementType = elementType;\n return this;\n }\n\n public Class getElementType() {\n return this.elementType;\n }\n\n public boolean atVertex() {\n if (null == this.elementType)\n throw new IllegalStateException(\"No element type can be inferred: start vertices (or edges) set must be defined\");\n return this.elementType.equals(Vertex.class);\n }\n\n public State setProperty(final String key, final Class type) {\n this.propertyKey = key;\n this.propertyType = convertJavaToHadoop(type);\n return this;\n }\n\n public Pair> popProperty() {\n if (null == this.propertyKey)\n return null;\n Pair> pair = new Pair>(this.propertyKey, this.propertyType);\n this.propertyKey = null;\n this.propertyType = null;\n return pair;\n }\n\n public int incrStep() {\n return ++this.step;\n }\n\n public int getStep() {\n return this.step;\n }\n\n public void assertNotLocked() {\n if (this.locked) throw new IllegalStateException(PIPELINE_IS_LOCKED);\n }\n\n public void assertNoProperty() {\n if (this.propertyKey != null)\n throw new IllegalStateException(\"This step can not follow a property reference\");\n }\n\n public void assertAtVertex() {\n if (!this.atVertex())\n throw new IllegalStateException(\"This step can not follow an edge-based step\");\n }\n\n public void assertAtEdge() {\n if (this.atVertex())\n throw new IllegalStateException(\"This step can not follow a vertex-based step\");\n }\n\n public boolean isLocked() {\n return this.locked;\n }\n\n public void lock() {\n this.locked = true;\n }\n\n public void addStep(final String name) {\n if (this.step == -1)\n throw new IllegalArgumentException(\"There is no previous step to name\");\n\n this.namedSteps.put(name, this.step);\n }\n\n public int getStep(final String name) {\n final Integer i = this.namedSteps.get(name);\n if (null == i)\n throw new IllegalArgumentException(\"There is no step identified by: \" + name);\n else\n return i;\n }\n }\n\n\n ////////////////////////////////\n ////////////////////////////////\n ////////////////////////////////\n\n /**\n * Construct a HadoopPipeline\n *\n * @param graph the HadoopGraph that is the source of the traversal\n */\n public HadoopPipeline(final HadoopGraph graph) {\n this.graph = graph;\n this.compiler = HadoopCompatLoader.getCompat().newCompiler(graph);\n this.state = new State();\n\n if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphInputFormat())) {\n try {\n ((Class) this.graph.getGraphInputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler);\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n }\n\n\n\n if (graph.hasEdgeCopyDirection()) {\n Direction ecDir = graph.getEdgeCopyDirection();\n this.compiler.addMapReduce(EdgeCopyMapReduce.Map.class,\n null,\n EdgeCopyMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n EdgeCopyMapReduce.createConfiguration(ecDir));\n }\n }\n\n //////// TRANSFORMS\n\n /**\n * The identity step does not alter the graph in anyway.\n * It has the benefit of emitting various useful graph statistic counters.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline _() {\n this.state.assertNotLocked();\n this.compiler.addMap(IdentityMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n IdentityMap.createConfiguration());\n makeMapReduceString(IdentityMap.class);\n return this;\n }\n\n /**\n * Apply the provided closure to the current element and emit the result.\n *\n * @param closure the closure to apply to the element\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline transform(final String closure) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(TransformMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n TransformMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure)));\n\n this.state.lock();\n makeMapReduceString(TransformMap.class);\n return this;\n }\n\n /**\n * Start a traversal at all vertices in the graph.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline V() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.set(Vertex.class);\n\n this.compiler.addMap(VerticesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n VerticesMap.createConfiguration(this.state.incrStep() != 0));\n\n makeMapReduceString(VerticesMap.class);\n return this;\n }\n\n /**\n * Start a traversal at all edges in the graph.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline E() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.set(Edge.class);\n\n this.compiler.addMap(EdgesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n EdgesMap.createConfiguration(this.state.incrStep() != 0));\n\n makeMapReduceString(EdgesMap.class);\n return this;\n }\n\n /**\n * Start a traversal at the vertices identified by the provided ids.\n *\n * @param ids the long ids of the vertices to start the traversal from\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline v(final long... ids) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.state.set(Vertex.class);\n this.state.incrStep();\n\n this.compiler.addMap(VertexMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n VertexMap.createConfiguration(ids));\n\n makeMapReduceString(VertexMap.class);\n return this;\n }\n\n /**\n * Take outgoing labeled edges to adjacent vertices.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline out(final String... labels) {\n return this.inOutBoth(OUT, labels);\n }\n\n /**\n * Take incoming labeled edges to adjacent vertices.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline in(final String... labels) {\n return this.inOutBoth(IN, labels);\n }\n\n /**\n * Take both incoming and outgoing labeled edges to adjacent vertices.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline both(final String... labels) {\n return this.inOutBoth(BOTH, labels);\n }\n\n private HadoopPipeline inOutBoth(final Direction direction, final String... labels) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtVertex();\n this.state.incrStep();\n\n this.compiler.addMapReduce(VerticesVerticesMapReduce.Map.class,\n null,\n VerticesVerticesMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n VerticesVerticesMapReduce.createConfiguration(direction, labels));\n this.state.set(Vertex.class);\n makeMapReduceString(VerticesVerticesMapReduce.class, direction.name(), Arrays.asList(labels));\n return this;\n\n }\n\n /**\n * Take outgoing labeled edges to incident edges.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline outE(final String... labels) {\n return this.inOutBothE(OUT, labels);\n }\n\n /**\n * Take incoming labeled edges to incident edges.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline inE(final String... labels) {\n return this.inOutBothE(IN, labels);\n }\n\n /**\n * Take both incoming and outgoing labeled edges to incident edges.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline bothE(final String... labels) {\n return this.inOutBothE(BOTH, labels);\n }\n\n private HadoopPipeline inOutBothE(final Direction direction, final String... labels) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtVertex();\n this.state.incrStep();\n\n this.compiler.addMapReduce(VerticesEdgesMapReduce.Map.class,\n null,\n VerticesEdgesMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n VerticesEdgesMapReduce.createConfiguration(direction, labels));\n this.state.set(Edge.class);\n makeMapReduceString(VerticesEdgesMapReduce.class, direction.name(), Arrays.asList(labels));\n return this;\n }\n\n /**\n * Go to the outgoing/tail vertex of the edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline outV() {\n return this.inOutBothV(OUT);\n }\n\n /**\n * Go to the incoming/head vertex of the edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline inV() {\n return this.inOutBothV(IN);\n }\n\n /**\n * Go to both the incoming/head and outgoing/tail vertices of the edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline bothV() {\n return this.inOutBothV(BOTH);\n }\n\n private HadoopPipeline inOutBothV(final Direction direction) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtEdge();\n this.state.incrStep();\n\n this.compiler.addMap(EdgesVerticesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n EdgesVerticesMap.createConfiguration(direction));\n this.state.set(Vertex.class);\n makeMapReduceString(EdgesVerticesMap.class, direction.name());\n return this;\n }\n\n /**\n * Emit the property value of an element.\n *\n * @param key the key identifying the property\n * @param type the class of the property value (so Hadoop can intelligently handle the result)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline property(final String key, final Class type) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.setProperty(key, type);\n return this;\n }\n\n /**\n * Emit the property value of an element.\n *\n * @param key the key identifying the property\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline property(final String key) {\n return this.property(key, String.class);\n }\n\n /**\n * Emit a string representation of the property map.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline map() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(PropertyMapMap.Map.class,\n LongWritable.class,\n Text.class,\n PropertyMapMap.createConfiguration(this.state.getElementType()));\n makeMapReduceString(PropertyMap.class);\n this.state.lock();\n return this;\n }\n\n /**\n * Emit the label of the current edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline label() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtEdge();\n\n this.property(Tokens.LABEL, String.class);\n return this;\n }\n\n /**\n * Emit the path taken from start to current element.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline path() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(PathMap.Map.class,\n NullWritable.class,\n Text.class,\n PathMap.createConfiguration(this.state.getElementType()));\n this.state.lock();\n makeMapReduceString(PathMap.class);\n return this;\n }\n\n /**\n * Order the previous property value results and emit them with another element property value.\n * It is important to emit the previous property with a provided type else it is ordered lexigraphically.\n *\n * @param order increasing and descending order\n * @param elementKey the key of the element to associate it with\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final TransformPipe.Order order, final String elementKey) {\n this.state.assertNotLocked();\n final Pair> pair = this.state.popProperty();\n if (null != pair) {\n this.compiler.addMapReduce(OrderMapReduce.Map.class,\n null,\n OrderMapReduce.Reduce.class,\n OrderMapReduce.createComparator(order, pair.getB()),\n pair.getB(),\n Text.class,\n Text.class,\n pair.getB(),\n OrderMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB(), elementKey));\n makeMapReduceString(OrderMapReduce.class, order.name(), elementKey);\n } else {\n throw new IllegalArgumentException(\"There is no specified property to order on\");\n }\n this.state.lock();\n return this;\n }\n\n /**\n * Order the previous property value results.\n *\n * @param order increasing and descending order\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final TransformPipe.Order order) {\n return this.order(order, Tokens.ID);\n }\n\n /**\n * Order the previous property value results and emit them with another element property value.\n * It is important to emit the previous property with a provided type else it is ordered lexigraphically.\n *\n * @param order increasing and descending order\n * @param elementKey the key of the element to associate it with\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order, final String elementKey) {\n return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order), elementKey);\n }\n\n /**\n * Order the previous property value results.\n *\n * @param order increasing and descending order\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order) {\n return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order));\n }\n\n\n //////// FILTERS\n\n /**\n * Emit or deny the current element based upon the provided boolean-based closure.\n *\n * @param closure return true to emit and false to remove.\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline filter(final String closure) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(FilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n FilterMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure)));\n makeMapReduceString(FilterMap.class);\n return this;\n }\n\n /**\n * Emit the current element if it has a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline has(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) {\n return this.has(key, convert(compare), values);\n }\n\n /**\n * Emit the current element if it does not have a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator (will be not'd)\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline hasNot(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) {\n return this.hasNot(key, convert(compare), values);\n }\n\n /**\n * Emit the current element if it has a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline has(final String key, final Compare compare, final Object... values) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(PropertyFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n PropertyFilterMap.createConfiguration(this.state.getElementType(), key, compare, values));\n makeMapReduceString(PropertyFilterMap.class, compare.name(), Arrays.asList(values));\n return this;\n }\n\n /**\n * Emit the current element if it does not have a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator (will be not'd)\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline hasNot(final String key, final Compare compare, final Object... values) {\n return this.has(key, compare.opposite(), values);\n }\n\n /**\n * Emit the current element it has a property value equal to the provided values.\n *\n * @param key the property key of the element\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline has(final String key, final Object... values) {\n return (values.length == 0) ? this.has(key, Compare.NOT_EQUAL, new Object[]{null}) : this.has(key, Compare.EQUAL, values);\n }\n\n /**\n * Emit the current element it does not have a property value equal to the provided values.\n *\n * @param key the property key of the element\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline hasNot(final String key, final Object... values) {\n return (values.length == 0) ? this.has(key, Compare.EQUAL, new Object[]{null}) : this.has(key, Compare.NOT_EQUAL, values);\n }\n\n /**\n * Emit the current element it has a property value equal within the provided range.\n *\n * @param key the property key of the element\n * @param startValue the start of the range (inclusive)\n * @param endValue the end of the range (exclusive)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline interval(final String key, final Object startValue, final Object endValue) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(IntervalFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n IntervalFilterMap.createConfiguration(this.state.getElementType(), key, startValue, endValue));\n makeMapReduceString(IntervalFilterMap.class, key, startValue, endValue);\n return this;\n }\n\n /**\n * Remove any duplicate traversers at a single element.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline dedup() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(DuplicateFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n DuplicateFilterMap.createConfiguration(this.state.getElementType()));\n makeMapReduceString(DuplicateFilterMap.class);\n return this;\n }\n\n /**\n * Go back to an element a named step ago.\n * Currently only backing up to vertices is supported.\n *\n * @param step the name of the step to back up to\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline back(final String step) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMapReduce(BackFilterMapReduce.Map.class,\n BackFilterMapReduce.Combiner.class,\n BackFilterMapReduce.Reduce.class,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n BackFilterMapReduce.createConfiguration(this.state.getElementType(), this.state.getStep(step)));\n makeMapReduceString(BackFilterMapReduce.class, step);\n return this;\n }\n\n /*public HadoopPipeline back(final int numberOfSteps) {\n this.state.assertNotLocked();\n this.compiler.backFilterMapReduce(this.state.getElementType(), this.state.getStep() - numberOfSteps);\n this.compiler.setPathEnabled(true);\n makeMapReduceString(BackFilterMapReduce.class, numberOfSteps);\n return this;\n }*/\n\n /**\n * Emit the element only if it was arrived at via a path that does not have cycles in it.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline simplePath() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(CyclicPathFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n CyclicPathFilterMap.createConfiguration(this.state.getElementType()));\n makeMapReduceString(CyclicPathFilterMap.class);\n return this;\n }\n\n //////// SIDEEFFECTS\n\n /**\n * Emit the element, but compute some sideeffect in the process.\n * For example, mutate the properties of the element.\n *\n * @param closure the sideeffect closure whose results are ignored.\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline sideEffect(final String closure) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(SideEffectMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n SideEffectMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure)));\n\n makeMapReduceString(SideEffectMap.class);\n return this;\n }\n\n /**\n * Name a step in order to reference it later in the expression.\n *\n * @param name the string representation of the name\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline as(final String name) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.state.addStep(name);\n\n final String string = \"As(\" + name + \",\" + this.stringRepresentation.get(this.state.getStep(name)) + \")\";\n this.stringRepresentation.set(this.state.getStep(name), string);\n return this;\n }\n\n /**\n * Have the elements for the named step previous project an edge to the current vertex with provided label.\n * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight.\n * No weight key is specified by \"_\" and then all duplicates are merged, but no weight is added to the resultant edge.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @param mergeWeightKey the property key to use for weight\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkIn(final String label, final String step, final String mergeWeightKey) {\n return this.link(IN, label, step, mergeWeightKey);\n }\n\n /**\n * Have the elements for the named step previous project an edge to the current vertex with provided label.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkIn(final String label, final String step) {\n return this.link(IN, label, step, null);\n }\n\n /**\n * Have the elements for the named step previous project an edge from the current vertex with provided label.\n * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight.\n * No weight key is specified by \"_\" and then all duplicates are merged, but no weight is added to the resultant edge.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @param mergeWeightKey the property key to use for weight\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkOut(final String label, final String step, final String mergeWeightKey) {\n return link(OUT, label, step, mergeWeightKey);\n }\n\n /**\n * Have the elements for the named step previous project an edge from the current vertex with provided label.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkOut(final String label, final String step) {\n return this.link(OUT, label, step, null);\n }\n\n private HadoopPipeline link(final Direction direction, final String label, final String step, final String mergeWeightKey) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n Preconditions.checkNotNull(direction);\n\n this.compiler.addMapReduce(LinkMapReduce.Map.class,\n LinkMapReduce.Combiner.class,\n LinkMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n LinkMapReduce.createConfiguration(direction, label, this.state.getStep(step), mergeWeightKey));\n\n log.debug(\"Added {} job with direction {}, label {}, step {}, merge weight key {}\", LinkMapReduce.class.getSimpleName(), direction, label, step, mergeWeightKey);\n\n if (null != mergeWeightKey)\n makeMapReduceString(LinkMapReduce.class, direction.name(), label, step, mergeWeightKey);\n else\n makeMapReduceString(LinkMapReduce.class, direction.name(), label, step);\n return this;\n }\n\n /**\n * Count the number of times the previous element (or property) has been traversed to.\n * The results are stored in the jobs sideeffect file in HDFS.\n *\n * @return the extended HadoopPipeline.\n */\n public HadoopPipeline groupCount() {\n this.state.assertNotLocked();\n final Pair> pair = this.state.popProperty();\n if (null == pair) {\n return this.groupCount(null, null);\n } else {\n this.compiler.addMapReduce(ValueGroupCountMapReduce.Map.class,\n ValueGroupCountMapReduce.Combiner.class,\n ValueGroupCountMapReduce.Reduce.class,\n pair.getB(),\n LongWritable.class,\n pair.getB(),\n LongWritable.class,\n ValueGroupCountMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB()));\n makeMapReduceString(ValueGroupCountMapReduce.class, pair.getA());\n }\n return this;\n }\n\n /**\n * Apply the provided closure to the incoming element to determine the grouping key.\n * The value of the count is incremented by 1\n * The results are stored in the jobs sideeffect file in HDFS.\n *\n * @return the extended HadoopPipeline.\n */\n public HadoopPipeline groupCount(final String keyClosure) {\n return this.groupCount(keyClosure, null);\n }\n\n /**\n * Apply the provided closure to the incoming element to determine the grouping key.\n * Then apply the value closure to the current element to determine the count increment.\n * The results are stored in the jobs sideeffect file in HDFS.\n *\n * @return the extended HadoopPipeline.\n */\n public HadoopPipeline groupCount(final String keyClosure, final String valueClosure) {\n this.state.assertNotLocked();\n\n\n this.compiler.addMapReduce(GroupCountMapReduce.Map.class,\n GroupCountMapReduce.Combiner.class,\n GroupCountMapReduce.Reduce.class,\n Text.class,\n LongWritable.class,\n Text.class,\n LongWritable.class,\n GroupCountMapReduce.createConfiguration(this.state.getElementType(),\n this.validateClosure(keyClosure), this.validateClosure(valueClosure)));\n\n makeMapReduceString(GroupCountMapReduce.class);\n return this;\n }\n\n\n private HadoopPipeline commit(final Tokens.Action action) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n if (this.state.atVertex()) {\n this.compiler.addMapReduce(CommitVerticesMapReduce.Map.class,\n CommitVerticesMapReduce.Combiner.class,\n CommitVerticesMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n CommitVerticesMapReduce.createConfiguration(action));\n makeMapReduceString(CommitVerticesMapReduce.class, action.name());\n } else {\n this.compiler.addMap(CommitEdgesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n CommitEdgesMap.createConfiguration(action));\n makeMapReduceString(CommitEdgesMap.class, action.name());\n }\n return this;\n }\n\n /**\n * Drop all the elements of respective type at the current step. Keep all others.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline drop() {\n return this.commit(Tokens.Action.DROP);\n }\n\n /**\n * Keep all the elements of the respetive type at the current step. Drop all others.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline keep() {\n return this.commit(Tokens.Action.KEEP);\n }\n\n public HadoopPipeline script(final String scriptUri, final String... args) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtVertex();\n\n this.compiler.addMap(ScriptMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n ScriptMap.createConfiguration(scriptUri, args));\n makeMapReduceString(CommitEdgesMap.class, scriptUri);\n // this.state.lock();\n return this;\n }\n\n /////////////// UTILITIES\n\n /**\n * Count the number of traversers currently in the graph\n *\n * @return the count\n */\n public HadoopPipeline count() {\n this.state.assertNotLocked();\n this.compiler.addMapReduce(CountMapReduce.Map.class,\n CountMapReduce.Combiner.class,\n CountMapReduce.Reduce.class,\n NullWritable.class,\n LongWritable.class,\n NullWritable.class,\n LongWritable.class,\n CountMapReduce.createConfiguration(this.state.getElementType()));\n makeMapReduceString(CountMapReduce.class);\n this.state.lock();\n return this;\n }\n\n public String toString() {\n return this.stringRepresentation.toString();\n }\n\n private HadoopPipeline done() {\n if (!this.state.isLocked()) {\n final Pair> pair = this.state.popProperty();\n if (null != pair) {\n this.compiler.addMap(PropertyMap.Map.class,\n LongWritable.class,\n pair.getB(),\n PropertyMap.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB()));\n makeMapReduceString(PropertyMap.class, pair.getA());\n this.state.lock();\n }\n }\n return this;\n }\n\n /**\n * Submit the HadoopPipeline to the Hadoop cluster.\n *\n * @throws Exception\n */\n public int submit() throws Exception {\n return submit(Tokens.EMPTY_STRING, false);\n }\n\n /**\n * Submit the HadoopPipeline to the Hadoop cluster and ensure that a header is emitted in the logs.\n *\n * @param script the Gremlin script\n * @param showHeader the Titan/Hadoop header\n * @throws Exception\n */\n public int submit(final String script, final Boolean showHeader) throws Exception {\n this.done();\n if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphOutputFormat())) {\n this.state.assertNotLocked();\n ((Class) this.graph.getGraphOutputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler);\n }\n this.compiler.completeSequence();\n return ToolRunner.run(this.compiler, new String[]{script, showHeader.toString()});\n }\n\n /**\n * Get a reference to the graph currently being used in this HadoopPipeline.\n *\n * @return the HadoopGraph\n */\n public HadoopGraph getGraph() {\n return this.graph;\n }\n\n public HadoopCompiler getCompiler() {\n return this.compiler;\n }\n\n private String validateClosure(String closure) {\n if (closure == null)\n return null;\n\n try {\n engine.eval(closure);\n return closure;\n } catch (ScriptException e) {\n closure = closure.trim();\n closure = closure.replaceFirst(\"\\\\{\", \"{it->\");\n try {\n engine.eval(closure);\n return closure;\n } catch (ScriptException e1) {\n }\n throw new IllegalArgumentException(\"The provided closure does not compile: \" + e.getMessage(), e);\n }\n }\n\n private void makeMapReduceString(final Class klass, final Object... arguments) {\n String result = klass.getSimpleName();\n if (arguments.length > 0) {\n result = result + \"(\";\n for (final Object arg : arguments) {\n result = result + arg + \",\";\n }\n result = result.substring(0, result.length() - 1) + \")\";\n }\n this.stringRepresentation.add(result);\n }\n\n private Class convertJavaToHadoop(final Class klass) {\n if (klass.equals(String.class)) {\n return Text.class;\n } else if (klass.equals(Integer.class)) {\n return IntWritable.class;\n } else if (klass.equals(Double.class)) {\n return DoubleWritable.class;\n } else if (klass.equals(Long.class)) {\n return LongWritable.class;\n } else if (klass.equals(Float.class)) {\n return FloatWritable.class;\n } else if (klass.equals(Boolean.class)) {\n return BooleanWritable.class;\n } else {\n throw new IllegalArgumentException(\"The provided class is not supported: \" + klass.getSimpleName());\n }\n }\n}\n"},"new_file":{"kind":"string","value":"titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/HadoopPipeline.java"},"old_contents":{"kind":"string","value":"package com.thinkaurelius.titan.hadoop;\n\nimport com.google.common.base.Preconditions;\nimport com.thinkaurelius.titan.hadoop.compat.HadoopCompatLoader;\nimport com.thinkaurelius.titan.hadoop.compat.HadoopCompiler;\nimport com.thinkaurelius.titan.hadoop.config.TitanHadoopConfiguration;\nimport com.thinkaurelius.titan.hadoop.formats.EdgeCopyMapReduce;\nimport com.thinkaurelius.titan.hadoop.formats.MapReduceFormat;\nimport com.thinkaurelius.titan.hadoop.mapreduce.IdentityMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.BackFilterMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.CyclicPathFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.DuplicateFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.FilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.IntervalFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.filter.PropertyFilterMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitEdgesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitVerticesMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.GroupCountMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.LinkMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ScriptMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.SideEffectMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ValueGroupCountMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesVerticesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.OrderMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.PathMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMapMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.TransformMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VertexMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesEdgesMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesMap;\nimport com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesVerticesMapReduce;\nimport com.thinkaurelius.titan.hadoop.mapreduce.util.CountMapReduce;\nimport com.tinkerpop.blueprints.Compare;\nimport com.tinkerpop.blueprints.Direction;\nimport com.tinkerpop.blueprints.Edge;\nimport com.tinkerpop.blueprints.Element;\nimport com.tinkerpop.blueprints.Vertex;\nimport com.tinkerpop.pipes.transform.TransformPipe;\nimport com.tinkerpop.pipes.util.structures.Pair;\n\nimport org.apache.hadoop.io.BooleanWritable;\nimport org.apache.hadoop.io.DoubleWritable;\nimport org.apache.hadoop.io.FloatWritable;\nimport org.apache.hadoop.io.IntWritable;\nimport org.apache.hadoop.io.LongWritable;\nimport org.apache.hadoop.io.NullWritable;\nimport org.apache.hadoop.io.Text;\nimport org.apache.hadoop.io.WritableComparable;\nimport org.apache.hadoop.util.ToolRunner;\nimport org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.script.ScriptEngine;\nimport javax.script.ScriptException;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static com.tinkerpop.blueprints.Direction.*;\n\n\n/**\n * A HadoopPipeline defines a breadth-first traversal through a property graph representation.\n * Gremlin/Hadoop compiles down to a HadoopPipeline which is ultimately a series of MapReduce jobs.\n *\n * @author Marko A. Rodriguez (http://markorodriguez.com)\n */\npublic class HadoopPipeline {\n\n private static final Logger log =\n LoggerFactory.getLogger(HadoopPipeline.class);\n\n // used to validate closure parse tree\n protected static final ScriptEngine engine = new GroovyScriptEngineImpl();\n public static final String PIPELINE_IS_LOCKED = \"No more steps are possible as pipeline is locked\";\n\n protected final HadoopCompiler compiler;\n protected final HadoopGraph graph;\n protected final State state;\n\n protected final List stringRepresentation = new ArrayList();\n\n private Compare convert(final com.tinkerpop.gremlin.Tokens.T compare) {\n if (compare.equals(com.tinkerpop.gremlin.Tokens.T.eq))\n return Compare.EQUAL;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.neq))\n return Compare.NOT_EQUAL;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gt))\n return Compare.GREATER_THAN;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gte))\n return Compare.GREATER_THAN_EQUAL;\n else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.lt))\n return Compare.LESS_THAN;\n else\n return Compare.LESS_THAN_EQUAL;\n }\n\n protected class State {\n private Class elementType;\n private String propertyKey;\n private Class propertyType;\n private int step = -1;\n private boolean locked = false;\n private Map namedSteps = new HashMap();\n\n public State set(Class elementType) {\n if (!elementType.equals(Vertex.class) && !elementType.equals(Edge.class))\n throw new IllegalArgumentException(\"The element class type must be either Vertex or Edge\");\n\n this.elementType = elementType;\n return this;\n }\n\n public Class getElementType() {\n return this.elementType;\n }\n\n public boolean atVertex() {\n if (null == this.elementType)\n throw new IllegalStateException(\"No element type can be inferred: start vertices (or edges) set must be defined\");\n return this.elementType.equals(Vertex.class);\n }\n\n public State setProperty(final String key, final Class type) {\n this.propertyKey = key;\n this.propertyType = convertJavaToHadoop(type);\n return this;\n }\n\n public Pair> popProperty() {\n if (null == this.propertyKey)\n return null;\n Pair> pair = new Pair>(this.propertyKey, this.propertyType);\n this.propertyKey = null;\n this.propertyType = null;\n return pair;\n }\n\n public int incrStep() {\n return ++this.step;\n }\n\n public int getStep() {\n return this.step;\n }\n\n public void assertNotLocked() {\n if (this.locked) throw new IllegalStateException(PIPELINE_IS_LOCKED);\n }\n\n public void assertNoProperty() {\n if (this.propertyKey != null)\n throw new IllegalStateException(\"This step can not follow a property reference\");\n }\n\n public void assertAtVertex() {\n if (!this.atVertex())\n throw new IllegalStateException(\"This step can not follow an edge-based step\");\n }\n\n public void assertAtEdge() {\n if (this.atVertex())\n throw new IllegalStateException(\"This step can not follow a vertex-based step\");\n }\n\n public boolean isLocked() {\n return this.locked;\n }\n\n public void lock() {\n this.locked = true;\n }\n\n public void addStep(final String name) {\n if (this.step == -1)\n throw new IllegalArgumentException(\"There is no previous step to name\");\n\n this.namedSteps.put(name, this.step);\n }\n\n public int getStep(final String name) {\n final Integer i = this.namedSteps.get(name);\n if (null == i)\n throw new IllegalArgumentException(\"There is no step identified by: \" + name);\n else\n return i;\n }\n }\n\n\n ////////////////////////////////\n ////////////////////////////////\n ////////////////////////////////\n\n /**\n * Construct a HadoopPipeline\n *\n * @param graph the HadoopGraph that is the source of the traversal\n */\n public HadoopPipeline(final HadoopGraph graph) {\n this.graph = graph;\n this.compiler = HadoopCompatLoader.getCompat().newCompiler(graph);\n this.state = new State();\n\n if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphInputFormat())) {\n try {\n ((Class) this.graph.getGraphInputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler);\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n }\n\n\n\n if (graph.hasEdgeCopyDirection()) {\n Direction ecDir = graph.getEdgeCopyDirection();\n this.compiler.addMapReduce(EdgeCopyMapReduce.Map.class,\n null,\n EdgeCopyMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n EdgeCopyMapReduce.createConfiguration(ecDir));\n }\n }\n\n //////// TRANSFORMS\n\n /**\n * The identity step does not alter the graph in anyway.\n * It has the benefit of emitting various useful graph statistic counters.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline _() {\n this.state.assertNotLocked();\n this.compiler.addMap(IdentityMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n IdentityMap.createConfiguration());\n makeMapReduceString(IdentityMap.class);\n return this;\n }\n\n /**\n * Apply the provided closure to the current element and emit the result.\n *\n * @param closure the closure to apply to the element\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline transform(final String closure) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(TransformMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n TransformMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure)));\n\n this.state.lock();\n makeMapReduceString(TransformMap.class);\n return this;\n }\n\n /**\n * Start a traversal at all vertices in the graph.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline V() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.set(Vertex.class);\n\n this.compiler.addMap(VerticesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n VerticesMap.createConfiguration(this.state.incrStep() != 0));\n\n makeMapReduceString(VerticesMap.class);\n return this;\n }\n\n /**\n * Start a traversal at all edges in the graph.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline E() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.set(Edge.class);\n\n this.compiler.addMap(EdgesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n EdgesMap.createConfiguration(this.state.incrStep() != 0));\n\n makeMapReduceString(EdgesMap.class);\n return this;\n }\n\n /**\n * Start a traversal at the vertices identified by the provided ids.\n *\n * @param ids the long ids of the vertices to start the traversal from\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline v(final long... ids) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.state.set(Vertex.class);\n this.state.incrStep();\n\n this.compiler.addMap(VertexMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n VertexMap.createConfiguration(ids));\n\n makeMapReduceString(VertexMap.class);\n return this;\n }\n\n /**\n * Take outgoing labeled edges to adjacent vertices.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline out(final String... labels) {\n return this.inOutBoth(OUT, labels);\n }\n\n /**\n * Take incoming labeled edges to adjacent vertices.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline in(final String... labels) {\n return this.inOutBoth(IN, labels);\n }\n\n /**\n * Take both incoming and outgoing labeled edges to adjacent vertices.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline both(final String... labels) {\n return this.inOutBoth(BOTH, labels);\n }\n\n private HadoopPipeline inOutBoth(final Direction direction, final String... labels) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtVertex();\n this.state.incrStep();\n\n this.compiler.addMapReduce(VerticesVerticesMapReduce.Map.class,\n null,\n VerticesVerticesMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n VerticesVerticesMapReduce.createConfiguration(direction, labels));\n this.state.set(Vertex.class);\n makeMapReduceString(VerticesVerticesMapReduce.class, direction.name(), Arrays.asList(labels));\n return this;\n\n }\n\n /**\n * Take outgoing labeled edges to incident edges.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline outE(final String... labels) {\n return this.inOutBothE(OUT, labels);\n }\n\n /**\n * Take incoming labeled edges to incident edges.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline inE(final String... labels) {\n return this.inOutBothE(IN, labels);\n }\n\n /**\n * Take both incoming and outgoing labeled edges to incident edges.\n *\n * @param labels the labels of the edges to traverse over\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline bothE(final String... labels) {\n return this.inOutBothE(BOTH, labels);\n }\n\n private HadoopPipeline inOutBothE(final Direction direction, final String... labels) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtVertex();\n this.state.incrStep();\n\n this.compiler.addMapReduce(VerticesEdgesMapReduce.Map.class,\n null,\n VerticesEdgesMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n VerticesEdgesMapReduce.createConfiguration(direction, labels));\n this.state.set(Edge.class);\n makeMapReduceString(VerticesEdgesMapReduce.class, direction.name(), Arrays.asList(labels));\n return this;\n }\n\n /**\n * Go to the outgoing/tail vertex of the edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline outV() {\n return this.inOutBothV(OUT);\n }\n\n /**\n * Go to the incoming/head vertex of the edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline inV() {\n return this.inOutBothV(IN);\n }\n\n /**\n * Go to both the incoming/head and outgoing/tail vertices of the edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline bothV() {\n return this.inOutBothV(BOTH);\n }\n\n private HadoopPipeline inOutBothV(final Direction direction) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtEdge();\n this.state.incrStep();\n\n this.compiler.addMap(EdgesVerticesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n EdgesVerticesMap.createConfiguration(direction));\n this.state.set(Vertex.class);\n makeMapReduceString(EdgesVerticesMap.class, direction.name());\n return this;\n }\n\n /**\n * Emit the property value of an element.\n *\n * @param key the key identifying the property\n * @param type the class of the property value (so Hadoop can intelligently handle the result)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline property(final String key, final Class type) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.setProperty(key, type);\n return this;\n }\n\n /**\n * Emit the property value of an element.\n *\n * @param key the key identifying the property\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline property(final String key) {\n return this.property(key, String.class);\n }\n\n /**\n * Emit a string representation of the property map.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline map() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(PropertyMapMap.Map.class,\n LongWritable.class,\n Text.class,\n PropertyMapMap.createConfiguration(this.state.getElementType()));\n makeMapReduceString(PropertyMap.class);\n this.state.lock();\n return this;\n }\n\n /**\n * Emit the label of the current edge.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline label() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtEdge();\n\n this.property(Tokens.LABEL, String.class);\n return this;\n }\n\n /**\n * Emit the path taken from start to current element.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline path() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(PathMap.Map.class,\n NullWritable.class,\n Text.class,\n PathMap.createConfiguration(this.state.getElementType()));\n this.state.lock();\n makeMapReduceString(PathMap.class);\n return this;\n }\n\n /**\n * Order the previous property value results and emit them with another element property value.\n * It is important to emit the previous property with a provided type else it is ordered lexigraphically.\n *\n * @param order increasing and descending order\n * @param elementKey the key of the element to associate it with\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final TransformPipe.Order order, final String elementKey) {\n this.state.assertNotLocked();\n final Pair> pair = this.state.popProperty();\n if (null != pair) {\n this.compiler.addMapReduce(OrderMapReduce.Map.class,\n null,\n OrderMapReduce.Reduce.class,\n OrderMapReduce.createComparator(order, pair.getB()),\n pair.getB(),\n Text.class,\n Text.class,\n pair.getB(),\n OrderMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB(), elementKey));\n makeMapReduceString(OrderMapReduce.class, order.name(), elementKey);\n } else {\n throw new IllegalArgumentException(\"There is no specified property to order on\");\n }\n this.state.lock();\n return this;\n }\n\n /**\n * Order the previous property value results.\n *\n * @param order increasing and descending order\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final TransformPipe.Order order) {\n return this.order(order, Tokens.ID);\n }\n\n /**\n * Order the previous property value results and emit them with another element property value.\n * It is important to emit the previous property with a provided type else it is ordered lexigraphically.\n *\n * @param order increasing and descending order\n * @param elementKey the key of the element to associate it with\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order, final String elementKey) {\n return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order), elementKey);\n }\n\n /**\n * Order the previous property value results.\n *\n * @param order increasing and descending order\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order) {\n return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order));\n }\n\n\n //////// FILTERS\n\n /**\n * Emit or deny the current element based upon the provided boolean-based closure.\n *\n * @param closure return true to emit and false to remove.\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline filter(final String closure) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(FilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n FilterMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure)));\n makeMapReduceString(FilterMap.class);\n return this;\n }\n\n /**\n * Emit the current element if it has a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline has(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) {\n return this.has(key, convert(compare), values);\n }\n\n /**\n * Emit the current element if it does not have a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator (will be not'd)\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline hasNot(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) {\n return this.hasNot(key, convert(compare), values);\n }\n\n /**\n * Emit the current element if it has a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline has(final String key, final Compare compare, final Object... values) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(PropertyFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n PropertyFilterMap.createConfiguration(this.state.getElementType(), key, compare, values));\n makeMapReduceString(PropertyFilterMap.class, compare.name(), Arrays.asList(values));\n return this;\n }\n\n /**\n * Emit the current element if it does not have a property value comparable to the provided values.\n *\n * @param key the property key of the element\n * @param compare the comparator (will be not'd)\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline hasNot(final String key, final Compare compare, final Object... values) {\n return this.has(key, compare.opposite(), values);\n }\n\n /**\n * Emit the current element it has a property value equal to the provided values.\n *\n * @param key the property key of the element\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline has(final String key, final Object... values) {\n return (values.length == 0) ? this.has(key, Compare.NOT_EQUAL, new Object[]{null}) : this.has(key, Compare.EQUAL, values);\n }\n\n /**\n * Emit the current element it does not have a property value equal to the provided values.\n *\n * @param key the property key of the element\n * @param values the values to compare against where only one needs to succeed (or'd)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline hasNot(final String key, final Object... values) {\n return (values.length == 0) ? this.has(key, Compare.EQUAL, new Object[]{null}) : this.has(key, Compare.NOT_EQUAL, values);\n }\n\n /**\n * Emit the current element it has a property value equal within the provided range.\n *\n * @param key the property key of the element\n * @param startValue the start of the range (inclusive)\n * @param endValue the end of the range (exclusive)\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline interval(final String key, final Object startValue, final Object endValue) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(IntervalFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n IntervalFilterMap.createConfiguration(this.state.getElementType(), key, startValue, endValue));\n makeMapReduceString(IntervalFilterMap.class, key, startValue, endValue);\n return this;\n }\n\n /**\n * Remove any duplicate traversers at a single element.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline dedup() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(DuplicateFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n DuplicateFilterMap.createConfiguration(this.state.getElementType()));\n makeMapReduceString(DuplicateFilterMap.class);\n return this;\n }\n\n /**\n * Go back to an element a named step ago.\n * Currently only backing up to vertices is supported.\n *\n * @param step the name of the step to back up to\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline back(final String step) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMapReduce(BackFilterMapReduce.Map.class,\n BackFilterMapReduce.Combiner.class,\n BackFilterMapReduce.Reduce.class,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n BackFilterMapReduce.createConfiguration(this.state.getElementType(), this.state.getStep(step)));\n makeMapReduceString(BackFilterMapReduce.class, step);\n return this;\n }\n\n /*public HadoopPipeline back(final int numberOfSteps) {\n this.state.assertNotLocked();\n this.compiler.backFilterMapReduce(this.state.getElementType(), this.state.getStep() - numberOfSteps);\n this.compiler.setPathEnabled(true);\n makeMapReduceString(BackFilterMapReduce.class, numberOfSteps);\n return this;\n }*/\n\n /**\n * Emit the element only if it was arrived at via a path that does not have cycles in it.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline simplePath() {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(CyclicPathFilterMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n CyclicPathFilterMap.createConfiguration(this.state.getElementType()));\n makeMapReduceString(CyclicPathFilterMap.class);\n return this;\n }\n\n //////// SIDEEFFECTS\n\n /**\n * Emit the element, but compute some sideeffect in the process.\n * For example, mutate the properties of the element.\n *\n * @param closure the sideeffect closure whose results are ignored.\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline sideEffect(final String closure) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.compiler.addMap(SideEffectMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n SideEffectMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure)));\n\n makeMapReduceString(SideEffectMap.class);\n return this;\n }\n\n /**\n * Name a step in order to reference it later in the expression.\n *\n * @param name the string representation of the name\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline as(final String name) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n this.state.addStep(name);\n\n final String string = \"As(\" + name + \",\" + this.stringRepresentation.get(this.state.getStep(name)) + \")\";\n this.stringRepresentation.set(this.state.getStep(name), string);\n return this;\n }\n\n /**\n * Have the elements for the named step previous project an edge to the current vertex with provided label.\n * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight.\n * No weight key is specified by \"_\" and then all duplicates are merged, but no weight is added to the resultant edge.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @param mergeWeightKey the property key to use for weight\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkIn(final String label, final String step, final String mergeWeightKey) {\n return this.link(IN, label, step, mergeWeightKey);\n }\n\n /**\n * Have the elements for the named step previous project an edge to the current vertex with provided label.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkIn(final String label, final String step) {\n return this.link(IN, label, step, null);\n }\n\n /**\n * Have the elements for the named step previous project an edge from the current vertex with provided label.\n * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight.\n * No weight key is specified by \"_\" and then all duplicates are merged, but no weight is added to the resultant edge.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @param mergeWeightKey the property key to use for weight\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkOut(final String label, final String step, final String mergeWeightKey) {\n return link(OUT, label, step, mergeWeightKey);\n }\n\n /**\n * Have the elements for the named step previous project an edge from the current vertex with provided label.\n *\n * @param step the name of the step where the source vertices were\n * @param label the label of the edge to project\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline linkOut(final String label, final String step) {\n return this.link(OUT, label, step, null);\n }\n\n private HadoopPipeline link(final Direction direction, final String label, final String step, final String mergeWeightKey) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n Preconditions.checkNotNull(direction);\n\n this.compiler.addMapReduce(LinkMapReduce.Map.class,\n LinkMapReduce.Combiner.class,\n LinkMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n LinkMapReduce.createConfiguration(direction, label, this.state.getStep(step), mergeWeightKey));\n\n log.debug(\"Added {} job with direction {}, label {}, step {}, merge weight key {}\", LinkMapReduce.class.getSimpleName(), direction, label, step, mergeWeightKey);\n\n if (null != mergeWeightKey)\n makeMapReduceString(LinkMapReduce.class, direction.name(), label, step, mergeWeightKey);\n else\n makeMapReduceString(LinkMapReduce.class, direction.name(), label, step);\n return this;\n }\n\n /**\n * Count the number of times the previous element (or property) has been traversed to.\n * The results are stored in the jobs sideeffect file in HDFS.\n *\n * @return the extended HadoopPipeline.\n */\n public HadoopPipeline groupCount() {\n this.state.assertNotLocked();\n final Pair> pair = this.state.popProperty();\n if (null == pair) {\n return this.groupCount(null, null);\n } else {\n this.compiler.addMapReduce(ValueGroupCountMapReduce.Map.class,\n ValueGroupCountMapReduce.Combiner.class,\n ValueGroupCountMapReduce.Reduce.class,\n pair.getB(),\n LongWritable.class,\n pair.getB(),\n LongWritable.class,\n ValueGroupCountMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB()));\n makeMapReduceString(ValueGroupCountMapReduce.class, pair.getA());\n }\n return this;\n }\n\n /**\n * Apply the provided closure to the incoming element to determine the grouping key.\n * The value of the count is incremented by 1\n * The results are stored in the jobs sideeffect file in HDFS.\n *\n * @return the extended HadoopPipeline.\n */\n public HadoopPipeline groupCount(final String keyClosure) {\n return this.groupCount(keyClosure, null);\n }\n\n /**\n * Apply the provided closure to the incoming element to determine the grouping key.\n * Then apply the value closure to the current element to determine the count increment.\n * The results are stored in the jobs sideeffect file in HDFS.\n *\n * @return the extended HadoopPipeline.\n */\n public HadoopPipeline groupCount(final String keyClosure, final String valueClosure) {\n this.state.assertNotLocked();\n\n\n this.compiler.addMapReduce(GroupCountMapReduce.Map.class,\n GroupCountMapReduce.Combiner.class,\n GroupCountMapReduce.Reduce.class,\n Text.class,\n LongWritable.class,\n Text.class,\n LongWritable.class,\n GroupCountMapReduce.createConfiguration(this.state.getElementType(),\n this.validateClosure(keyClosure), this.validateClosure(valueClosure)));\n\n makeMapReduceString(GroupCountMapReduce.class);\n return this;\n }\n\n\n private HadoopPipeline commit(final Tokens.Action action) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n\n if (this.state.atVertex()) {\n this.compiler.addMapReduce(CommitVerticesMapReduce.Map.class,\n CommitVerticesMapReduce.Combiner.class,\n CommitVerticesMapReduce.Reduce.class,\n null,\n LongWritable.class,\n Holder.class,\n NullWritable.class,\n FaunusVertex.class,\n CommitVerticesMapReduce.createConfiguration(action));\n makeMapReduceString(CommitVerticesMapReduce.class, action.name());\n } else {\n this.compiler.addMap(CommitEdgesMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n CommitEdgesMap.createConfiguration(action));\n makeMapReduceString(CommitEdgesMap.class, action.name());\n }\n return this;\n }\n\n /**\n * Drop all the elements of respective type at the current step. Keep all others.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline drop() {\n return this.commit(Tokens.Action.DROP);\n }\n\n /**\n * Keep all the elements of the respetive type at the current step. Drop all others.\n *\n * @return the extended HadoopPipeline\n */\n public HadoopPipeline keep() {\n return this.commit(Tokens.Action.KEEP);\n }\n\n public HadoopPipeline script(final String scriptUri, final String... args) {\n this.state.assertNotLocked();\n this.state.assertNoProperty();\n this.state.assertAtVertex();\n\n this.compiler.addMap(ScriptMap.Map.class,\n NullWritable.class,\n FaunusVertex.class,\n ScriptMap.createConfiguration(scriptUri, args));\n makeMapReduceString(CommitEdgesMap.class, scriptUri);\n // this.state.lock();\n return this;\n }\n\n /////////////// UTILITIES\n\n /**\n * Count the number of traversers currently in the graph\n *\n * @return the count\n */\n public HadoopPipeline count() {\n this.state.assertNotLocked();\n this.compiler.addMapReduce(CountMapReduce.Map.class,\n CountMapReduce.Combiner.class,\n CountMapReduce.Reduce.class,\n NullWritable.class,\n LongWritable.class,\n NullWritable.class,\n LongWritable.class,\n CountMapReduce.createConfiguration(this.state.getElementType()));\n makeMapReduceString(CountMapReduce.class);\n this.state.lock();\n return this;\n }\n\n public String toString() {\n return this.stringRepresentation.toString();\n }\n\n private HadoopPipeline done() {\n if (!this.state.isLocked()) {\n final Pair> pair = this.state.popProperty();\n if (null != pair) {\n this.compiler.addMap(PropertyMap.Map.class,\n LongWritable.class,\n pair.getB(),\n PropertyMap.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB()));\n makeMapReduceString(PropertyMap.class, pair.getA());\n this.state.lock();\n }\n }\n return this;\n }\n\n /**\n * Submit the HadoopPipeline to the Hadoop cluster.\n *\n * @throws Exception\n */\n public void submit() throws Exception {\n submit(Tokens.EMPTY_STRING, false);\n }\n\n /**\n * Submit the HadoopPipeline to the Hadoop cluster and ensure that a header is emitted in the logs.\n *\n * @param script the Gremlin script\n * @param showHeader the Titan/Hadoop header\n * @throws Exception\n */\n public void submit(final String script, final Boolean showHeader) throws Exception {\n this.done();\n if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphOutputFormat())) {\n this.state.assertNotLocked();\n ((Class) this.graph.getGraphOutputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler);\n }\n this.compiler.completeSequence();\n ToolRunner.run(this.compiler, new String[]{script, showHeader.toString()});\n }\n\n /**\n * Get a reference to the graph currently being used in this HadoopPipeline.\n *\n * @return the HadoopGraph\n */\n public HadoopGraph getGraph() {\n return this.graph;\n }\n\n public HadoopCompiler getCompiler() {\n return this.compiler;\n }\n\n private String validateClosure(String closure) {\n if (closure == null)\n return null;\n\n try {\n engine.eval(closure);\n return closure;\n } catch (ScriptException e) {\n closure = closure.trim();\n closure = closure.replaceFirst(\"\\\\{\", \"{it->\");\n try {\n engine.eval(closure);\n return closure;\n } catch (ScriptException e1) {\n }\n throw new IllegalArgumentException(\"The provided closure does not compile: \" + e.getMessage(), e);\n }\n }\n\n private void makeMapReduceString(final Class klass, final Object... arguments) {\n String result = klass.getSimpleName();\n if (arguments.length > 0) {\n result = result + \"(\";\n for (final Object arg : arguments) {\n result = result + arg + \",\";\n }\n result = result.substring(0, result.length() - 1) + \")\";\n }\n this.stringRepresentation.add(result);\n }\n\n private Class convertJavaToHadoop(final Class klass) {\n if (klass.equals(String.class)) {\n return Text.class;\n } else if (klass.equals(Integer.class)) {\n return IntWritable.class;\n } else if (klass.equals(Double.class)) {\n return DoubleWritable.class;\n } else if (klass.equals(Long.class)) {\n return LongWritable.class;\n } else if (klass.equals(Float.class)) {\n return FloatWritable.class;\n } else if (klass.equals(Boolean.class)) {\n return BooleanWritable.class;\n } else {\n throw new IllegalArgumentException(\"The provided class is not supported: \" + klass.getSimpleName());\n }\n }\n}\n"},"message":{"kind":"string","value":"Making HadoopPipeline.submit return Tool status\n\nThis submit method is a thin wrapper around ToolRunner.run.\nToolRunner.run returns the integer exit status produced by the Tool\nimplementation it executes. Prior to this commit, submit returned\nvoid and threw the status away. Now the status is returned from\nsubmit. This change is groundwork for a new integration test method\nrelated to #806 and #826 that will submit a HadoopPipeline that\nsubmits a typical graphson-to-sequencefile dump job and needs to know\nwhether the job succeeded.\n"},"old_file":{"kind":"string","value":"titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/HadoopPipeline.java"},"subject":{"kind":"string","value":"Making HadoopPipeline.submit return Tool status"}}},{"rowIdx":1259,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"eb134def7c2d629a4fec3b507e45cdefaf204421"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"willkara/sakai,willkara/sakai,frasese/sakai,Fudan-University/sakai,Fudan-University/sakai,OpenCollabZA/sakai,willkara/sakai,frasese/sakai,frasese/sakai,ouit0408/sakai,frasese/sakai,frasese/sakai,OpenCollabZA/sakai,willkara/sakai,ouit0408/sakai,ouit0408/sakai,willkara/sakai,OpenCollabZA/sakai,frasese/sakai,OpenCollabZA/sakai,Fudan-University/sakai,frasese/sakai,willkara/sakai,OpenCollabZA/sakai,ouit0408/sakai,Fudan-University/sakai,ouit0408/sakai,OpenCollabZA/sakai,ouit0408/sakai,OpenCollabZA/sakai,ouit0408/sakai,Fudan-University/sakai,ouit0408/sakai,willkara/sakai,Fudan-University/sakai,OpenCollabZA/sakai,Fudan-University/sakai,willkara/sakai,frasese/sakai,Fudan-University/sakai"},"new_contents":{"kind":"string","value":"/**********************************************************************************\n * $URL$\n * $Id$\n ***********************************************************************************\n *\n * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation\n *\n * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 **********************************************************************************/\n\npackage org.sakaiproject.portal.service;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.servlet.http.HttpServletRequest;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.sakaiproject.alias.api.Alias;\nimport org.sakaiproject.alias.api.AliasService;\nimport org.sakaiproject.component.api.ServerConfigurationService;\nimport org.sakaiproject.entity.api.ResourceProperties;\nimport org.sakaiproject.exception.IdUnusedException;\nimport org.sakaiproject.exception.PermissionException;\nimport org.sakaiproject.portal.api.PortalService;\nimport org.sakaiproject.portal.api.SiteNeighbourhoodService;\nimport org.sakaiproject.site.api.Site;\nimport org.sakaiproject.site.api.SiteService;\nimport org.sakaiproject.thread_local.api.ThreadLocalManager;\nimport org.sakaiproject.tool.api.Session;\nimport org.sakaiproject.user.api.Preferences;\nimport org.sakaiproject.user.api.PreferencesService;\nimport org.sakaiproject.user.api.UserDirectoryService;\nimport org.sakaiproject.user.api.UserNotDefinedException;\n\n/**\n * @author ieb\n */\npublic class SiteNeighbourhoodServiceImpl implements SiteNeighbourhoodService\n{\n\n\tprivate static final String SITE_ALIAS = \"/sitealias/\";\n\n\tprivate static final Logger log = LoggerFactory.getLogger(SiteNeighbourhoodServiceImpl.class);\n\n\tprivate SiteService siteService;\n\n\tprivate PreferencesService preferencesService;\n\n\tprivate UserDirectoryService userDirectoryService;\n\n\tprivate ServerConfigurationService serverConfigurationService;\n\t\n\tprivate AliasService aliasService;\n\n\tprivate ThreadLocalManager threadLocalManager;\n\t\n\t/** Should all site aliases have a prefix */\n\tprivate boolean useAliasPrefix = false;\n\t\n\tprivate boolean useSiteAliases = false; \n\n\tpublic void init()\n\t{\n\t\tuseSiteAliases = serverConfigurationService.getBoolean(\"portal.use.site.aliases\", false);\n\t}\n\n\tpublic void destroy()\n\t{\n\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.sakaiproject.portal.api.SiteNeighbourhoodService#getSitesAtNode(javax.servlet.http.HttpServletRequest,\n\t * org.sakaiproject.tool.api.Session, boolean)\n\t */\n\tpublic List getSitesAtNode(HttpServletRequest request, Session session,\n\t\t\tboolean includeMyWorkspace)\n\t{\n\t\treturn getAllSites(request, session, includeMyWorkspace);\n\t}\n\n\t/**\n\t * Get All Sites for the current user. If the user is not logged in we\n\t * return the list of publically viewable gateway sites.\n\t * \n\t * @param includeMyWorkspace\n\t * When this is true - include the user's My Workspace as the first\n\t * parameter. If false, do not include the MyWorkspace anywhere in\n\t * the list. Some uses - such as the portlet styled portal or the rss\n\t * styled portal simply want all of the sites with the MyWorkspace\n\t * first. Other portals like the basic tabbed portal treats My\n\t * Workspace separately from all of the rest of the workspaces.\n\t * @see org.sakaiproject.portal.api.PortalSiteHelper#getAllSites(javax.servlet.http.HttpServletRequest,\n\t * org.sakaiproject.tool.api.Session, boolean)\n\t */\n\tpublic List getAllSites(HttpServletRequest req, Session session,\n\t\t\tboolean includeMyWorkspace)\n\t{\n\n\t\tboolean loggedIn = session.getUserId() != null;\n\t\tList mySites;\n\n\t\t// collect the Publically Viewable Sites\n\t\tif (!loggedIn)\n\t\t{\n\t\t\tmySites = getGatewaySites();\n\t\t\treturn mySites;\n\t\t}\n\n\t\t// collect the user's sites - don't care whether long descriptions are loaded\n\t\tmySites = siteService.getUserSites(false);\n\n\t\t// collect the user's preferences\n\t\tList prefExclude = new ArrayList();\n\t\tList prefOrder = new ArrayList();\n\t\tif (session.getUserId() != null)\n\t\t{\n\t\t\tPreferences prefs = preferencesService.getPreferences(session.getUserId());\n\t\t\tResourceProperties props = prefs.getProperties(\"sakai:portal:sitenav\");\n\n\t\t\tList l = props.getPropertyList(\"exclude\");\n\t\t\tif (l != null)\n\t\t\t{\n\t\t\t\tprefExclude = l;\n\t\t\t}\n\n\t\t\tl = props.getPropertyList(\"order\");\n\t\t\tif (l != null)\n\t\t\t{\n\t\t\t\tprefOrder = l;\n\t\t\t}\n\t\t}\n\n\t\t// remove all in exclude from mySites\n\t\tList visibleSites = new ArrayList();\n\t\tfor (Site site: mySites) {\n\t\t\tif ( ! prefExclude.contains(site.getId())) {\n\t\t\t\tvisibleSites.add(site);\n\t\t\t}\n\t\t}\n\t\tmySites = visibleSites;\n\n\t\t// Prepare to put sites in the right order\n\t\tVector ordered = new Vector();\n\t\tSet added = new HashSet();\n\n\t\t// First, place or remove MyWorkspace as requested\n\t\tSite myWorkspace = getMyWorkspace(session);\n\t\tif (myWorkspace != null)\n\t\t{\n\t\t\tif (includeMyWorkspace)\n\t\t\t{\n\t\t\t\tordered.add(myWorkspace);\n\t\t\t\tadded.add(myWorkspace.getId());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint pos = listIndexOf(myWorkspace.getId(), mySites);\n\t\t\t\tif (pos != -1) mySites.remove(pos);\n\t\t\t}\n\t\t}\n\n\t\t// re-order mySites to have order first, the rest later\n\t\tfor (Iterator i = prefOrder.iterator(); i.hasNext();)\n\t\t{\n\t\t\tString id = (String) i.next();\n\n\t\t\t// find this site in the mySites list\n\t\t\tint pos = listIndexOf(id, mySites);\n\t\t\tif (pos != -1)\n\t\t\t{\n\t\t\t\tSite s = mySites.get(pos);\n\t\t\t\tif (!added.contains(s.getId()))\n\t\t\t\t{\n\t\t\t\t\tordered.add(s);\n\t\t\t\t\tadded.add(s.getId());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// We only do the child processing if we have less than 200 sites\n\t\tboolean haveChildren = false;\n\t\tint siteCount = mySites.size();\n\n\t\t// pick up the rest of the top-level-sites\n\t\tfor (int i = 0; i < mySites.size(); i++)\n\t\t{\n\t\t\tSite s = mySites.get(i);\n\t\t\tif (added.contains(s.getId())) continue;\n\t\t\t// Once the user takes over the order, \n\t\t\t// ignore parent/child sorting put all the sites\n\t\t\t// at the top\n\t\t\tString ourParent = null;\n\t\t\tif ( prefOrder.size() == 0 ) \n\t\t\t{\n\t\t\t\tResourceProperties rp = s.getProperties();\n\t\t\t\tourParent = rp.getProperty(SiteService.PROP_PARENT_ID);\n\t\t\t}\n\t\t\t// System.out.println(\"Top Site:\"+s.getTitle()+\"\n\t\t\t// parent=\"+ourParent);\n\t\t\tif (siteCount > 200 || ourParent == null)\n\t\t\t{\n\t\t\t\t// System.out.println(\"Added at root\");\n\t\t\t\tordered.add(s);\n\t\t\t\tadded.add(s.getId());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thaveChildren = true;\n\t\t\t}\n\t\t}\n\n\t\t// If and only if we have some child nodes, we repeatedly\n\t\t// pull up children nodes to be behind their parents\n\t\t// This is O N**2 - so if we had thousands of sites it\n\t\t// it would be costly - hence we only do it for < 200 sites\n\t\t// and limited depth - that makes it O(N) not O(N**2)\n\t\tboolean addedSites = true;\n\t\tint depth = 0;\n\t\twhile (depth < 20 && addedSites && haveChildren)\n\t\t{\n\t\t\tdepth++;\n\t\t\taddedSites = false;\n\t\t\thaveChildren = false;\n\t\t\tfor (int i = mySites.size() - 1; i >= 0; i--)\n\t\t\t{\n\t\t\t\tSite s = mySites.get(i);\n\t\t\t\tif (added.contains(s.getId())) continue;\n\t\t\t\tResourceProperties rp = s.getProperties();\n\t\t\t\tString ourParent = rp.getProperty(SiteService.PROP_PARENT_ID);\n\t\t\t\tif (ourParent == null) continue;\n\t\t\t\thaveChildren = true;\n\t\t\t\t// System.out.println(\"Child Site:\"+s.getTitle()+\n\t\t\t\t// \"parent=\"+ourParent);\n\t\t\t\t// Search the already added pages for a parent\n\t\t\t\t// or sibling node\n\t\t\t\tboolean found = false;\n\t\t\t\tint j = -1;\n\t\t\t\tfor (j = ordered.size() - 1; j >= 0; j--)\n\t\t\t\t{\n\t\t\t\t\tSite ps = ordered.get(j);\n\t\t\t\t\t// See if this site is our parent\n\t\t\t\t\tif (ourParent.equals(ps.getId()))\n\t\t\t\t\t{\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// See if this site is our sibling\n\t\t\t\t\trp = ps.getProperties();\n\t\t\t\t\tString peerParent = rp.getProperty(SiteService.PROP_PARENT_ID);\n\t\t\t\t\tif (ourParent.equals(peerParent))\n\t\t\t\t\t{\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// We want to insert *after* the identified node\n\t\t\t\tj = j + 1;\n\t\t\t\tif (found && j >= 0 && j < ordered.size())\n\t\t\t\t{\n\t\t\t\t\t// System.out.println(\"Added after parent\");\n\t\t\t\t\tordered.insertElementAt(s, j);\n\t\t\t\t\tadded.add(s.getId());\n\t\t\t\t\taddedSites = true; // Worth going another level deeper\n\t\t\t\t}\n\t\t\t}\n\t\t} // End while depth\n\n\t\t// If we still have children drop them at the end\n\t\tif (haveChildren) for (int i = 0; i < mySites.size(); i++)\n\t\t{\n\t\t\tSite s = mySites.get(i);\n\t\t\tif (added.contains(s.getId())) continue;\n\t\t\t// System.out.println(\"Orphan Site:\"+s.getId()+\" \"+s.getTitle());\n\t\t\tordered.add(s);\n\t\t}\n\n\t\t// All done\n\t\tmySites = ordered;\n\t\treturn mySites;\n\t}\n\n\t// Get the sites which are to be displayed for the gateway\n\t/**\n\t * @return\n\t */\n\tprivate List getGatewaySites()\n\t{\n\t\tList mySites = new ArrayList();\n\t\tString[] gatewaySiteIds = getGatewaySiteList();\n\t\tif (gatewaySiteIds == null)\n\t\t{\n\t\t\treturn mySites; // An empty list - deal with this higher up in the\n\t\t\t// food chain\n\t\t}\n\n\t\t// Loop throught the sites making sure they exist and are visitable\n\t\tfor (int i = 0; i < gatewaySiteIds.length; i++)\n\t\t{\n\t\t\tString siteId = gatewaySiteIds[i];\n\n\t\t\tSite site = null;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tsite = getSiteVisit(siteId);\n\t\t\t}\n\t\t\tcatch (IdUnusedException e)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcatch (PermissionException e)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (site != null)\n\t\t\t{\n\t\t\t\tmySites.add(site);\n\t\t\t}\n\t\t}\n\n\t\tif (mySites.size() < 1)\n\t\t{\n\t\t\tlog.warn(\"No suitable gateway sites found, gatewaySiteList preference had \"\n\t\t\t\t\t+ gatewaySiteIds.length + \" sites.\");\n\t\t}\n\t\treturn mySites;\n\t}\n\n\t/**\n\t * @see org.sakaiproject.portal.api.PortalSiteHelper#getMyWorkspace(org.sakaiproject.tool.api.Session)\n\t */\n\tprivate Site getMyWorkspace(Session session)\n\t{\n\t\tString siteId = siteService.getUserSiteId(session.getUserId());\n\n\t\t// Make sure we can visit\n\t\tSite site = null;\n\t\ttry\n\t\t{\n\t\t\tsite = getSiteVisit(siteId);\n\t\t}\n\t\tcatch (IdUnusedException e)\n\t\t{\n\t\t\tsite = null;\n\t\t}\n\t\tcatch (PermissionException e)\n\t\t{\n\t\t\tsite = null;\n\t\t}\n\n\t\treturn site;\n\t}\n\n\t/**\n\t * Find the site in the list that has this id - return the position.\n\t * \n\t * @param value\n\t * The site id to find.\n\t * @param siteList\n\t * The list of Site objects.\n\t * @return The index position in siteList of the site with site id = value,\n\t * or -1 if not found.\n\t */\n\tprivate int listIndexOf(String value, List siteList)\n\t{\n\t\tfor (int i = 0; i < siteList.size(); i++)\n\t\t{\n\t\t\tSite site = (Site) siteList.get(i);\n\t\t\tif (site.getId().equals(value))\n\t\t\t{\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\t// Return the list of tabs for the anonymous view (Gateway)\n\t// If we have a list of sites, return that - if not simply pull in the\n\t// single\n\t// Gateway site\n\t/**\n\t * @return\n\t */\n\tprivate String[] getGatewaySiteList()\n\t{\n\t\tString gatewaySiteListPref = serverConfigurationService\n\t\t\t\t.getString(\"gatewaySiteList\");\n\n\t\tif (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1)\n\t\t{\n\t\t\tgatewaySiteListPref = serverConfigurationService.getGatewaySiteId();\n\t\t}\n\t\tif (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1)\n\t\t\treturn null;\n\n\t\tString[] gatewaySites = gatewaySiteListPref.split(\",\");\n\t\tif (gatewaySites.length < 1) return null;\n\n\t\treturn gatewaySites;\n\t}\n\n\t/**\n\t * Do the getSiteVisit, but if not found and the id is a user site, try\n\t * translating from user EID to ID.\n\t * \n\t * @param siteId\n\t * The Site Id.\n\t * @return The Site.\n\t * @throws PermissionException\n\t * If not allowed.\n\t * @throws IdUnusedException\n\t * If not found.\n\t */\n\tpublic Site getSiteVisit(String siteId) throws PermissionException, IdUnusedException\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn siteService.getSiteVisit(siteId);\n\t\t}\n\t\tcatch (IdUnusedException e)\n\t\t{\n\t\t\tif (siteService.isUserSite(siteId))\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tString userEid = siteService.getSiteUserId(siteId);\n\t\t\t\t\tString userId = userDirectoryService.getUserId(userEid);\n\t\t\t\t\tString alternateSiteId = siteService.getUserSiteId(userId);\n\t\t\t\t\treturn siteService.getSiteVisit(alternateSiteId);\n\t\t\t\t}\n\t\t\t\tcatch (UserNotDefinedException ee)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// re-throw if that didn't work\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/**\n\t * @return the preferencesService\n\t */\n\tpublic PreferencesService getPreferencesService()\n\t{\n\t\treturn preferencesService;\n\t}\n\n\t/**\n\t * @param preferencesService\n\t * the preferencesService to set\n\t */\n\tpublic void setPreferencesService(PreferencesService preferencesService)\n\t{\n\t\tthis.preferencesService = preferencesService;\n\t}\n\n\t/**\n\t * @return the serverConfigurationService\n\t */\n\tpublic ServerConfigurationService getServerConfigurationService()\n\t{\n\t\treturn serverConfigurationService;\n\t}\n\n\t/**\n\t * @param serverConfigurationService\n\t * the serverConfigurationService to set\n\t */\n\tpublic void setServerConfigurationService(\n\t\t\tServerConfigurationService serverConfigurationService)\n\t{\n\t\tthis.serverConfigurationService = serverConfigurationService;\n\t}\n\n\t/**\n\t * @return the siteService\n\t */\n\tpublic SiteService getSiteService()\n\t{\n\t\treturn siteService;\n\t}\n\n\t/**\n\t * @param siteService\n\t * the siteService to set\n\t */\n\tpublic void setSiteService(SiteService siteService)\n\t{\n\t\tthis.siteService = siteService;\n\t}\n\n\t/**\n\t * @return the userDirectoryService\n\t */\n\tpublic UserDirectoryService getUserDirectoryService()\n\t{\n\t\treturn userDirectoryService;\n\t}\n\n\t/**\n\t * @param userDirectoryService\n\t * the userDirectoryService to set\n\t */\n\tpublic void setUserDirectoryService(UserDirectoryService userDirectoryService)\n\t{\n\t\tthis.userDirectoryService = userDirectoryService;\n\t}\n\n\tpublic void setThreadLocalManager(ThreadLocalManager threadLocalManager)\n\t{\n\t\tthis.threadLocalManager = threadLocalManager;\n\t}\n\n\tpublic String lookupSiteAlias(String id, String context)\n\t{\n\t\t// TODO Constant extraction\n\t\tif (\"/site/!error\".equals(id)) {\n\t\t\tObject originalId = threadLocalManager.get(PortalService.SAKAI_PORTAL_ORIGINAL_SITEID);\n\t\t\tif (originalId instanceof String) {\n\t\t\t\treturn (String)originalId;\n\t\t\t}\n\t\t}\n\t\tif (!useSiteAliases)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\tList aliases = aliasService.getAliases(id);\n\t\tif (aliases.size() > 0)\n\t\t{\n\t\t\tif (aliases.size() > 1 && log.isInfoEnabled())\n\t\t\t{\n\t\t\t\tif (log.isDebugEnabled())\n\t\t\t\t{\n\t\t\t\t\tlog.debug(\"More than one alias for \"+ id+ \" sorting.\");\n\t\t\t\t}\n\t\t\t\tCollections.sort(aliases, new Comparator()\n\t\t\t\t{\n\t\t\t\t\tpublic int compare(Alias o1, Alias o2)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn o1.getId().compareTo(o2.getId());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (Alias alias : aliases)\n\t\t\t{\n\t\t\t\tString aliasId = alias.getId();\n\t\t\t\tboolean startsWithPrefix = aliasId.startsWith(SITE_ALIAS);\n\t\t\t\tif (startsWithPrefix)\n\t\t\t\t{\n\t\t\t\t\tif (useAliasPrefix)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn aliasId.substring(SITE_ALIAS.length());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!useAliasPrefix)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn aliasId;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String parseSiteAlias(String alias)\n\t{\n\t\tif (alias == null)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\t// Prepend site alias prefix if it's being used.\n\t\tString id = ((useAliasPrefix)?SITE_ALIAS:\"\")+alias;\n\n\t\ttry\n\t\t{\n\t\t\tString reference = aliasService.getTarget(id);\n\t\t\treturn reference;\n\t\t}\n\t\tcatch (IdUnusedException e)\n\t\t{\n\t\t\tif (log.isDebugEnabled())\n\t\t\t{\n\t\t\t\tlog.debug(\"No alias found for \"+ id);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void setAliasService(AliasService aliasService) {\n\t\tthis.aliasService = aliasService;\n\t}\n\n\tpublic boolean isUseAliasPrefix()\n\t{\n\t\treturn useAliasPrefix;\n\t}\n\n\tpublic void setUseAliasPrefix(boolean useAliasPrefix)\n\t{\n\t\tthis.useAliasPrefix = useAliasPrefix;\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/SiteNeighbourhoodServiceImpl.java"},"old_contents":{"kind":"string","value":"/**********************************************************************************\n * $URL$\n * $Id$\n ***********************************************************************************\n *\n * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation\n *\n * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 **********************************************************************************/\n\npackage org.sakaiproject.portal.service;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.servlet.http.HttpServletRequest;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.sakaiproject.alias.api.Alias;\nimport org.sakaiproject.alias.api.AliasService;\nimport org.sakaiproject.component.api.ServerConfigurationService;\nimport org.sakaiproject.entity.api.ResourceProperties;\nimport org.sakaiproject.exception.IdUnusedException;\nimport org.sakaiproject.exception.PermissionException;\nimport org.sakaiproject.portal.api.PortalService;\nimport org.sakaiproject.portal.api.SiteNeighbourhoodService;\nimport org.sakaiproject.site.api.Site;\nimport org.sakaiproject.site.api.SiteService;\nimport org.sakaiproject.thread_local.api.ThreadLocalManager;\nimport org.sakaiproject.tool.api.Session;\nimport org.sakaiproject.user.api.Preferences;\nimport org.sakaiproject.user.api.PreferencesService;\nimport org.sakaiproject.user.api.UserDirectoryService;\nimport org.sakaiproject.user.api.UserNotDefinedException;\n\n/**\n * @author ieb\n */\npublic class SiteNeighbourhoodServiceImpl implements SiteNeighbourhoodService\n{\n\n\tprivate static final String SITE_ALIAS = \"/sitealias/\";\n\n\tprivate static final Logger log = LoggerFactory.getLogger(SiteNeighbourhoodServiceImpl.class);\n\n\tprivate SiteService siteService;\n\n\tprivate PreferencesService preferencesService;\n\n\tprivate UserDirectoryService userDirectoryService;\n\n\tprivate ServerConfigurationService serverConfigurationService;\n\t\n\tprivate AliasService aliasService;\n\n\tprivate ThreadLocalManager threadLocalManager;\n\t\n\t/** Should all site aliases have a prefix */\n\tprivate boolean useAliasPrefix = false;\n\t\n\tprivate boolean useSiteAliases = false; \n\n\tpublic void init()\n\t{\n\t\tuseSiteAliases = serverConfigurationService.getBoolean(\"portal.use.site.aliases\", false);\n\t}\n\n\tpublic void destroy()\n\t{\n\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.sakaiproject.portal.api.SiteNeighbourhoodService#getSitesAtNode(javax.servlet.http.HttpServletRequest,\n\t * org.sakaiproject.tool.api.Session, boolean)\n\t */\n\tpublic List getSitesAtNode(HttpServletRequest request, Session session,\n\t\t\tboolean includeMyWorkspace)\n\t{\n\t\treturn getAllSites(request, session, includeMyWorkspace);\n\t}\n\n\t/**\n\t * Get All Sites for the current user. If the user is not logged in we\n\t * return the list of publically viewable gateway sites.\n\t * \n\t * @param includeMyWorkspace\n\t * When this is true - include the user's My Workspace as the first\n\t * parameter. If false, do not include the MyWorkspace anywhere in\n\t * the list. Some uses - such as the portlet styled portal or the rss\n\t * styled portal simply want all of the sites with the MyWorkspace\n\t * first. Other portals like the basic tabbed portal treats My\n\t * Workspace separately from all of the rest of the workspaces.\n\t * @see org.sakaiproject.portal.api.PortalSiteHelper#getAllSites(javax.servlet.http.HttpServletRequest,\n\t * org.sakaiproject.tool.api.Session, boolean)\n\t */\n\tpublic List getAllSites(HttpServletRequest req, Session session,\n\t\t\tboolean includeMyWorkspace)\n\t{\n\n\t\tboolean loggedIn = session.getUserId() != null;\n\t\tList mySites;\n\n\t\t// collect the Publically Viewable Sites\n\t\tif (!loggedIn)\n\t\t{\n\t\t\tmySites = getGatewaySites();\n\t\t\treturn mySites;\n\t\t}\n\n\t\t// collect the user's sites - don't care whether long descriptions are loaded\n\t\tmySites = siteService.getUserSites(false);\n\n\t\t// collect the user's preferences\n\t\tList prefExclude = new ArrayList();\n\t\tList prefOrder = new ArrayList();\n\t\tif (session.getUserId() != null)\n\t\t{\n\t\t\tPreferences prefs = preferencesService.getPreferences(session.getUserId());\n\t\t\tResourceProperties props = prefs.getProperties(\"sakai:portal:sitenav\");\n\n\t\t\tList l = props.getPropertyList(\"exclude\");\n\t\t\tif (l != null)\n\t\t\t{\n\t\t\t\tprefExclude = l;\n\t\t\t}\n\n\t\t\tl = props.getPropertyList(\"order\");\n\t\t\tif (l != null)\n\t\t\t{\n\t\t\t\tprefOrder = l;\n\t\t\t}\n\t\t}\n\n\t\t// remove all in exclude from mySites\n\t\tList visibleSites = new ArrayList();\n\t\tfor (Site site: mySites) {\n\t\t\tif ( ! prefExclude.contains(site.getId())) {\n\t\t\t\tvisibleSites.add(site);\n\t\t\t}\n\t\t}\n\t\tmySites = visibleSites;\n\n\t\t// Prepare to put sites in the right order\n\t\tVector ordered = new Vector();\n\t\tSet added = new HashSet();\n\n\t\t// First, place or remove MyWorkspace as requested\n\t\tSite myWorkspace = getMyWorkspace(session);\n\t\tif (myWorkspace != null)\n\t\t{\n\t\t\tif (includeMyWorkspace)\n\t\t\t{\n\t\t\t\tordered.add(myWorkspace);\n\t\t\t\tadded.add(myWorkspace.getId());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint pos = listIndexOf(myWorkspace.getId(), mySites);\n\t\t\t\tif (pos != -1) mySites.remove(pos);\n\t\t\t}\n\t\t}\n\n\t\t// re-order mySites to have order first, the rest later\n\t\tfor (Iterator i = prefOrder.iterator(); i.hasNext();)\n\t\t{\n\t\t\tString id = (String) i.next();\n\n\t\t\t// find this site in the mySites list\n\t\t\tint pos = listIndexOf(id, mySites);\n\t\t\tif (pos != -1)\n\t\t\t{\n\t\t\t\tSite s = mySites.get(pos);\n\t\t\t\tif (!added.contains(s.getId()))\n\t\t\t\t{\n\t\t\t\t\tordered.add(s);\n\t\t\t\t\tadded.add(s.getId());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// We only do the child processing if we have less than 200 sites\n\t\tboolean haveChildren = false;\n\t\tint siteCount = mySites.size();\n\n\t\t// pick up the rest of the top-level-sites\n\t\tfor (int i = 0; i < mySites.size(); i++)\n\t\t{\n\t\t\tSite s = mySites.get(i);\n\t\t\tif (added.contains(s.getId())) continue;\n\t\t\t// Once the user takes over the order, \n\t\t\t// ignore parent/child sorting put all the sites\n\t\t\t// at the top\n\t\t\tString ourParent = null;\n\t\t\tif ( prefOrder.size() == 0 ) \n\t\t\t{\n\t\t\t\tResourceProperties rp = s.getProperties();\n\t\t\t\tourParent = rp.getProperty(SiteService.PROP_PARENT_ID);\n\t\t\t}\n\t\t\t// System.out.println(\"Top Site:\"+s.getTitle()+\"\n\t\t\t// parent=\"+ourParent);\n\t\t\tif (siteCount > 200 || ourParent == null)\n\t\t\t{\n\t\t\t\t// System.out.println(\"Added at root\");\n\t\t\t\tordered.add(s);\n\t\t\t\tadded.add(s.getId());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thaveChildren = true;\n\t\t\t}\n\t\t}\n\n\t\t// If and only if we have some child nodes, we repeatedly\n\t\t// pull up children nodes to be behind their parents\n\t\t// This is O N**2 - so if we had thousands of sites it\n\t\t// it would be costly - hence we only do it for < 200 sites\n\t\t// and limited depth - that makes it O(N) not O(N**2)\n\t\tboolean addedSites = true;\n\t\tint depth = 0;\n\t\twhile (depth < 20 && addedSites && haveChildren)\n\t\t{\n\t\t\tdepth++;\n\t\t\taddedSites = false;\n\t\t\thaveChildren = false;\n\t\t\tfor (int i = mySites.size() - 1; i >= 0; i--)\n\t\t\t{\n\t\t\t\tSite s = mySites.get(i);\n\t\t\t\tif (added.contains(s.getId())) continue;\n\t\t\t\tResourceProperties rp = s.getProperties();\n\t\t\t\tString ourParent = rp.getProperty(SiteService.PROP_PARENT_ID);\n\t\t\t\tif (ourParent == null) continue;\n\t\t\t\thaveChildren = true;\n\t\t\t\t// System.out.println(\"Child Site:\"+s.getTitle()+\n\t\t\t\t// \"parent=\"+ourParent);\n\t\t\t\t// Search the already added pages for a parent\n\t\t\t\t// or sibling node\n\t\t\t\tboolean found = false;\n\t\t\t\tint j = -1;\n\t\t\t\tfor (j = ordered.size() - 1; j >= 0; j--)\n\t\t\t\t{\n\t\t\t\t\tSite ps = ordered.get(j);\n\t\t\t\t\t// See if this site is our parent\n\t\t\t\t\tif (ourParent.equals(ps.getId()))\n\t\t\t\t\t{\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// See if this site is our sibling\n\t\t\t\t\trp = ps.getProperties();\n\t\t\t\t\tString peerParent = rp.getProperty(SiteService.PROP_PARENT_ID);\n\t\t\t\t\tif (ourParent.equals(peerParent))\n\t\t\t\t\t{\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// We want to insert *after* the identified node\n\t\t\t\tj = j + 1;\n\t\t\t\tif (found && j >= 0 && j < ordered.size())\n\t\t\t\t{\n\t\t\t\t\t// System.out.println(\"Added after parent\");\n\t\t\t\t\tordered.insertElementAt(s, j);\n\t\t\t\t\tadded.add(s.getId());\n\t\t\t\t\taddedSites = true; // Worth going another level deeper\n\t\t\t\t}\n\t\t\t}\n\t\t} // End while depth\n\n\t\t// If we still have children drop them at the end\n\t\tif (haveChildren) for (int i = 0; i < mySites.size(); i++)\n\t\t{\n\t\t\tSite s = mySites.get(i);\n\t\t\tif (added.contains(s.getId())) continue;\n\t\t\t// System.out.println(\"Orphan Site:\"+s.getId()+\" \"+s.getTitle());\n\t\t\tordered.add(s);\n\t\t}\n\n\t\t// All done\n\t\tmySites = ordered;\n\t\treturn mySites;\n\t}\n\n\t// Get the sites which are to be displayed for the gateway\n\t/**\n\t * @return\n\t */\n\tprivate List getGatewaySites()\n\t{\n\t\tList mySites = new ArrayList();\n\t\tString[] gatewaySiteIds = getGatewaySiteList();\n\t\tif (gatewaySiteIds == null)\n\t\t{\n\t\t\treturn mySites; // An empty list - deal with this higher up in the\n\t\t\t// food chain\n\t\t}\n\n\t\t// Loop throught the sites making sure they exist and are visitable\n\t\tfor (int i = 0; i < gatewaySiteIds.length; i++)\n\t\t{\n\t\t\tString siteId = gatewaySiteIds[i];\n\n\t\t\tSite site = null;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tsite = getSiteVisit(siteId);\n\t\t\t}\n\t\t\tcatch (IdUnusedException e)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcatch (PermissionException e)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (site != null)\n\t\t\t{\n\t\t\t\tmySites.add(site);\n\t\t\t}\n\t\t}\n\n\t\tif (mySites.size() < 1)\n\t\t{\n\t\t\tlog.warn(\"No suitable gateway sites found, gatewaySiteList preference had \"\n\t\t\t\t\t+ gatewaySiteIds.length + \" sites.\");\n\t\t}\n\t\treturn mySites;\n\t}\n\n\t/**\n\t * @see org.sakaiproject.portal.api.PortalSiteHelper#getMyWorkspace(org.sakaiproject.tool.api.Session)\n\t */\n\tprivate Site getMyWorkspace(Session session)\n\t{\n\t\tString siteId = siteService.getUserSiteId(session.getUserId());\n\n\t\t// Make sure we can visit\n\t\tSite site = null;\n\t\ttry\n\t\t{\n\t\t\tsite = getSiteVisit(siteId);\n\t\t}\n\t\tcatch (IdUnusedException e)\n\t\t{\n\t\t\tsite = null;\n\t\t}\n\t\tcatch (PermissionException e)\n\t\t{\n\t\t\tsite = null;\n\t\t}\n\n\t\treturn site;\n\t}\n\n\t/**\n\t * Find the site in the list that has this id - return the position.\n\t * \n\t * @param value\n\t * The site id to find.\n\t * @param siteList\n\t * The list of Site objects.\n\t * @return The index position in siteList of the site with site id = value,\n\t * or -1 if not found.\n\t */\n\tprivate int listIndexOf(String value, List siteList)\n\t{\n\t\tfor (int i = 0; i < siteList.size(); i++)\n\t\t{\n\t\t\tSite site = (Site) siteList.get(i);\n\t\t\tif (site.getId().equals(value))\n\t\t\t{\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\t// Return the list of tabs for the anonymous view (Gateway)\n\t// If we have a list of sites, return that - if not simply pull in the\n\t// single\n\t// Gateway site\n\t/**\n\t * @return\n\t */\n\tprivate String[] getGatewaySiteList()\n\t{\n\t\tString gatewaySiteListPref = serverConfigurationService\n\t\t\t\t.getString(\"gatewaySiteList\");\n\n\t\tif (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1)\n\t\t{\n\t\t\tgatewaySiteListPref = serverConfigurationService.getGatewaySiteId();\n\t\t}\n\t\tif (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1)\n\t\t\treturn null;\n\n\t\tString[] gatewaySites = gatewaySiteListPref.split(\",\");\n\t\tif (gatewaySites.length < 1) return null;\n\n\t\treturn gatewaySites;\n\t}\n\n\t/**\n\t * Do the getSiteVisit, but if not found and the id is a user site, try\n\t * translating from user EID to ID.\n\t * \n\t * @param siteId\n\t * The Site Id.\n\t * @return The Site.\n\t * @throws PermissionException\n\t * If not allowed.\n\t * @throws IdUnusedException\n\t * If not found.\n\t */\n\tpublic Site getSiteVisit(String siteId) throws PermissionException, IdUnusedException\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn siteService.getSiteVisit(siteId);\n\t\t}\n\t\tcatch (IdUnusedException e)\n\t\t{\n\t\t\tif (siteService.isUserSite(siteId))\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tString userEid = siteService.getSiteUserId(siteId);\n\t\t\t\t\tString userId = userDirectoryService.getUserId(userEid);\n\t\t\t\t\tString alternateSiteId = siteService.getUserSiteId(userId);\n\t\t\t\t\treturn siteService.getSiteVisit(alternateSiteId);\n\t\t\t\t}\n\t\t\t\tcatch (UserNotDefinedException ee)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// re-throw if that didn't work\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/**\n\t * @return the preferencesService\n\t */\n\tpublic PreferencesService getPreferencesService()\n\t{\n\t\treturn preferencesService;\n\t}\n\n\t/**\n\t * @param preferencesService\n\t * the preferencesService to set\n\t */\n\tpublic void setPreferencesService(PreferencesService preferencesService)\n\t{\n\t\tthis.preferencesService = preferencesService;\n\t}\n\n\t/**\n\t * @return the serverConfigurationService\n\t */\n\tpublic ServerConfigurationService getServerConfigurationService()\n\t{\n\t\treturn serverConfigurationService;\n\t}\n\n\t/**\n\t * @param serverConfigurationService\n\t * the serverConfigurationService to set\n\t */\n\tpublic void setServerConfigurationService(\n\t\t\tServerConfigurationService serverConfigurationService)\n\t{\n\t\tthis.serverConfigurationService = serverConfigurationService;\n\t}\n\n\t/**\n\t * @return the siteService\n\t */\n\tpublic SiteService getSiteService()\n\t{\n\t\treturn siteService;\n\t}\n\n\t/**\n\t * @param siteService\n\t * the siteService to set\n\t */\n\tpublic void setSiteService(SiteService siteService)\n\t{\n\t\tthis.siteService = siteService;\n\t}\n\n\t/**\n\t * @return the userDirectoryService\n\t */\n\tpublic UserDirectoryService getUserDirectoryService()\n\t{\n\t\treturn userDirectoryService;\n\t}\n\n\t/**\n\t * @param userDirectoryService\n\t * the userDirectoryService to set\n\t */\n\tpublic void setUserDirectoryService(UserDirectoryService userDirectoryService)\n\t{\n\t\tthis.userDirectoryService = userDirectoryService;\n\t}\n\n\tpublic void setThreadLocalManager(ThreadLocalManager threadLocalManager)\n\t{\n\t\tthis.threadLocalManager = threadLocalManager;\n\t}\n\n\tpublic String lookupSiteAlias(String id, String context)\n\t{\n\t\t// TODO Constant extraction\n\t\tif (\"/site/!error\".equals(id)) {\n\t\t\tObject originalId = threadLocalManager.get(PortalService.SAKAI_PORTAL_ORIGINAL_SITEID);\n\t\t\tif (originalId instanceof String) {\n\t\t\t\treturn (String)originalId;\n\t\t\t}\n\t\t}\n\t\tList aliases = aliasService.getAliases(id);\n\t\tif (!useSiteAliases)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\tif (aliases.size() > 0)\n\t\t{\n\t\t\tif (aliases.size() > 1 && log.isInfoEnabled())\n\t\t\t{\n\t\t\t\tif (log.isDebugEnabled())\n\t\t\t\t{\n\t\t\t\t\tlog.debug(\"More than one alias for \"+ id+ \" sorting.\");\n\t\t\t\t}\n\t\t\t\tCollections.sort(aliases, new Comparator()\n\t\t\t\t{\n\t\t\t\t\tpublic int compare(Alias o1, Alias o2)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn o1.getId().compareTo(o2.getId());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (Alias alias : aliases)\n\t\t\t{\n\t\t\t\tString aliasId = alias.getId();\n\t\t\t\tboolean startsWithPrefix = aliasId.startsWith(SITE_ALIAS);\n\t\t\t\tif (startsWithPrefix)\n\t\t\t\t{\n\t\t\t\t\tif (useAliasPrefix)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn aliasId.substring(SITE_ALIAS.length());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!useAliasPrefix)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn aliasId;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String parseSiteAlias(String alias)\n\t{\n\t\tif (alias == null)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\t// Prepend site alias prefix if it's being used.\n\t\tString id = ((useAliasPrefix)?SITE_ALIAS:\"\")+alias;\n\n\t\ttry\n\t\t{\n\t\t\tString reference = aliasService.getTarget(id);\n\t\t\treturn reference;\n\t\t}\n\t\tcatch (IdUnusedException e)\n\t\t{\n\t\t\tif (log.isDebugEnabled())\n\t\t\t{\n\t\t\t\tlog.debug(\"No alias found for \"+ id);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void setAliasService(AliasService aliasService) {\n\t\tthis.aliasService = aliasService;\n\t}\n\n\tpublic boolean isUseAliasPrefix()\n\t{\n\t\treturn useAliasPrefix;\n\t}\n\n\tpublic void setUseAliasPrefix(boolean useAliasPrefix)\n\t{\n\t\tthis.useAliasPrefix = useAliasPrefix;\n\t}\n\n}\n"},"message":{"kind":"string","value":"SAK-31670 When aliases disabled don’t query DB. (#3185)\n\nIf aliases are disabled we would still look in the DB for any aliases. This is wrong and we should only be looking when aliases are enabled."},"old_file":{"kind":"string","value":"portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/SiteNeighbourhoodServiceImpl.java"},"subject":{"kind":"string","value":"SAK-31670 When aliases disabled don’t query DB. (#3185)"}}},{"rowIdx":1260,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"a6c881f8c42433b49eb378881b9bdd63a1a52202"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"apache/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs,mohanaraosv/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs"},"new_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.apache.commons.jcs.jcache;\n\nimport org.junit.Test;\n\nimport javax.cache.annotation.BeanProvider;\nimport java.util.Iterator;\nimport java.util.ServiceLoader;\n\nimport static org.hamcrest.CoreMatchers.instanceOf;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n\n// useless test but without it we are not sure\n// CDI TCKs passed\npublic class EnsureCDIIsTestedWhenTCKsRunTest\n{\n @Test\n public void checkOWBProvider()\n {\n try {\n final Iterator iterator = ServiceLoader.load(BeanProvider.class).iterator();\n assertTrue(iterator.hasNext());\n assertThat(iterator.next(), instanceOf(OWBBeanProvider.class));\n } catch (java.lang.UnsupportedClassVersionError e) {\n System.err.println(\"Ignoring checkOWBProvider test failure on \" + System.getProperty(\"java.version\"));\n }\n }\n}\n"},"new_file":{"kind":"string","value":"commons-jcs-tck-tests/src/test/java/org/apache/commons/jcs/jcache/EnsureCDIIsTestedWhenTCKsRunTest.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.apache.commons.jcs.jcache;\n\nimport org.junit.Test;\n\nimport javax.cache.annotation.BeanProvider;\nimport java.util.Iterator;\nimport java.util.ServiceLoader;\n\nimport static org.hamcrest.CoreMatchers.instanceOf;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;\n\n// useless test but without it we are not sure\n// CDI TCKs passed\npublic class EnsureCDIIsTestedWhenTCKsRunTest\n{\n @Test\n public void checkOWBProvider()\n {\n final Iterator iterator = ServiceLoader.load(BeanProvider.class).iterator();\n assertTrue(iterator.hasNext());\n assertThat(iterator.next(), instanceOf(OWBBeanProvider.class));\n }\n}\n"},"message":{"kind":"string","value":"JCS-132 EnsureCDIIsTestedWhenTCKsRunTest fails on Java 1.6\n\ngit-svn-id: fd52ae19693b7be904def34076a5ebbd6e132215@1632295 13f79535-47bb-0310-9956-ffa450edef68\n"},"old_file":{"kind":"string","value":"commons-jcs-tck-tests/src/test/java/org/apache/commons/jcs/jcache/EnsureCDIIsTestedWhenTCKsRunTest.java"},"subject":{"kind":"string","value":"JCS-132 EnsureCDIIsTestedWhenTCKsRunTest fails on Java 1.6"}}},{"rowIdx":1261,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ab558f105adf48c895400c154e3ee5dec966ab47"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sangramjadhav/testrs"},"new_contents":{"kind":"string","value":"2270c6b8-2ece-11e5-905b-74de2bd44bed"},"new_file":{"kind":"string","value":"hello.java"},"old_contents":{"kind":"string","value":"22703716-2ece-11e5-905b-74de2bd44bed"},"message":{"kind":"string","value":"2270c6b8-2ece-11e5-905b-74de2bd44bed"},"old_file":{"kind":"string","value":"hello.java"},"subject":{"kind":"string","value":"2270c6b8-2ece-11e5-905b-74de2bd44bed"}}},{"rowIdx":1262,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"0c5c7644972757fea8db0821fd69e62891f7d7ae"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"klehmann/domino-jna"},"new_contents":{"kind":"string","value":"package com.mindoo.domino.jna.formula;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport com.mindoo.domino.jna.IAdaptable;\nimport com.mindoo.domino.jna.NotesItem;\nimport com.mindoo.domino.jna.NotesNote;\nimport com.mindoo.domino.jna.NotesTimeDate;\nimport com.mindoo.domino.jna.constants.FormulaAttributes;\nimport com.mindoo.domino.jna.errors.FormulaCompilationError;\nimport com.mindoo.domino.jna.errors.INotesErrorConstants;\nimport com.mindoo.domino.jna.errors.NotesError;\nimport com.mindoo.domino.jna.errors.NotesErrorUtils;\nimport com.mindoo.domino.jna.errors.UnsupportedItemValueError;\nimport com.mindoo.domino.jna.gc.IRecyclableNotesObject;\nimport com.mindoo.domino.jna.gc.NotesGC;\nimport com.mindoo.domino.jna.internal.ItemDecoder;\nimport com.mindoo.domino.jna.internal.Mem32;\nimport com.mindoo.domino.jna.internal.Mem64;\nimport com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMCMDSPROC;\nimport com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMFUNCPROC;\nimport com.mindoo.domino.jna.internal.NotesConstants;\nimport com.mindoo.domino.jna.internal.NotesNativeAPI;\nimport com.mindoo.domino.jna.internal.NotesNativeAPI32;\nimport com.mindoo.domino.jna.internal.NotesNativeAPI64;\nimport com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMCMDSPROCWin32;\nimport com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMFUNCPROCWin32;\nimport com.mindoo.domino.jna.internal.handles.DHANDLE;\nimport com.mindoo.domino.jna.internal.handles.DHANDLE32;\nimport com.mindoo.domino.jna.internal.handles.DHANDLE64;\nimport com.mindoo.domino.jna.utils.NotesStringUtils;\nimport com.mindoo.domino.jna.utils.PlatformUtils;\nimport com.sun.jna.Memory;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.ptr.IntByReference;\nimport com.sun.jna.ptr.LongByReference;\nimport com.sun.jna.ptr.ShortByReference;\n\n/**\n * Utility class to execute a Domino formula on one or more {@link NotesNote} objects.
\n *
\n * The implementation supports more than the usual 64K of return value, e.g. to use\n * @DBColumn to read the column values in views with many entries.\n * \n * @author Karsten Lehmann\n */\npublic class FormulaExecution implements IRecyclableNotesObject, IAdaptable {\n\tpublic enum Disallow {\n\t\t/** Setting of environment variables */\n\t\tSETENVIRONMENT(NotesConstants.COMPUTE_CAPABILITY_SETENVIRONMENT),\n\t\t/** Commands like @Prompt */\n\t\tUICOMMANDS(NotesConstants.COMPUTE_CAPABILITY_UICOMMANDS),\n\t\t/** FIELD Foo := */\n\t\tASSIGN(NotesConstants.COMPUTE_CAPABILITY_ASSIGN),\n\t\t /** @SetDocField, @DocMark. */\n\t\tSIDEEFFECTS(NotesConstants.COMPUTE_CAPABILITY_SIDEEFFECTS),\n\t\t/** Any compute extension. */\n\t\tEXTENSION(NotesConstants.COMPUTE_CAPABILITY_EXTENSION),\n\t\t /** Any compute extension with side-effects */\n\t\tUNSAFE_EXTENSION(NotesConstants.COMPUTE_CAPABILITY_UNSAFE_EXTENSION),\n\t\t/** Built-in compute extensions */\n\t\tFALLBACK_EXT(NotesConstants.COMPUTE_CAPABILITY_FALLBACK_EXT),\n\t\t/**\tUnsafe is any @func that creates/modifies anything (i.e. not \"read only\") */\n\t\tUNSAFE(NotesConstants.COMPUTE_CAPABILITY_UNSAFE);\n\t\t\n\t\tprivate final int m_value;\n\t\t\n\t\tprivate Disallow(int value) {\n\t\t\tm_value = value;\n\t\t}\n\t\t\n\t\tpublic int getValue() {\n\t\t\treturn m_value;\n\t\t}\n\t}\n\t\n\tprivate String m_formula;\n\t\n\tprivate long m_hFormula64;\n\tprivate long m_hCompute64;\n\t\n\tprivate int m_hFormula32;\n\tprivate int m_hCompute32;\n\t\n\tprivate int m_compiledFormulaLength;\n\t\n\tprivate Pointer m_ptrCompiledFormula;\n\t\n\tprivate Boolean m_preferNotesTimeDates;\n\tprivate Set m_disallowedActions = new HashSet<>();\n\t\n\t/**\n\t * Creates a new instance. The constructure compiles the formula and throws a {@link FormulaCompilationError},\n\t * if there are any compilation errors\n\t * \n\t * @param formula formula\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic FormulaExecution(String formula) throws FormulaCompilationError {\n\t\tm_formula = formula;\n\t\t\n\t\tMemory formulaName = null;\n\t\tshort formulaNameLength = 0;\n\t\tMemory formulaText = NotesStringUtils.toLMBCS(formula, false, false);\n\t\tshort formulaTextLength = (short) formulaText.size();\n\n\t\tshort computeFlags = 0;\n\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tm_hFormula64 = 0;\n\t\t\t\n\t\t\tLongByReference rethFormula = new LongByReference();\n\t\t\tShortByReference retFormulaLength = new ShortByReference();\n\t\t\tShortByReference retCompileError = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLine = new ShortByReference();\n\t\t\tShortByReference retCompileErrorColumn = new ShortByReference();\n\t\t\tShortByReference retCompileErrorOffset = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLength = new ShortByReference();\n\t\t\t\n\t\t\tshort result = NotesNativeAPI64.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText,\n\t\t\t\t\tformulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine,\n\t\t\t\t\tretCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength);\n\n\t\t\tif (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) {\n\t\t\t\tString errMsg = NotesErrorUtils.errToString(result);\n\n\t\t\t\tthrow new FormulaCompilationError(result, errMsg, formula,\n\t\t\t\t\t\tretCompileError.getValue(),\n\t\t\t\t\t\tretCompileErrorLine.getValue(),\n\t\t\t\t\t\tretCompileErrorColumn.getValue(),\n\t\t\t\t\t\tretCompileErrorOffset.getValue(),\n\t\t\t\t\t\tretCompileErrorLength.getValue());\n\t\t\t}\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\tm_hFormula64 = rethFormula.getValue();\n\t\t\tm_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff);\n\t\t\t\n\t\t\tLongByReference rethCompute = new LongByReference();\n\t\t\t\n\t\t\tm_ptrCompiledFormula = Mem64.OSLockObject(m_hFormula64);\n\t\t\t\n\t\t\tresult = NotesNativeAPI64.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tm_hCompute64 = rethCompute.getValue();\n\t\t\t\n\t\t\tNotesGC.__objectCreated(FormulaExecution.class, this);\n\t\t}\n\t\telse {\n\t\t\tm_hFormula32 = 0;\n\t\t\t\n\t\t\tIntByReference rethFormula = new IntByReference();\n\t\t\tShortByReference retFormulaLength = new ShortByReference();\n\t\t\tShortByReference retCompileError = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLine = new ShortByReference();\n\t\t\tShortByReference retCompileErrorColumn = new ShortByReference();\n\t\t\tShortByReference retCompileErrorOffset = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLength = new ShortByReference();\n\n\t\t\tshort result = NotesNativeAPI32.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText,\n\t\t\t\t\tformulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine,\n\t\t\t\t\tretCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength);\n\n\t\t\tif (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) {\n\t\t\t\tString errMsg = NotesErrorUtils.errToString(result);\n\n\t\t\t\tthrow new FormulaCompilationError(result, errMsg, formula,\n\t\t\t\t\t\tretCompileError.getValue(),\n\t\t\t\t\t\tretCompileErrorLine.getValue(),\n\t\t\t\t\t\tretCompileErrorColumn.getValue(),\n\t\t\t\t\t\tretCompileErrorOffset.getValue(),\n\t\t\t\t\t\tretCompileErrorLength.getValue());\n\t\t\t}\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\tm_hFormula32 = rethFormula.getValue();\n\t\t\tm_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff);\n\t\t\t\n\t\t\tIntByReference rethCompute = new IntByReference();\n\t\t\t\n\t\t\tm_ptrCompiledFormula = Mem32.OSLockObject(m_hFormula32);\n\t\t\t\n\t\t\tresult = NotesNativeAPI32.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tm_hCompute32 = rethCompute.getValue();\n\n\t\t\tNotesGC.__objectCreated(FormulaExecution.class, this);\n\t\t}\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic T getAdapter(Class clazz) {\n\t\tcheckHandle();\n\t\t\n\t\tif (clazz == byte[].class) {\n\t\t\t//return compiled formula as byte array\n\t\t\tbyte[] compiledFormula = m_ptrCompiledFormula.getByteArray(0, m_compiledFormulaLength);\n\t\t\treturn (T) compiledFormula;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic String getFormula() {\n\t\treturn m_formula;\n\t}\n\t\n\t/**\n\t * Sets whether date/time values returned by the executed formulas should be\n\t * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}.\n\t * \n\t * @param b true to prefer NotesTimeDate (false by default)\n\t * @return this instance\n\t */\n\tpublic FormulaExecution setPreferNotesTimeDates(boolean b) {\n\t\tm_preferNotesTimeDates = b;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Returns whether date/time values returned by the executed formulas should be\n\t * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}.\n\t * \n\t * @return true to prefer NotesTimeDate\n\t */\n\tpublic boolean isPreferNotesTimeDates() {\n\t\tif (m_preferNotesTimeDates==null) {\n\t\t\treturn NotesGC.isPreferNotesTimeDate();\n\t\t}\n\t\treturn m_preferNotesTimeDates.booleanValue();\n\t}\n\t\n\t/**\n\t * Blocks execution of certain unsafe actions\n\t * \n\t * @param val action\n\t * @return this instance\n\t */\n\tpublic FormulaExecution disallow(Disallow val) {\n\t\tm_disallowedActions.add(val);\n\t\treturn this;\n\t}\n\t\n\tpublic boolean isDisallowed(Disallow val) {\n\t\treturn m_disallowedActions.contains(val);\n\t}\n\t\n\tpublic String toString() {\n\t\tif (isRecycled()) {\n\t\t\treturn \"Compiled formula [recycled, formula=\"+m_formula+\"]\";\n\t\t}\n\t\telse {\n\t\t\treturn \"Compiled formula [formula=\"+m_formula+\"]\";\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to execute a formula on a single note and return the result as a string.
\n\t *
\n\t * Please note:
\n\t * If the same formula should be run\n\t * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution}\n\t * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only\n\t * once, which results in better performance and optimized memory usage.
\n\t * \n\t * @param formula formula\n\t * @param note note\n\t * @return computation result as string; if the formula returns a list, we pick the first value\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic static String evaluateAsString(String formula, NotesNote note) throws FormulaCompilationError {\n\t\tList result = evaluate(formula, note);\n\t\tif (result.isEmpty())\n\t\t\treturn \"\";\n\t\telse {\n\t\t\treturn result.get(0).toString();\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to execute a formula on a single note.
\n\t *
\n\t * Please note:
\n\t * If the same formula should be run\n\t * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution}\n\t * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only\n\t * once, which results in better performance and optimized memory usage.
\n\t * \n\t * @param formula formula\n\t * @param note note\n\t * @return computation result\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic static List evaluate(String formula, NotesNote note) throws FormulaCompilationError {\n\t\tFormulaExecution instance = new FormulaExecution(formula);\n\t\ttry {\n\t\t\tList result = instance.evaluate(note);\n\t\t\treturn result;\n\t\t}\n\t\tfinally {\n\t\t\tinstance.recycle();\n\t\t}\n\t}\n\n\t/**\n\t * Convenience method to execute a formula on a single note. Provides extended information.
\n\t *
\n\t * Please note:
\n\t * If the same formula should be run\n\t * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution}\n\t * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only\n\t * once, which results in better performance.
\n\t * \n\t * @param formula formula\n\t * @param note note\n\t * @return computation result\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic static FormulaExecutionResult evaluateExt(String formula, NotesNote note) throws FormulaCompilationError {\n\t\tFormulaExecution instance = new FormulaExecution(formula);\n\t\ttry {\n\t\t\tFormulaExecutionResult result = instance.evaluateExt(note);\n\t\t\treturn result;\n\t\t}\n\t\tfinally {\n\t\t\tinstance.recycle();\n\t\t}\n\t}\n\t\n\tprivate void checkHandle() {\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (m_hCompute64==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t\tif (m_hFormula64==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (m_hCompute32==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t\tif (m_hFormula32==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate List parseFormulaResult(Pointer valuePtr, int valueLength) {\n\t\tshort dataType = valuePtr.getShort(0);\n\t\tint dataTypeAsInt = (int) (dataType & 0xffff);\n\t\t\n\t\tboolean supportedType = false;\n\t\tif (dataTypeAsInt == NotesItem.TYPE_TEXT) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_ERROR) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\t\n\t\tif (!supportedType) {\n\t\t\tthrow new UnsupportedItemValueError(\"Data type is currently unsupported: \"+dataTypeAsInt);\n\t\t}\n\n\t\tint checkDataType = valuePtr.getShort(0) & 0xffff;\n\t\tPointer valueDataPtr = valuePtr.share(2);\n\t\tint valueDataLength = valueLength - 2;\n\t\t\n\t\tif (checkDataType!=dataTypeAsInt) {\n\t\t\tthrow new IllegalStateException(\"Value data type does not meet expected date type: found \"+checkDataType+\", expected \"+dataTypeAsInt);\n\t\t}\n\t\tif (dataTypeAsInt == NotesItem.TYPE_TEXT) {\n\t\t\tString txtVal = (String) ItemDecoder.decodeTextValue(valueDataPtr, valueDataLength, false);\n\t\t\treturn txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal);\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) {\n\t\t\tList textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(valueDataPtr, false);\n\t\t\treturn textList==null ? Collections.emptyList() : textList;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER) {\n\t\t\tdouble numVal = ItemDecoder.decodeNumber(valueDataPtr, valueDataLength);\n\t\t\treturn Arrays.asList((Object) Double.valueOf(numVal));\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) {\n\t\t\tList numberList = ItemDecoder.decodeNumberList(valueDataPtr, valueDataLength);\n\t\t\treturn numberList==null ? Collections.emptyList() : numberList;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME) {\n\t\t\tif (isPreferNotesTimeDates()) {\n\t\t\t\tNotesTimeDate td = ItemDecoder.decodeTimeDateAsNotesTimeDate(valueDataPtr, valueDataLength);\n\t\t\t\treturn td==null ? Collections.emptyList() : Arrays.asList((Object) td);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tCalendar cal = ItemDecoder.decodeTimeDate(valueDataPtr, valueDataLength);\n\t\t\t\treturn cal==null ? Collections.emptyList() : Arrays.asList((Object) cal);\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) {\n\t\t\tif (isPreferNotesTimeDates()) {\n\t\t\t\tList tdValues = ItemDecoder.decodeTimeDateListAsNotesTimeDate(valueDataPtr);\n\t\t\t\treturn tdValues==null ? Collections.emptyList() : tdValues;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tList calendarValues = ItemDecoder.decodeTimeDateList(valueDataPtr);\n\t\t\t\treturn calendarValues==null ? Collections.emptyList() : calendarValues;\n\t\t\t}\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) {\n\t\t\t//e.g. returned by formula \"@DeleteDocument\"\n\t\t\treturn Collections.emptyList();\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_ERROR) {\n\t\t\tif (valueLength>=2) {\n\t\t\t\tshort formulaErrorCode = valueDataPtr.getShort(0);\n\t\t\t\tString errMsg = NotesErrorUtils.errToString(formulaErrorCode);\n\t\t\t\tthrow new NotesError(formulaErrorCode, \"Could not evaluate formula \"+m_formula+\"\\nError: \"+errMsg);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new NotesError(0, \"Could not evaluate formula \"+m_formula);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new UnsupportedItemValueError(\"Data is currently unsupported: \"+dataTypeAsInt);\n\t\t}\n\t}\n\n\t/**\n\t * Evaluates the formula on a note\n\t * \n\t * @param note note\n\t * @return formula computation result\n\t */\n\tpublic List evaluate(NotesNote note) {\n\t\treturn evaluateExt(note).getValue();\n\t}\n\n\t/**\n\t * Evaluates the formula on a note. Provides extended information.\n\t * \n\t * @param note note to be used as additional variables available to the formula or null\n\t * @return formula computation result with flags\n\t */\n\tpublic FormulaExecutionResult evaluateExt(NotesNote note) {\n\t\tcheckHandle();\n\n\t\tif (note!=null) {\n\t\t\tif (note.isRecycled()) {\n\t\t\t\tthrow new NotesError(0, \"Note is already recycled\");\n\t\t\t}\n\t\t}\n\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (!m_disallowedActions.isEmpty()) {\n\t\t\t\tint disallowedFlags = 0;\n\t\t\t\tfor (Disallow currAction : m_disallowedActions) {\n\t\t\t\t\tdisallowedFlags |= currAction.getValue();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tNotesNativeAPI64.get().NSFComputeSetDisallowFlags(m_hCompute64, disallowedFlags);\n\t\t\t}\n\t\t\t\n\t\t\tLongByReference rethResult = new LongByReference();\n\t\t\tIntByReference retResultLength = new IntByReference();\n\t\t\tIntByReference retNoteMatchesFormula = new IntByReference();\n\t\t\tIntByReference retNoteShouldBeDeleted = new IntByReference();\n\t\t\tIntByReference retNoteModified = new IntByReference();\n\n\t\t\t//NSFComputeEvaluateExt supports more than the usual 64K of formula result data\n\t\t\tfinal int retDWordResultLength = 1;\n\t\t\tshort result = NotesNativeAPI64.get().NSFComputeEvaluateExt(m_hCompute64, note==null ? 0 : note.getHandle64(), rethResult, retResultLength, retDWordResultLength,\n\t\t\t\t\tretNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified\n\t\t\t\t\t);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tint valueLength = retResultLength.getValue();\n\n\t\t\tList formulaResult = null;\n\t\t\t\n\t\t\tlong hResult = rethResult.getValue();\n\t\t\tif (hResult!=0) {\n\t\t\t\tPointer valuePtr = Mem64.OSLockObject(hResult);\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tformulaResult = parseFormulaResult(valuePtr, valueLength);\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tMem64.OSUnlockObject(hResult);\n\t\t\t\t\tresult = Mem64.OSMemFree(hResult);\n\t\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalStateException(\"got a null handle as computation result\");\n\t\t\t}\n\t\t\t\n\t\t\treturn new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1,\n\t\t\t\t\tretNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1);\n\t\t}\n\t\telse {\n\t\t\tif (!m_disallowedActions.isEmpty()) {\n\t\t\t\tint disallowedFlags = 0;\n\t\t\t\tfor (Disallow currAction : m_disallowedActions) {\n\t\t\t\t\tdisallowedFlags |= currAction.getValue();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tNotesNativeAPI64.get().NSFComputeSetDisallowFlags(m_hCompute64, disallowedFlags);\n\t\t\t}\n\n\t\t\tIntByReference rethResult = new IntByReference();\n\t\t\tIntByReference retResultLength = new IntByReference();\n\t\t\tIntByReference retNoteMatchesFormula = new IntByReference();\n\t\t\tIntByReference retNoteShouldBeDeleted = new IntByReference();\n\t\t\tIntByReference retNoteModified = new IntByReference();\n\n\t\t\t//NSFComputeEvaluateExt supports more than the usual 64K of formula result data\n\t\t\tfinal int retDWordResultLength = 1;\n\t\t\tshort result = NotesNativeAPI32.get().NSFComputeEvaluateExt(m_hCompute32, note==null ? 0 : note.getHandle32(), rethResult, retResultLength, retDWordResultLength,\n\t\t\t\t\tretNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified\n\t\t\t\t\t);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tList formulaResult = null;\n\t\t\t\n\t\t\tint hResult = rethResult.getValue();\n\t\t\tif (hResult!=0) {\n\t\t\t\tPointer valuePtr = Mem32.OSLockObject(hResult);\n\t\t\t\tint valueLength = retResultLength.getValue();\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tformulaResult = parseFormulaResult(valuePtr, valueLength);\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tMem32.OSUnlockObject(hResult);\n\t\t\t\t\tresult = Mem32.OSMemFree(hResult);\n\t\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalStateException(\"got a null handle as computation result\");\n\t\t\t}\n\t\t\t\n\t\t\treturn new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1,\n\t\t\t\t\tretNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1);\n\t\t}\n\t}\n\t\n\t/**\n\t * Formula computation result\n\t * \n\t * @author Karsten Lehmann\n\t */\n\tpublic static class FormulaExecutionResult {\n\t\tprivate List m_result;\n\t\tprivate boolean m_matchesFormula;\n\t\tprivate boolean m_shouldBeDeleted;\n\t\tprivate boolean m_noteModified;\n\t\t\n\t\tpublic FormulaExecutionResult(List result, boolean matchesFormula, boolean shouldBeDeleted, boolean noteModified) {\n\t\t\tm_result = result;\n\t\t\tm_matchesFormula = matchesFormula;\n\t\t\tm_shouldBeDeleted = shouldBeDeleted;\n\t\t\tm_noteModified = noteModified;\n\t\t}\n\t\t\n\t\tpublic List getValue() {\n\t\t\treturn m_result;\n\t\t}\n\t\t\n\t\tpublic boolean matchesFormula() {\n\t\t\treturn m_matchesFormula;\n\t\t}\n\t\t\n\t\tpublic boolean shouldBeDeleted() {\n\t\t\treturn m_shouldBeDeleted;\n\t\t}\n\t\t\n\t\tpublic boolean isNoteModified() {\n\t\t\treturn m_noteModified;\n\t\t}\n\t\t\n\t}\n\n\t@Override\n\tpublic void recycle() {\n\t\tif (isRecycled())\n\t\t\treturn;\n\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (m_hCompute64!=0) {\n\t\t\t\tshort result = NotesNativeAPI64.get().NSFComputeStop(m_hCompute64);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\tm_hCompute64=0;\n\t\t\t}\n\t\t\tif (m_hFormula64!=0) {\n\t\t\t\tMem64.OSUnlockObject(m_hFormula64);\n\t\t\t\tshort result = Mem64.OSMemFree(m_hFormula64);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t\n\t\t\t\tNotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this);\n\t\t\t\tm_hFormula64 = 0;\n\t\t\t\tm_ptrCompiledFormula=null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (m_hCompute32!=0) {\n\t\t\t\tshort result = NotesNativeAPI32.get().NSFComputeStop(m_hCompute32);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\tm_hCompute32=0;\n\t\t\t}\n\t\t\tif (m_hFormula32!=0) {\n\t\t\t\tMem32.OSUnlockObject(m_hFormula32);\n\t\t\t\tshort result = Mem32.OSMemFree(m_hFormula32);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t\n\t\t\t\tNotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this);\n\t\t\t\tm_hFormula32 = 0;\n\t\t\t\tm_ptrCompiledFormula=null;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isRecycled() {\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (m_hFormula64==0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (m_hFormula32==0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isNoRecycle() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int getHandle32() {\n\t\treturn m_hFormula32;\n\t}\n\n\t@Override\n\tpublic long getHandle64() {\n\t\treturn m_hFormula64;\n\t}\n\t\n\tpublic DHANDLE getHandle() {\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\treturn DHANDLE64.newInstance(m_hFormula64);\n\t\t}\n\t\telse {\n\t\t\treturn DHANDLE32.newInstance(m_hFormula32);\n\t\t}\n\t}\n\t\n\t/**\n\t * Returns a list of all registered (public) formula functions. Use {@link #getFunctionParameters(String)}\n\t * to get a list of function parameters.\n\t * \n\t * @return functions, e.g. \"@Left(\"\n\t */\n\tpublic static List getAllFunctions() {\n\t\tList retNames = new ArrayList<>();\n\t\t\n\t\tNSFFORMFUNCPROC callback;\n\t\tif (PlatformUtils.isWin32()) {\n\t\t\tcallback = new NSFFORMFUNCPROCWin32() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\telse {\n\t\t\tcallback = new NSFFORMFUNCPROC() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\tshort result = NotesNativeAPI.get().NSFFormulaFunctions(callback);\n\t\tNotesErrorUtils.checkResult(result);\n\t\t\n\t\treturn retNames;\n\t}\n\n\t/**\n\t * Returns a list of all registered (public) formula commands. Use {@link #getFunctionParameters(String)}\n\t * to get a list of command parameters.\n\t * \n\t * @return commands, e.g. \"MailSend\"\n\t */\n\tpublic static List getAllCommands() {\n\t\tList retNames = new ArrayList<>();\n\t\t\n\t\tNSFFORMCMDSPROC callback;\n\t\tif (PlatformUtils.isWin32()) {\n\t\t\tcallback = new NSFFORMCMDSPROCWin32() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr, short code, IntByReference stopFlag) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\telse {\n\t\t\tcallback = new NSFFORMCMDSPROC() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr, short code, IntByReference stopFlag) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\tshort result = NotesNativeAPI.get().NSFFormulaCommands(callback);\n\t\tNotesErrorUtils.checkResult(result);\n\t\t\n\t\treturn retNames;\n\t}\n\t\n\tpublic static class FormulaAnalyzeResult {\n\t\tprivate EnumSet attributes;\n\t\t\n\t\tprivate FormulaAnalyzeResult(EnumSet attributes) {\n\t\t\tthis.attributes = attributes;\n\t\t}\n\t\t\n\t\tpublic Set getAttributes() {\n\t\t\treturn Collections.unmodifiableSet(this.attributes);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"FormulaAnalyzeResult [attributes=\" + attributes + \"]\";\n\t\t}\n\t\t\n\t}\n\n\t/**\n\t * Scan through the function table (ftable) or keyword table (ktable)\n\t * to find parameters of an @ function or an @ command.\n\t * \n\t * @param formulaName name returned by {@link FormulaExecution#getAllFunctions()}, e.g. \"@Left(\"\n\t * @return function parameters, e.g. \"stringToSearch; numberOfChars)stringToSearch; subString)\" for the function \"@Left(\"\n\t */\n\tpublic static List getFunctionParameters(String formulaName) {\n\t\tMemory formulaMem = NotesStringUtils.toLMBCS(formulaName, true);\n\t\tPointer ptr = NotesNativeAPI.get().NSFFindFormulaParameters(formulaMem);\n\t\tif (ptr==null) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\t\telse {\n\t\t\t//example format for @Middle(:\n\t\t\t//string; offset; numberchars)string; offset; endstring)string; startString; endstring)string; startString; numberchars)\n\t\t\tList params = new ArrayList<>();\n\t\t\tString paramsConc = NotesStringUtils.fromLMBCS(ptr, -1);\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tfor (int i=0; i attributes = FormulaAttributes.toFormulaAttributes(retAttributes.getValue());\n\t\treturn new FormulaAnalyzeResult(attributes);\n\t}\n\t\n}\n"},"new_file":{"kind":"string","value":"domino-jna/src/main/java/com/mindoo/domino/jna/formula/FormulaExecution.java"},"old_contents":{"kind":"string","value":"package com.mindoo.domino.jna.formula;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport com.mindoo.domino.jna.IAdaptable;\nimport com.mindoo.domino.jna.NotesItem;\nimport com.mindoo.domino.jna.NotesNote;\nimport com.mindoo.domino.jna.NotesTimeDate;\nimport com.mindoo.domino.jna.constants.FormulaAttributes;\nimport com.mindoo.domino.jna.errors.FormulaCompilationError;\nimport com.mindoo.domino.jna.errors.INotesErrorConstants;\nimport com.mindoo.domino.jna.errors.NotesError;\nimport com.mindoo.domino.jna.errors.NotesErrorUtils;\nimport com.mindoo.domino.jna.errors.UnsupportedItemValueError;\nimport com.mindoo.domino.jna.gc.IRecyclableNotesObject;\nimport com.mindoo.domino.jna.gc.NotesGC;\nimport com.mindoo.domino.jna.internal.ItemDecoder;\nimport com.mindoo.domino.jna.internal.Mem32;\nimport com.mindoo.domino.jna.internal.Mem64;\nimport com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMCMDSPROC;\nimport com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMFUNCPROC;\nimport com.mindoo.domino.jna.internal.NotesNativeAPI;\nimport com.mindoo.domino.jna.internal.NotesNativeAPI32;\nimport com.mindoo.domino.jna.internal.NotesNativeAPI64;\nimport com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMCMDSPROCWin32;\nimport com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMFUNCPROCWin32;\nimport com.mindoo.domino.jna.internal.handles.DHANDLE;\nimport com.mindoo.domino.jna.internal.handles.DHANDLE32;\nimport com.mindoo.domino.jna.internal.handles.DHANDLE64;\nimport com.mindoo.domino.jna.utils.NotesStringUtils;\nimport com.mindoo.domino.jna.utils.PlatformUtils;\nimport com.sun.jna.Memory;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.ptr.IntByReference;\nimport com.sun.jna.ptr.LongByReference;\nimport com.sun.jna.ptr.ShortByReference;\n\n/**\n * Utility class to execute a Domino formula on one or more {@link NotesNote} objects.
\n *
\n * The implementation supports more than the usual 64K of return value, e.g. to use\n * @DBColumn to read the column values in views with many entries.\n * \n * @author Karsten Lehmann\n */\npublic class FormulaExecution implements IRecyclableNotesObject, IAdaptable {\n\tprivate String m_formula;\n\t\n\tprivate long m_hFormula64;\n\tprivate long m_hCompute64;\n\t\n\tprivate int m_hFormula32;\n\tprivate int m_hCompute32;\n\t\n\tprivate int m_compiledFormulaLength;\n\t\n\tprivate Pointer m_ptrCompiledFormula;\n\t\n\tprivate boolean m_preferNotesTimeDates;\n\n\t/**\n\t * Creates a new instance. The constructure compiles the formula and throws a {@link FormulaCompilationError},\n\t * if there are any compilation errors\n\t * \n\t * @param formula formula\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic FormulaExecution(String formula) throws FormulaCompilationError {\n\t\tm_formula = formula;\n\t\t\n\t\tMemory formulaName = null;\n\t\tshort formulaNameLength = 0;\n\t\tMemory formulaText = NotesStringUtils.toLMBCS(formula, false, false);\n\t\tshort formulaTextLength = (short) formulaText.size();\n\n\t\tshort computeFlags = 0;\n\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tm_hFormula64 = 0;\n\t\t\t\n\t\t\tLongByReference rethFormula = new LongByReference();\n\t\t\tShortByReference retFormulaLength = new ShortByReference();\n\t\t\tShortByReference retCompileError = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLine = new ShortByReference();\n\t\t\tShortByReference retCompileErrorColumn = new ShortByReference();\n\t\t\tShortByReference retCompileErrorOffset = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLength = new ShortByReference();\n\t\t\t\n\t\t\tshort result = NotesNativeAPI64.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText,\n\t\t\t\t\tformulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine,\n\t\t\t\t\tretCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength);\n\n\t\t\tif (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) {\n\t\t\t\tString errMsg = NotesErrorUtils.errToString(result);\n\n\t\t\t\tthrow new FormulaCompilationError(result, errMsg, formula,\n\t\t\t\t\t\tretCompileError.getValue(),\n\t\t\t\t\t\tretCompileErrorLine.getValue(),\n\t\t\t\t\t\tretCompileErrorColumn.getValue(),\n\t\t\t\t\t\tretCompileErrorOffset.getValue(),\n\t\t\t\t\t\tretCompileErrorLength.getValue());\n\t\t\t}\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\tm_hFormula64 = rethFormula.getValue();\n\t\t\tm_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff);\n\t\t\t\n\t\t\tLongByReference rethCompute = new LongByReference();\n\t\t\t\n\t\t\tm_ptrCompiledFormula = Mem64.OSLockObject(m_hFormula64);\n\t\t\t\n\t\t\tresult = NotesNativeAPI64.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tm_hCompute64 = rethCompute.getValue();\n\t\t\t\n\t\t\tNotesGC.__objectCreated(FormulaExecution.class, this);\n\t\t}\n\t\telse {\n\t\t\tm_hFormula32 = 0;\n\t\t\t\n\t\t\tIntByReference rethFormula = new IntByReference();\n\t\t\tShortByReference retFormulaLength = new ShortByReference();\n\t\t\tShortByReference retCompileError = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLine = new ShortByReference();\n\t\t\tShortByReference retCompileErrorColumn = new ShortByReference();\n\t\t\tShortByReference retCompileErrorOffset = new ShortByReference();\n\t\t\tShortByReference retCompileErrorLength = new ShortByReference();\n\n\t\t\tshort result = NotesNativeAPI32.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText,\n\t\t\t\t\tformulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine,\n\t\t\t\t\tretCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength);\n\n\t\t\tif (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) {\n\t\t\t\tString errMsg = NotesErrorUtils.errToString(result);\n\n\t\t\t\tthrow new FormulaCompilationError(result, errMsg, formula,\n\t\t\t\t\t\tretCompileError.getValue(),\n\t\t\t\t\t\tretCompileErrorLine.getValue(),\n\t\t\t\t\t\tretCompileErrorColumn.getValue(),\n\t\t\t\t\t\tretCompileErrorOffset.getValue(),\n\t\t\t\t\t\tretCompileErrorLength.getValue());\n\t\t\t}\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\tm_hFormula32 = rethFormula.getValue();\n\t\t\tm_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff);\n\t\t\t\n\t\t\tIntByReference rethCompute = new IntByReference();\n\t\t\t\n\t\t\tm_ptrCompiledFormula = Mem32.OSLockObject(m_hFormula32);\n\t\t\t\n\t\t\tresult = NotesNativeAPI32.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tm_hCompute32 = rethCompute.getValue();\n\n\t\t\tNotesGC.__objectCreated(FormulaExecution.class, this);\n\t\t}\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic T getAdapter(Class clazz) {\n\t\tcheckHandle();\n\t\t\n\t\tif (clazz == byte[].class) {\n\t\t\t//return compiled formula as byte array\n\t\t\tbyte[] compiledFormula = m_ptrCompiledFormula.getByteArray(0, m_compiledFormulaLength);\n\t\t\treturn (T) compiledFormula;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic String getFormula() {\n\t\treturn m_formula;\n\t}\n\t\n\t/**\n\t * Sets whether date/time values returned by the executed formulas should be\n\t * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}.\n\t * \n\t * @param b true to prefer NotesTimeDate (false by default)\n\t */\n\tpublic void setPreferNotesTimeDates(boolean b) {\n\t\tm_preferNotesTimeDates = b;\n\t}\n\t\n\t/**\n\t * Returns whether date/time values returned by the executed formulas should be\n\t * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}.\n\t * \n\t * @return true to prefer NotesTimeDate\n\t */\n\tpublic boolean isPreferNotesTimeDates() {\n\t\treturn m_preferNotesTimeDates;\n\t}\n\t\n\tpublic String toString() {\n\t\tif (isRecycled()) {\n\t\t\treturn \"Compiled formula [recycled, formula=\"+m_formula+\"]\";\n\t\t}\n\t\telse {\n\t\t\treturn \"Compiled formula [formula=\"+m_formula+\"]\";\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to execute a formula on a single note and return the result as a string.
\n\t *
\n\t * Please note:
\n\t * If the same formula should be run\n\t * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution}\n\t * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only\n\t * once, which results in better performance and optimized memory usage.
\n\t * \n\t * @param formula formula\n\t * @param note note\n\t * @return computation result as string; if the formula returns a list, we pick the first value\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic static String evaluateAsString(String formula, NotesNote note) throws FormulaCompilationError {\n\t\tList result = evaluate(formula, note);\n\t\tif (result.isEmpty())\n\t\t\treturn \"\";\n\t\telse {\n\t\t\treturn result.get(0).toString();\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to execute a formula on a single note.
\n\t *
\n\t * Please note:
\n\t * If the same formula should be run\n\t * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution}\n\t * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only\n\t * once, which results in better performance and optimized memory usage.
\n\t * \n\t * @param formula formula\n\t * @param note note\n\t * @return computation result\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic static List evaluate(String formula, NotesNote note) throws FormulaCompilationError {\n\t\tFormulaExecution instance = new FormulaExecution(formula);\n\t\ttry {\n\t\t\tList result = instance.evaluate(note);\n\t\t\treturn result;\n\t\t}\n\t\tfinally {\n\t\t\tinstance.recycle();\n\t\t}\n\t}\n\n\t/**\n\t * Convenience method to execute a formula on a single note. Provides extended information.
\n\t *
\n\t * Please note:
\n\t * If the same formula should be run\n\t * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution}\n\t * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only\n\t * once, which results in better performance.
\n\t * \n\t * @param formula formula\n\t * @param note note\n\t * @return computation result\n\t * @throws FormulaCompilationError if formula has wrong syntax\n\t */\n\tpublic static FormulaExecutionResult evaluateExt(String formula, NotesNote note) throws FormulaCompilationError {\n\t\tFormulaExecution instance = new FormulaExecution(formula);\n\t\ttry {\n\t\t\tFormulaExecutionResult result = instance.evaluateExt(note);\n\t\t\treturn result;\n\t\t}\n\t\tfinally {\n\t\t\tinstance.recycle();\n\t\t}\n\t}\n\t\n\tprivate void checkHandle() {\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (m_hCompute64==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t\tif (m_hFormula64==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (m_hCompute32==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t\tif (m_hFormula32==0) {\n\t\t\t\tthrow new NotesError(0, \"Object already recycled\");\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate List parseFormulaResult(Pointer valuePtr, int valueLength) {\n\t\tshort dataType = valuePtr.getShort(0);\n\t\tint dataTypeAsInt = (int) (dataType & 0xffff);\n\t\t\n\t\tboolean supportedType = false;\n\t\tif (dataTypeAsInt == NotesItem.TYPE_TEXT) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_ERROR) {\n\t\t\tsupportedType = true;\n\t\t}\n\t\t\n\t\tif (!supportedType) {\n\t\t\tthrow new UnsupportedItemValueError(\"Data type is currently unsupported: \"+dataTypeAsInt);\n\t\t}\n\n\t\tint checkDataType = valuePtr.getShort(0) & 0xffff;\n\t\tPointer valueDataPtr = valuePtr.share(2);\n\t\tint valueDataLength = valueLength - 2;\n\t\t\n\t\tif (checkDataType!=dataTypeAsInt) {\n\t\t\tthrow new IllegalStateException(\"Value data type does not meet expected date type: found \"+checkDataType+\", expected \"+dataTypeAsInt);\n\t\t}\n\t\tif (dataTypeAsInt == NotesItem.TYPE_TEXT) {\n\t\t\tString txtVal = (String) ItemDecoder.decodeTextValue(valueDataPtr, valueDataLength, false);\n\t\t\treturn txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal);\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) {\n\t\t\tList textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(valueDataPtr, false);\n\t\t\treturn textList==null ? Collections.emptyList() : textList;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER) {\n\t\t\tdouble numVal = ItemDecoder.decodeNumber(valueDataPtr, valueDataLength);\n\t\t\treturn Arrays.asList((Object) Double.valueOf(numVal));\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) {\n\t\t\tList numberList = ItemDecoder.decodeNumberList(valueDataPtr, valueDataLength);\n\t\t\treturn numberList==null ? Collections.emptyList() : numberList;\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME) {\n\t\t\tif (isPreferNotesTimeDates()) {\n\t\t\t\tNotesTimeDate td = ItemDecoder.decodeTimeDateAsNotesTimeDate(valueDataPtr, valueDataLength);\n\t\t\t\treturn td==null ? Collections.emptyList() : Arrays.asList((Object) td);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tCalendar cal = ItemDecoder.decodeTimeDate(valueDataPtr, valueDataLength);\n\t\t\t\treturn cal==null ? Collections.emptyList() : Arrays.asList((Object) cal);\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) {\n\t\t\tif (isPreferNotesTimeDates()) {\n\t\t\t\tList tdValues = ItemDecoder.decodeTimeDateListAsNotesTimeDate(valueDataPtr);\n\t\t\t\treturn tdValues==null ? Collections.emptyList() : tdValues;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tList calendarValues = ItemDecoder.decodeTimeDateList(valueDataPtr);\n\t\t\t\treturn calendarValues==null ? Collections.emptyList() : calendarValues;\n\t\t\t}\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) {\n\t\t\t//e.g. returned by formula \"@DeleteDocument\"\n\t\t\treturn Collections.emptyList();\n\t\t}\n\t\telse if (dataTypeAsInt == NotesItem.TYPE_ERROR) {\n\t\t\tif (valueLength>=2) {\n\t\t\t\tshort formulaErrorCode = valueDataPtr.getShort(0);\n\t\t\t\tString errMsg = NotesErrorUtils.errToString(formulaErrorCode);\n\t\t\t\tthrow new NotesError(formulaErrorCode, \"Could not evaluate formula \"+m_formula+\"\\nError: \"+errMsg);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new NotesError(0, \"Could not evaluate formula \"+m_formula);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new UnsupportedItemValueError(\"Data is currently unsupported: \"+dataTypeAsInt);\n\t\t}\n\t}\n\n\t/**\n\t * Evaluates the formula on a note\n\t * \n\t * @param note note\n\t * @return formula computation result\n\t */\n\tpublic List evaluate(NotesNote note) {\n\t\treturn evaluateExt(note).getValue();\n\t}\n\n\t/**\n\t * Evaluates the formula on a note. Provides extended information.\n\t * \n\t * @param note note to be used as additional variables available to the formula or null\n\t * @return formula computation result with flags\n\t */\n\tpublic FormulaExecutionResult evaluateExt(NotesNote note) {\n\t\tcheckHandle();\n\n\t\tif (note!=null) {\n\t\t\tif (note.isRecycled()) {\n\t\t\t\tthrow new NotesError(0, \"Note is already recycled\");\n\t\t\t}\n\t\t}\n\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tLongByReference rethResult = new LongByReference();\n\t\t\tIntByReference retResultLength = new IntByReference();\n\t\t\tIntByReference retNoteMatchesFormula = new IntByReference();\n\t\t\tIntByReference retNoteShouldBeDeleted = new IntByReference();\n\t\t\tIntByReference retNoteModified = new IntByReference();\n\n\t\t\t//NSFComputeEvaluateExt supports more than the usual 64K of formula result data\n\t\t\tfinal int retDWordResultLength = 1;\n\t\t\tshort result = NotesNativeAPI64.get().NSFComputeEvaluateExt(m_hCompute64, note==null ? 0 : note.getHandle64(), rethResult, retResultLength, retDWordResultLength,\n\t\t\t\t\tretNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified\n\t\t\t\t\t);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tint valueLength = retResultLength.getValue();\n\n\t\t\tList formulaResult = null;\n\t\t\t\n\t\t\tlong hResult = rethResult.getValue();\n\t\t\tif (hResult!=0) {\n\t\t\t\tPointer valuePtr = Mem64.OSLockObject(hResult);\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tformulaResult = parseFormulaResult(valuePtr, valueLength);\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tMem64.OSUnlockObject(hResult);\n\t\t\t\t\tresult = Mem64.OSMemFree(hResult);\n\t\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalStateException(\"got a null handle as computation result\");\n\t\t\t}\n\t\t\t\n\t\t\treturn new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1,\n\t\t\t\t\tretNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1);\n\t\t}\n\t\telse {\n\t\t\tIntByReference rethResult = new IntByReference();\n\t\t\tIntByReference retResultLength = new IntByReference();\n\t\t\tIntByReference retNoteMatchesFormula = new IntByReference();\n\t\t\tIntByReference retNoteShouldBeDeleted = new IntByReference();\n\t\t\tIntByReference retNoteModified = new IntByReference();\n\n\t\t\t//NSFComputeEvaluateExt supports more than the usual 64K of formula result data\n\t\t\tfinal int retDWordResultLength = 1;\n\t\t\tshort result = NotesNativeAPI32.get().NSFComputeEvaluateExt(m_hCompute32, note==null ? 0 : note.getHandle32(), rethResult, retResultLength, retDWordResultLength,\n\t\t\t\t\tretNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified\n\t\t\t\t\t);\n\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\n\t\t\tList formulaResult = null;\n\t\t\t\n\t\t\tint hResult = rethResult.getValue();\n\t\t\tif (hResult!=0) {\n\t\t\t\tPointer valuePtr = Mem32.OSLockObject(hResult);\n\t\t\t\tint valueLength = retResultLength.getValue();\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tformulaResult = parseFormulaResult(valuePtr, valueLength);\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tMem32.OSUnlockObject(hResult);\n\t\t\t\t\tresult = Mem32.OSMemFree(hResult);\n\t\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalStateException(\"got a null handle as computation result\");\n\t\t\t}\n\t\t\t\n\t\t\treturn new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1,\n\t\t\t\t\tretNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1);\n\t\t}\n\t}\n\t\n\t/**\n\t * Formula computation result\n\t * \n\t * @author Karsten Lehmann\n\t */\n\tpublic static class FormulaExecutionResult {\n\t\tprivate List m_result;\n\t\tprivate boolean m_matchesFormula;\n\t\tprivate boolean m_shouldBeDeleted;\n\t\tprivate boolean m_noteModified;\n\t\t\n\t\tpublic FormulaExecutionResult(List result, boolean matchesFormula, boolean shouldBeDeleted, boolean noteModified) {\n\t\t\tm_result = result;\n\t\t\tm_matchesFormula = matchesFormula;\n\t\t\tm_shouldBeDeleted = shouldBeDeleted;\n\t\t\tm_noteModified = noteModified;\n\t\t}\n\t\t\n\t\tpublic List getValue() {\n\t\t\treturn m_result;\n\t\t}\n\t\t\n\t\tpublic boolean matchesFormula() {\n\t\t\treturn m_matchesFormula;\n\t\t}\n\t\t\n\t\tpublic boolean shouldBeDeleted() {\n\t\t\treturn m_shouldBeDeleted;\n\t\t}\n\t\t\n\t\tpublic boolean isNoteModified() {\n\t\t\treturn m_noteModified;\n\t\t}\n\t\t\n\t}\n\n\t@Override\n\tpublic void recycle() {\n\t\tif (isRecycled())\n\t\t\treturn;\n\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (m_hCompute64!=0) {\n\t\t\t\tshort result = NotesNativeAPI64.get().NSFComputeStop(m_hCompute64);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\tm_hCompute64=0;\n\t\t\t}\n\t\t\tif (m_hFormula64!=0) {\n\t\t\t\tMem64.OSUnlockObject(m_hFormula64);\n\t\t\t\tshort result = Mem64.OSMemFree(m_hFormula64);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t\n\t\t\t\tNotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this);\n\t\t\t\tm_hFormula64 = 0;\n\t\t\t\tm_ptrCompiledFormula=null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (m_hCompute32!=0) {\n\t\t\t\tshort result = NotesNativeAPI32.get().NSFComputeStop(m_hCompute32);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\tm_hCompute32=0;\n\t\t\t}\n\t\t\tif (m_hFormula32!=0) {\n\t\t\t\tMem32.OSUnlockObject(m_hFormula32);\n\t\t\t\tshort result = Mem32.OSMemFree(m_hFormula32);\n\t\t\t\tNotesErrorUtils.checkResult(result);\n\t\t\t\t\n\t\t\t\tNotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this);\n\t\t\t\tm_hFormula32 = 0;\n\t\t\t\tm_ptrCompiledFormula=null;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isRecycled() {\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\tif (m_hFormula64==0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (m_hFormula32==0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isNoRecycle() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int getHandle32() {\n\t\treturn m_hFormula32;\n\t}\n\n\t@Override\n\tpublic long getHandle64() {\n\t\treturn m_hFormula64;\n\t}\n\t\n\tpublic DHANDLE getHandle() {\n\t\tif (PlatformUtils.is64Bit()) {\n\t\t\treturn DHANDLE64.newInstance(m_hFormula64);\n\t\t}\n\t\telse {\n\t\t\treturn DHANDLE32.newInstance(m_hFormula32);\n\t\t}\n\t}\n\t\n\t/**\n\t * Returns a list of all registered (public) formula functions. Use {@link #getFunctionParameters(String)}\n\t * to get a list of function parameters.\n\t * \n\t * @return functions, e.g. \"@Left(\"\n\t */\n\tpublic static List getAllFunctions() {\n\t\tList retNames = new ArrayList<>();\n\t\t\n\t\tNSFFORMFUNCPROC callback;\n\t\tif (PlatformUtils.isWin32()) {\n\t\t\tcallback = new NSFFORMFUNCPROCWin32() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\telse {\n\t\t\tcallback = new NSFFORMFUNCPROC() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\tshort result = NotesNativeAPI.get().NSFFormulaFunctions(callback);\n\t\tNotesErrorUtils.checkResult(result);\n\t\t\n\t\treturn retNames;\n\t}\n\n\t/**\n\t * Returns a list of all registered (public) formula commands. Use {@link #getFunctionParameters(String)}\n\t * to get a list of command parameters.\n\t * \n\t * @return commands, e.g. \"MailSend\"\n\t */\n\tpublic static List getAllCommands() {\n\t\tList retNames = new ArrayList<>();\n\t\t\n\t\tNSFFORMCMDSPROC callback;\n\t\tif (PlatformUtils.isWin32()) {\n\t\t\tcallback = new NSFFORMCMDSPROCWin32() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr, short code, IntByReference stopFlag) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\telse {\n\t\t\tcallback = new NSFFORMCMDSPROC() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic short invoke(Pointer ptr, short code, IntByReference stopFlag) {\n\t\t\t\t\tString name = NotesStringUtils.fromLMBCS(ptr, -1);\n\t\t\t\t\tretNames.add(name);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t};\n\t\t}\n\t\tshort result = NotesNativeAPI.get().NSFFormulaCommands(callback);\n\t\tNotesErrorUtils.checkResult(result);\n\t\t\n\t\treturn retNames;\n\t}\n\t\n\tpublic static class FormulaAnalyzeResult {\n\t\tprivate EnumSet attributes;\n\t\t\n\t\tprivate FormulaAnalyzeResult(EnumSet attributes) {\n\t\t\tthis.attributes = attributes;\n\t\t}\n\t\t\n\t\tpublic Set getAttributes() {\n\t\t\treturn Collections.unmodifiableSet(this.attributes);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"FormulaAnalyzeResult [attributes=\" + attributes + \"]\";\n\t\t}\n\t\t\n\t}\n\n\t/**\n\t * Scan through the function table (ftable) or keyword table (ktable)\n\t * to find parameters of an @ function or an @ command.\n\t * \n\t * @param formulaName name returned by {@link FormulaExecution#getAllFunctions()}, e.g. \"@Left(\"\n\t * @return function parameters, e.g. \"stringToSearch; numberOfChars)stringToSearch; subString)\" for the function \"@Left(\"\n\t */\n\tpublic static List getFunctionParameters(String formulaName) {\n\t\tMemory formulaMem = NotesStringUtils.toLMBCS(formulaName, true);\n\t\tPointer ptr = NotesNativeAPI.get().NSFFindFormulaParameters(formulaMem);\n\t\tif (ptr==null) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\t\telse {\n\t\t\t//example format for @Middle(:\n\t\t\t//string; offset; numberchars)string; offset; endstring)string; startString; endstring)string; startString; numberchars)\n\t\t\tList params = new ArrayList<>();\n\t\t\tString paramsConc = NotesStringUtils.fromLMBCS(ptr, -1);\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tfor (int i=0; i attributes = FormulaAttributes.toFormulaAttributes(retAttributes.getValue());\n\t\treturn new FormulaAnalyzeResult(attributes);\n\t}\n\t\n}\n"},"message":{"kind":"string","value":"API to apply security to formula execution\n"},"old_file":{"kind":"string","value":"domino-jna/src/main/java/com/mindoo/domino/jna/formula/FormulaExecution.java"},"subject":{"kind":"string","value":"API to apply security to formula execution"}}},{"rowIdx":1263,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"351aeb957c2c46d0c8c1580f28c79057bcdc5bba"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"adgear/secor,adgear/secor"},"new_contents":{"kind":"string","value":"package com.pinterest.secor.io.impl;\n\nimport com.pinterest.secor.common.SecorConfig;\nimport com.pinterest.secor.io.AdgearReader;\nimport com.pinterest.secor.io.KeyValue;\n\nimport net.minidev.json.JSONObject;\nimport net.minidev.json.JSONValue;\n\n// Converts gateway JSON to Beh TSV\npublic class AdgearGatewayJsonReader implements AdgearReader {\n private final String timestampFieldname;\n private final boolean logGeo;\n private final String logGeoInclude;\n\n public AdgearGatewayJsonReader(SecorConfig secorConfig) {\n timestampFieldname = secorConfig.getMessageTimestampName();\n logGeo = secorConfig.getSecorAdgearLogFieldsGeo();\n logGeoInclude = secorConfig.getSecorAdgearLogFieldsGeoInclude();\n }\n\n public String convert(KeyValue kv) {\n JSONObject jsonObject = null;\n Object value = JSONValue.parse(kv.getValue());\n if (value instanceof JSONObject) {\n jsonObject = (JSONObject) value;\n } else {\n return null;\n }\n\n Double timestamp = (Double) jsonObject.get(timestampFieldname);\n String cookieId = (String) getAtPath(jsonObject, \"bid_request.user.buyeruid\");\n String urlDomain = (String) getAtPath(jsonObject,\"bid_request.site.domain\");\n\n // Extra fields, logged if present\n String country = null, region = null;\n if (logGeo) {\n String c = (String) getAtPath(jsonObject, \"bid_request.device.geo.country\");\n\n // Apply whitelist if set\n if (logGeoInclude == null || logGeoInclude.equals(c)) {\n country = c;\n region = (String) getAtPath(jsonObject, \"bid_request.device.geo.region\");\n }\n }\n\n if (timestamp == null || cookieId == null || urlDomain == null) {\n return null;\n }\n\n StringBuffer output = new StringBuffer();\n output\n .append(cookieId).append('\\t')\n .append(Math.round(timestamp)).append('\\t')\n .append(\"urld:\").append(urlDomain);\n\n // FIXME: Duplicated code (see sibling class)\n // FIXME: Add validation?\n if (logGeo) {\n if (country != null) {\n output.append(\",country:\").append(country);\n }\n if (region != null) {\n output.append(\",region:\").append(region);\n }\n }\n\n output.append(\"\\n\");\n return output.toString();\n }\n\n // 1. Horrible\n // 2. Why isn't this part of json-smart?\n private static Object getAtPath(JSONObject json, String path) {\n String[] components = path.split(\"\\\\.\");\n Object object = json;\n for (String component : components) {\n if (!(object instanceof JSONObject)) return null; // That's really an error.\n object = ((JSONObject) object).get(component);\n if (object == null) return null;\n }\n\n return object;\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/pinterest/secor/io/impl/AdgearGatewayJsonReader.java"},"old_contents":{"kind":"string","value":"package com.pinterest.secor.io.impl;\n\nimport com.pinterest.secor.common.SecorConfig;\nimport com.pinterest.secor.io.AdgearReader;\nimport com.pinterest.secor.io.KeyValue;\n\nimport net.minidev.json.JSONObject;\nimport net.minidev.json.JSONValue;\n\n// Converts gateway JSON to Beh TSV\npublic class AdgearGatewayJsonReader implements AdgearReader {\n private final String timestampFieldname;\n private final boolean logGeo;\n private final String logGeoInclude;\n\n public AdgearGatewayJsonReader(SecorConfig secorConfig) {\n timestampFieldname = secorConfig.getMessageTimestampName();\n logGeo = secorConfig.getSecorAdgearLogFieldsGeo();\n logGeoInclude = secorConfig.getSecorAdgearLogFieldsGeoInclude();\n }\n\n public String convert(KeyValue kv) {\n JSONObject jsonObject = null;\n Object value = JSONValue.parse(kv.getValue());\n if (value instanceof JSONObject) {\n jsonObject = (JSONObject) value;\n } else {\n return null;\n }\n\n Double timestamp = (Double) jsonObject.get(timestampFieldname);\n String cookieId = (String) getAtPath(jsonObject, \"bid_request.user.buyeruid\");\n String urlDomain = (String) getAtPath(jsonObject,\"bid_request.site.domain\");\n\n // Extra fields, logged if present\n String country = null, region = null;\n if (logGeo) {\n String c = (String) getAtPath(jsonObject, \"bid_request.device.geo.country\");\n\n // Apply whitelist if set\n if (logGeoInclude == null || c == logGeoInclude) {\n country = c;\n region = (String) getAtPath(jsonObject, \"bid_request.device.geo.region\");\n }\n }\n\n if (timestamp == null || cookieId == null || urlDomain == null) {\n return null;\n }\n\n StringBuffer output = new StringBuffer();\n output\n .append(cookieId).append('\\t')\n .append(Math.round(timestamp)).append('\\t')\n .append(\"urld:\").append(urlDomain);\n\n // FIXME: Duplicated code (see sibling class)\n // FIXME: Add validation?\n if (logGeo) {\n if (country != null) {\n output.append(\",country:\").append(country);\n }\n if (region != null) {\n output.append(\",region:\").append(region);\n }\n }\n\n output.append(\"\\n\");\n return output.toString();\n }\n\n // 1. Horrible\n // 2. Why isn't this part of json-smart?\n private static Object getAtPath(JSONObject json, String path) {\n String[] components = path.split(\"\\\\.\");\n Object object = json;\n for (String component : components) {\n if (!(object instanceof JSONObject)) return null; // That's really an error.\n object = ((JSONObject) object).get(component);\n if (object == null) return null;\n }\n\n return object;\n }\n}\n"},"message":{"kind":"string","value":"Fix string comparison.\n"},"old_file":{"kind":"string","value":"src/main/java/com/pinterest/secor/io/impl/AdgearGatewayJsonReader.java"},"subject":{"kind":"string","value":"Fix string comparison."}}},{"rowIdx":1264,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8a857e21525b88839da99ba236eb42485f800ed4"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"aldebaran/libqi-java,aldebaran/libqi-java,aldebaran/libqi-java"},"new_contents":{"kind":"string","value":"package com.aldebaran.qimessaging;\n\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Hashtable;\nimport java.util.Map;\n\n/**\n * Tool class providing QiMessaging<->Java type system loading and\n * dynamic library loader designed to load libraries included in jar package.\n * @author proullon\n *\n */\npublic class EmbeddedTools\n{\n\n private File tmpDir = null;\n\n public static boolean LOADED_EMBEDDED_LIBRARY = false;\n private static native void initTypeSystem(java.lang.Object str, java.lang.Object i, java.lang.Object f, java.lang.Object d, java.lang.Object l, java.lang.Object m, java.lang.Object al, java.lang.Object t, java.lang.Object o, java.lang.Object b);\n private static native void initTupleInTypeSystem(java.lang.Object t1, java.lang.Object t2, java.lang.Object t3, java.lang.Object t4, java.lang.Object t5, java.lang.Object t6, java.lang.Object t7, java.lang.Object t8);\n\n public static String getSuitableLibraryExtention()\n {\n String[] ext = new String[] {\".so\", \".dylib\", \".dll\"};\n String osName = System.getProperty(\"os.name\");\n\n if (osName == \"Windows\")\n return ext[2];\n if (osName == \"Mac\")\n return ext[1];\n\n return ext[0];\n }\n\n /**\n * To work correctly, QiMessaging<->java type system needs to compare type class template.\n * Unfortunately, call template cannot be retrieve on native android thread.\n * The only available way to do is to store instance of wanted object\n * and get fresh class template from it right before using it.\n */\n private boolean initTypeSystem()\n {\n String str = new String();\n Integer i = new Integer(0);\n Float f = new Float(0);\n Double d = new Double(0);\n Long l = new Long(0);\n Tuple t = new Tuple1();\n Boolean b = new Boolean(true);\n\n GenericObjectBuilder ob = new GenericObjectBuilder();\n Object obj = ob.object();\n\n Map m = new Hashtable();\n ArrayList al = new ArrayList();\n\n // Initialize generic type system\n EmbeddedTools.initTypeSystem(str, i, f, d, l, m, al, t, obj, b);\n\n Tuple t1 = Tuple.makeTuple(0);\n Tuple t2 = Tuple.makeTuple(0, 0);\n Tuple t3 = Tuple.makeTuple(0, 0, 0);\n Tuple t4 = Tuple.makeTuple(0, 0, 0, 0);\n Tuple t5 = Tuple.makeTuple(0, 0, 0, 0, 0);\n Tuple t6 = Tuple.makeTuple(0, 0, 0, 0, 0, 0);\n Tuple t7 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0);\n Tuple t8 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0);\n // Initialize tuple\n EmbeddedTools.initTupleInTypeSystem(t1, t2, t3, t4, t5, t6, t7, t8);\n return true;\n }\n\n /**\n * Override directory where native libraries are extracted.\n */\n public void overrideTempDirectory(File newValue)\n {\n tmpDir = newValue;\n }\n\n /**\n * Override directory where native libraries are extracted.\n */\n public void overrideTempDirectory(File newValue)\n {\n tmpDir = newValue;\n }\n\n /**\n * Native C++ librairies are package with java sources.\n * This way, we are able to load them anywhere, anytime.\n */\n public boolean loadEmbeddedLibraries()\n {\n if (LOADED_EMBEDDED_LIBRARY == true)\n {\n System.out.print(\"Native libraries already loaded\");\n return true;\n }\n\n /*\n * Since we use multiple shared libraries,\n * we need to use libstlport_shared to avoid multiple STL declarations\n */\n loadEmbeddedLibrary(\"libgnustl_shared\");\n\n if (loadEmbeddedLibrary(\"libqi\") == false ||\n loadEmbeddedLibrary(\"libqitype\") == false ||\n loadEmbeddedLibrary(\"libqimessaging\") == false ||\n loadEmbeddedLibrary(\"libqimessagingjni\") == false)\n {\n LOADED_EMBEDDED_LIBRARY = false;\n return false;\n }\n\n System.out.printf(\"Libraries loaded. Initializing type system...\\n\");\n LOADED_EMBEDDED_LIBRARY = true;\n if (initTypeSystem() == false)\n {\n System.out.printf(\"Cannot initialize type system\\n\");\n LOADED_EMBEDDED_LIBRARY = false;\n return false;\n }\n\n return true;\n }\n\n public boolean loadEmbeddedLibrary(String libname)\n {\n boolean usingEmbedded = false;\n\n // Locate native library within qimessaging.jar\n StringBuilder path = new StringBuilder();\n path.append(\"/\" + libname+getSuitableLibraryExtention());\n\n // Search native library for host system\n URL nativeLibrary = null;\n if ((nativeLibrary = EmbeddedTools.class.getResource(path.toString())) == null)\n {\n try\n {\n System.loadLibrary(libname);\n }\n catch (UnsatisfiedLinkError e)\n {\n if (libname != \"libgnustl_shared\") // Disable warning to avoid false positive.\n System.out.printf(\"[WARN ] Unsatified link error : %s\\n\", e.getMessage());\n return false;\n }\n return true;\n }\n\n // Delete if already exists\n File toDelete = new File(tmpDir.getAbsolutePath() + path.toString());\n if (toDelete.exists())\n {\n System.out.printf(\"Deleting %s\\n\", toDelete.getAbsolutePath());\n toDelete.delete();\n }\n\n // Extract and load native library\n try\n {\n final File libfile = File.createTempFile(libname, getSuitableLibraryExtention(), tmpDir);\n libfile.deleteOnExit();\n\n final InputStream in = nativeLibrary.openStream();\n final OutputStream out = new BufferedOutputStream(new FileOutputStream(libfile));\n\n int len = 0;\n byte[] buffer = new byte[10000];\n while ((len = in.read(buffer)) > -1)\n {\n out.write(buffer, 0, len);\n }\n\n out.close();\n in.close();\n\n int actualPathLength = libfile.getAbsolutePath().length();\n int actualNameLength = libfile.getName().length();\n int endIndex = actualPathLength - actualNameLength;\n\n // Rename tmp file to actual library name\n String pathToTmp = libfile.getAbsolutePath().substring(0, endIndex);\n File so = new File(pathToTmp + \"/\" + libname + getSuitableLibraryExtention());\n System.out.printf(\"Extracting %s in %s...\\n\", libname + getSuitableLibraryExtention(), pathToTmp);\n\n libfile.renameTo(so);\n System.load(so.getAbsolutePath());\n\n usingEmbedded = true;\n }\n catch (IOException x)\n {\n System.out.printf(\"Cannot extract native library %s: %s\\n\", libname, x);\n return false;\n }\n catch (UnsatisfiedLinkError e)\n {\n System.out.printf(\"Cannot load native library %s: %s\\n\", libname, e);\n return false;\n }\n\n return usingEmbedded;\n }\n}\n"},"new_file":{"kind":"string","value":"java/qimessaging/src/main/java/com/aldebaran/qimessaging/EmbeddedTools.java"},"old_contents":{"kind":"string","value":"package com.aldebaran.qimessaging;\n\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Hashtable;\nimport java.util.Map;\n\n/**\n * Tool class providing QiMessaging<->Java type system loading and\n * dynamic library loader designed to load libraries included in jar package.\n * @author proullon\n *\n */\npublic class EmbeddedTools\n{\n\n private File tmpDir = null;\n\n public static boolean LOADED_EMBEDDED_LIBRARY = false;\n private static native void initTypeSystem(java.lang.Object str, java.lang.Object i, java.lang.Object f, java.lang.Object d, java.lang.Object l, java.lang.Object m, java.lang.Object al, java.lang.Object t, java.lang.Object o, java.lang.Object b);\n private static native void initTupleInTypeSystem(java.lang.Object t1, java.lang.Object t2, java.lang.Object t3, java.lang.Object t4, java.lang.Object t5, java.lang.Object t6, java.lang.Object t7, java.lang.Object t8);\n\n public static String getSuitableLibraryExtention()\n {\n String[] ext = new String[] {\".so\", \".dylib\", \".dll\"};\n String osName = System.getProperty(\"os.name\");\n\n if (osName == \"Windows\")\n return ext[2];\n if (osName == \"Mac\")\n return ext[1];\n\n return ext[0];\n }\n\n /**\n * To work correctly, QiMessaging<->java type system needs to compare type class template.\n * Unfortunately, call template cannot be retrieve on native android thread.\n * The only available way to do is to store instance of wanted object\n * and get fresh class template from it right before using it.\n */\n private boolean initTypeSystem()\n {\n String str = new String();\n Integer i = new Integer(0);\n Float f = new Float(0);\n Double d = new Double(0);\n Long l = new Long(0);\n Tuple t = new Tuple1();\n Boolean b = new Boolean(true);\n\n GenericObjectBuilder ob = new GenericObjectBuilder();\n Object obj = ob.object();\n\n Map m = new Hashtable();\n ArrayList al = new ArrayList();\n\n // Initialize generic type system\n EmbeddedTools.initTypeSystem(str, i, f, d, l, m, al, t, obj, b);\n\n Tuple t1 = Tuple.makeTuple(0);\n Tuple t2 = Tuple.makeTuple(0, 0);\n Tuple t3 = Tuple.makeTuple(0, 0, 0);\n Tuple t4 = Tuple.makeTuple(0, 0, 0, 0);\n Tuple t5 = Tuple.makeTuple(0, 0, 0, 0, 0);\n Tuple t6 = Tuple.makeTuple(0, 0, 0, 0, 0, 0);\n Tuple t7 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0);\n Tuple t8 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0);\n // Initialize tuple\n EmbeddedTools.initTupleInTypeSystem(t1, t2, t3, t4, t5, t6, t7, t8);\n return true;\n }\n\n /**\n * Override directory where native libraries are extracted.\n */\n public void overrideTempDirectory(File newValue)\n {\n tmpDir = newValue;\n }\n\n /**\n * Native C++ librairies are package with java sources.\n * This way, we are able to load them anywhere, anytime.\n */\n public boolean loadEmbeddedLibraries()\n {\n if (LOADED_EMBEDDED_LIBRARY == true)\n {\n System.out.print(\"Native libraries already loaded\");\n return true;\n }\n\n /*\n * Since we use multiple shared libraries,\n * we need to use libstlport_shared to avoid multiple STL declarations\n */\n loadEmbeddedLibrary(\"libgnustl_shared\");\n\n if (loadEmbeddedLibrary(\"libqi\") == false ||\n loadEmbeddedLibrary(\"libqitype\") == false ||\n loadEmbeddedLibrary(\"libqimessaging\") == false ||\n loadEmbeddedLibrary(\"libqimessagingjni\") == false)\n {\n LOADED_EMBEDDED_LIBRARY = false;\n return false;\n }\n\n LOADED_EMBEDDED_LIBRARY = true;\n if (initTypeSystem() == false)\n {\n LOADED_EMBEDDED_LIBRARY = false;\n return false;\n }\n\n return true;\n }\n\n public boolean loadEmbeddedLibrary(String libname)\n {\n boolean usingEmbedded = false;\n\n // Locate native library within qimessaging.jar\n StringBuilder path = new StringBuilder();\n path.append(\"/\" + libname+getSuitableLibraryExtention());\n\n // Search native library for host system\n URL nativeLibrary = null;\n if ((nativeLibrary = EmbeddedTools.class.getResource(path.toString())) == null)\n {\n try\n {\n System.loadLibrary(libname);\n }\n catch (UnsatisfiedLinkError e)\n {\n if (libname != \"libgnustl_shared\") // Disable warning to avoid false positive.\n System.out.printf(\"[WARN ] Unsatified link error : %s\\n\", e.getMessage());\n return false;\n }\n return true;\n }\n\n // Extract and load native library\n try\n {\n final File libfile = File.createTempFile(libname, getSuitableLibraryExtention(), tmpDir);\n libfile.deleteOnExit();\n\n final InputStream in = nativeLibrary.openStream();\n final OutputStream out = new BufferedOutputStream(new FileOutputStream(libfile));\n\n int len = 0;\n byte[] buffer = new byte[10000];\n while ((len = in.read(buffer)) > -1)\n {\n out.write(buffer, 0, len);\n }\n\n out.close();\n in.close();\n\n int actualPathLength = libfile.getAbsolutePath().length();\n int actualNameLength = libfile.getName().length();\n int endIndex = actualPathLength - actualNameLength;\n\n // Rename tmp file to actual library name\n String pathToTmp = libfile.getAbsolutePath().substring(0, endIndex);\n File so = new File(pathToTmp + \"/\" + libname + getSuitableLibraryExtention());\n System.out.printf(\"Extracting %s in %s...\\n\", libname + getSuitableLibraryExtention(), pathToTmp);\n\n libfile.renameTo(so);\n System.load(so.getAbsolutePath());\n\n usingEmbedded = true;\n }\n catch (IOException x)\n {\n usingEmbedded = false;\n }\n\n return usingEmbedded;\n }\n}\n"},"message":{"kind":"string","value":"Java: Add method to override directory where native libraries are extracted\n\nChange-Id: I4390f87dd00fb60db13b1b1dc08e6eeaeb315c52\nReviewed-on: http://gerrit.aldebaran.lan/20228\nReviewed-by: proullon \nTested-by: proullon \n"},"old_file":{"kind":"string","value":"java/qimessaging/src/main/java/com/aldebaran/qimessaging/EmbeddedTools.java"},"subject":{"kind":"string","value":"Java: Add method to override directory where native libraries are extracted"}}},{"rowIdx":1265,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d296c18880aaf986f04fa326f2c101cc5908f8e7"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"salesforce/storm-dynamic-spout,salesforce/storm-dynamic-spout"},"new_contents":{"kind":"string","value":"package com.salesforce.storm.spout.sideline;\n\nimport com.salesforce.storm.spout.sideline.kafka.DelegateSidelineSpout;\nimport com.salesforce.storm.spout.sideline.metrics.MetricsRecorder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.time.Clock;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Spout Coordinator.\n *\n * Manages X number of spouts and coordinates their nextTuple(), ack() and fail() calls across threads\n */\npublic class SpoutCoordinator {\n\n private static final Logger logger = LoggerFactory.getLogger(SpoutCoordinator.class);\n\n /**\n * How long our monitor thread will sit around and sleep between monitoring\n * if new VirtualSpouts need to be started up, in Milliseconds.\n */\n public static final int MONITOR_THREAD_SLEEP_MS = 2000;\n\n /**\n * How long we'll wait for all VirtualSpout's to cleanly shut down, before we stop\n * them with force, in Milliseconds.\n */\n public static final int MAX_SPOUT_STOP_TIME_MS = 10000;\n\n /**\n * How often we'll make sure each VirtualSpout persists its state, in Milliseconds.\n */\n public static final long FLUSH_INTERVAL_MS = 30000;\n\n /**\n * The size of the thread pool for running virtual spouts for sideline requests.\n */\n public static final int SPOUT_RUNNER_THREAD_POOL_SIZE = 10;\n\n /**\n * Which Clock instance to get reference to the system time.\n * We use this to allow injecting a fake System clock in tests.\n *\n * ThreadSafety - Lucky for us, Clock is all thread safe :)\n */\n private Clock clock = Clock.systemUTC();\n\n /**\n * Queue of spouts that need to be passed to the monitor and spun up.\n */\n private final Queue newSpoutQueue = new ConcurrentLinkedQueue<>();\n\n /**\n * Buffer by spout consumer id of messages that have been acked.\n */\n private final Map> ackedTuplesInputQueue = new ConcurrentHashMap<>();\n\n /**\n * Buffer by spout consumer id of messages that have been failed.\n */\n private final Map> failedTuplesInputQueue = new ConcurrentHashMap<>();\n\n /**\n * Thread Pool Executor.\n */\n private final ExecutorService executor;\n\n /**\n * For capturing metrics.\n */\n private final MetricsRecorder metricsRecorder;\n\n /**\n * The spout monitor runnable, which handles spinning up threads for sideline spouts.\n */\n private SpoutMonitor spoutMonitor;\n\n /**\n * Flag that gets set to false on shutdown, to signal to close up shop.\n * This probably should be renamed at some point.\n */\n private boolean isOpen = false;\n\n /**\n * Create a new coordinator, supplying the 'fire hose' or the starting spouts.\n * @param spout Fire hose spout\n */\n public SpoutCoordinator(final DelegateSidelineSpout spout, final MetricsRecorder metricsRecorder) {\n this.executor = Executors.newFixedThreadPool(SPOUT_RUNNER_THREAD_POOL_SIZE);\n\n this.metricsRecorder = metricsRecorder;\n\n addSidelineSpout(spout);\n }\n\n /**\n * Add a new spout to the coordinator, this will get picked up by the coordinator's monitor, opened and\n * managed with teh other currently running spouts.\n * @param spout New delegate spout\n */\n public void addSidelineSpout(final DelegateSidelineSpout spout) {\n newSpoutQueue.add(spout);\n }\n\n /**\n * Open the coordinator and begin spinning up virtual spout threads.\n * @param tupleOutputQueue The queue to put messages onto\n */\n public void open(final BlockingQueue tupleOutputQueue) {\n isOpen = true;\n\n final CountDownLatch latch = new CountDownLatch(newSpoutQueue.size());\n\n spoutMonitor = new SpoutMonitor(\n executor,\n newSpoutQueue,\n tupleOutputQueue,\n ackedTuplesInputQueue,\n failedTuplesInputQueue,\n latch,\n clock\n );\n\n executor.submit(spoutMonitor);\n\n try {\n latch.await();\n } catch (InterruptedException ex) {\n logger.error(\"Exception while waiting for the coordinator to open it's spouts {}\", ex);\n }\n }\n\n /**\n * Acks a tuple on the spout that it belongs to.\n * @param id Tuple message id to ack\n */\n public void ack(final TupleMessageId id) {\n if (!ackedTuplesInputQueue.containsKey(id.getSrcConsumerId())) {\n logger.warn(\"Acking tuple for unknown consumer\");\n return;\n }\n\n ackedTuplesInputQueue.get(id.getSrcConsumerId()).add(id);\n }\n\n /**\n * Fails a tuple on the spout that it belongs to.\n * @param id Tuple message id to fail\n */\n public void fail(final TupleMessageId id) {\n if (!failedTuplesInputQueue.containsKey(id.getSrcConsumerId())) {\n logger.warn(\"Failing tuple for unknown consumer\");\n return;\n }\n\n failedTuplesInputQueue.get(id.getSrcConsumerId()).add(id);\n }\n\n /**\n * Stop coordinating spouts, calling this should shut down and finish the coordinator's spouts.\n */\n public void close() {\n spoutMonitor.close();\n\n try {\n executor.awaitTermination(MAX_SPOUT_STOP_TIME_MS, TimeUnit.MILLISECONDS);\n } catch (InterruptedException ex) {\n logger.error(\"Caught Exception while stopping: {}\", ex);\n }\n\n executor.shutdownNow();\n\n // Will trigger the monitor thread to stop running, which should be the end of it\n isOpen = false;\n }\n\n /**\n * For testing, returns the total number of running spouts.\n * @return The total number of spouts the coordinator is running\n */\n int getTotalSpouts() {\n return spoutMonitor.getTotalSpouts();\n }\n\n\n /**\n * Monitors the lifecycle of spinning up virtual spouts.\n */\n private static class SpoutMonitor implements Runnable {\n\n private static final Logger logger = LoggerFactory.getLogger(SpoutMonitor.class);\n\n private final ExecutorService executor;\n private final Queue newSpoutQueue;\n private final BlockingQueue tupleOutputQueue;\n private final Map> ackedTuplesInputQueue;\n private final Map> failedTuplesInputQueue;\n private final CountDownLatch latch;\n private final Clock clock;\n\n private final Map spoutRunners = new ConcurrentHashMap<>();\n private final Map spoutThreads = new ConcurrentHashMap<>();\n private boolean isOpen = true;\n\n SpoutMonitor(\n final ExecutorService executor,\n final Queue newSpoutQueue,\n final BlockingQueue tupleOutputQueue,\n final Map> ackedTuplesInputQueue,\n final Map> failedTuplesInputQueue,\n final CountDownLatch latch,\n final Clock clock\n ) {\n this.executor = executor;\n this.newSpoutQueue = newSpoutQueue;\n this.tupleOutputQueue = tupleOutputQueue;\n this.ackedTuplesInputQueue = ackedTuplesInputQueue;\n this.failedTuplesInputQueue = failedTuplesInputQueue;\n this.latch = latch;\n this.clock = clock;\n }\n\n @Override\n public void run() {\n try {\n // Rename our thread.\n Thread.currentThread().setName(\"SidelineSpout-NewSpoutMonitor\");\n\n // Start monitoring loop.\n while (isOpen) {\n logger.info(\"Still here.. my input queue is {}\", newSpoutQueue.size());\n\n for (DelegateSidelineSpout spout; (spout = newSpoutQueue.poll()) != null;) {\n logger.info(\"Preparing thread for spout {}\", spout.getConsumerId());\n\n final SpoutRunner spoutRunner = new SpoutRunner(\n spout,\n tupleOutputQueue,\n ackedTuplesInputQueue,\n failedTuplesInputQueue,\n latch,\n clock\n );\n\n spoutRunners.put(spout.getConsumerId(), spoutRunner);\n\n final Future spoutInstance = executor.submit(spoutRunner);\n\n spoutThreads.put(spout.getConsumerId(), spoutInstance);\n }\n\n // Pause for a period before checking for more spouts\n try {\n Thread.sleep(MONITOR_THREAD_SLEEP_MS);\n } catch (InterruptedException ex) {\n logger.warn(\"!!!!!! Thread interrupted, shutting down...\");\n return;\n }\n }\n\n logger.warn(\"!!!!!! Spout coordinator is ceasing to run...\");\n } catch (Exception ex) {\n // TODO: Should we restart the monitor?\n logger.error(\"SpoutMonitor threw an exception {}\", ex);\n\n }\n }\n\n public void close() {\n isOpen = false;\n\n for (SpoutRunner spoutRunner : spoutRunners.values()) {\n spoutRunner.requestStop();\n }\n\n spoutRunners.clear();\n spoutThreads.clear();\n }\n\n public int getTotalSpouts() {\n return spoutRunners.size();\n }\n }\n\n private static class SpoutRunner implements Runnable {\n\n private static final Logger logger = LoggerFactory.getLogger(SpoutRunner.class);\n\n private final DelegateSidelineSpout spout;\n private final BlockingQueue tupleOutputQueue;\n private final Map> ackedTupleInputQueue;\n private final Map> failedTupleInputQueue;\n private final CountDownLatch latch;\n private final Clock clock;\n\n SpoutRunner(\n final DelegateSidelineSpout spout,\n final BlockingQueue tupleOutputQueue,\n final Map> ackedTupleInputQueue,\n final Map> failedTupleInputQueue,\n final CountDownLatch latch,\n final Clock clock\n ) {\n this.spout = spout;\n this.tupleOutputQueue = tupleOutputQueue;\n this.ackedTupleInputQueue = ackedTupleInputQueue;\n this.failedTupleInputQueue = failedTupleInputQueue;\n this.latch = latch;\n this.clock = clock;\n }\n\n @Override\n public void run() {\n try {\n logger.info(\"Opening {} spout\", spout.getConsumerId());\n\n // Rename thread to use the spout's consumer id\n Thread.currentThread().setName(spout.getConsumerId());\n\n spout.open();\n\n ackedTupleInputQueue.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>());\n failedTupleInputQueue.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>());\n\n latch.countDown();\n\n long lastFlush = clock.millis();\n\n // Loop forever until someone requests the spout to stop\n while (!spout.isStopRequested()) {\n // First look for any new tuples to be emitted.\n logger.debug(\"Requesting next tuple for spout {}\", spout.getConsumerId());\n\n final KafkaMessage message = spout.nextTuple();\n\n if (message != null) {\n try {\n tupleOutputQueue.put(message);\n } catch (InterruptedException ex) {\n // TODO: Revisit this\n logger.error(\"{}\", ex);\n }\n }\n\n // Lemon's note: Should we ack and then remove from the queue? What happens in the event\n // of a failure in ack(), the tuple will be removed from the queue despite a failed ack\n\n // Ack anything that needs to be acked\n while (!ackedTupleInputQueue.get(spout.getConsumerId()).isEmpty()) {\n TupleMessageId id = ackedTupleInputQueue.get(spout.getConsumerId()).poll();\n spout.ack(id);\n }\n\n // Fail anything that needs to be failed\n while (!failedTupleInputQueue.get(spout.getConsumerId()).isEmpty()) {\n TupleMessageId id = failedTupleInputQueue.get(spout.getConsumerId()).poll();\n spout.fail(id);\n }\n\n // Periodically we flush the state of the spout to capture progress\n if (lastFlush + FLUSH_INTERVAL_MS < clock.millis()) {\n logger.info(\"Flushing state for spout {}\", spout.getConsumerId());\n spout.flushState();\n lastFlush = clock.millis();\n }\n }\n\n // Looks like someone requested that we stop this instance.\n // So we call close on it.\n logger.info(\"Finishing {} spout\", spout.getConsumerId());\n spout.close();\n\n // Remove our entries from the acked and failed queue.\n ackedTupleInputQueue.remove(spout.getConsumerId());\n failedTupleInputQueue.remove(spout.getConsumerId());\n } catch (Exception ex) {\n // TODO: Should we restart the SpoutRunner?\n logger.error(\"SpoutRunner for {} threw an exception {}\", spout.getConsumerId(), ex);\n }\n }\n\n public void requestStop() {\n this.spout.requestStop();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/salesforce/storm/spout/sideline/SpoutCoordinator.java"},"old_contents":{"kind":"string","value":"package com.salesforce.storm.spout.sideline;\n\nimport com.salesforce.storm.spout.sideline.kafka.DelegateSidelineSpout;\nimport com.salesforce.storm.spout.sideline.metrics.MetricsRecorder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.time.Clock;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Spout Coordinator.\n *\n * Manages X number of spouts and coordinates their nextTuple(), ack() and fail() calls across threads\n */\npublic class SpoutCoordinator {\n\n private static final Logger logger = LoggerFactory.getLogger(SpoutCoordinator.class);\n\n /**\n * How long our monitor thread will sit around and sleep between monitoring\n * if new VirtualSpouts need to be started up, in Milliseconds.\n */\n public static final int MONITOR_THREAD_SLEEP_MS = 2000;\n\n /**\n * How long we'll wait for all VirtualSpout's to cleanly shut down, before we stop\n * them with force, in Milliseconds.\n */\n public static final int MAX_SPOUT_STOP_TIME_MS = 10000;\n\n /**\n * How often we'll make sure each VirtualSpout persists its state, in Milliseconds.\n */\n public static final long FLUSH_INTERVAL_MS = 30000;\n\n /**\n * The size of the thread pool for running virtual spouts for sideline requests.\n */\n public static final int SPOUT_RUNNER_THREAD_POOL_SIZE = 10;\n\n /**\n * Which Clock instance to get reference to the system time.\n * We use this to allow injecting a fake System clock in tests.\n *\n * ThreadSafety - Lucky for us, Clock is all thread safe :)\n */\n private Clock clock = Clock.systemUTC();\n\n /**\n * Queue of spouts that need to be passed to the monitor and spun up.\n */\n private final Queue newSpoutQueue = new ConcurrentLinkedQueue<>();\n\n /**\n * Buffer by spout consumer id of messages that have been acked.\n */\n private final Map> ackedTuplesInputQueue = new ConcurrentHashMap<>();\n\n /**\n * Buffer by spout consumer id of messages that have been failed.\n */\n private final Map> failedTuplesInputQueue = new ConcurrentHashMap<>();\n\n /**\n * Thread Pool Executor.\n */\n private final ExecutorService executor;\n\n /**\n * For capturing metrics.\n */\n private final MetricsRecorder metricsRecorder;\n\n /**\n * The spout monitor runnable, which handles spinning up threads for sideline spouts.\n */\n private SpoutMonitor spoutMonitor;\n\n /**\n * Flag that gets set to false on shutdown, to signal to close up shop.\n * This probably should be renamed at some point.\n */\n private boolean isOpen = false;\n\n /**\n * Create a new coordinator, supplying the 'fire hose' or the starting spouts.\n * @param spout Fire hose spout\n */\n public SpoutCoordinator(final DelegateSidelineSpout spout, final MetricsRecorder metricsRecorder) {\n this.executor = Executors.newFixedThreadPool(SPOUT_RUNNER_THREAD_POOL_SIZE);\n\n this.metricsRecorder = metricsRecorder;\n\n addSidelineSpout(spout);\n }\n\n /**\n * Add a new spout to the coordinator, this will get picked up by the coordinator's monitor, opened and\n * managed with teh other currently running spouts.\n * @param spout New delegate spout\n */\n public void addSidelineSpout(final DelegateSidelineSpout spout) {\n newSpoutQueue.add(spout);\n }\n\n /**\n * Open the coordinator and begin spinning up virtual spout threads.\n * @param queue The queue to put messages onto\n */\n public void open(final BlockingQueue queue) {\n isOpen = true;\n\n final CountDownLatch latch = new CountDownLatch(newSpoutQueue.size());\n\n spoutMonitor = new SpoutMonitor(\n executor,\n newSpoutQueue,\n queue,\n ackedTuplesInputQueue,\n failedTuplesInputQueue,\n latch,\n clock\n );\n\n executor.submit(spoutMonitor);\n\n try {\n latch.await();\n } catch (InterruptedException ex) {\n logger.error(\"Exception while waiting for the coordinator to open it's spouts {}\", ex);\n }\n }\n\n /**\n * Acks a tuple on the spout that it belongs to.\n * @param id Tuple message id to ack\n */\n public void ack(final TupleMessageId id) {\n if (!ackedTuplesInputQueue.containsKey(id.getSrcConsumerId())) {\n logger.warn(\"Acking tuple for unknown consumer\");\n return;\n }\n\n ackedTuplesInputQueue.get(id.getSrcConsumerId()).add(id);\n }\n\n /**\n * Fails a tuple on the spout that it belongs to.\n * @param id Tuple message id to fail\n */\n public void fail(final TupleMessageId id) {\n if (!failedTuplesInputQueue.containsKey(id.getSrcConsumerId())) {\n logger.warn(\"Failing tuple for unknown consumer\");\n return;\n }\n\n failedTuplesInputQueue.get(id.getSrcConsumerId()).add(id);\n }\n\n /**\n * Stop coordinating spouts, calling this should shut down and finish the coordinator's spouts.\n */\n public void close() {\n spoutMonitor.close();\n\n try {\n executor.awaitTermination(MAX_SPOUT_STOP_TIME_MS, TimeUnit.MILLISECONDS);\n } catch (InterruptedException ex) {\n logger.error(\"Caught Exception while stopping: {}\", ex);\n }\n\n executor.shutdownNow();\n\n // Will trigger the monitor thread to stop running, which should be the end of it\n isOpen = false;\n }\n\n /**\n * For testing, returns the total number of running spouts.\n * @return The total number of spouts the coordinator is running\n */\n int getTotalSpouts() {\n return spoutMonitor.getTotalSpouts();\n }\n\n\n /**\n * Monitors the lifecycle of spinning up virtual spouts.\n */\n private static class SpoutMonitor implements Runnable {\n\n private static final Logger logger = LoggerFactory.getLogger(SpoutMonitor.class);\n\n private final ExecutorService executor;\n private final Queue spouts;\n private final BlockingQueue queue;\n private final Map> acked;\n private final Map> failed;\n private final CountDownLatch latch;\n private final Clock clock;\n\n private final Map spoutRunners = new ConcurrentHashMap<>();\n private final Map spoutThreads = new ConcurrentHashMap<>();\n private boolean isOpen = true;\n\n SpoutMonitor(\n final ExecutorService executor,\n final Queue spouts,\n final BlockingQueue queue,\n final Map> acked,\n final Map> failed,\n final CountDownLatch latch,\n final Clock clock\n ) {\n this.executor = executor;\n this.spouts = spouts;\n this.queue = queue;\n this.acked = acked;\n this.failed = failed;\n this.latch = latch;\n this.clock = clock;\n }\n\n @Override\n public void run() {\n try {\n // Rename our thread.\n Thread.currentThread().setName(\"SidelineSpout-NewSpoutMonitor\");\n\n // Start monitoring loop.\n while (isOpen) {\n logger.info(\"Still here.. my input queue is {}\", spouts.size());\n\n for (DelegateSidelineSpout spout; (spout = spouts.poll()) != null;) {\n logger.info(\"Preparing thread for spout {}\", spout.getConsumerId());\n\n final SpoutRunner spoutRunner = new SpoutRunner(\n spout,\n queue,\n acked,\n failed,\n latch,\n clock\n );\n\n spoutRunners.put(spout.getConsumerId(), spoutRunner);\n\n final Future spoutInstance = executor.submit(spoutRunner);\n\n spoutThreads.put(spout.getConsumerId(), spoutInstance);\n }\n\n // Pause for a period before checking for more spouts\n try {\n Thread.sleep(MONITOR_THREAD_SLEEP_MS);\n } catch (InterruptedException ex) {\n logger.warn(\"!!!!!! Thread interrupted, shutting down...\");\n return;\n }\n }\n\n logger.warn(\"!!!!!! Spout coordinator is ceasing to run...\");\n } catch (Exception ex) {\n // TODO: Should we restart the monitor?\n logger.error(\"SpoutMonitor threw an exception {}\", ex);\n\n }\n }\n\n public void close() {\n isOpen = false;\n\n for (SpoutRunner spoutRunner : spoutRunners.values()) {\n spoutRunner.requestStop();\n }\n\n spoutRunners.clear();\n spoutThreads.clear();\n }\n\n public int getTotalSpouts() {\n return spoutRunners.size();\n }\n }\n\n private static class SpoutRunner implements Runnable {\n\n private static final Logger logger = LoggerFactory.getLogger(SpoutRunner.class);\n\n private final DelegateSidelineSpout spout;\n private final BlockingQueue queue;\n private final Map> acked;\n private final Map> failed;\n private final CountDownLatch latch;\n private final Clock clock;\n\n SpoutRunner(\n final DelegateSidelineSpout spout,\n final BlockingQueue queue,\n final Map> acked,\n final Map> failed,\n final CountDownLatch latch,\n final Clock clock\n ) {\n this.spout = spout;\n this.queue = queue;\n this.acked = acked;\n this.failed = failed;\n this.latch = latch;\n this.clock = clock;\n }\n\n @Override\n public void run() {\n try {\n logger.info(\"Opening {} spout\", spout.getConsumerId());\n\n // Rename thread to use the spout's consumer id\n Thread.currentThread().setName(spout.getConsumerId());\n\n spout.open();\n\n acked.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>());\n failed.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>());\n\n latch.countDown();\n\n long lastFlush = clock.millis();\n\n // Loop forever until someone requests the spout to stop\n while (!spout.isStopRequested()) {\n // First look for any new tuples to be emitted.\n logger.debug(\"Requesting next tuple for spout {}\", spout.getConsumerId());\n\n final KafkaMessage message = spout.nextTuple();\n\n if (message != null) {\n try {\n queue.put(message);\n } catch (InterruptedException ex) {\n // TODO: Revisit this\n logger.error(\"{}\", ex);\n }\n }\n\n // Lemon's note: Should we ack and then remove from the queue? What happens in the event\n // of a failure in ack(), the tuple will be removed from the queue despite a failed ack\n\n // Ack anything that needs to be acked\n while (!acked.get(spout.getConsumerId()).isEmpty()) {\n TupleMessageId id = acked.get(spout.getConsumerId()).poll();\n spout.ack(id);\n }\n\n // Fail anything that needs to be failed\n while (!failed.get(spout.getConsumerId()).isEmpty()) {\n TupleMessageId id = failed.get(spout.getConsumerId()).poll();\n spout.fail(id);\n }\n\n // Periodically we flush the state of the spout to capture progress\n if (lastFlush + FLUSH_INTERVAL_MS < clock.millis()) {\n logger.info(\"Flushing state for spout {}\", spout.getConsumerId());\n spout.flushState();\n lastFlush = clock.millis();\n }\n }\n\n // Looks like someone requested that we stop this instance.\n // So we call close on it.\n logger.info(\"Finishing {} spout\", spout.getConsumerId());\n spout.close();\n\n // Remove our entries from the acked and failed queue.\n acked.remove(spout.getConsumerId());\n failed.remove(spout.getConsumerId());\n } catch (Exception ex) {\n // TODO: Should we restart the SpoutRunner?\n logger.error(\"SpoutRunner for {} threw an exception {}\", spout.getConsumerId(), ex);\n }\n }\n\n public void requestStop() {\n this.spout.requestStop();\n }\n }\n}\n"},"message":{"kind":"string","value":"Rename some properties\n"},"old_file":{"kind":"string","value":"src/main/java/com/salesforce/storm/spout/sideline/SpoutCoordinator.java"},"subject":{"kind":"string","value":"Rename some properties"}}},{"rowIdx":1266,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"965bde15e839382fa7841cfecd231ca43593fa2f"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"maillouxc/git-rekt"},"new_contents":{"kind":"string","value":"package com.gitrekt.resort.controller;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.ResourceBundle;\nimport javafx.fxml.FXML;\nimport javafx.fxml.FXMLLoader;\nimport javafx.fxml.Initializable;\nimport javafx.scene.Parent;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.stage.Stage;\n\n/**\n * FXML Controller class for the staff home screen.\n */\npublic class StaffHomeScreenController implements Initializable {\n\n @FXML\n private Button viewReportsButton;\n \n /**\n * Initializes the controller class.\n */\n @Override\n public void initialize(URL url, ResourceBundle rb) {\n // TODO\n } \n \n public void onViewReportsButtonClicked() throws IOException {\n Stage mainStage = (Stage) viewReportsButton.getScene().getWindow();\n Parent viewReportsScreenRoot = FXMLLoader.load(\n getClass().getResource(\"/fxml/ViewReportsScreenController.fxml\")\n );\n Scene viewReportsScreen = new Scene(viewReportsScreenRoot);\n mainStage.setScene(viewReportsScreen);\n }\n \n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/gitrekt/resort/controller/StaffHomeScreenController.java"},"old_contents":{"kind":"string","value":"package com.gitrekt.resort.controller;\n\nimport java.net.URL;\nimport java.util.ResourceBundle;\nimport javafx.fxml.Initializable;\n\n/**\n * FXML Controller class for the staff home screen.\n */\npublic class StaffHomeScreenController implements Initializable {\n\n /**\n * Initializes the controller class.\n */\n @Override\n public void initialize(URL url, ResourceBundle rb) {\n // TODO\n } \n \n}\n"},"message":{"kind":"string","value":"Display view reports screen on button click\n"},"old_file":{"kind":"string","value":"src/main/java/com/gitrekt/resort/controller/StaffHomeScreenController.java"},"subject":{"kind":"string","value":"Display view reports screen on button click"}}},{"rowIdx":1267,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"0698bc769d3389bd99ebb3afd46f539eddbc1620"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"berryma4/diirt,richardfearn/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,berryma4/diirt,diirt/diirt,diirt/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,richardfearn/diirt,richardfearn/diirt,ControlSystemStudio/diirt"},"new_contents":{"kind":"string","value":"/**\n * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT\n * All rights reserved. Use is subject to license terms. See LICENSE.TXT\n */\npackage org.epics.pvmanager.formula;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Objects;\nimport org.epics.util.array.ArrayDouble;\nimport org.epics.util.text.NumberFormats;\nimport org.epics.util.time.Timestamp;\nimport org.epics.vtype.Alarm;\nimport org.epics.vtype.AlarmSeverity;\nimport org.epics.vtype.Display;\nimport org.epics.vtype.Time;\nimport org.epics.vtype.VBoolean;\nimport org.epics.vtype.VDouble;\nimport org.epics.vtype.VNumber;\nimport org.epics.vtype.VNumberArray;\nimport org.epics.vtype.VString;\nimport org.epics.vtype.VStringArray;\nimport org.epics.vtype.VType;\nimport org.epics.vtype.VTypeToString;\nimport org.epics.vtype.VTypeValueEquals;\nimport org.epics.vtype.ValueFactory;\nimport static org.epics.vtype.ValueFactory.*;\nimport org.epics.vtype.ValueUtil;\nimport org.epics.vtype.table.Column;\nimport org.hamcrest.Matcher;\nimport static org.hamcrest.Matchers.*;\nimport org.junit.Assert;\nimport static org.junit.Assert.assertThat;\n\n/**\n *\n * @author carcassi\n */\npublic class FunctionTester {\n \n private final FormulaFunction function;\n private boolean convertTypes = true;\n \n private FunctionTester(FormulaFunction function) {\n this.function = function;\n }\n \n public static FunctionTester findByName(FormulaFunctionSet set, String name) {\n Collection functions = set.findFunctions(name);\n\tassertThat(\"Function '\" + name + \"' not found.\", functions.isEmpty(),\n\t\tequalTo(false));\n\tassertThat(\"Multiple matches for function '\" + name + \"'.\", functions.size(),\n\t\tequalTo(1));\n return new FunctionTester(functions.iterator().next());\n }\n \n public static FunctionTester findBySignature(FormulaFunctionSet set, String name, Class... argTypes) {\n Collection functions = set.findFunctions(name);\n\tassertThat(\"Function '\" + name + \"' not found.\", functions.isEmpty(),\n\t\tequalTo(false));\n \n functions = FormulaFunctions.findArgTypeMatch(Arrays.asList(argTypes), functions);\n\tassertThat(\"No matches found for function '\" + name + \"'.\", functions.isEmpty(),\n\t\tequalTo(false));\n\tassertThat(\"Multiple matches for function '\" + name + \"'.\", functions.size(),\n\t\tequalTo(1));\n return new FunctionTester(functions.iterator().next());\n }\n \n public FunctionTester convertTypes(boolean convertTypes) {\n this.convertTypes = convertTypes;\n return this;\n }\n \n public FunctionTester matchReturnValue(Matcher matcher, Object... args) {\n if (convertTypes) {\n args = convertTypes(args);\n }\n\tObject result = function.calculate(Arrays.asList(args));\n Assert.assertThat(result, matcher);\n return this;\n }\n\n public FunctionTester compareReturnValue(Object expected, Object... args) {\n if (convertTypes) {\n expected = convertType(expected);\n args = convertTypes(args);\n }\n\tObject result = function.calculate(Arrays.asList(args));\n if (result instanceof VDouble && expected instanceof VDouble) {\n assertThat(\"Wrong result for function '\" + function.getName() + \"(\"\n + Arrays.toString(args) + \")'.\", ((VDouble) result).getValue().doubleValue(),\n\t\tcloseTo(((VDouble) expected).getValue().doubleValue(), 0.0001));\n } else {\n assertThat(\n \"Wrong result for function '\" + function.getName() + \"(\"\n + Arrays.toString(args) + \")'. Was (\" + result\n + \") expected (\" + expected + \")\",\n compareValues(result, expected), equalTo(true));\n }\n return this;\n }\n \n public static boolean compareValues(Object obj1, Object obj2) {\n if (Objects.equals(obj1, obj2)) {\n return true;\n }\n if (obj1 instanceof VType && obj2 instanceof VType) {\n return VTypeValueEquals.valueEquals(obj1, obj2);\n } else if (obj1 instanceof Column && obj2 instanceof Column) {\n Column column1 = (Column) obj1;\n Column column2 = (Column) obj2;\n return column1.getName().equals(column2.getName()) &&\n column1.isGenerated() == column2.isGenerated() &&\n column1.getType().equals(column2.getType()) &&\n column1.getData(column1.isGenerated() ? 10 : -1).equals(column2.getData(column2.isGenerated() ? 10 : -1));\n }\n return false;\n }\n \n private Object convertType(Object obj) {\n if (obj instanceof VType) {\n return obj;\n }\n Object converted = ValueFactory.toVType(obj);\n if (converted != null) {\n return converted;\n }\n return obj;\n }\n \n private Object[] convertTypes(Object... obj) {\n Object[] result = new Object[obj.length];\n for (int i = 0; i < result.length; i++) {\n result[i] = convertType(obj[i]);\n \n }\n return result;\n }\n\n public FunctionTester compareReturnAlarm(Alarm expected, Object... args) {\n if (convertTypes) {\n args = convertTypes(args);\n }\n\tAlarm result = ValueUtil.alarmOf(function.calculate(Arrays.asList(args)));\n\tassertThat(\n\t\t\"Wrong result for function '\" + function.getName() + \"(\"\n\t\t\t+ Arrays.toString(args) + \")'. Was (\" + VTypeToString.alarmToString(result)\n\t\t\t+ \") expected (\" + VTypeToString.alarmToString(expected) + \")\",\n VTypeValueEquals.alarmEquals(result, expected), equalTo(true));\n return this;\n }\n\n public FunctionTester compareReturnTime(Time expected, Object... args) {\n if (convertTypes) {\n args = convertTypes(args);\n }\n\tTime result = ValueUtil.timeOf(function.calculate(Arrays.asList(args)));\n\tassertThat(\n\t\t\"Wrong result for function '\" + function.getName() + \"(\"\n\t\t\t+ Arrays.toString(args) + \")'. Was (\" + VTypeToString.timeToString(result)\n\t\t\t+ \") expected (\" + VTypeToString.timeToString(expected) + \")\",\n\t\tVTypeValueEquals.timeEquals(result, expected), equalTo(true));\n return this;\n }\n \n public FunctionTester highestAlarmReturned() {\n if (function.isVarArgs() || function.getArgumentTypes().size() > 1) {\n highestAlarmReturnedMultipleArgs(function);\n } else {\n highestAlarmReturnedSingleArg(function);\n }\n return this;\n }\n\n private Object createValue(Class clazz, Alarm alarm, Time time, Display display) {\n if (clazz.equals(VNumber.class)) {\n return newVNumber(1.0, alarm, time, display);\n } else if (clazz.equals(VNumberArray.class)) {\n return newVNumberArray(new ArrayDouble(1.0), alarm, time, display);\n } else if (clazz.equals(VString.class)) {\n return newVString(\"A\", alarm, time);\n } else if (clazz.equals(VStringArray.class)) {\n return newVStringArray(Arrays.asList(\"A\"), alarm, time);\n } else if (clazz.equals(VBoolean.class)) {\n return newVBoolean(true, alarm, time);\n } else {\n throw new IllegalArgumentException(\"Can't create sample argument for class \" + clazz);\n }\n }\n \n private void highestAlarmReturnedSingleArg(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Alarm none = alarmNone();\n Alarm minor = newAlarm(AlarmSeverity.MINOR, \"HIGH\");\n Alarm major = newAlarm(AlarmSeverity.MAJOR, \"LOLO\");\n\n compareReturnAlarm(none, createValue(function.getArgumentTypes().get(0), none, timeNow(), display));\n compareReturnAlarm(minor, createValue(function.getArgumentTypes().get(0), minor, timeNow(), display));\n compareReturnAlarm(major, createValue(function.getArgumentTypes().get(0), major, timeNow(), display));\n }\n \n private void highestAlarmReturnedMultipleArgs(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Object[] args;\n if (function.isVarArgs()) {\n args = new Object[function.getArgumentTypes().size() + 1];\n } else {\n args = new Object[function.getArgumentTypes().size()];\n }\n Alarm none = alarmNone();\n Alarm minor = newAlarm(AlarmSeverity.MINOR, \"HIGH\");\n Alarm major = newAlarm(AlarmSeverity.MAJOR, \"LOLO\");\n \n // Prepare arguments with no alarm\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display);\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display);\n }\n compareReturnAlarm(none, args);\n \n // Prepare arguments with one minor and everything else none\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display);\n }\n compareReturnAlarm(minor, args);\n \n // Prepare arguments with one minor and everything else major\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), major, timeNow(), display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), major, timeNow(), display);\n }\n compareReturnAlarm(major, args);\n }\n \n public FunctionTester latestTimeReturned() {\n if (function.isVarArgs() || function.getArgumentTypes().size() > 1) {\n latestTimeReturnedMultipleArgs(function);\n } else {\n latestTimeReturnedSingleArg(function);\n }\n return this;\n }\n \n private void latestTimeReturnedSingleArg(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Object[] args;\n Time time1 = newTime(Timestamp.of(12340000, 0));\n Time time2 = newTime(Timestamp.of(12350000, 0));\n \n compareReturnTime(time1, createValue(function.getArgumentTypes().get(0), alarmNone(), time1, display));\n compareReturnTime(time2, createValue(function.getArgumentTypes().get(0), alarmNone(), time2, display));\n }\n \n private void latestTimeReturnedMultipleArgs(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Object[] args;\n if (function.isVarArgs()) {\n args = new Object[function.getArgumentTypes().size() + 1];\n } else {\n args = new Object[function.getArgumentTypes().size()];\n }\n Time time1 = newTime(Timestamp.of(12340000, 0));\n Time time2 = newTime(Timestamp.of(12350000, 0));\n \n // Prepare arguments with all time1\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display);\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display);\n }\n compareReturnTime(time1, args);\n \n // Prepare arguments with one time2 and everything else time1\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display);\n }\n compareReturnTime(time2, args);\n \n // Prepare arguments with one minor and everything else major\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time2, display);\n }\n compareReturnTime(time2, args);\n }\n}\n"},"new_file":{"kind":"string","value":"pvmanager-extra/src/test/java/org/epics/pvmanager/formula/FunctionTester.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT\n * All rights reserved. Use is subject to license terms. See LICENSE.TXT\n */\npackage org.epics.pvmanager.formula;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Objects;\nimport org.epics.util.array.ArrayDouble;\nimport org.epics.util.text.NumberFormats;\nimport org.epics.util.time.Timestamp;\nimport org.epics.vtype.Alarm;\nimport org.epics.vtype.AlarmSeverity;\nimport org.epics.vtype.Display;\nimport org.epics.vtype.Time;\nimport org.epics.vtype.VBoolean;\nimport org.epics.vtype.VDouble;\nimport org.epics.vtype.VNumber;\nimport org.epics.vtype.VNumberArray;\nimport org.epics.vtype.VString;\nimport org.epics.vtype.VStringArray;\nimport org.epics.vtype.VType;\nimport org.epics.vtype.VTypeToString;\nimport org.epics.vtype.VTypeValueEquals;\nimport org.epics.vtype.ValueFactory;\nimport static org.epics.vtype.ValueFactory.*;\nimport org.epics.vtype.ValueUtil;\nimport org.epics.vtype.table.Column;\nimport org.hamcrest.Matcher;\nimport static org.hamcrest.Matchers.*;\nimport org.junit.Assert;\nimport static org.junit.Assert.assertThat;\n\n/**\n *\n * @author carcassi\n */\npublic class FunctionTester {\n \n private final FormulaFunction function;\n private boolean convertTypes = true;\n \n private FunctionTester(FormulaFunction function) {\n this.function = function;\n }\n \n public static FunctionTester findByName(FormulaFunctionSet set, String name) {\n Collection functions = set.findFunctions(name);\n\tassertThat(\"Function '\" + name + \"' not found.\", functions.isEmpty(),\n\t\tequalTo(false));\n\tassertThat(\"Multiple matches for function '\" + name + \"'.\", functions.size(),\n\t\tequalTo(1));\n return new FunctionTester(functions.iterator().next());\n }\n \n public static FunctionTester findBySignature(FormulaFunctionSet set, String name, Class... argTypes) {\n Collection functions = set.findFunctions(name);\n\tassertThat(\"Function '\" + name + \"' not found.\", functions.isEmpty(),\n\t\tequalTo(false));\n \n functions = FormulaFunctions.findArgTypeMatch(Arrays.asList(argTypes), functions);\n\tassertThat(\"No matches found for function '\" + name + \"'.\", functions.isEmpty(),\n\t\tequalTo(false));\n\tassertThat(\"Multiple matches for function '\" + name + \"'.\", functions.size(),\n\t\tequalTo(1));\n return new FunctionTester(functions.iterator().next());\n }\n \n public FunctionTester convertTypes(boolean convertTypes) {\n this.convertTypes = convertTypes;\n return this;\n }\n \n public FunctionTester matchReturnValue(Matcher matcher, Object... args) {\n if (convertTypes) {\n args = convertTypes(args);\n }\n\tObject result = function.calculate(Arrays.asList(args));\n Assert.assertThat(result, matcher);\n return this;\n }\n\n public FunctionTester compareReturnValue(Object expected, Object... args) {\n if (convertTypes) {\n expected = convertType(expected);\n args = convertTypes(args);\n }\n\tObject result = function.calculate(Arrays.asList(args));\n if (result instanceof VDouble && expected instanceof VDouble) {\n assertThat(\"Wrong result for function '\" + function.getName() + \"(\"\n + Arrays.toString(args) + \")'.\", ((VDouble) result).getValue().doubleValue(),\n\t\tcloseTo(((VDouble) expected).getValue().doubleValue(), 0.0001));\n } else {\n assertThat(\n \"Wrong result for function '\" + function.getName() + \"(\"\n + Arrays.toString(args) + \")'. Was (\" + result\n + \") expected (\" + expected + \")\",\n compareValues(result, expected), equalTo(true));\n }\n return this;\n }\n \n public static boolean compareValues(Object obj1, Object obj2) {\n if (Objects.equals(obj1, obj2)) {\n return true;\n }\n if (obj1 instanceof VType && obj2 instanceof VType) {\n return VTypeValueEquals.valueEquals(obj1, obj2);\n } else if (obj1 instanceof Column && obj2 instanceof Column) {\n Column column1 = (Column) obj1;\n Column column2 = (Column) obj2;\n return column1.getName().equals(column2.getName()) &&\n column1.isGenerated() == column2.isGenerated() &&\n column1.getType().equals(column2.getType()) &&\n column1.getData(10).equals(column2.getData(10));\n }\n return false;\n }\n \n private Object convertType(Object obj) {\n if (obj instanceof VType) {\n return obj;\n }\n Object converted = ValueFactory.toVType(obj);\n if (converted != null) {\n return converted;\n }\n return obj;\n }\n \n private Object[] convertTypes(Object... obj) {\n Object[] result = new Object[obj.length];\n for (int i = 0; i < result.length; i++) {\n result[i] = convertType(obj[i]);\n \n }\n return result;\n }\n\n public FunctionTester compareReturnAlarm(Alarm expected, Object... args) {\n if (convertTypes) {\n args = convertTypes(args);\n }\n\tAlarm result = ValueUtil.alarmOf(function.calculate(Arrays.asList(args)));\n\tassertThat(\n\t\t\"Wrong result for function '\" + function.getName() + \"(\"\n\t\t\t+ Arrays.toString(args) + \")'. Was (\" + VTypeToString.alarmToString(result)\n\t\t\t+ \") expected (\" + VTypeToString.alarmToString(expected) + \")\",\n VTypeValueEquals.alarmEquals(result, expected), equalTo(true));\n return this;\n }\n\n public FunctionTester compareReturnTime(Time expected, Object... args) {\n if (convertTypes) {\n args = convertTypes(args);\n }\n\tTime result = ValueUtil.timeOf(function.calculate(Arrays.asList(args)));\n\tassertThat(\n\t\t\"Wrong result for function '\" + function.getName() + \"(\"\n\t\t\t+ Arrays.toString(args) + \")'. Was (\" + VTypeToString.timeToString(result)\n\t\t\t+ \") expected (\" + VTypeToString.timeToString(expected) + \")\",\n\t\tVTypeValueEquals.timeEquals(result, expected), equalTo(true));\n return this;\n }\n \n public FunctionTester highestAlarmReturned() {\n if (function.isVarArgs() || function.getArgumentTypes().size() > 1) {\n highestAlarmReturnedMultipleArgs(function);\n } else {\n highestAlarmReturnedSingleArg(function);\n }\n return this;\n }\n\n private Object createValue(Class clazz, Alarm alarm, Time time, Display display) {\n if (clazz.equals(VNumber.class)) {\n return newVNumber(1.0, alarm, time, display);\n } else if (clazz.equals(VNumberArray.class)) {\n return newVNumberArray(new ArrayDouble(1.0), alarm, time, display);\n } else if (clazz.equals(VString.class)) {\n return newVString(\"A\", alarm, time);\n } else if (clazz.equals(VStringArray.class)) {\n return newVStringArray(Arrays.asList(\"A\"), alarm, time);\n } else if (clazz.equals(VBoolean.class)) {\n return newVBoolean(true, alarm, time);\n } else {\n throw new IllegalArgumentException(\"Can't create sample argument for class \" + clazz);\n }\n }\n \n private void highestAlarmReturnedSingleArg(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Alarm none = alarmNone();\n Alarm minor = newAlarm(AlarmSeverity.MINOR, \"HIGH\");\n Alarm major = newAlarm(AlarmSeverity.MAJOR, \"LOLO\");\n\n compareReturnAlarm(none, createValue(function.getArgumentTypes().get(0), none, timeNow(), display));\n compareReturnAlarm(minor, createValue(function.getArgumentTypes().get(0), minor, timeNow(), display));\n compareReturnAlarm(major, createValue(function.getArgumentTypes().get(0), major, timeNow(), display));\n }\n \n private void highestAlarmReturnedMultipleArgs(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Object[] args;\n if (function.isVarArgs()) {\n args = new Object[function.getArgumentTypes().size() + 1];\n } else {\n args = new Object[function.getArgumentTypes().size()];\n }\n Alarm none = alarmNone();\n Alarm minor = newAlarm(AlarmSeverity.MINOR, \"HIGH\");\n Alarm major = newAlarm(AlarmSeverity.MAJOR, \"LOLO\");\n \n // Prepare arguments with no alarm\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display);\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display);\n }\n compareReturnAlarm(none, args);\n \n // Prepare arguments with one minor and everything else none\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display);\n }\n compareReturnAlarm(minor, args);\n \n // Prepare arguments with one minor and everything else major\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), major, timeNow(), display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), major, timeNow(), display);\n }\n compareReturnAlarm(major, args);\n }\n \n public FunctionTester latestTimeReturned() {\n if (function.isVarArgs() || function.getArgumentTypes().size() > 1) {\n latestTimeReturnedMultipleArgs(function);\n } else {\n latestTimeReturnedSingleArg(function);\n }\n return this;\n }\n \n private void latestTimeReturnedSingleArg(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Object[] args;\n Time time1 = newTime(Timestamp.of(12340000, 0));\n Time time2 = newTime(Timestamp.of(12350000, 0));\n \n compareReturnTime(time1, createValue(function.getArgumentTypes().get(0), alarmNone(), time1, display));\n compareReturnTime(time2, createValue(function.getArgumentTypes().get(0), alarmNone(), time2, display));\n }\n \n private void latestTimeReturnedMultipleArgs(FormulaFunction function) {\n Display display = newDisplay(-5.0, -4.0, -3.0, \"m\", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0);\n Object[] args;\n if (function.isVarArgs()) {\n args = new Object[function.getArgumentTypes().size() + 1];\n } else {\n args = new Object[function.getArgumentTypes().size()];\n }\n Time time1 = newTime(Timestamp.of(12340000, 0));\n Time time2 = newTime(Timestamp.of(12350000, 0));\n \n // Prepare arguments with all time1\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display);\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display);\n }\n compareReturnTime(time1, args);\n \n // Prepare arguments with one time2 and everything else time1\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display);\n }\n compareReturnTime(time2, args);\n \n // Prepare arguments with one minor and everything else major\n for (int i = 0; i < function.getArgumentTypes().size(); i++) {\n if (i == args.length - 1) {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display);\n } else {\n args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display);\n }\n }\n if (function.isVarArgs()) {\n args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time2, display);\n }\n compareReturnTime(time2, args);\n }\n}\n"},"message":{"kind":"string","value":"formula: fixing compareValue for columns"},"old_file":{"kind":"string","value":"pvmanager-extra/src/test/java/org/epics/pvmanager/formula/FunctionTester.java"},"subject":{"kind":"string","value":"formula: fixing compareValue for columns"}}},{"rowIdx":1268,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"73cb70c2c651189121cb0754a6118c8aec37a78e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"eaglerainbow/docker-plugin,jenkinsci/docker-plugin,jenkinsci/docker-plugin,jenkinsci/docker-plugin,eaglerainbow/docker-plugin,eaglerainbow/docker-plugin"},"new_contents":{"kind":"string","value":"package com.nirima.jenkins.plugins.docker;\n\nimport com.github.dockerjava.api.DockerClient;\nimport com.github.dockerjava.api.command.PushImageCmd;\nimport com.github.dockerjava.api.exception.DockerException;\nimport com.github.dockerjava.api.model.AuthConfig;\nimport com.github.dockerjava.api.model.Identifier;\nimport com.github.dockerjava.api.model.PushResponseItem;\nimport com.github.dockerjava.core.NameParser;\nimport com.github.dockerjava.core.command.PushImageResultCallback;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.nirima.jenkins.plugins.docker.action.DockerBuildAction;\nimport hudson.Extension;\nimport hudson.model.AbstractBuild;\nimport hudson.model.Descriptor;\nimport hudson.model.Queue;\nimport hudson.model.Run;\nimport hudson.model.TaskListener;\nimport hudson.model.queue.CauseOfBlockage;\nimport hudson.slaves.AbstractCloudSlave;\nimport hudson.slaves.Cloud;\nimport hudson.slaves.ComputerLauncher;\nimport hudson.slaves.NodeProperty;\nimport hudson.slaves.RetentionStrategy;\nimport jenkins.model.Jenkins;\nimport org.jenkinsci.plugins.tokenmacro.TokenMacro;\n\nimport javax.annotation.CheckForNull;\nimport java.io.IOException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport static com.nirima.jenkins.plugins.docker.utils.JenkinsUtils.getAuthConfigFor;\nimport static com.nirima.jenkins.plugins.docker.utils.LogUtils.printResponseItemToListener;\nimport static org.apache.commons.lang.StringUtils.isEmpty;\n\n\npublic class DockerSlave extends AbstractCloudSlave {\n private static final Logger LOGGER = Logger.getLogger(DockerSlave.class.getName());\n\n public DockerTemplate dockerTemplate;\n\n // remember container id\n @CheckForNull private String containerId;\n\n // remember cloud name\n @CheckForNull private String cloudId;\n\n private transient Run theRun;\n\n public DockerSlave(DockerTemplate dockerTemplate, String containerId,\n String name, String nodeDescription,\n String remoteFS, int numExecutors, Mode mode,\n String labelString, ComputerLauncher launcher,\n RetentionStrategy retentionStrategy,\n List> nodeProperties)\n throws Descriptor.FormException, IOException {\n super(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, nodeProperties);\n Preconditions.checkNotNull(dockerTemplate);\n Preconditions.checkNotNull(containerId);\n\n setDockerTemplate(dockerTemplate);\n this.containerId = containerId;\n }\n\n public DockerSlave(String slaveName, String nodeDescription, ComputerLauncher launcher, String containerId,\n DockerTemplate dockerTemplate, String cloudId)\n throws IOException, Descriptor.FormException {\n super(slaveName,\n nodeDescription, //description\n dockerTemplate.getRemoteFs(),\n dockerTemplate.getNumExecutors(),\n dockerTemplate.getMode(),\n dockerTemplate.getLabelString(),\n launcher,\n dockerTemplate.getRetentionStrategyCopy(),\n dockerTemplate.getNodeProperties()\n );\n setContainerId(containerId);\n setDockerTemplate(dockerTemplate);\n setCloudId(cloudId);\n }\n\n public DockerSlave(DockerCloud cloud, DockerTemplate template, ComputerLauncher launcher) throws IOException, Descriptor.FormException {\n super(\n cloud.getDisplayName() + '-' + Long.toHexString(System.nanoTime()),\n \"Docker Node [\" + template.getDockerTemplateBase().getImage() + \" on \"+ cloud.getDisplayName() + \"]\",\n template.getRemoteFs(),\n template.getNumExecutors(),\n template.getMode(),\n template.getLabelString(),\n launcher,\n template.getRetentionStrategyCopy(),\n Collections.>emptyList()\n );\n this.cloudId = cloud.getDisplayName();\n this.dockerTemplate = template;\n }\n\n public String getContainerId() {\n return containerId;\n }\n\n public void setContainerId(String containerId) {\n this.containerId = containerId;\n }\n\n public String getCloudId() {\n return cloudId;\n }\n\n public void setCloudId(String cloudId) {\n this.cloudId = cloudId;\n }\n\n public DockerTemplate getDockerTemplate() {\n return dockerTemplate;\n }\n\n public void setDockerTemplate(DockerTemplate dockerTemplate) {\n this.dockerTemplate = dockerTemplate;\n }\n\n public DockerCloud getCloud() {\n final Cloud cloud = Jenkins.getInstance().getCloud(getCloudId());\n\n if (cloud == null) {\n throw new RuntimeException(\"Docker template \" + dockerTemplate + \" has no assigned Cloud.\");\n }\n\n if (cloud.getClass() != DockerCloud.class) {\n throw new RuntimeException(\"Assigned cloud is not DockerCloud\");\n }\n\n return (DockerCloud) cloud;\n }\n\n @Override\n public DockerComputer getComputer() {\n return (DockerComputer) super.getComputer();\n }\n\n @Override\n public String getDisplayName() {\n return name;\n }\n\n public void setRun(Run run) {\n this.theRun = run;\n }\n\n @Override\n public DockerComputer createComputer() {\n return new DockerComputer(this);\n }\n\n @Override\n public CauseOfBlockage canTake(Queue.BuildableItem item) {\n if (item.task instanceof Queue.FlyweightTask) {\n return new CauseOfBlockage() {\n public String getShortDescription() {\n return \"Don't run FlyweightTask on Docker node\";\n }\n };\n }\n return super.canTake(item);\n }\n\n public boolean containerExistsInCloud() {\n try {\n DockerClient client = getClient();\n client.inspectContainerCmd(containerId).exec();\n return true;\n } catch (Exception ex) {\n return false;\n }\n }\n\n @Override\n protected void _terminate(TaskListener listener) throws IOException, InterruptedException {\n try {\n toComputer().disconnect(new DockerOfflineCause());\n LOGGER.log(Level.INFO, \"Disconnected computer\");\n } catch (Exception e) {\n LOGGER.log(Level.SEVERE, \"Can't disconnect\", e);\n }\n\n if (containerId != null) {\n try {\n DockerClient client = getClient();\n client.stopContainerCmd(getContainerId()).exec();\n LOGGER.log(Level.INFO, \"Stopped container {0}\", getContainerId());\n } catch (Exception ex) {\n LOGGER.log(Level.SEVERE, \"Failed to stop instance \" + getContainerId() + \" for slave \" + name + \" due to exception\", ex.getMessage());\n LOGGER.log(Level.SEVERE, \"Causing exception for failure on stopping the instance was\", ex);\n }\n\n // If the run was OK, then do any tagging here\n if (theRun != null) {\n try {\n slaveShutdown(listener);\n LOGGER.log(Level.INFO, \"Shutdowned slave for {0}\", getContainerId());\n } catch (Exception e) {\n LOGGER.log(Level.SEVERE, \"Failure to slaveShutdown instance \" + getContainerId() + \" for slave \" + name, e);\n LOGGER.log(Level.SEVERE, \"Causing exception for failure on slaveShutdown was\", e);\n }\n }\n\n try {\n DockerClient client = getClient();\n client.removeContainerCmd(containerId)\n .withRemoveVolumes(getDockerTemplate().isRemoveVolumes())\n .exec();\n\n LOGGER.log(Level.INFO, \"Removed container {0}\", getContainerId());\n } catch (Exception ex) {\n LOGGER.log(Level.SEVERE, \"Failed to remove instance \" + getContainerId() + \" for slave \" + name + \" due to exception: \" + ex.getMessage());\n LOGGER.log(Level.SEVERE, \"Causing exception for failre on removing instance was\", ex);\n }\n } else {\n LOGGER.log(Level.SEVERE, \"ContainerId is absent, no way to remove/stop container\");\n }\n }\n\n private void slaveShutdown(final TaskListener listener) throws DockerException, IOException {\n\n // The slave has stopped. Should we commit / tag / push ?\n\n if (!getJobProperty().tagOnCompletion) {\n addJenkinsAction(null);\n return;\n }\n\n DockerClient client = getClient();\n\n\n // Commit\n String tag_image = client.commitCmd(containerId)\n .withRepository(theRun.getParent().getDisplayName())\n .withTag(theRun.getDisplayName().replace(\"#\", \"b\")) // allowed only ([a-zA-Z_][a-zA-Z0-9_]*)\n .withAuthor(\"Jenkins\")\n .exec();\n\n // Tag it with the jenkins name\n addJenkinsAction(tag_image);\n\n // SHould we add additional tags?\n try {\n String tagToken = getAdditionalTag(listener);\n\n if (!Strings.isNullOrEmpty(tagToken)) {\n\n\n final NameParser.ReposTag reposTag = NameParser.parseRepositoryTag(tagToken);\n final String commitTag = isEmpty(reposTag.tag) ? \"latest\" : reposTag.tag;\n\n getClient().tagImageCmd(tag_image, reposTag.repos, commitTag).withForce().exec();\n\n addJenkinsAction(tagToken);\n\n if (getJobProperty().pushOnSuccess) {\n Identifier identifier = Identifier.fromCompoundString(tagToken);\n\n PushImageResultCallback resultCallback = new PushImageResultCallback() {\n public void onNext(PushResponseItem item) {\n printResponseItemToListener(listener, item);\n super.onNext(item);\n }\n };\n try {\n\n PushImageCmd cmd = getClient().pushImageCmd(identifier);\n AuthConfig authConfig = getAuthConfigFor(tagToken);\n if( authConfig != null ) {\n cmd.withAuthConfig(authConfig);\n }\n cmd.exec(resultCallback).awaitSuccess();\n\n } catch(DockerException ex) {\n\n LOGGER.log(Level.SEVERE, \"Exception pushing docker image. Check that the destination registry is running.\", ex);\n throw ex;\n }\n }\n }\n } catch (Exception ex) {\n LOGGER.log(Level.SEVERE, \"Could not add additional tags\", ex);\n }\n\n if (getJobProperty().cleanImages) {\n\n client.removeImageCmd(tag_image)\n .withForce(true)\n .exec();\n }\n\n }\n\n private String getAdditionalTag(TaskListener listener) {\n // Do a macro expansion on the addJenkinsAction token\n\n // Job property\n String tagToken = getJobProperty().additionalTag;\n\n // Do any macro expansions\n try {\n if (!Strings.isNullOrEmpty(tagToken))\n tagToken = TokenMacro.expandAll((AbstractBuild) theRun, listener, tagToken);\n } catch (Exception e) {\n LOGGER.log(Level.WARNING, \"can't expand macroses\", e);\n }\n return tagToken;\n }\n\n /**\n * Add a built on docker action.\n */\n private void addJenkinsAction(String tag_image) throws IOException {\n theRun.addAction(new DockerBuildAction(getCloud().getServerUrl(), containerId, tag_image, dockerTemplate.remoteFsMapping));\n theRun.save();\n }\n\n public DockerClient getClient() {\n return getCloud().getClient();\n }\n\n private DockerJobProperty getJobProperty() {\n\n try {\n DockerJobProperty p = (DockerJobProperty) ((AbstractBuild) theRun).getProject().getProperty(DockerJobProperty.class);\n\n if (p != null)\n return p;\n } catch (Exception ex) {\n // Don't care.\n }\n // Safe default\n return new DockerJobProperty(false, null, false, true, null);\n }\n\n @Override\n public String toString() {\n return Objects.toStringHelper(this)\n .add(\"name\", name)\n .add(\"containerId\", containerId)\n .add(\"template\", dockerTemplate)\n .toString();\n }\n\n @Extension\n public static final class DescriptorImpl extends SlaveDescriptor {\n\n @Override\n public String getDisplayName() {\n return \"Docker Slave\";\n }\n\n @Override\n public boolean isInstantiable() {\n return false;\n }\n\n }\n}\n"},"new_file":{"kind":"string","value":"docker-plugin/src/main/java/com/nirima/jenkins/plugins/docker/DockerSlave.java"},"old_contents":{"kind":"string","value":"package com.nirima.jenkins.plugins.docker;\n\nimport com.github.dockerjava.api.DockerClient;\nimport com.github.dockerjava.api.command.PushImageCmd;\nimport com.github.dockerjava.api.exception.DockerException;\nimport com.github.dockerjava.api.model.AuthConfig;\nimport com.github.dockerjava.api.model.Identifier;\nimport com.github.dockerjava.api.model.PushResponseItem;\nimport com.github.dockerjava.core.NameParser;\nimport com.github.dockerjava.core.command.PushImageResultCallback;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.nirima.jenkins.plugins.docker.action.DockerBuildAction;\nimport hudson.Extension;\nimport hudson.model.AbstractBuild;\nimport hudson.model.Descriptor;\nimport hudson.model.Queue;\nimport hudson.model.Run;\nimport hudson.model.TaskListener;\nimport hudson.model.queue.CauseOfBlockage;\nimport hudson.slaves.AbstractCloudSlave;\nimport hudson.slaves.Cloud;\nimport hudson.slaves.ComputerLauncher;\nimport hudson.slaves.NodeProperty;\nimport hudson.slaves.RetentionStrategy;\nimport jenkins.model.Jenkins;\nimport org.jenkinsci.plugins.tokenmacro.TokenMacro;\n\nimport javax.annotation.CheckForNull;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport static com.nirima.jenkins.plugins.docker.utils.JenkinsUtils.getAuthConfigFor;\nimport static com.nirima.jenkins.plugins.docker.utils.LogUtils.printResponseItemToListener;\nimport static org.apache.commons.lang.StringUtils.isEmpty;\n\n\npublic class DockerSlave extends AbstractCloudSlave {\n private static final Logger LOGGER = Logger.getLogger(DockerSlave.class.getName());\n\n public DockerTemplate dockerTemplate;\n\n // remember container id\n @CheckForNull private String containerId;\n\n // remember cloud name\n @CheckForNull private String cloudId;\n\n private transient Run theRun;\n\n public DockerSlave(DockerTemplate dockerTemplate, String containerId,\n String name, String nodeDescription,\n String remoteFS, int numExecutors, Mode mode,\n String labelString, ComputerLauncher launcher,\n RetentionStrategy retentionStrategy,\n List> nodeProperties)\n throws Descriptor.FormException, IOException {\n super(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, nodeProperties);\n Preconditions.checkNotNull(dockerTemplate);\n Preconditions.checkNotNull(containerId);\n\n setDockerTemplate(dockerTemplate);\n this.containerId = containerId;\n }\n\n public DockerSlave(String slaveName, String nodeDescription, ComputerLauncher launcher, String containerId,\n DockerTemplate dockerTemplate, String cloudId)\n throws IOException, Descriptor.FormException {\n super(slaveName,\n nodeDescription, //description\n dockerTemplate.getRemoteFs(),\n dockerTemplate.getNumExecutors(),\n dockerTemplate.getMode(),\n dockerTemplate.getLabelString(),\n launcher,\n dockerTemplate.getRetentionStrategyCopy(),\n dockerTemplate.getNodeProperties()\n );\n setContainerId(containerId);\n setDockerTemplate(dockerTemplate);\n setCloudId(cloudId);\n }\n\n public DockerSlave(DockerCloud cloud, DockerTemplate template, ComputerLauncher launcher) throws IOException, Descriptor.FormException {\n super(\n cloud.getDisplayName() + '-' + Long.toHexString(System.nanoTime()),\n \"Docker Node [\" + template.getDockerTemplateBase().getImage() + \" on \"+ cloud.getDisplayName() + \"]\",\n template.getRemoteFs(),\n template.getNumExecutors(),\n template.getMode(),\n template.getLabelString(),\n launcher,\n template.getRetentionStrategyCopy(),\n Collections.>emptyList()\n );\n this.cloudId = cloud.getDisplayName();\n this.dockerTemplate = template;\n }\n\n public String getContainerId() {\n return containerId;\n }\n\n public void setContainerId(String containerId) {\n this.containerId = containerId;\n }\n\n public String getCloudId() {\n return cloudId;\n }\n\n public void setCloudId(String cloudId) {\n this.cloudId = cloudId;\n }\n\n public DockerTemplate getDockerTemplate() {\n return dockerTemplate;\n }\n\n public void setDockerTemplate(DockerTemplate dockerTemplate) {\n this.dockerTemplate = dockerTemplate;\n }\n\n public DockerCloud getCloud() {\n final Cloud cloud = Jenkins.getInstance().getCloud(getCloudId());\n\n if (cloud == null) {\n throw new RuntimeException(\"Docker template \" + dockerTemplate + \" has no assigned Cloud.\");\n }\n\n if (cloud.getClass() != DockerCloud.class) {\n throw new RuntimeException(\"Assigned cloud is not DockerCloud\");\n }\n\n return (DockerCloud) cloud;\n }\n\n @Override\n public DockerComputer getComputer() {\n return (DockerComputer) super.getComputer();\n }\n\n @Override\n public String getDisplayName() {\n return name;\n }\n\n public void setRun(Run run) {\n this.theRun = run;\n }\n\n @Override\n public DockerComputer createComputer() {\n return new DockerComputer(this);\n }\n\n @Override\n public CauseOfBlockage canTake(Queue.BuildableItem item) {\n if (item.task instanceof Queue.FlyweightTask) {\n return new CauseOfBlockage() {\n public String getShortDescription() {\n return \"Don't run FlyweightTask on Docker node\";\n }\n };\n }\n return super.canTake(item);\n }\n\n public boolean containerExistsInCloud() {\n try {\n DockerClient client = getClient();\n client.inspectContainerCmd(containerId).exec();\n return true;\n } catch (Exception ex) {\n return false;\n }\n }\n\n @Override\n protected void _terminate(TaskListener listener) throws IOException, InterruptedException {\n try {\n toComputer().disconnect(new DockerOfflineCause());\n LOGGER.log(Level.INFO, \"Disconnected computer\");\n } catch (Exception e) {\n LOGGER.log(Level.SEVERE, \"Can't disconnect\", e);\n }\n\n if (containerId != null) {\n try {\n DockerClient client = getClient();\n client.stopContainerCmd(getContainerId()).exec();\n LOGGER.log(Level.INFO, \"Stopped container {0}\", getContainerId());\n } catch (Exception ex) {\n LOGGER.log(Level.SEVERE, \"Failed to stop instance \" + getContainerId() + \" for slave \" + name + \" due to exception\", ex.getMessage());\n LOGGER.log(Level.SEVERE, \"Causing exception for failure on stopping the instance was\", ex);\n }\n\n // If the run was OK, then do any tagging here\n if (theRun != null) {\n try {\n slaveShutdown(listener);\n LOGGER.log(Level.INFO, \"Shutdowned slave for {0}\", getContainerId());\n } catch (Exception e) {\n LOGGER.log(Level.SEVERE, \"Failure to slaveShutdown instance \" + getContainerId() + \" for slave \" + name, e);\n LOGGER.log(Level.SEVERE, \"Causing exception for failure on slaveShutdown was\", e);\n }\n }\n\n try {\n DockerClient client = getClient();\n client.removeContainerCmd(containerId)\n .withRemoveVolumes(getDockerTemplate().isRemoveVolumes())\n .exec();\n\n LOGGER.log(Level.INFO, \"Removed container {0}\", getContainerId());\n } catch (Exception ex) {\n LOGGER.log(Level.SEVERE, \"Failed to remove instance \" + getContainerId() + \" for slave \" + name + \" due to exception: \" + ex.getMessage());\n LOGGER.log(Level.SEVERE, \"Causing exception for failre on removing instance was\", ex);\n }\n } else {\n LOGGER.log(Level.SEVERE, \"ContainerId is absent, no way to remove/stop container\");\n }\n }\n\n private void slaveShutdown(final TaskListener listener) throws DockerException, IOException {\n\n // The slave has stopped. Should we commit / tag / push ?\n\n if (!getJobProperty().tagOnCompletion) {\n addJenkinsAction(null);\n return;\n }\n\n DockerClient client = getClient();\n\n\n // Commit\n String tag_image = client.commitCmd(containerId)\n .withRepository(theRun.getParent().getDisplayName())\n .withTag(theRun.getDisplayName().replace(\"#\", \"b\")) // allowed only ([a-zA-Z_][a-zA-Z0-9_]*)\n .withAuthor(\"Jenkins\")\n .exec();\n\n // Tag it with the jenkins name\n addJenkinsAction(tag_image);\n\n // SHould we add additional tags?\n try {\n String tagToken = getAdditionalTag(listener);\n\n if (!Strings.isNullOrEmpty(tagToken)) {\n\n\n final NameParser.ReposTag reposTag = NameParser.parseRepositoryTag(tagToken);\n final String commitTag = isEmpty(reposTag.tag) ? \"latest\" : reposTag.tag;\n\n getClient().tagImageCmd(tag_image, reposTag.repos, commitTag).withForce().exec();\n\n addJenkinsAction(tagToken);\n\n if (getJobProperty().pushOnSuccess) {\n Identifier identifier = Identifier.fromCompoundString(tagToken);\n\n PushImageResultCallback resultCallback = new PushImageResultCallback() {\n public void onNext(PushResponseItem item) {\n printResponseItemToListener(listener, item);\n super.onNext(item);\n }\n };\n try {\n\n PushImageCmd cmd = getClient().pushImageCmd(identifier);\n AuthConfig authConfig = getAuthConfigFor(tagToken);\n if( authConfig != null ) {\n cmd.withAuthConfig(authConfig);\n }\n cmd.exec(resultCallback).awaitSuccess();\n\n } catch(DockerException ex) {\n\n LOGGER.log(Level.SEVERE, \"Exception pushing docker image. Check that the destination registry is running.\", ex);\n throw ex;\n }\n }\n }\n } catch (Exception ex) {\n LOGGER.log(Level.SEVERE, \"Could not add additional tags\", ex);\n }\n\n if (getJobProperty().cleanImages) {\n\n client.removeImageCmd(tag_image)\n .withForce(true)\n .exec();\n }\n\n }\n\n private String getAdditionalTag(TaskListener listener) {\n // Do a macro expansion on the addJenkinsAction token\n\n // Job property\n String tagToken = getJobProperty().additionalTag;\n\n // Do any macro expansions\n try {\n if (!Strings.isNullOrEmpty(tagToken))\n tagToken = TokenMacro.expandAll((AbstractBuild) theRun, listener, tagToken);\n } catch (Exception e) {\n LOGGER.log(Level.WARNING, \"can't expand macroses\", e);\n }\n return tagToken;\n }\n\n /**\n * Add a built on docker action.\n */\n private void addJenkinsAction(String tag_image) throws IOException {\n theRun.addAction(new DockerBuildAction(getCloud().getServerUrl(), containerId, tag_image, dockerTemplate.remoteFsMapping));\n theRun.save();\n }\n\n public DockerClient getClient() {\n return getCloud().getClient();\n }\n\n private DockerJobProperty getJobProperty() {\n\n try {\n DockerJobProperty p = (DockerJobProperty) ((AbstractBuild) theRun).getProject().getProperty(DockerJobProperty.class);\n\n if (p != null)\n return p;\n } catch (Exception ex) {\n // Don't care.\n }\n // Safe default\n return new DockerJobProperty(false, null, false, true, null);\n }\n\n @Override\n public String toString() {\n return Objects.toStringHelper(this)\n .add(\"name\", name)\n .add(\"containerId\", containerId)\n .add(\"template\", dockerTemplate)\n .toString();\n }\n\n @Extension\n public static final class DescriptorImpl extends SlaveDescriptor {\n\n @Override\n public String getDisplayName() {\n return \"Docker Slave\";\n }\n\n @Override\n public boolean isInstantiable() {\n return false;\n }\n\n }\n}\n"},"message":{"kind":"string","value":"missing import"},"old_file":{"kind":"string","value":"docker-plugin/src/main/java/com/nirima/jenkins/plugins/docker/DockerSlave.java"},"subject":{"kind":"string","value":"missing import"}}},{"rowIdx":1269,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"163b37ed377f90f929c78cf17ad1b94ce405cb49"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"vgt-tomek/image-draw"},"new_contents":{"kind":"string","value":"package pl.vgtworld.imagedraw.processing;\n\nimport java.awt.Image;\nimport java.awt.image.BufferedImage;\n\nimport pl.vgtworld.imagedraw.ImageDrawEntity;\n\nclass ImageResizeActions {\n\t\n\tpublic void resize(ImageDrawEntity image, Integer newWidth, Integer newHeight) {\n\t\tdimensionValidation(newWidth, newHeight);\n\t\tif (newWidth == null) {\n\t\t\tnewWidth = calculateNewWidth(image, newHeight);\n\t\t}\n\t\tif (newHeight == null) {\n\t\t\tnewHeight = calculateNewHeight(image, newWidth);\n\t\t}\n\t\tBufferedImage currentImageData = image.getImage();\n\t\tImage scaledInstance = currentImageData.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);\n\t\tBufferedImage resizedImageData = new BufferedImage(newWidth, newHeight, image.getImage().getType());\n\t\tresizedImageData.getGraphics().drawImage(scaledInstance, 0, 0, null);\n\t\timage.setImage(resizedImageData);\n\t}\n\n\tprivate int calculateNewWidth(ImageDrawEntity image, int newHeight) {\n\t\treturn calculateNewEdgeLength(image.getImage().getWidth(), image.getImage().getHeight(), newHeight);\n\t}\n\t\n\tprivate int calculateNewHeight(ImageDrawEntity image, int newWidth) {\n\t\treturn calculateNewEdgeLength(image.getImage().getHeight(), image.getImage().getWidth(), newWidth);\n\t}\n\n\tprivate int calculateNewEdgeLength(int currentEdgeLength, int currentOtherEdgeLength, int newOtherEdgeLength) {\n\t\tfloat resizeRatio = newOtherEdgeLength / (float)currentOtherEdgeLength;\n\t\tfloat calculatedLength = currentEdgeLength * resizeRatio;\n\t\tint roundedLength = Math.round(calculatedLength);\n\t\treturn roundedLength == 0 ? 1 : roundedLength;\n\t}\n\n\tprivate void dimensionValidation(Integer newWidth, Integer newHeight) {\n\t\tif (newWidth == null && newHeight == null) {\n\t\t\tthrow new IllegalStateException(\"At least one dimension must not be null\");\n\t\t}\n\t\tif ((newWidth != null && newWidth <= 0) || (newHeight != null && newHeight <= 0)) {\n\t\t\tthrow new IllegalArgumentException(\"Dimension cannot be negative\");\n\t\t}\n\t}\n\t\n}\n"},"new_file":{"kind":"string","value":"image-draw/src/main/java/pl/vgtworld/imagedraw/processing/ImageResizeActions.java"},"old_contents":{"kind":"string","value":"package pl.vgtworld.imagedraw.processing;\n\nimport java.awt.image.BufferedImage;\n\nimport pl.vgtworld.imagedraw.ImageDrawEntity;\n\nclass ImageResizeActions {\n\t\n\tpublic void resize(ImageDrawEntity image, Integer newWidth, Integer newHeight) {\n\t\tdimensionValidation(newWidth, newHeight);\n\t\tif (newWidth == null) {\n\t\t\tnewWidth = calculateNewWidth(image, newHeight);\n\t\t}\n\t\tif (newHeight == null) {\n\t\t\tnewHeight = calculateNewHeight(image, newWidth);\n\t\t}\n\t\tBufferedImage currentImageData = image.getImage();\n\t\tjava.awt.Image scaledInstance = currentImageData.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH);\n\t\tBufferedImage resizedImageData = new BufferedImage(newWidth, newHeight, image.getImage().getType());\n\t\tresizedImageData.getGraphics().drawImage(scaledInstance, 0, 0, null);\n\t\timage.setImage(resizedImageData);\n\t}\n\n\tprivate int calculateNewWidth(ImageDrawEntity image, int newHeight) {\n\t\treturn calculateNewEdgeLength(image.getImage().getWidth(), image.getImage().getHeight(), newHeight);\n\t}\n\t\n\tprivate int calculateNewHeight(ImageDrawEntity image, int newWidth) {\n\t\treturn calculateNewEdgeLength(image.getImage().getHeight(), image.getImage().getWidth(), newWidth);\n\t}\n\n\tprivate int calculateNewEdgeLength(int currentEdgeLength, int currentOtherEdgeLength, int newOtherEdgeLength) {\n\t\tfloat resizeRatio = newOtherEdgeLength / (float)currentOtherEdgeLength;\n\t\tfloat calculatedLength = currentEdgeLength * resizeRatio;\n\t\tint roundedLength = Math.round(calculatedLength);\n\t\treturn roundedLength == 0 ? 1 : roundedLength;\n\t}\n\n\tprivate void dimensionValidation(Integer newWidth, Integer newHeight) {\n\t\tif (newWidth == null && newHeight == null) {\n\t\t\tthrow new IllegalStateException(\"At least one dimension must not be null\");\n\t\t}\n\t\tif ((newWidth != null && newWidth <= 0) || (newHeight != null && newHeight <= 0)) {\n\t\t\tthrow new IllegalArgumentException(\"Dimension cannot be negative\");\n\t\t}\n\t}\n\t\n}\n"},"message":{"kind":"string","value":"Import java.awt.Image instead of using full name."},"old_file":{"kind":"string","value":"image-draw/src/main/java/pl/vgtworld/imagedraw/processing/ImageResizeActions.java"},"subject":{"kind":"string","value":"Import java.awt.Image instead of using full name."}}},{"rowIdx":1270,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d54a39183e348223a42a94c238d584cf4387be51"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sstrickx/yahoofinance-api,chris-ch/yahoofinance-api"},"new_contents":{"kind":"string","value":"package yahoofinance;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.Calendar;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport yahoofinance.histquotes.HistQuotesRequest;\nimport yahoofinance.histquotes.HistoricalQuote;\nimport yahoofinance.histquotes.Interval;\nimport yahoofinance.quotes.stock.StockDividend;\nimport yahoofinance.quotes.stock.StockQuote;\nimport yahoofinance.quotes.stock.StockQuotesData;\nimport yahoofinance.quotes.stock.StockQuotesRequest;\nimport yahoofinance.quotes.stock.StockStats;\n\n/**\n *\n * @author Stijn Strickx\n */\npublic class Stock {\n\n private final String symbol;\n private String name;\n private String currency;\n private String stockExchange;\n \n private StockQuote quote;\n private StockStats stats;\n private StockDividend dividend;\n \n private List history;\n \n public Stock(String symbol) {\n this.symbol = symbol;\n }\n \n private void update() throws IOException {\n StockQuotesRequest request = new StockQuotesRequest(this.symbol);\n StockQuotesData data = request.getSingleResult();\n if(data != null) {\n this.setQuote(data.getQuote());\n this.setStats(data.getStats());\n this.setDividend(data.getDividend());\n YahooFinance.logger.log(Level.INFO, \"Updated Stock with symbol: {0}\", this.symbol);\n } else {\n YahooFinance.logger.log(Level.SEVERE, \"Failed to update Stock with symbol: {0}\", this.symbol);\n }\n }\n\n /**\n * Checks if the returned name is null. This probably means that the symbol was not recognized by Yahoo Finance.\n * @return whether this stock's symbol is known by Yahoo Finance (true) or not (false)\n */\n public boolean isValid() {\n return this.name != null;\n }\n \n /**\n * Returns the basic quotes data available for this stock.\n * \n * @return basic quotes data available for this stock\n * @see #getQuote(boolean) \n */\n public StockQuote getQuote() {\n return this.quote;\n }\n \n /**\n * Returns the basic quotes data available for this stock.\n * This method will return null in the following situations:\n *
    \n *
  • the data hasn't been loaded yet\n * in a previous request and refresh is set to false.\n *
  • refresh is true and the data cannot be retrieved from Yahoo Finance \n * for whatever reason (symbol not recognized, no network connection, ...)\n *
\n *

\n * When the quote data gets refreshed, it will automatically also refresh\n * the statistics and dividend data of the stock from Yahoo Finance \n * in the same request.\n * \n * @param refresh indicates whether the data should be requested again to Yahoo Finance\n * @return basic quotes data available for this stock\n * @throws java.io.IOException when there's a connection problem\n */\n public StockQuote getQuote(boolean refresh) throws IOException {\n if(refresh) {\n this.update();\n }\n return this.quote;\n }\n \n public void setQuote(StockQuote quote) {\n this.quote = quote;\n }\n \n /**\n * Returns the statistics available for this stock.\n * \n * @return statistics available for this stock\n * @see #getStats(boolean) \n */\n public StockStats getStats() {\n return this.stats;\n }\n \n /**\n * Returns the statistics available for this stock.\n * This method will return null in the following situations:\n *

    \n *
  • the data hasn't been loaded yet\n * in a previous request and refresh is set to false.\n *
  • refresh is true and the data cannot be retrieved from Yahoo Finance \n * for whatever reason (symbol not recognized, no network connection, ...)\n *
\n *

\n * When the statistics get refreshed, it will automatically also refresh\n * the quote and dividend data of the stock from Yahoo Finance \n * in the same request.\n * \n * @param refresh indicates whether the data should be requested again to Yahoo Finance\n * @return statistics available for this stock\n * @throws java.io.IOException when there's a connection problem\n */\n public StockStats getStats(boolean refresh) throws IOException {\n if(refresh) {\n this.update();\n }\n return this.stats;\n }\n \n public void setStats(StockStats stats) {\n this.stats = stats;\n }\n \n /**\n * Returns the dividend data available for this stock.\n * \n * @return dividend data available for this stock\n * @see #getDividend(boolean) \n */\n public StockDividend getDividend() {\n return this.dividend;\n }\n \n /**\n * Returns the dividend data available for this stock.\n * \n * This method will return null in the following situations:\n *

    \n *
  • the data hasn't been loaded yet\n * in a previous request and refresh is set to false.\n *
  • refresh is true and the data cannot be retrieved from Yahoo Finance \n * for whatever reason (symbol not recognized, no network connection, ...)\n *
\n *

\n * When the dividend data get refreshed, it will automatically also refresh\n * the quote and statistics data of the stock from Yahoo Finance \n * in the same request.\n * \n * @param refresh indicates whether the data should be requested again to Yahoo Finance\n * @return dividend data available for this stock\n * @throws java.io.IOException when there's a connection problem\n */\n public StockDividend getDividend(boolean refresh) throws IOException {\n if(refresh) {\n this.update();\n }\n return this.dividend;\n }\n \n public void setDividend(StockDividend dividend) {\n this.dividend = dividend;\n }\n \n /**\n * This method will return historical quotes from this stock.\n * If the historical quotes are not available yet, they will \n * be requested first from Yahoo Finance.\n *

\n * If the historical quotes are not available yet, the\n * following characteristics will be used for the request:\n *

    \n *
  • from: 1 year ago (default)\n *
  • to: today (default)\n *
  • interval: MONTHLY (default)\n *
\n *

\n * There are several more methods available that allow you\n * to define some characteristics of the historical data.\n * Calling one of those methods will result in a new request\n * being sent to Yahoo Finance.\n * \n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory(yahoofinance.histquotes.Interval) \n * @see #getHistory(java.util.Calendar) \n * @see #getHistory(java.util.Calendar, java.util.Calendar) \n * @see #getHistory(java.util.Calendar, yahoofinance.histquotes.Interval) \n * @see #getHistory(java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval) \n */\n public List getHistory() throws IOException {\n if(this.history != null) {\n return this.history;\n }\n return this.getHistory(HistQuotesRequest.DEFAULT_FROM);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *

    \n *
  • from: 1 year ago (default)\n *
  • to: today (default)\n *
  • interval: specified value\n *
\n * \n * @param interval the interval of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Interval interval) throws IOException {\n return this.getHistory(HistQuotesRequest.DEFAULT_FROM, interval);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: today (default)\n *
  • interval: MONTHLY (default)\n *
\n * \n * @param from start date of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from) throws IOException {\n return this.getHistory(from, HistQuotesRequest.DEFAULT_TO);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: today (default)\n *
  • interval: specified value\n *
\n * \n * @param from start date of the historical data\n * @param interval the interval of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from, Interval interval) throws IOException {\n return this.getHistory(from, HistQuotesRequest.DEFAULT_TO, interval);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: specified value\n *
  • interval: MONTHLY (default)\n *
\n * \n * @param from start date of the historical data\n * @param to end date of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from, Calendar to) throws IOException {\n return this.getHistory(from, to, Interval.MONTHLY);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: specified value\n *
  • interval: specified value\n *
\n * \n * @param from start date of the historical data\n * @param to end date of the historical data\n * @param interval the interval of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from, Calendar to, Interval interval) throws IOException {\n HistQuotesRequest hist = new HistQuotesRequest(this.symbol, from, to, interval);\n this.setHistory(hist.getResult());\n return this.history;\n }\n \n public void setHistory(List history) {\n this.history = history;\n }\n \n public String getSymbol() {\n return symbol;\n }\n \n /**\n * Get the full name of the stock\n * \n * @return the name or null if the data is not available\n */\n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n /**\n * Get the currency of the stock\n * \n * @return the currency or null if the data is not available\n */\n public String getCurrency() {\n return currency;\n }\n \n public void setCurrency(String currency) {\n this.currency = currency;\n }\n \n /**\n * Get the exchange on which the stock is traded\n * \n * @return the exchange or null if the data is not available\n */\n public String getStockExchange() {\n return stockExchange;\n }\n \n public void setStockExchange(String stockExchange) {\n this.stockExchange = stockExchange;\n }\n \n @Override\n public String toString() {\n return this.symbol + \": \" + this.quote.getPrice();\n }\n \n public void print() {\n System.out.println(this.symbol);\n System.out.println(\"--------------------------------\");\n for (Field f : this.getClass().getDeclaredFields()) {\n try {\n System.out.println(f.getName() + \": \" + f.get(this));\n } catch (IllegalArgumentException ex) {\n Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);\n } catch (IllegalAccessException ex) {\n Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n System.out.println(\"--------------------------------\");\n }\n \n}\n"},"new_file":{"kind":"string","value":"src/main/java/yahoofinance/Stock.java"},"old_contents":{"kind":"string","value":"package yahoofinance;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.Calendar;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport yahoofinance.histquotes.HistQuotesRequest;\nimport yahoofinance.histquotes.HistoricalQuote;\nimport yahoofinance.histquotes.Interval;\nimport yahoofinance.quotes.stock.StockDividend;\nimport yahoofinance.quotes.stock.StockQuote;\nimport yahoofinance.quotes.stock.StockQuotesData;\nimport yahoofinance.quotes.stock.StockQuotesRequest;\nimport yahoofinance.quotes.stock.StockStats;\n\n/**\n *\n * @author Stijn Strickx\n */\npublic class Stock {\n\n private final String symbol;\n private String name;\n private String currency;\n private String stockExchange;\n \n private StockQuote quote;\n private StockStats stats;\n private StockDividend dividend;\n \n private List history;\n \n public Stock(String symbol) {\n this.symbol = symbol;\n }\n \n private void update() throws IOException {\n StockQuotesRequest request = new StockQuotesRequest(this.symbol);\n StockQuotesData data = request.getSingleResult();\n if(data != null) {\n this.setQuote(data.getQuote());\n this.setStats(data.getStats());\n this.setDividend(data.getDividend());\n YahooFinance.logger.log(Level.INFO, \"Updated Stock with symbol: {0}\", this.symbol);\n } else {\n YahooFinance.logger.log(Level.SEVERE, \"Failed to update Stock with symbol: {0}\", this.symbol);\n }\n }\n \n /**\n * Returns the basic quotes data available for this stock.\n * \n * @return basic quotes data available for this stock\n * @see #getQuote(boolean) \n */\n public StockQuote getQuote() {\n return this.quote;\n }\n \n /**\n * Returns the basic quotes data available for this stock.\n * This method will return null in the following situations:\n *
    \n *
  • the data hasn't been loaded yet\n * in a previous request and refresh is set to false.\n *
  • refresh is true and the data cannot be retrieved from Yahoo Finance \n * for whatever reason (symbol not recognized, no network connection, ...)\n *
\n *

\n * When the quote data gets refreshed, it will automatically also refresh\n * the statistics and dividend data of the stock from Yahoo Finance \n * in the same request.\n * \n * @param refresh indicates whether the data should be requested again to Yahoo Finance\n * @return basic quotes data available for this stock\n * @throws java.io.IOException when there's a connection problem\n */\n public StockQuote getQuote(boolean refresh) throws IOException {\n if(refresh) {\n this.update();\n }\n return this.quote;\n }\n \n public void setQuote(StockQuote quote) {\n this.quote = quote;\n }\n \n /**\n * Returns the statistics available for this stock.\n * \n * @return statistics available for this stock\n * @see #getStats(boolean) \n */\n public StockStats getStats() {\n return this.stats;\n }\n \n /**\n * Returns the statistics available for this stock.\n * This method will return null in the following situations:\n *

    \n *
  • the data hasn't been loaded yet\n * in a previous request and refresh is set to false.\n *
  • refresh is true and the data cannot be retrieved from Yahoo Finance \n * for whatever reason (symbol not recognized, no network connection, ...)\n *
\n *

\n * When the statistics get refreshed, it will automatically also refresh\n * the quote and dividend data of the stock from Yahoo Finance \n * in the same request.\n * \n * @param refresh indicates whether the data should be requested again to Yahoo Finance\n * @return statistics available for this stock\n * @throws java.io.IOException when there's a connection problem\n */\n public StockStats getStats(boolean refresh) throws IOException {\n if(refresh) {\n this.update();\n }\n return this.stats;\n }\n \n public void setStats(StockStats stats) {\n this.stats = stats;\n }\n \n /**\n * Returns the dividend data available for this stock.\n * \n * @return dividend data available for this stock\n * @see #getDividend(boolean) \n */\n public StockDividend getDividend() {\n return this.dividend;\n }\n \n /**\n * Returns the dividend data available for this stock.\n * \n * This method will return null in the following situations:\n *

    \n *
  • the data hasn't been loaded yet\n * in a previous request and refresh is set to false.\n *
  • refresh is true and the data cannot be retrieved from Yahoo Finance \n * for whatever reason (symbol not recognized, no network connection, ...)\n *
\n *

\n * When the dividend data get refreshed, it will automatically also refresh\n * the quote and statistics data of the stock from Yahoo Finance \n * in the same request.\n * \n * @param refresh indicates whether the data should be requested again to Yahoo Finance\n * @return dividend data available for this stock\n * @throws java.io.IOException when there's a connection problem\n */\n public StockDividend getDividend(boolean refresh) throws IOException {\n if(refresh) {\n this.update();\n }\n return this.dividend;\n }\n \n public void setDividend(StockDividend dividend) {\n this.dividend = dividend;\n }\n \n /**\n * This method will return historical quotes from this stock.\n * If the historical quotes are not available yet, they will \n * be requested first from Yahoo Finance.\n *

\n * If the historical quotes are not available yet, the\n * following characteristics will be used for the request:\n *

    \n *
  • from: 1 year ago (default)\n *
  • to: today (default)\n *
  • interval: MONTHLY (default)\n *
\n *

\n * There are several more methods available that allow you\n * to define some characteristics of the historical data.\n * Calling one of those methods will result in a new request\n * being sent to Yahoo Finance.\n * \n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory(yahoofinance.histquotes.Interval) \n * @see #getHistory(java.util.Calendar) \n * @see #getHistory(java.util.Calendar, java.util.Calendar) \n * @see #getHistory(java.util.Calendar, yahoofinance.histquotes.Interval) \n * @see #getHistory(java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval) \n */\n public List getHistory() throws IOException {\n if(this.history != null) {\n return this.history;\n }\n return this.getHistory(HistQuotesRequest.DEFAULT_FROM);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *

    \n *
  • from: 1 year ago (default)\n *
  • to: today (default)\n *
  • interval: specified value\n *
\n * \n * @param interval the interval of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Interval interval) throws IOException {\n return this.getHistory(HistQuotesRequest.DEFAULT_FROM, interval);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: today (default)\n *
  • interval: MONTHLY (default)\n *
\n * \n * @param from start date of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from) throws IOException {\n return this.getHistory(from, HistQuotesRequest.DEFAULT_TO);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: today (default)\n *
  • interval: specified value\n *
\n * \n * @param from start date of the historical data\n * @param interval the interval of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from, Interval interval) throws IOException {\n return this.getHistory(from, HistQuotesRequest.DEFAULT_TO, interval);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: specified value\n *
  • interval: MONTHLY (default)\n *
\n * \n * @param from start date of the historical data\n * @param to end date of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from, Calendar to) throws IOException {\n return this.getHistory(from, to, Interval.MONTHLY);\n }\n \n /**\n * Requests the historical quotes for this stock with the following characteristics.\n *
    \n *
  • from: specified value\n *
  • to: specified value\n *
  • interval: specified value\n *
\n * \n * @param from start date of the historical data\n * @param to end date of the historical data\n * @param interval the interval of the historical data\n * @return a list of historical quotes from this stock\n * @throws java.io.IOException when there's a connection problem\n * @see #getHistory() \n */\n public List getHistory(Calendar from, Calendar to, Interval interval) throws IOException {\n HistQuotesRequest hist = new HistQuotesRequest(this.symbol, from, to, interval);\n this.setHistory(hist.getResult());\n return this.history;\n }\n \n public void setHistory(List history) {\n this.history = history;\n }\n \n public String getSymbol() {\n return symbol;\n }\n \n /**\n * Get the full name of the stock\n * \n * @return the name or null if the data is not available\n */\n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n /**\n * Get the currency of the stock\n * \n * @return the currency or null if the data is not available\n */\n public String getCurrency() {\n return currency;\n }\n \n public void setCurrency(String currency) {\n this.currency = currency;\n }\n \n /**\n * Get the exchange on which the stock is traded\n * \n * @return the exchange or null if the data is not available\n */\n public String getStockExchange() {\n return stockExchange;\n }\n \n public void setStockExchange(String stockExchange) {\n this.stockExchange = stockExchange;\n }\n \n @Override\n public String toString() {\n return this.symbol + \": \" + this.quote.getPrice();\n }\n \n public void print() {\n System.out.println(this.symbol);\n System.out.println(\"--------------------------------\");\n for (Field f : this.getClass().getDeclaredFields()) {\n try {\n System.out.println(f.getName() + \": \" + f.get(this));\n } catch (IllegalArgumentException ex) {\n Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);\n } catch (IllegalAccessException ex) {\n Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n System.out.println(\"--------------------------------\");\n }\n \n}\n"},"message":{"kind":"string","value":"Provide a check to see if the returned Stock is valid #64\n"},"old_file":{"kind":"string","value":"src/main/java/yahoofinance/Stock.java"},"subject":{"kind":"string","value":"Provide a check to see if the returned Stock is valid #64"}}},{"rowIdx":1271,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"5f06582136881696df1c6f53a2c49389c0530e2b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"braintree/braintree_android,braintree/braintree_android,braintree/braintree_android,braintree/braintree_android"},"new_contents":{"kind":"string","value":"package com.braintreepayments.api.dropin;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Build.VERSION;\nimport android.os.Build.VERSION_CODES;\nimport android.widget.ImageView;\n\nimport com.braintreepayments.api.BraintreeApi;\nimport com.braintreepayments.api.dropin.Customization.CustomizationBuilder;\nimport com.braintreepayments.api.exceptions.BraintreeException;\nimport com.braintreepayments.api.exceptions.ErrorWithResponse;\nimport com.braintreepayments.api.models.CardBuilder;\nimport com.braintreepayments.testutils.TestClientTokenBuilder;\n\nimport static android.support.test.espresso.Espresso.onView;\nimport static android.support.test.espresso.assertion.ViewAssertions.matches;\nimport static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;\nimport static android.support.test.espresso.matcher.ViewMatchers.withText;\nimport static com.braintreepayments.api.utils.PaymentFormHelpers.waitForAddPaymentFormHeader;\nimport static com.braintreepayments.api.utils.PaymentFormHelpers.waitForPaymentMethodList;\nimport static com.braintreepayments.testutils.CardNumber.VISA;\nimport static com.braintreepayments.testutils.ui.Assertions.assertBitmapsEqual;\nimport static com.braintreepayments.testutils.ui.Matchers.withId;\nimport static com.braintreepayments.testutils.ui.ViewHelper.waitForView;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.Matchers.startsWith;\n\npublic class CustomizationTest extends BraintreePaymentActivityTestCase {\n\n public void testDescriptionIsNotNecessary() {\n Intent intent = createIntent();\n String clientToken = new TestClientTokenBuilder().build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_primary_description)).check(matches(not(isDisplayed())));\n }\n\n public void testSubmitButtonUsesDefaultTextIfNoCustomizationProvided() {\n Intent intent = createIntent();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(R.string.bt_default_submit_button_text)));\n }\n\n public void testSubmitButtonUsesCustomizationForCardFormIfIncludedAsAnExtra() {\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .submitButtonText(\"Subscribe\")\n .amount(\"$19\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(\"$19 - Subscribe\")));\n }\n\n public void testSubmitButtonUsesCustomizationForSelectPaymentMethodIfIncludedAsAnExtra()\n throws ErrorWithResponse, BraintreeException {\n String clientToken = new TestClientTokenBuilder().build();\n BraintreeApi api = new BraintreeApi(mContext, clientToken);\n api.create(new CardBuilder()\n .cardNumber(VISA)\n .expirationDate(\"0819\"));\n\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .submitButtonText(\"Subscribe\")\n .amount(\"$19\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForPaymentMethodList();\n onView(withId(R.id.bt_select_payment_method_submit_button)).check(matches(withText(\"$19 - Subscribe\")));\n }\n\n public void testDescriptionsAreDisplayedIfIncludedAsAnExtra() {\n Intent intent = createIntent();\n String clientToken = new TestClientTokenBuilder().build();\n Customization customization = new CustomizationBuilder()\n .primaryDescription(\"Hello, World!\")\n .secondaryDescription(\"Some stuffz\")\n .amount(\"$1,000,000,000.00\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForView(withId(R.id.bt_primary_description)).check(matches(withText(\"Hello, World!\")));\n onView(withId(R.id.bt_secondary_description)).check(matches(withText(\"Some stuffz\")));\n onView(withId(R.id.bt_description_amount)).check(matches(withText(\"$1,000,000,000.00\")));\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(\n startsWith(\"$1,000,000,000.00\"))));\n }\n\n public void testDefaultButtonTextIsUsedWhenCustomizationIsPresentWithoutSpecifyingButtonText() {\n Intent intent = createIntent();\n String clientToken = new TestClientTokenBuilder().build();\n Customization customization = new CustomizationBuilder()\n .amount(\"$19\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(\"$19 - Purchase\")));\n }\n\n @TargetApi(VERSION_CODES.HONEYCOMB)\n public void testActionBarTitleAndLogoAreUsedIfIncludedAsAnExtra() {\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .actionBarTitle(\"This is a title\")\n .actionBarLogo(android.R.drawable.ic_delete)\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n Activity activity = getActivity();\n\n assertEquals(\"This is a title\", activity.getActionBar().getTitle());\n\n if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {\n ImageView actual = (ImageView) activity.findViewById(android.R.id.home);\n assertBitmapsEqual(actual.getDrawable(),\n mContext.getResources().getDrawable(android.R.drawable.ic_delete)\n );\n }\n }\n\n @TargetApi(VERSION_CODES.HONEYCOMB)\n public void testDefaultActionBarTitleAndLogoAreUsedWhenCustomizationIsPresentWithoutSpecifyingTitleAndLogo() {\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .primaryDescription(\"Description\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n Activity activity = getActivity();\n\n assertEquals(\"Purchase\", activity.getActionBar().getTitle());\n\n if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {\n ImageView actual = (ImageView) activity.findViewById(android.R.id.home);\n ColorDrawable expected = new ColorDrawable(mContext.getResources().getColor(\n android.R.color.transparent));\n assertEquals(actual.getDrawable().getOpacity(), expected.getOpacity());\n }\n }\n\n private Intent createIntent() {\n return new Intent(mContext, BraintreePaymentActivity.class);\n }\n\n}\n"},"new_file":{"kind":"string","value":"Drop-In/src/androidTest/java/com/braintreepayments/api/dropin/CustomizationTest.java"},"old_contents":{"kind":"string","value":"package com.braintreepayments.api.dropin;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Build.VERSION_CODES;\nimport android.widget.ImageView;\n\nimport com.braintreepayments.api.BraintreeApi;\nimport com.braintreepayments.api.dropin.Customization.CustomizationBuilder;\nimport com.braintreepayments.api.exceptions.BraintreeException;\nimport com.braintreepayments.api.exceptions.ErrorWithResponse;\nimport com.braintreepayments.api.models.CardBuilder;\nimport com.braintreepayments.testutils.TestClientTokenBuilder;\n\nimport static android.support.test.espresso.Espresso.onView;\nimport static android.support.test.espresso.assertion.ViewAssertions.matches;\nimport static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;\nimport static android.support.test.espresso.matcher.ViewMatchers.withText;\nimport static com.braintreepayments.api.utils.PaymentFormHelpers.waitForAddPaymentFormHeader;\nimport static com.braintreepayments.api.utils.PaymentFormHelpers.waitForPaymentMethodList;\nimport static com.braintreepayments.testutils.CardNumber.VISA;\nimport static com.braintreepayments.testutils.ui.Assertions.assertBitmapsEqual;\nimport static com.braintreepayments.testutils.ui.Matchers.withId;\nimport static com.braintreepayments.testutils.ui.ViewHelper.waitForView;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.Matchers.startsWith;\n\npublic class CustomizationTest extends BraintreePaymentActivityTestCase {\n\n public void testDescriptionIsNotNecessary() {\n Intent intent = createIntent();\n String clientToken = new TestClientTokenBuilder().build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_primary_description)).check(matches(not(isDisplayed())));\n }\n\n public void testSubmitButtonUsesDefaultTextIfNoCustomizationProvided() {\n Intent intent = createIntent();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(R.string.bt_default_submit_button_text)));\n }\n\n public void testSubmitButtonUsesCustomizationForCardFormIfIncludedAsAnExtra() {\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .submitButtonText(\"Subscribe\")\n .amount(\"$19\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(\"$19 - Subscribe\")));\n }\n\n public void testSubmitButtonUsesCustomizationForSelectPaymentMethodIfIncludedAsAnExtra()\n throws ErrorWithResponse, BraintreeException {\n String clientToken = new TestClientTokenBuilder().build();\n BraintreeApi api = new BraintreeApi(mContext, clientToken);\n api.create(new CardBuilder()\n .cardNumber(VISA)\n .expirationDate(\"0819\"));\n\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .submitButtonText(\"Subscribe\")\n .amount(\"$19\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForPaymentMethodList();\n onView(withId(R.id.bt_select_payment_method_submit_button)).check(matches(withText(\"$19 - Subscribe\")));\n }\n\n public void testDescriptionsAreDisplayedIfIncludedAsAnExtra() {\n Intent intent = createIntent();\n String clientToken = new TestClientTokenBuilder().build();\n Customization customization = new CustomizationBuilder()\n .primaryDescription(\"Hello, World!\")\n .secondaryDescription(\"Some stuffz\")\n .amount(\"$1,000,000,000.00\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForView(withId(R.id.bt_primary_description)).check(matches(withText(\"Hello, World!\")));\n onView(withId(R.id.bt_secondary_description)).check(matches(withText(\"Some stuffz\")));\n onView(withId(R.id.bt_description_amount)).check(matches(withText(\"$1,000,000,000.00\")));\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(\n startsWith(\"$1,000,000,000.00\"))));\n }\n\n public void testDefaultButtonTextIsUsedWhenCustomizationIsPresentWithoutSpecifyingButtonText() {\n Intent intent = createIntent();\n String clientToken = new TestClientTokenBuilder().build();\n Customization customization = new CustomizationBuilder()\n .amount(\"$19\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n getActivity();\n\n waitForAddPaymentFormHeader();\n onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(\"$19 - Purchase\")));\n }\n\n @TargetApi(VERSION_CODES.HONEYCOMB)\n public void testActionBarTitleAndLogoAreUsedIfIncludedAsAnExtra() {\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .actionBarTitle(\"This is a title\")\n .actionBarLogo(android.R.drawable.ic_delete)\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n Activity activity = getActivity();\n\n assertEquals(\"This is a title\", activity.getActionBar().getTitle());\n\n ImageView actual = (ImageView) activity.findViewById(android.R.id.home);\n\n assertBitmapsEqual(actual.getDrawable(),\n mContext.getResources().getDrawable(android.R.drawable.ic_delete)\n );\n }\n\n @TargetApi(VERSION_CODES.HONEYCOMB)\n public void testDefaultActionBarTitleAndLogoAreUsedWhenCustomizationIsPresentWithoutSpecifyingTitleAndLogo() {\n Intent intent = createIntent();\n Customization customization = new CustomizationBuilder()\n .primaryDescription(\"Description\")\n .build();\n intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build());\n intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization);\n setActivityIntent(intent);\n Activity activity = getActivity();\n\n assertEquals(\"Purchase\", activity.getActionBar().getTitle());\n ImageView actual = (ImageView) activity.findViewById(android.R.id.home);\n ColorDrawable expected = new ColorDrawable(mContext.getResources().getColor(\n android.R.color.transparent));\n assertEquals(actual.getDrawable().getOpacity(), expected.getOpacity());\n }\n\n private Intent createIntent() {\n return new Intent(mContext, BraintreePaymentActivity.class);\n }\n\n}\n"},"message":{"kind":"string","value":"More Android 5.0 UI test fixes\n"},"old_file":{"kind":"string","value":"Drop-In/src/androidTest/java/com/braintreepayments/api/dropin/CustomizationTest.java"},"subject":{"kind":"string","value":"More Android 5.0 UI test fixes"}}},{"rowIdx":1272,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24df834f73f4b2c5c50046364c1a8525eda68f91"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"bonczj/vertx-messaging-sample"},"new_contents":{"kind":"string","value":"package bonczj.vertx.message;\n\nimport bonczj.vertx.models.Result;\nimport bonczj.vertx.models.Status;\nimport io.vertx.core.AbstractVerticle;\nimport io.vertx.core.json.Json;\nimport io.vertx.core.json.JsonObject;\n\nimport java.util.Random;\nimport java.util.logging.Logger;\n\npublic class MessageHandlerVerticle extends AbstractVerticle\n{\n private static final Logger logger = Logger.getLogger(MessageHandlerVerticle.class.getSimpleName());\n\n @Override public void start() throws Exception\n {\n super.start();\n\n getVertx().eventBus().consumer(\"message.handle\", objectMessage -> {\n JsonObject object = (JsonObject) objectMessage.body();\n Result result = Json.decodeValue(object.encode(), Result.class);\n logger.info(String.format(\"Processing message %s\", result.getId().toString()));\n\n Random random = new Random();\n int seconds = random.nextInt(9) + 1;\n\n // Thread.sleep is blocking, so allow vertx to handle it cleaner than normal.\n getVertx().executeBlocking(objectFuture -> {\n try\n {\n Thread.sleep(seconds * 1000);\n }\n catch (InterruptedException e)\n {\n objectFuture.fail(e);\n }\n\n objectFuture.complete();\n }, objectAsyncResult -> {\n if (objectAsyncResult.succeeded())\n {\n result.setStatus(Status.COMPLETED);\n result.setResult(String.format(\"Message complete in %d seconds!\", seconds));\n logger.info(String.format(\"Message %s complete in %d seconds\", result.getId(), seconds));\n\n JsonObject json = new JsonObject(Json.encode(result));\n\n getVertx().eventBus().send(\"result.message.handle\", json);\n\n logger.info(String.format(\"Response sent to result.message.handle for result %s\", result.getId()));\n\n }\n else\n {\n result.setStatus(Status.FAILED);\n result.setResult(String.format(\"Failed to sleep %d seconds for result %s\", seconds, result.getId()));\n JsonObject json = new JsonObject(Json.encode(result));\n\n getVertx().eventBus().send(\"result.message.handle\", json);\n\n logger.severe(result.getResult());\n }\n });\n });\n }\n}\n"},"new_file":{"kind":"string","value":"message-handler-verticle/src/main/java/bonczj/vertx/message/MessageHandlerVerticle.java"},"old_contents":{"kind":"string","value":"package bonczj.vertx.message;\n\nimport bonczj.vertx.models.Result;\nimport bonczj.vertx.models.Status;\nimport io.vertx.core.AbstractVerticle;\nimport io.vertx.core.eventbus.EventBus;\nimport io.vertx.core.json.Json;\nimport io.vertx.core.json.JsonObject;\n\nimport java.util.Random;\nimport java.util.logging.Logger;\n\npublic class MessageHandlerVerticle extends AbstractVerticle\n{\n private static final Logger logger = Logger.getLogger(MessageHandlerVerticle.class.getSimpleName());\n\n @Override public void start() throws Exception\n {\n super.start();\n\n getVertx().eventBus().consumer(\"message.handle\", objectMessage -> {\n JsonObject object = (JsonObject) objectMessage.body();\n Result result = Json.decodeValue(object.encode(), Result.class);\n logger.info(String.format(\"Processing message %s\", result.getId().toString()));\n\n Random random = new Random();\n int seconds = random.nextInt(9) + 1;\n\n for (int i = 0; i < seconds; i++)\n {\n try\n {\n Thread.sleep(100);\n }\n catch (InterruptedException e)\n {\n // do nothing\n }\n }\n\n result.setStatus(Status.COMPLETED);\n result.setResult(String.format(\"Message complete in %f seconds!\", seconds / 100.0f));\n logger.info(String.format(\"Message %s complete in %f seconds\", result.getId(), seconds / 100.0f));\n\n object = new JsonObject(Json.encode(result));\n\n getVertx().eventBus().send(\"result.message.handle\", object);\n logger.info(String.format(\"Response sent to result.message.handle for result %s\", result.getId()));\n });\n }\n}\n"},"message":{"kind":"string","value":"Moved the blocking call to a blocking execution block so that is follows the correct pattern for vert.\n"},"old_file":{"kind":"string","value":"message-handler-verticle/src/main/java/bonczj/vertx/message/MessageHandlerVerticle.java"},"subject":{"kind":"string","value":"Moved the blocking call to a blocking execution block so that is follows the correct pattern for vert."}}},{"rowIdx":1273,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f4e2df9cc4565f34592997bcf958e608e43eb074"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"lew/mitzi"},"new_contents":{"kind":"string","value":"package mitzi;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class NaiveBoard implements IBoard {\n\n\tprotected static int[][] initial_board = {\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 12, 13, 14, 15, 16, 14, 13, 12, 00, 00 },\n\t\t\t{ 00, 00, 11, 11, 11, 11, 11, 11, 11, 11, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 01, 01, 01, 01, 01, 01, 01, 01, 00, 00 },\n\t\t\t{ 00, 00, 02, 03, 04, 05, 06, 04, 03, 02, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 } };\n\n\tprivate int[][] board = new int[12][12];\n\n\tprivate int full_move_clock;\n\n\tprivate int half_move_clock;\n\n\t// squares c1, g1, c8 and g8 in ICCF numeric notation\n\t// do not change the squares' order or bad things will happen!\n\t// set to -1 if castling not allowed\n\tprivate int[] castling = { -1, -1, -1, -1 };\n\n\tprivate int en_passant_target = -1;\n\n\tprivate int active_color;\n\n\t// The following class members are used to prevent multiple computations\n\tprivate Set possible_moves; // Set of all possible moves\n\n\tprivate Boolean is_check; // using the class Boolean, which can be null!\n\n\tprivate Boolean is_mate;\n\n\tprivate Boolean is_stale_mate;\n\n\t// the following maps takes and Integer, representing the color, type or\n\t// PieceValue and returns the set of squares or the number of squares!\n\tprivate Map> occupied_squares_by_color_and_type = new HashMap>();\n\n\tprivate Map> occupied_squares_by_color = new HashMap>();\n\n\tprivate Map> occupied_squares_by_type = new HashMap>();\n\n\tprivate Map num_occupied_squares_by_color_and_type = new HashMap();\n\n\tprivate Map num_occupied_squares_by_color = new HashMap();\n\n\tprivate Map num_occupied_squares_by_type = new HashMap();\n\n\t// --------------------------------------------------------\n\n\tprivate NaiveBoard returnCopy() {\n\t\tNaiveBoard newBoard = new NaiveBoard();\n\n\t\tnewBoard.active_color = active_color;\n\t\tnewBoard.en_passant_target = en_passant_target;\n\t\tnewBoard.full_move_clock = full_move_clock;\n\t\tnewBoard.half_move_clock = half_move_clock;\n\t\tSystem.arraycopy(castling, 0, newBoard.castling, 0, 4);\n\n\t\t// from row and column 1,2,11,12 are 0..\n\t\tfor (int i = 2; i < 11; i++)\n\t\t\tSystem.arraycopy(board[i], 2, newBoard.board[i], 2, 8);\n\n\t\treturn newBoard;\n\t}\n\n\tprivate int getFromBoard(int square) {\n\t\tint row = SquareHelper.getRow(square);\n\t\tint column = SquareHelper.getColumn(square);\n\t\treturn board[10 - row][1 + column];\n\t}\n\n\tprivate void setOnBoard(int square, int piece_value) {\n\t\tint row = SquareHelper.getRow(square);\n\t\tint column = SquareHelper.getColumn(square);\n\t\tboard[10 - row][1 + column] = piece_value;\n\t}\n\n\tpublic int getOpponentsColor() {\n\t\tif (active_color == PieceHelper.BLACK)\n\t\t\treturn PieceHelper.WHITE;\n\t\telse\n\t\t\treturn PieceHelper.BLACK;\n\t}\n\n\t@Override\n\tpublic void setToInitial() {\n\t\tboard = initial_board;\n\n\t\tfull_move_clock = 1;\n\n\t\thalf_move_clock = 0;\n\n\t\tcastling[0] = 31;\n\t\tcastling[1] = 71;\n\t\tcastling[2] = 38;\n\t\tcastling[3] = 78;\n\n\t\ten_passant_target = -1;\n\n\t\tactive_color = PieceHelper.WHITE;\n\t}\n\n\t@Override\n\tpublic void setToFEN(String fen) {\n\t\tboard = new int[12][12];\n\t\tcastling[0] = -1;\n\t\tcastling[1] = -1;\n\t\tcastling[2] = -1;\n\t\tcastling[3] = -1;\n\t\ten_passant_target = -1;\n\n\t\tString[] fen_parts = fen.split(\" \");\n\n\t\t// populate the squares\n\t\tString[] fen_rows = fen_parts[0].split(\"/\");\n\t\tchar[] pieces;\n\t\tfor (int row = 1; row <= 8; row++) {\n\t\t\tint offset = 0;\n\t\t\tfor (int column = 1; column + offset <= 8; column++) {\n\t\t\t\tpieces = fen_rows[8 - row].toCharArray();\n\t\t\t\tint square = (column + offset) * 10 + row;\n\t\t\t\tswitch (pieces[column - 1]) {\n\t\t\t\tcase 'P':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN,\n\t\t\t\t\t\t\tPieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'R':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK,\n\t\t\t\t\t\t\tPieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'N':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.KNIGHT, PieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'B':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.BISHOP, PieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Q':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.QUEEN, PieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'K':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING,\n\t\t\t\t\t\t\tPieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'p':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN,\n\t\t\t\t\t\t\tPieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'r':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK,\n\t\t\t\t\t\t\tPieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'n':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.KNIGHT, PieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'b':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.BISHOP, PieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'q':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.QUEEN, PieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'k':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING,\n\t\t\t\t\t\t\tPieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\toffset += Character.getNumericValue(pieces[column - 1]) - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set active color\n\t\tswitch (fen_parts[1]) {\n\t\tcase \"b\":\n\t\t\tactive_color = PieceHelper.BLACK;\n\t\t\tbreak;\n\t\tcase \"w\":\n\t\t\tactive_color = PieceHelper.WHITE;\n\t\t\tbreak;\n\t\t}\n\n\t\t// set possible castling moves\n\t\tif (!fen_parts[2].equals(\"-\")) {\n\t\t\tchar[] castlings = fen_parts[2].toCharArray();\n\t\t\tfor (int i = 0; i < castlings.length; i++) {\n\t\t\t\tswitch (castlings[i]) {\n\t\t\t\tcase 'K':\n\t\t\t\t\tcastling[1] = 71;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Q':\n\t\t\t\t\tcastling[0] = 31;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'k':\n\t\t\t\t\tcastling[3] = 78;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'q':\n\t\t\t\t\tcastling[2] = 38;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set en passant square\n\t\tif (!fen_parts[3].equals(\"-\")) {\n\t\t\ten_passant_target = SquareHelper.fromString(fen_parts[3]);\n\t\t}\n\n\t\t// set half move clock\n\t\thalf_move_clock = Integer.parseInt(fen_parts[4]);\n\n\t\t// set full move clock\n\t\tfull_move_clock = Integer.parseInt(fen_parts[5]);\n\t}\n\n\t@Override\n\tpublic NaiveBoard doMove(IMove move) {\n\n\t\tNaiveBoard newBoard = this.returnCopy();\n\n\t\tint src = move.getFromSquare();\n\t\tint dest = move.getToSquare();\n\n\t\tint piece = getFromBoard(src); // reducing calls of getFormBoard\n\n\t\t// if promotion\n\t\tif (move.getPromotion() != 0) {\n\t\t\tnewBoard.setOnBoard(src, 0);\n\t\t\tnewBoard.setOnBoard(dest,\n\t\t\t\t\tPieceHelper.pieceValue(move.getPromotion(), active_color));\n\n\t\t\tnewBoard.half_move_clock = 0;\n\n\t\t}\n\t\t// If rochade\n\t\telse if (PieceHelper.pieceType(piece) == PieceHelper.KING\n\t\t\t\t&& Math.abs((src - dest)) == 20) {\n\t\t\tnewBoard.setOnBoard(dest,\n\t\t\t\t\tPieceHelper.pieceValue(PieceHelper.KING, active_color));\n\t\t\tnewBoard.setOnBoard(src, 0);\n\t\t\tnewBoard.setOnBoard((src + dest) / 2,\n\t\t\t\t\tPieceHelper.pieceValue(PieceHelper.ROOK, active_color));\n\t\t\tif (SquareHelper.getColumn(dest) == 3)\n\t\t\t\tnewBoard.setOnBoard(src - 40, 0);\n\t\t\telse\n\t\t\t\tnewBoard.setOnBoard(src + 30, 0);\n\n\t\t\tnewBoard.half_move_clock++;\n\n\t\t}\n\t\t// If en passant\n\t\telse if (PieceHelper.pieceType(piece) == PieceHelper.PAWN\n\t\t\t\t&& dest == this.getEnPassant()) {\n\t\t\tnewBoard.setOnBoard(dest,\n\t\t\t\t\tPieceHelper.pieceValue(PieceHelper.PAWN, active_color));\n\t\t\tnewBoard.setOnBoard(src, 0);\n\t\t\tif (active_color == PieceHelper.WHITE)\n\t\t\t\tnewBoard.setOnBoard(dest - 1, 0);\n\t\t\telse\n\t\t\t\tnewBoard.setOnBoard(dest + 1, 0);\n\n\t\t\tnewBoard.half_move_clock = 0;\n\t\t}\n\t\t// Usual move\n\t\telse {\n\t\t\tnewBoard.setOnBoard(dest, piece);\n\t\t\tnewBoard.setOnBoard(src, 0);\n\n\t\t\tif (this.getFromBoard(dest) != 0\n\t\t\t\t\t|| PieceHelper.pieceType(piece) == PieceHelper.PAWN)\n\t\t\t\tnewBoard.half_move_clock = 0;\n\t\t\telse\n\t\t\t\tnewBoard.half_move_clock++;\n\n\t\t}\n\n\t\t// Change active_color after move\n\t\tnewBoard.active_color = PieceHelper.pieceOppositeColor(piece);\n\t\tif (active_color == PieceHelper.BLACK)\n\t\t\tnewBoard.full_move_clock++;\n\n\t\t// Update en_passant\n\t\tif (PieceHelper.pieceType(piece) == PieceHelper.PAWN\n\t\t\t\t&& Math.abs(dest - src) == 2)\n\t\t\tnewBoard.en_passant_target = (dest + src) / 2;\n\t\telse\n\t\t\tnewBoard.en_passant_target = -1;\n\n\t\t// Update castling\n\t\tif (PieceHelper.pieceType(piece) == PieceHelper.KING) {\n\t\t\tif (active_color == PieceHelper.WHITE && src == 51) {\n\t\t\t\tnewBoard.castling[0] = -1;\n\t\t\t\tnewBoard.castling[1] = -1;\n\t\t\t} else if (active_color == PieceHelper.BLACK && src == 58) {\n\t\t\t\tnewBoard.castling[2] = -1;\n\t\t\t\tnewBoard.castling[3] = -1;\n\t\t\t}\n\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.ROOK) {\n\t\t\tif (active_color == PieceHelper.WHITE) {\n\t\t\t\tif (src == 81)\n\t\t\t\t\tnewBoard.castling[1] = -1;\n\t\t\t\telse if (src == 11)\n\t\t\t\t\tnewBoard.castling[0] = -1;\n\t\t\t} else {\n\t\t\t\tif (src == 88)\n\t\t\t\t\tnewBoard.castling[3] = -1;\n\t\t\t\telse if (src == 18)\n\t\t\t\t\tnewBoard.castling[2] = -1;\n\t\t\t}\n\t\t}\n\t\treturn newBoard;\n\t}\n\n\t@Override\n\tpublic int getEnPassant() {\n\t\treturn en_passant_target;\n\t}\n\n\t@Override\n\tpublic boolean canCastle(int king_to) {\n\t\tif ((king_to == 31 && castling[0] != -1)\n\t\t\t\t|| (king_to == 71 && castling[1] != -1)\n\t\t\t\t|| (king_to == 38 && castling[2] != -1)\n\t\t\t\t|| (king_to == 78 && castling[3] != -1)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic Set getOccupiedSquaresByColor(int color) {\n\n\t\tif (occupied_squares_by_color.containsKey(color) == false) {\n\t\t\tint square;\n\t\t\tSet set = new HashSet();\n\n\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t&& PieceHelper\n\t\t\t\t\t\t\t\t\t.pieceColor(this.getFromBoard(square)) == color)\n\t\t\t\t\t\tset.add(square);\n\t\t\t\t}\n\n\t\t\toccupied_squares_by_color.put(color, set);\n\t\t\treturn set;\n\t\t}\n\t\treturn occupied_squares_by_color.get(color);\n\t}\n\n\t@Override\n\tpublic Set getOccupiedSquaresByType(int type) {\n\n\t\tif (occupied_squares_by_type.containsKey(type) == false) {\n\t\t\tint square;\n\t\t\tSet set = new HashSet();\n\n\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceType(this.getFromBoard(square)) == type)\n\t\t\t\t\t\tset.add(square);\n\t\t\t\t}\n\n\t\t\toccupied_squares_by_type.put(type, set);\n\t\t\treturn set;\n\t\t}\n\t\treturn occupied_squares_by_type.get(type);\n\n\t}\n\n\t@Override\n\tpublic Set getOccupiedSquaresByColorAndType(int color, int type) {\n\n\t\tint value = PieceHelper.pieceValue(type, color);\n\t\tif (occupied_squares_by_color_and_type.containsKey(value) == false) {\n\t\t\tint square;\n\t\t\tSet set = new HashSet();\n\n\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\tif (value == this.getFromBoard(square))\n\t\t\t\t\t\tset.add(square);\n\t\t\t\t}\n\t\t\toccupied_squares_by_color_and_type.put(value, set);\n\t\t\treturn set;\n\t\t}\n\t\treturn occupied_squares_by_color_and_type.get(value);\n\t}\n\n\t@Override\n\tpublic int getNumberOfPiecesByColor(int color) {\n\n\t\tif (num_occupied_squares_by_color.containsKey(color) == false) {\n\t\t\tif (occupied_squares_by_color.containsKey(color) == false) {\n\t\t\t\tint square;\n\t\t\t\tint num = 0;\n\n\t\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t\t&& PieceHelper.pieceColor(this\n\t\t\t\t\t\t\t\t\t\t.getFromBoard(square)) == color)\n\t\t\t\t\t\t\tnum++;\n\t\t\t\t\t}\n\t\t\t\tnum_occupied_squares_by_color.put(color, num);\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tnum_occupied_squares_by_color.put(color, occupied_squares_by_color\n\t\t\t\t\t.get(color).size());\n\t\t}\n\t\treturn num_occupied_squares_by_color.get(color);\n\n\t}\n\n\t@Override\n\tpublic int getNumberOfPiecesByType(int type) {\n\n\t\tif (num_occupied_squares_by_type.containsKey(type) == false) {\n\t\t\tif (occupied_squares_by_type.containsKey(type) == false) {\n\t\t\t\tint square;\n\t\t\t\tint num = 0;\n\n\t\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t\t&& PieceHelper.pieceType(this\n\t\t\t\t\t\t\t\t\t\t.getFromBoard(square)) == type)\n\t\t\t\t\t\t\tnum++;\n\t\t\t\t\t}\n\t\t\t\tnum_occupied_squares_by_type.put(type, num);\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tnum_occupied_squares_by_type.put(type, occupied_squares_by_type\n\t\t\t\t\t.get(type).size());\n\t\t}\n\t\treturn num_occupied_squares_by_type.get(type);\n\n\t}\n\n\t@Override\n\tpublic int getNumberOfPiecesByColorAndType(int color, int type) {\n\n\t\tint value = PieceHelper.pieceValue(type, color);\n\t\tif (num_occupied_squares_by_color_and_type.containsKey(value) == false) {\n\t\t\tif (occupied_squares_by_color_and_type.containsKey(value) == false) {\n\t\t\t\tint square;\n\t\t\t\tint num = 0;\n\n\t\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\t\tif (value == this.getFromBoard(square))\n\t\t\t\t\t\t\tnum++;\n\t\t\t\t\t}\n\t\t\t\tnum_occupied_squares_by_color_and_type.put(value, num);\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tnum_occupied_squares_by_color_and_type.put(value,\n\t\t\t\t\toccupied_squares_by_color_and_type.get(value).size());\n\t\t}\n\t\treturn num_occupied_squares_by_color_and_type.get(value);\n\t}\n\n\t@Override\n\tpublic Set getPossibleMoves() {\n\n\t\tif (possible_moves == null) {\n\t\t\tSet total_set = new HashSet();\n\t\t\tSet temp_set;\n\n\t\t\t// all the active squares\n\t\t\tSet squares = getOccupiedSquaresByColor(active_color);\n\n\t\t\t// loop over all squares\n\t\t\tfor (int square : squares) {\n\t\t\t\ttemp_set = getPossibleMovesFrom(square);\n\t\t\t\ttotal_set.addAll(temp_set);\n\t\t\t}\n\t\t\tpossible_moves = total_set;\n\t\t}\n\t\treturn possible_moves;\n\n\t}\n\n\t@Override\n\tpublic Set getPossibleMovesFrom(int square) {\n\t\t// The case, that the destination is the opponents king cannot happen.\n\n\t\tint type = PieceHelper.pieceType(getFromBoard(square));\n\t\tint opp_color = getOpponentsColor();\n\t\tList squares;\n\t\tSet moves = new HashSet();\n\t\tMove move;\n\n\t\t// Types BISHOP, QUEEN, ROOK\n\t\tif (type == PieceHelper.BISHOP || type == PieceHelper.QUEEN\n\t\t\t\t|| type == PieceHelper.ROOK) {\n\n\t\t\t// Loop over all directions and skip not appropriate ones\n\t\t\tfor (Direction direction : Direction.values()) {\n\n\t\t\t\t// Skip N,W,E,W with BISHOP and skip NE,NW,SE,SW with ROOK\n\t\t\t\tif (((direction == Direction.NORTH\n\t\t\t\t\t\t|| direction == Direction.EAST\n\t\t\t\t\t\t|| direction == Direction.SOUTH || direction == Direction.WEST) && type == PieceHelper.BISHOP)\n\t\t\t\t\t\t|| ((direction == Direction.NORTHWEST\n\t\t\t\t\t\t\t\t|| direction == Direction.NORTHEAST\n\t\t\t\t\t\t\t\t|| direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && type == PieceHelper.ROOK)) {\n\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\t// do stuff\n\t\t\t\t\tsquares = SquareHelper.getAllSquaresInDirection(square,\n\t\t\t\t\t\t\tdirection);\n\n\t\t\t\t\tfor (Integer new_square : squares) {\n\t\t\t\t\t\tint piece = getFromBoard(new_square);\n\t\t\t\t\t\tif (piece == 0\n\t\t\t\t\t\t\t\t|| PieceHelper.pieceColor(piece) == opp_color) {\n\n\t\t\t\t\t\t\tmove = new Move(square, new_square);\n\t\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t\t\tif (piece != 0\n\t\t\t\t\t\t\t\t\t&& PieceHelper.pieceColor(piece) == opp_color)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (type == PieceHelper.PAWN) {\n\t\t\t// If Pawn has not moved yet (steps possible)\n\t\t\tif ((SquareHelper.getRow(square) == 2 && active_color == PieceHelper.WHITE)\n\t\t\t\t\t|| (SquareHelper.getRow(square) == 7 && active_color == PieceHelper.BLACK)) {\n\n\t\t\t\tif (getFromBoard(square\n\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tif (getFromBoard(square + 2\n\t\t\t\t\t\t\t* Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\t\tmove = new Move(square, square + 2\n\t\t\t\t\t\t\t\t* Direction.pawnDirection(active_color).offset);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tSet pawn_capturing_directions = Direction\n\t\t\t\t\t\t.pawnCapturingDirections(active_color);\n\t\t\t\tfor (Direction direction : pawn_capturing_directions) {\n\t\t\t\t\tif (getFromBoard(square + direction.offset) != 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceColor(getFromBoard(square\n\t\t\t\t\t\t\t\t\t+ direction.offset)) == getOpponentsColor()) {\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// if Promotion will happen\n\t\t\telse if ((SquareHelper.getRow(square) == 7 && active_color == PieceHelper.WHITE)\n\t\t\t\t\t|| (SquareHelper.getRow(square) == 2 && active_color == PieceHelper.BLACK)) {\n\t\t\t\tif (getFromBoard(square\n\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.QUEEN);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.KNIGHT);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.ROOK);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.BISHOP);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t\tSet pawn_capturing_directions = Direction\n\t\t\t\t\t\t.pawnCapturingDirections(active_color);\n\t\t\t\tfor (Direction direction : pawn_capturing_directions) {\n\t\t\t\t\tif (getFromBoard(square + direction.offset) != 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceColor(getFromBoard(square\n\t\t\t\t\t\t\t\t\t+ direction.offset)) == getOpponentsColor()) {\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset,\n\t\t\t\t\t\t\t\tPieceHelper.QUEEN);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset,\n\t\t\t\t\t\t\t\tPieceHelper.KNIGHT);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// Usual turn and en passente is possible, no promotion\n\t\t\telse {\n\t\t\t\tif (getFromBoard(square\n\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t\tSet pawn_capturing_directions = Direction\n\t\t\t\t\t\t.pawnCapturingDirections(active_color);\n\t\t\t\tfor (Direction direction : pawn_capturing_directions) {\n\t\t\t\t\tif ((getFromBoard(square + direction.offset) != 0 && PieceHelper\n\t\t\t\t\t\t\t.pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor())\n\t\t\t\t\t\t\t|| square + direction.offset == getEnPassant()) {\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif (type == PieceHelper.KING) {\n\t\t\tfor (Direction direction : Direction.values()) {\n\t\t\t\tInteger new_square = square + direction.offset;\n\t\t\t\tmove = new Move(square, new_square);\n\t\t\t\tif (SquareHelper.isValidSquare(new_square)) {\n\t\t\t\t\t// if the new square is empty or occupied by the opponent\n\t\t\t\t\tif (getFromBoard(new_square) == 0\n\t\t\t\t\t\t\t|| PieceHelper.pieceColor(getFromBoard(new_square)) != active_color)\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Castle Moves\n\t\t\t// If the King is not check now, try castle moves\n\t\t\tif (!isCheckPosition()) {\n\t\t\t\tint off = 0;\n\t\t\t\tif (active_color == PieceHelper.BLACK)\n\t\t\t\t\toff = 2;\n\n\t\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\t\tint castle_flag = 0;\n\t\t\t\t\tInteger new_square = castling[i + off];\n\t\t\t\t\t// castling must still be possible to this side\n\t\t\t\t\tif (new_square != -1) {\n\n\t\t\t\t\t\tDirection dir;\n\t\t\t\t\t\tif (i == 0)\n\t\t\t\t\t\t\tdir = Direction.WEST;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdir = Direction.EAST;\n\n\t\t\t\t\t\tList line = SquareHelper\n\t\t\t\t\t\t\t\t.getAllSquaresInDirection(square, dir);\n\n\t\t\t\t\t\t// Check each square if it is empty\n\t\t\t\t\t\tfor (Integer squ : line) {\n\t\t\t\t\t\t\tif (getFromBoard(squ) != 0) {\n\t\t\t\t\t\t\t\tcastle_flag = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (squ == new_square)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (castle_flag == 1)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t// Check each square if the king on it would be check\n\t\t\t\t\t\tfor (Integer squ : line) {\n\t\t\t\t\t\t\tmove = new Move(square, squ);\n\t\t\t\t\t\t\tNaiveBoard board = doMove(move);\n\t\t\t\t\t\t\tboard.active_color = active_color; // TODO: ugly\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// solution ! ;)\n\t\t\t\t\t\t\tif (board.isCheckPosition())\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tif (squ == new_square) { // if EVERYTHING is right,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// then add the move\n\t\t\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (type == PieceHelper.KNIGHT) {\n\t\t\tsquares = SquareHelper.getAllSquaresByKnightStep(square);\n\t\t\tfor (Integer new_square : squares) {\n\t\t\t\tif (getFromBoard(new_square) == 0\n\t\t\t\t\t\t|| PieceHelper.pieceColor(getFromBoard(new_square)) != active_color) {\n\t\t\t\t\tmove = new Move(square, new_square);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// remove invalid positions\n\t\t// TODO do this in a more efficient way\n\t\tIterator iter = moves.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tIMove m = iter.next();\n\t\t\tNaiveBoard temp_board = this.doMove(m);\n\t\t\ttemp_board.active_color = active_color; // ugly solution…\n\t\t\tif (temp_board.isCheckPosition()) {\n\t\t\t\titer.remove();\n\n\t\t\t}\n\t\t}\n\n\t\treturn moves;\n\t}\n\n\t@Override\n\tpublic Set getPossibleMovesTo(int square) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isCheckPosition() {\n\t\tif (is_check == null) {\n\t\t\tis_check = true;\n\t\t\tSet temp_king_pos = getOccupiedSquaresByColorAndType(\n\t\t\t\t\tactive_color, PieceHelper.KING);\n\t\t\tint king_pos = temp_king_pos.iterator().next();\n\n\t\t\t// go in each direction\n\t\t\tfor (Direction direction : Direction.values()) {\n\t\t\t\tList line = SquareHelper.getAllSquaresInDirection(\n\t\t\t\t\t\tking_pos, direction);\n\t\t\t\t// go until…\n\t\t\t\tint iter = 0;\n\t\t\t\tfor (int square : line) {\n\t\t\t\t\titer++;\n\t\t\t\t\t// …some piece is found\n\t\t\t\t\tint piece = getFromBoard(square);\n\t\t\t\t\tif (piece != 0) {\n\t\t\t\t\t\tif (PieceHelper.pieceColor(piece) == active_color) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (PieceHelper.pieceType(piece) == PieceHelper.PAWN\n\t\t\t\t\t\t\t\t\t&& iter == 1) {\n\t\t\t\t\t\t\t\tif (((direction == Direction.NORTHEAST || direction == Direction.NORTHWEST) && active_color == PieceHelper.WHITE)\n\t\t\t\t\t\t\t\t\t\t|| ((direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && active_color == PieceHelper.BLACK)) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.ROOK) {\n\t\t\t\t\t\t\t\tif (direction == Direction.EAST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.WEST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.NORTH\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.SOUTH) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.BISHOP) {\n\t\t\t\t\t\t\t\tif (direction == Direction.NORTHEAST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.NORTHWEST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.SOUTHEAST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.SOUTHWEST) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.QUEEN) {\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.KING\n\t\t\t\t\t\t\t\t\t&& iter == 1) {\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// check for knight attacks\n\t\t\tList knight_squares = SquareHelper\n\t\t\t\t\t.getAllSquaresByKnightStep(king_pos);\n\t\t\tfor (int square : knight_squares) {\n\t\t\t\tint piece = getFromBoard(square);\n\t\t\t\tif (piece != 0) {\n\t\t\t\t\tif (PieceHelper.pieceColor(piece) != active_color\n\t\t\t\t\t\t\t&& PieceHelper.pieceType(piece) == PieceHelper.KNIGHT) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tis_check = false;\n\t\t}\n\t\treturn is_check.booleanValue();\n\n\t}\n\n\t@Override\n\tpublic boolean isMatePosition() {\n\t\tif (is_mate == null) {\n\t\t\tis_mate = true;\n\t\t\tSet moves = getPossibleMoves();\n\t\t\tif (moves.isEmpty() && isCheckPosition())\n\t\t\t\treturn true;\n\t\t\tis_mate = false;\n\t\t}\n\t\treturn is_mate.booleanValue();\n\t}\n\n\t@Override\n\tpublic boolean isStaleMatePosition() {\n\t\tif (is_stale_mate == null) {\n\t\t\tis_stale_mate = true;\n\t\t\tSet moves = getPossibleMoves();\n\t\t\tif (moves.isEmpty())\n\t\t\t\treturn true;\n\t\t\tis_stale_mate = false;\n\t\t}\n\t\treturn is_stale_mate.booleanValue();\n\t}\n\n\t@Override\n\tpublic boolean isPossibleMove(IMove move) {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\tpublic String toString() {\n\t\treturn toFEN();\n\t}\n\n\t@Override\n\tpublic String toFEN() {\n\t\tStringBuilder fen = new StringBuilder();\n\n\t\t// piece placement\n\t\tfor (int row = 2; row < 10; row++) {\n\n\t\t\tint counter = 0;\n\n\t\t\tfor (int column = 2; column < 10; column++) {\n\t\t\t\tif (board[row][column] == 0) {\n\t\t\t\t\tcounter++;\n\t\t\t\t} else {\n\t\t\t\t\tif (counter != 0) {\n\t\t\t\t\t\tfen.append(counter);\n\t\t\t\t\t\tcounter = 0;\n\t\t\t\t\t}\n\t\t\t\t\tfen.append(PieceHelper.toString(board[row][column]));\n\t\t\t\t}\n\t\t\t\tif (column == 9 && counter != 0) {\n\t\t\t\t\tfen.append(counter);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (row != 9) {\n\t\t\t\tfen.append(\"/\");\n\t\t\t}\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// active color\n\t\tif (active_color == PieceHelper.WHITE) {\n\t\t\tfen.append(\"w\");\n\t\t} else {\n\t\t\tfen.append(\"b\");\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// castling availability\n\t\tboolean castle_flag = false;\n\t\tif (castling[1] != -1) {\n\t\t\tfen.append(\"K\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (castling[0] != -1) {\n\t\t\tfen.append(\"Q\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (castling[3] != -1) {\n\t\t\tfen.append(\"k\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (castling[2] != -1) {\n\t\t\tfen.append(\"q\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (!castle_flag) {\n\t\t\tfen.append(\"-\");\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// en passant target square\n\t\tif (en_passant_target == -1) {\n\t\t\tfen.append(\"-\");\n\t\t} else {\n\t\t\tfen.append(SquareHelper.toString(en_passant_target));\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// halfmove clock\n\t\tfen.append(half_move_clock);\n\t\tfen.append(\" \");\n\n\t\t// fullmove clock\n\t\tfen.append(full_move_clock);\n\n\t\treturn fen.toString();\n\t}\n\n\t@Override\n\tpublic int getActiveColor() {\n\t\treturn active_color;\n\t}\n\n\t@Override\n\tpublic int getHalfMoveClock() {\n\t\treturn half_move_clock;\n\t}\n\n\t@Override\n\tpublic int getFullMoveClock() {\n\t\treturn full_move_clock;\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"src/mitzi/NaiveBoard.java"},"old_contents":{"kind":"string","value":"package mitzi;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class NaiveBoard implements IBoard {\n\n\tprotected static int[][] initial_board = {\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 12, 13, 14, 15, 16, 14, 13, 12, 00, 00 },\n\t\t\t{ 00, 00, 11, 11, 11, 11, 11, 11, 11, 11, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 01, 01, 01, 01, 01, 01, 01, 01, 00, 00 },\n\t\t\t{ 00, 00, 02, 03, 04, 05, 06, 04, 03, 02, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 },\n\t\t\t{ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 } };\n\n\tprivate int[][] board = new int[12][12];\n\n\tprivate int full_move_clock;\n\n\tprivate int half_move_clock;\n\n\t// squares c1, g1, c8 and g8 in ICCF numeric notation\n\t// do not change the squares' order or bad things will happen!\n\t// set to -1 if castling not allowed\n\tprivate int[] castling = { -1, -1, -1, -1 };\n\n\tprivate int en_passant_target = -1;\n\n\tprivate int active_color;\n\n\t// The following class members are used to prevent multiple computations\n\tprivate Set possible_moves;\n\n\tprivate Boolean is_check; // using the class Boolean, which can be null!\n\n\tprivate Boolean is_mate;\n\n\tprivate Boolean is_stale_mate;\n\n\t// the following maps takes and Integer, representing the color, type or\n\t// PieceValue and returns the set of squares or the number of squares!\n\tprivate Map> occupied_squares_by_color_and_type = new HashMap>();\n\n\tprivate Map> occupied_squares_by_color = new HashMap>();\n\n\tprivate Map> occupied_squares_by_type = new HashMap>();\n\n\tprivate Map num_occupied_squares_by_color_and_type = new HashMap();\n\n\tprivate Map num_occupied_squares_by_color = new HashMap();\n\n\tprivate Map num_occupied_squares_by_type = new HashMap();\n\n\t// --------------------------------------------------------\n\n\tprivate NaiveBoard returnCopy() {\n\t\tNaiveBoard newBoard = new NaiveBoard();\n\n\t\tnewBoard.active_color = active_color;\n\t\tnewBoard.en_passant_target = en_passant_target;\n\t\tnewBoard.full_move_clock = full_move_clock;\n\t\tnewBoard.half_move_clock = half_move_clock;\n\t\tSystem.arraycopy(castling, 0, newBoard.castling, 0, 4);\n\n\t\t// from row and column 1,2,11,12 are 0..\n\t\tfor (int i = 2; i < 11; i++)\n\t\t\tSystem.arraycopy(board[i], 2, newBoard.board[i], 2, 8);\n\n\t\treturn newBoard;\n\t}\n\n\tprivate int getFromBoard(int square) {\n\t\tint row = SquareHelper.getRow(square);\n\t\tint column = SquareHelper.getColumn(square);\n\t\treturn board[10 - row][1 + column];\n\t}\n\n\tprivate void setOnBoard(int square, int piece_value) {\n\t\tint row = SquareHelper.getRow(square);\n\t\tint column = SquareHelper.getColumn(square);\n\t\tboard[10 - row][1 + column] = piece_value;\n\t}\n\n\tpublic int getOpponentsColor() {\n\t\tif (active_color == PieceHelper.BLACK)\n\t\t\treturn PieceHelper.WHITE;\n\t\telse\n\t\t\treturn PieceHelper.BLACK;\n\t}\n\n\t@Override\n\tpublic void setToInitial() {\n\t\tboard = initial_board;\n\n\t\tfull_move_clock = 1;\n\n\t\thalf_move_clock = 0;\n\n\t\tcastling[0] = 31;\n\t\tcastling[1] = 71;\n\t\tcastling[2] = 38;\n\t\tcastling[3] = 78;\n\n\t\ten_passant_target = -1;\n\n\t\tactive_color = PieceHelper.WHITE;\n\t}\n\n\t@Override\n\tpublic void setToFEN(String fen) {\n\t\tboard = new int[12][12];\n\t\tcastling[0] = -1;\n\t\tcastling[1] = -1;\n\t\tcastling[2] = -1;\n\t\tcastling[3] = -1;\n\t\ten_passant_target = -1;\n\n\t\tString[] fen_parts = fen.split(\" \");\n\n\t\t// populate the squares\n\t\tString[] fen_rows = fen_parts[0].split(\"/\");\n\t\tchar[] pieces;\n\t\tfor (int row = 1; row <= 8; row++) {\n\t\t\tint offset = 0;\n\t\t\tfor (int column = 1; column + offset <= 8; column++) {\n\t\t\t\tpieces = fen_rows[8 - row].toCharArray();\n\t\t\t\tint square = (column + offset) * 10 + row;\n\t\t\t\tswitch (pieces[column - 1]) {\n\t\t\t\tcase 'P':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN,\n\t\t\t\t\t\t\tPieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'R':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK,\n\t\t\t\t\t\t\tPieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'N':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.KNIGHT, PieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'B':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.BISHOP, PieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Q':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.QUEEN, PieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'K':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING,\n\t\t\t\t\t\t\tPieceHelper.WHITE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'p':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN,\n\t\t\t\t\t\t\tPieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'r':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK,\n\t\t\t\t\t\t\tPieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'n':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.KNIGHT, PieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'b':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.BISHOP, PieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'q':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(\n\t\t\t\t\t\t\tPieceHelper.QUEEN, PieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'k':\n\t\t\t\t\tsetOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING,\n\t\t\t\t\t\t\tPieceHelper.BLACK));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\toffset += Character.getNumericValue(pieces[column - 1]) - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set active color\n\t\tswitch (fen_parts[1]) {\n\t\tcase \"b\":\n\t\t\tactive_color = PieceHelper.BLACK;\n\t\t\tbreak;\n\t\tcase \"w\":\n\t\t\tactive_color = PieceHelper.WHITE;\n\t\t\tbreak;\n\t\t}\n\n\t\t// set possible castling moves\n\t\tif (!fen_parts[2].equals(\"-\")) {\n\t\t\tchar[] castlings = fen_parts[2].toCharArray();\n\t\t\tfor (int i = 0; i < castlings.length; i++) {\n\t\t\t\tswitch (castlings[i]) {\n\t\t\t\tcase 'K':\n\t\t\t\t\tcastling[1] = 71;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Q':\n\t\t\t\t\tcastling[0] = 31;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'k':\n\t\t\t\t\tcastling[3] = 78;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'q':\n\t\t\t\t\tcastling[2] = 38;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set en passant square\n\t\tif (!fen_parts[3].equals(\"-\")) {\n\t\t\ten_passant_target = SquareHelper.fromString(fen_parts[3]);\n\t\t}\n\n\t\t// set half move clock\n\t\thalf_move_clock = Integer.parseInt(fen_parts[4]);\n\n\t\t// set full move clock\n\t\tfull_move_clock = Integer.parseInt(fen_parts[5]);\n\t}\n\n\t@Override\n\tpublic NaiveBoard doMove(IMove move) {\n\n\t\tNaiveBoard newBoard = this.returnCopy();\n\n\t\tint src = move.getFromSquare();\n\t\tint dest = move.getToSquare();\n\n\t\t// if promotion\n\t\tif (move.getPromotion() != 0) {\n\t\t\tnewBoard.setOnBoard(src, 0);\n\t\t\tnewBoard.setOnBoard(dest,\n\t\t\t\t\tPieceHelper.pieceValue(move.getPromotion(), active_color));\n\n\t\t\tnewBoard.half_move_clock = 0;\n\n\t\t}\n\t\t// If rochade\n\t\telse if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.KING\n\t\t\t\t&& Math.abs((src - dest)) == 20) {\n\t\t\tnewBoard.setOnBoard(dest,\n\t\t\t\t\tPieceHelper.pieceValue(PieceHelper.KING, active_color));\n\t\t\tnewBoard.setOnBoard(src, 0);\n\t\t\tnewBoard.setOnBoard((src + dest) / 2,\n\t\t\t\t\tPieceHelper.pieceValue(PieceHelper.ROOK, active_color));\n\t\t\tif (SquareHelper.getColumn(dest) == 3)\n\t\t\t\tnewBoard.setOnBoard(src - 40, 0);\n\t\t\telse\n\t\t\t\tnewBoard.setOnBoard(src + 30, 0);\n\n\t\t\tnewBoard.half_move_clock++;\n\n\t\t}\n\t\t// If en passant\n\t\telse if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.PAWN\n\t\t\t\t&& dest == this.getEnPassant()) {\n\t\t\tnewBoard.setOnBoard(dest,\n\t\t\t\t\tPieceHelper.pieceValue(PieceHelper.PAWN, active_color));\n\t\t\tnewBoard.setOnBoard(src, 0);\n\t\t\tif (active_color == PieceHelper.WHITE)\n\t\t\t\tnewBoard.setOnBoard(dest - 1, 0);\n\t\t\telse\n\t\t\t\tnewBoard.setOnBoard(dest + 1, 0);\n\n\t\t\tnewBoard.half_move_clock = 0;\n\t\t}\n\t\t// Usual move\n\t\telse {\n\t\t\tnewBoard.setOnBoard(dest, this.getFromBoard(src));\n\t\t\tnewBoard.setOnBoard(src, 0);\n\n\t\t\tif (this.getFromBoard(dest) != 0\n\t\t\t\t\t|| PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.PAWN)\n\t\t\t\tnewBoard.half_move_clock = 0;\n\t\t\telse\n\t\t\t\tnewBoard.half_move_clock++;\n\n\t\t}\n\n\t\t// Change active_color after move\n\t\tnewBoard.active_color = PieceHelper.pieceOppositeColor(this\n\t\t\t\t.getFromBoard(src));\n\t\tif (active_color == PieceHelper.BLACK)\n\t\t\tnewBoard.full_move_clock++;\n\n\t\t// Update en_passant\n\t\tif (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.PAWN\n\t\t\t\t&& Math.abs(dest - src) == 2)\n\t\t\tnewBoard.en_passant_target = (dest + src) / 2;\n\t\telse\n\t\t\tnewBoard.en_passant_target = -1;\n\n\t\t// Update castling\n\t\tif (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.KING) {\n\t\t\tif (active_color == PieceHelper.WHITE && src == 51) {\n\t\t\t\tnewBoard.castling[0] = -1;\n\t\t\t\tnewBoard.castling[1] = -1;\n\t\t\t} else if (active_color == PieceHelper.BLACK && src == 58) {\n\t\t\t\tnewBoard.castling[2] = -1;\n\t\t\t\tnewBoard.castling[3] = -1;\n\t\t\t}\n\t\t} else if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.ROOK) {\n\t\t\tif (active_color == PieceHelper.WHITE) {\n\t\t\t\tif (src == 81)\n\t\t\t\t\tnewBoard.castling[1] = -1;\n\t\t\t\telse if (src == 11)\n\t\t\t\t\tnewBoard.castling[0] = -1;\n\t\t\t} else {\n\t\t\t\tif (src == 88)\n\t\t\t\t\tnewBoard.castling[3] = -1;\n\t\t\t\telse if (src == 18)\n\t\t\t\t\tnewBoard.castling[2] = -1;\n\t\t\t}\n\t\t}\n\t\treturn newBoard;\n\t}\n\n\t@Override\n\tpublic int getEnPassant() {\n\t\treturn en_passant_target;\n\t}\n\n\t@Override\n\tpublic boolean canCastle(int king_to) {\n\t\tif ((king_to == 31 && castling[0] != -1)\n\t\t\t\t|| (king_to == 71 && castling[1] != -1)\n\t\t\t\t|| (king_to == 38 && castling[2] != -1)\n\t\t\t\t|| (king_to == 78 && castling[3] != -1)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic Set getOccupiedSquaresByColor(int color) {\n\n\t\tif (occupied_squares_by_color.containsKey(color) == false) {\n\t\t\tint square;\n\t\t\tSet set = new HashSet();\n\n\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t&& PieceHelper\n\t\t\t\t\t\t\t\t\t.pieceColor(this.getFromBoard(square)) == color)\n\t\t\t\t\t\tset.add(square);\n\t\t\t\t}\n\n\t\t\toccupied_squares_by_color.put(color, set);\n\t\t\treturn set;\n\t\t}\n\t\treturn occupied_squares_by_color.get(color);\n\t}\n\n\t@Override\n\tpublic Set getOccupiedSquaresByType(int type) {\n\n\t\tif (occupied_squares_by_type.containsKey(type) == false) {\n\t\t\tint square;\n\t\t\tSet set = new HashSet();\n\n\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceType(this.getFromBoard(square)) == type)\n\t\t\t\t\t\tset.add(square);\n\t\t\t\t}\n\n\t\t\toccupied_squares_by_type.put(type, set);\n\t\t\treturn set;\n\t\t}\n\t\treturn occupied_squares_by_type.get(type);\n\n\t}\n\n\t@Override\n\tpublic Set getOccupiedSquaresByColorAndType(int color, int type) {\n\n\t\tif (occupied_squares_by_color_and_type.containsKey(PieceHelper\n\t\t\t\t.pieceValue(type, color)) == false) {\n\t\t\tint square;\n\t\t\tSet set = new HashSet();\n\n\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceValue(type, color) == this\n\t\t\t\t\t\t\t\t\t.getFromBoard(square))\n\t\t\t\t\t\tset.add(square);\n\t\t\t\t}\n\t\t\toccupied_squares_by_color_and_type.put(\n\t\t\t\t\tPieceHelper.pieceValue(type, color), set);\n\t\t\treturn set;\n\t\t}\n\t\treturn occupied_squares_by_color_and_type.get(PieceHelper.pieceValue(\n\t\t\t\ttype, color));\n\t}\n\n\t@Override\n\tpublic int getNumberOfPiecesByColor(int color) {\n\n\t\tif (num_occupied_squares_by_color.containsKey(color) == false) {\n\t\t\tif (occupied_squares_by_color.containsKey(color) == false) {\n\t\t\t\tint square;\n\t\t\t\tint num = 0;\n\n\t\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t\t&& PieceHelper.pieceColor(this\n\t\t\t\t\t\t\t\t\t\t.getFromBoard(square)) == color)\n\t\t\t\t\t\t\tnum++;\n\t\t\t\t\t}\n\t\t\t\tnum_occupied_squares_by_color.put(color, num);\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tnum_occupied_squares_by_color.put(color, occupied_squares_by_color\n\t\t\t\t\t.get(color).size());\n\t\t}\n\t\treturn num_occupied_squares_by_color.get(color);\n\n\t}\n\n\t@Override\n\tpublic int getNumberOfPiecesByType(int type) {\n\n\t\tif (num_occupied_squares_by_type.containsKey(type) == false) {\n\t\t\tif (occupied_squares_by_type.containsKey(type) == false) {\n\t\t\t\tint square;\n\t\t\t\tint num = 0;\n\n\t\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t\t&& PieceHelper.pieceType(this\n\t\t\t\t\t\t\t\t\t\t.getFromBoard(square)) == type)\n\t\t\t\t\t\t\tnum++;\n\t\t\t\t\t}\n\t\t\t\tnum_occupied_squares_by_type.put(type, num);\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tnum_occupied_squares_by_type.put(type, occupied_squares_by_type\n\t\t\t\t\t.get(type).size());\n\t\t}\n\t\treturn num_occupied_squares_by_type.get(type);\n\n\t}\n\n\t@Override\n\tpublic int getNumberOfPiecesByColorAndType(int color, int type) {\n\n\t\tint value = PieceHelper.pieceValue(type, color);\n\t\tif (num_occupied_squares_by_color_and_type.containsKey(value) == false) {\n\t\t\tif (occupied_squares_by_color_and_type.containsKey(value) == false) {\n\t\t\t\tint square;\n\t\t\t\tint num = 0;\n\n\t\t\t\tfor (int i = 1; i < 9; i++)\n\t\t\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\t\t\tsquare = SquareHelper.getSquare(i, j);\n\t\t\t\t\t\tif (this.getFromBoard(square) > 0\n\t\t\t\t\t\t\t\t&& value == this.getFromBoard(square))\n\n\t\t\t\t\t\t\tnum++;\n\t\t\t\t\t}\n\t\t\t\tnum_occupied_squares_by_color_and_type.put(value, num);\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tnum_occupied_squares_by_color_and_type.put(value,\n\t\t\t\t\toccupied_squares_by_color_and_type.get(value).size());\n\t\t}\n\t\treturn num_occupied_squares_by_color_and_type.get(value);\n\t}\n\n\t@Override\n\tpublic Set getPossibleMoves() {\n\n\t\tif (possible_moves == null) {\n\t\t\tSet total_set = new HashSet();\n\t\t\tSet temp_set;\n\n\t\t\t// all the active squares\n\t\t\tSet squares = getOccupiedSquaresByColor(active_color);\n\n\t\t\t// loop over all squares\n\t\t\tfor (int square : squares) {\n\t\t\t\ttemp_set = getPossibleMovesFrom(square);\n\t\t\t\ttotal_set.addAll(temp_set);\n\t\t\t}\n\t\t\tpossible_moves = total_set;\n\t\t}\n\t\treturn possible_moves;\n\n\t}\n\n\t@Override\n\tpublic Set getPossibleMovesFrom(int square) {\n\t\t// The case, that the destination is the opponents king cannot happen.\n\n\t\tint type = PieceHelper.pieceType(getFromBoard(square));\n\t\tint opp_color = getOpponentsColor();\n\t\tList squares;\n\t\tSet moves = new HashSet();\n\t\tMove move;\n\n\t\t// Types BISHOP, QUEEN, ROOK\n\t\tif (type == PieceHelper.BISHOP || type == PieceHelper.QUEEN\n\t\t\t\t|| type == PieceHelper.ROOK) {\n\n\t\t\t// Loop over all directions and skip not appropriate ones\n\t\t\tfor (Direction direction : Direction.values()) {\n\n\t\t\t\t// Skip N,W,E,W with BISHOP and skip NE,NW,SE,SW with ROOK\n\t\t\t\tif (((direction == Direction.NORTH\n\t\t\t\t\t\t|| direction == Direction.EAST\n\t\t\t\t\t\t|| direction == Direction.SOUTH || direction == Direction.WEST) && type == PieceHelper.BISHOP)\n\t\t\t\t\t\t|| ((direction == Direction.NORTHWEST\n\t\t\t\t\t\t\t\t|| direction == Direction.NORTHEAST\n\t\t\t\t\t\t\t\t|| direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && type == PieceHelper.ROOK)) {\n\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\t// do stuff\n\t\t\t\t\tsquares = SquareHelper.getAllSquaresInDirection(square,\n\t\t\t\t\t\t\tdirection);\n\n\t\t\t\t\tfor (Integer new_square : squares) {\n\t\t\t\t\t\tif (getFromBoard(new_square) == 0\n\t\t\t\t\t\t\t\t|| PieceHelper\n\t\t\t\t\t\t\t\t\t\t.pieceColor(getFromBoard(new_square)) == opp_color) {\n\n\t\t\t\t\t\t\tmove = new Move(square, new_square);\n\t\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t\t\tif (getFromBoard(new_square) != 0\n\t\t\t\t\t\t\t\t\t&& PieceHelper\n\t\t\t\t\t\t\t\t\t\t\t.pieceColor(getFromBoard(new_square)) == opp_color)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (type == PieceHelper.PAWN) {\n\t\t\t// If Pawn has not moved yet (steps possible)\n\t\t\tif ((SquareHelper.getRow(square) == 2 && active_color == PieceHelper.WHITE)\n\t\t\t\t\t|| (SquareHelper.getRow(square) == 7 && active_color == PieceHelper.BLACK)) {\n\n\t\t\t\tif (getFromBoard(square\n\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tif (getFromBoard(square + 2\n\t\t\t\t\t\t\t* Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\t\tmove = new Move(square, square + 2\n\t\t\t\t\t\t\t\t* Direction.pawnDirection(active_color).offset);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tSet pawn_capturing_directions = Direction\n\t\t\t\t\t\t.pawnCapturingDirections(active_color);\n\t\t\t\tfor (Direction direction : pawn_capturing_directions) {\n\t\t\t\t\tif (getFromBoard(square + direction.offset) != 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceColor(getFromBoard(square\n\t\t\t\t\t\t\t\t\t+ direction.offset)) == getOpponentsColor()) {\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// if Promotion will happen\n\t\t\telse if ((SquareHelper.getRow(square) == 7 && active_color == PieceHelper.WHITE)\n\t\t\t\t\t|| (SquareHelper.getRow(square) == 2 && active_color == PieceHelper.BLACK)) {\n\t\t\t\tif (getFromBoard(square\n\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.QUEEN);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.KNIGHT);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.ROOK);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset,\n\t\t\t\t\t\t\tPieceHelper.BISHOP);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t\tSet pawn_capturing_directions = Direction\n\t\t\t\t\t\t.pawnCapturingDirections(active_color);\n\t\t\t\tfor (Direction direction : pawn_capturing_directions) {\n\t\t\t\t\tif (getFromBoard(square + direction.offset) != 0\n\t\t\t\t\t\t\t&& PieceHelper.pieceColor(getFromBoard(square\n\t\t\t\t\t\t\t\t\t+ direction.offset)) == getOpponentsColor()) {\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset,\n\t\t\t\t\t\t\t\tPieceHelper.QUEEN);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset,\n\t\t\t\t\t\t\t\tPieceHelper.KNIGHT);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// Usual turn and en passente is possible, no promotion\n\t\t\telse {\n\t\t\t\tif (getFromBoard(square\n\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset) == 0) {\n\t\t\t\t\tmove = new Move(square, square\n\t\t\t\t\t\t\t+ Direction.pawnDirection(active_color).offset);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t\tSet pawn_capturing_directions = Direction\n\t\t\t\t\t\t.pawnCapturingDirections(active_color);\n\t\t\t\tfor (Direction direction : pawn_capturing_directions) {\n\t\t\t\t\tif ((getFromBoard(square + direction.offset) != 0 && PieceHelper\n\t\t\t\t\t\t\t.pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor())\n\t\t\t\t\t\t\t|| square + direction.offset == getEnPassant()) {\n\t\t\t\t\t\tmove = new Move(square, square + direction.offset);\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif (type == PieceHelper.KING) {\n\t\t\tfor (Direction direction : Direction.values()) {\n\t\t\t\tInteger new_square = square + direction.offset;\n\t\t\t\tmove = new Move(square, new_square);\n\t\t\t\tif (SquareHelper.isValidSquare(new_square)) {\n\t\t\t\t\t// if the new square is empty or occupied by the opponent\n\t\t\t\t\tif (getFromBoard(new_square) == 0\n\t\t\t\t\t\t\t|| PieceHelper.pieceColor(getFromBoard(new_square)) != active_color)\n\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Castle Moves\n\t\t\t// If the King is not check now, try castle moves\n\t\t\tif (!isCheckPosition()) {\n\t\t\t\tint off = 0;\n\t\t\t\tif (active_color == PieceHelper.BLACK)\n\t\t\t\t\toff = 2;\n\n\t\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\t\tint castle_flag = 0;\n\t\t\t\t\tInteger new_square = castling[i + off];\n\t\t\t\t\t// castling must still be possible to this side\n\t\t\t\t\tif (new_square != -1) {\n\n\t\t\t\t\t\tDirection dir;\n\t\t\t\t\t\tif (i == 0)\n\t\t\t\t\t\t\tdir = Direction.WEST;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdir = Direction.EAST;\n\n\t\t\t\t\t\tList line = SquareHelper\n\t\t\t\t\t\t\t\t.getAllSquaresInDirection(square, dir);\n\n\t\t\t\t\t\t// Check each square if it is empty\n\t\t\t\t\t\tfor (Integer squ : line) {\n\t\t\t\t\t\t\tif (getFromBoard(squ) != 0) {\n\t\t\t\t\t\t\t\tcastle_flag = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (squ == new_square)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (castle_flag == 1)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t// Check each square if the king on it would be check\n\t\t\t\t\t\tfor (Integer squ : line) {\n\t\t\t\t\t\t\tmove = new Move(square, squ);\n\t\t\t\t\t\t\tNaiveBoard board = doMove(move);\n\t\t\t\t\t\t\tboard.active_color = active_color; // TODO: ugly\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// solution ! ;)\n\t\t\t\t\t\t\tif (board.isCheckPosition())\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tif (squ == new_square) { // if EVERYTHING is right,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// then add the move\n\t\t\t\t\t\t\t\tmoves.add(move);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (type == PieceHelper.KNIGHT) {\n\t\t\tsquares = SquareHelper.getAllSquaresByKnightStep(square);\n\t\t\tfor (Integer new_square : squares) {\n\t\t\t\tif (getFromBoard(new_square) == 0\n\t\t\t\t\t\t|| PieceHelper.pieceColor(getFromBoard(new_square)) != active_color) {\n\t\t\t\t\tmove = new Move(square, new_square);\n\t\t\t\t\tmoves.add(move);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// remove invalid positions\n\t\t// TODO do this in a more efficient way\n\t\tIterator iter = moves.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tNaiveBoard temp_board = this.doMove(iter.next());\n\t\t\ttemp_board.active_color = active_color; // ugly solution…\n\t\t\tif (temp_board.isCheckPosition()) {\n\t\t\t\titer.remove();\n\t\t\t}\n\t\t}\n\n\t\treturn moves;\n\t}\n\n\t@Override\n\tpublic Set getPossibleMovesTo(int square) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isCheckPosition() {\n\t\tif (is_check == null) {\n\t\t\tis_check = true;\n\t\t\tSet temp_king_pos = getOccupiedSquaresByColorAndType(\n\t\t\t\t\tactive_color, PieceHelper.KING);\n\t\t\tint king_pos = temp_king_pos.iterator().next();\n\n\t\t\t// go in each direction\n\t\t\tfor (Direction direction : Direction.values()) {\n\t\t\t\tList line = SquareHelper.getAllSquaresInDirection(\n\t\t\t\t\t\tking_pos, direction);\n\t\t\t\t// go until…\n\t\t\t\tint iter = 0;\n\t\t\t\tfor (int square : line) {\n\t\t\t\t\titer++;\n\t\t\t\t\t// …some piece is found\n\t\t\t\t\tint piece = getFromBoard(square);\n\t\t\t\t\tif (piece != 0) {\n\t\t\t\t\t\tif (PieceHelper.pieceColor(piece) == active_color) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (PieceHelper.pieceType(piece) == PieceHelper.PAWN\n\t\t\t\t\t\t\t\t\t&& iter == 1) {\n\t\t\t\t\t\t\t\tif (((direction == Direction.NORTHEAST || direction == Direction.NORTHWEST) && active_color == PieceHelper.WHITE)\n\t\t\t\t\t\t\t\t\t\t|| ((direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && active_color == PieceHelper.BLACK)) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.ROOK) {\n\t\t\t\t\t\t\t\tif (direction == Direction.EAST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.WEST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.NORTH\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.SOUTH) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.BISHOP) {\n\t\t\t\t\t\t\t\tif (direction == Direction.NORTHEAST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.NORTHWEST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.SOUTHEAST\n\t\t\t\t\t\t\t\t\t\t|| direction == Direction.SOUTHWEST) {\n\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.QUEEN) {\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t} else if (PieceHelper.pieceType(piece) == PieceHelper.KING\n\t\t\t\t\t\t\t\t\t&& iter == 1) {\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// check for knight attacks\n\t\t\tList knight_squares = SquareHelper\n\t\t\t\t\t.getAllSquaresByKnightStep(king_pos);\n\t\t\tfor (int square : knight_squares) {\n\t\t\t\tint piece = getFromBoard(square);\n\t\t\t\tif (piece != 0) {\n\t\t\t\t\tif (PieceHelper.pieceColor(piece) != active_color\n\t\t\t\t\t\t\t&& PieceHelper.pieceType(piece) == PieceHelper.KNIGHT) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tis_check = false;\n\t\t}\n\t\treturn is_check.booleanValue();\n\n\t}\n\n\t@Override\n\tpublic boolean isMatePosition() {\n\t\tif (is_mate == null) {\n\t\t\tis_mate = true;\n\t\t\tSet moves = getPossibleMoves();\n\t\t\tif (moves.isEmpty() && isCheckPosition())\n\t\t\t\treturn true;\n\t\t\tis_mate = false;\n\t\t}\n\t\treturn is_mate.booleanValue();\n\t}\n\n\t@Override\n\tpublic boolean isStaleMatePosition() {\n\t\tif (is_stale_mate == null) {\n\t\t\tis_stale_mate = true;\n\t\t\tSet moves = getPossibleMoves();\n\t\t\tif (moves.isEmpty())\n\t\t\t\treturn true;\n\t\t\tis_stale_mate = false;\n\t\t}\n\t\treturn is_stale_mate.booleanValue();\n\t}\n\n\t@Override\n\tpublic boolean isPossibleMove(IMove move) {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\tpublic String toString() {\n\t\treturn toFEN();\n\t}\n\n\t@Override\n\tpublic String toFEN() {\n\t\tStringBuilder fen = new StringBuilder();\n\n\t\t// piece placement\n\t\tfor (int row = 2; row < 10; row++) {\n\n\t\t\tint counter = 0;\n\n\t\t\tfor (int column = 2; column < 10; column++) {\n\t\t\t\tif (board[row][column] == 0) {\n\t\t\t\t\tcounter++;\n\t\t\t\t} else {\n\t\t\t\t\tif (counter != 0) {\n\t\t\t\t\t\tfen.append(counter);\n\t\t\t\t\t\tcounter = 0;\n\t\t\t\t\t}\n\t\t\t\t\tfen.append(PieceHelper.toString(board[row][column]));\n\t\t\t\t}\n\t\t\t\tif (column == 9 && counter != 0) {\n\t\t\t\t\tfen.append(counter);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (row != 9) {\n\t\t\t\tfen.append(\"/\");\n\t\t\t}\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// active color\n\t\tif (active_color == PieceHelper.WHITE) {\n\t\t\tfen.append(\"w\");\n\t\t} else {\n\t\t\tfen.append(\"b\");\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// castling availability\n\t\tboolean castle_flag = false;\n\t\tif (castling[1] != -1) {\n\t\t\tfen.append(\"K\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (castling[0] != -1) {\n\t\t\tfen.append(\"Q\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (castling[3] != -1) {\n\t\t\tfen.append(\"k\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (castling[2] != -1) {\n\t\t\tfen.append(\"q\");\n\t\t\tcastle_flag = true;\n\t\t}\n\t\tif (!castle_flag) {\n\t\t\tfen.append(\"-\");\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// en passant target square\n\t\tif (en_passant_target == -1) {\n\t\t\tfen.append(\"-\");\n\t\t} else {\n\t\t\tfen.append(SquareHelper.toString(en_passant_target));\n\t\t}\n\t\tfen.append(\" \");\n\n\t\t// halfmove clock\n\t\tfen.append(half_move_clock);\n\t\tfen.append(\" \");\n\n\t\t// fullmove clock\n\t\tfen.append(full_move_clock);\n\n\t\treturn fen.toString();\n\t}\n\n\t@Override\n\tpublic int getActiveColor() {\n\t\treturn active_color;\n\t}\n\n\t@Override\n\tpublic int getHalfMoveClock() {\n\t\treturn half_move_clock;\n\t}\n\n\t@Override\n\tpublic int getFullMoveClock() {\n\t\treturn full_move_clock;\n\t}\n\n}\n"},"message":{"kind":"string","value":"reduced the number of getFromBoard calls... Mitzi is again a bit faster\n:)"},"old_file":{"kind":"string","value":"src/mitzi/NaiveBoard.java"},"subject":{"kind":"string","value":"reduced the number of getFromBoard calls... Mitzi is again a bit faster :)"}}},{"rowIdx":1274,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"667955f70b12e8c45fc591e00b59a9b231ca02ef"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"GluuFederation/oxCore,madumlao/oxCore"},"new_contents":{"kind":"string","value":"/*\n * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.\n *\n * Copyright (c) 2014, Gluu\n */\n\npackage org.gluu.ldap.model;\n\nimport java.io.Serializable;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Transient;\n\nimport org.gluu.site.ldap.persistence.annotation.LdapAttribute;\nimport org.gluu.site.ldap.persistence.annotation.LdapDN;\nimport org.gluu.site.ldap.persistence.annotation.LdapEntry;\nimport org.gluu.site.ldap.persistence.annotation.LdapJsonObject;\nimport org.gluu.site.ldap.persistence.annotation.LdapObjectClass;\n\n/**\n * @author Yuriy Zabrovarnyy\n * @author Javier Rojas Blum\n * @version December 15, 2015\n */\n@LdapEntry\n@LdapObjectClass(values = { \"top\", \"oxAuthSessionId\" })\npublic class SimpleSessionState implements Serializable {\n\n private static final long serialVersionUID = -237476411915686378L;\n\n @LdapDN\n private String dn;\n\n @LdapAttribute(name = \"uniqueIdentifier\")\n private String id;\n\n @LdapAttribute(name = \"oxLastAccessTime\")\n private Date lastUsedAt;\n\n @LdapAttribute(name = \"oxAuthUserDN\")\n private String userDn;\n\n @LdapAttribute(name = \"oxAuthAuthenticationTime\")\n private Date authenticationTime;\n\n @LdapAttribute(name = \"oxAuthSessionState\")\n private Boolean permissionGranted;\n\n @LdapAttribute(name = \"oxAsJwt\")\n private Boolean isJwt = false;\n\n @LdapAttribute(name = \"oxJwt\")\n private String jwt;\n\n @LdapJsonObject\n @LdapAttribute(name = \"oxAuthSessionAttribute\")\n private Map sessionAttributes;\n\n @Transient\n private transient boolean persisted;\n\n public String getDn() {\n return dn;\n }\n\n public void setDn(String dn) {\n this.dn = dn;\n }\n\n public String getJwt() {\n return jwt;\n }\n\n public void setJwt(String jwt) {\n this.jwt = jwt;\n }\n\n public Boolean getIsJwt() {\n return isJwt;\n }\n\n public void setIsJwt(Boolean isJwt) {\n this.isJwt = isJwt;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public Date getLastUsedAt() {\n return lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null;\n }\n\n public void setLastUsedAt(Date lastUsedAt) {\n this.lastUsedAt = lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null;\n }\n\n public String getUserDn() {\n return userDn;\n }\n\n public void setUserDn(String userDn) {\n this.userDn = userDn != null ? userDn : \"\";\n }\n\n public Date getAuthenticationTime() {\n return authenticationTime != null ? new Date(authenticationTime.getTime()) : null;\n }\n\n public void setAuthenticationTime(Date authenticationTime) {\n this.authenticationTime = authenticationTime != null ? new Date(authenticationTime.getTime()) : null;\n }\n\n public Boolean getPermissionGranted() {\n return permissionGranted;\n }\n\n public void setPermissionGranted(Boolean permissionGranted) {\n this.permissionGranted = permissionGranted;\n }\n\n public Map getSessionAttributes() {\n if (sessionAttributes == null) {\n sessionAttributes = new HashMap();\n }\n return sessionAttributes;\n }\n\n public void setSessionAttributes(Map sessionAttributes) {\n this.sessionAttributes = sessionAttributes;\n }\n\n public boolean isPersisted() {\n return persisted;\n }\n\n public void setPersisted(boolean persisted) {\n this.persisted = persisted;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n SimpleSessionState id1 = (SimpleSessionState) o;\n\n return !(id != null ? !id.equals(id1.id) : id1.id != null);\n }\n\n @Override\n public int hashCode() {\n return id != null ? id.hashCode() : 0;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(\"SessionState\");\n sb.append(\", dn='\").append(dn).append('\\'');\n sb.append(\", id='\").append(id).append('\\'');\n sb.append(\", isJwt=\").append(isJwt);\n sb.append(\", lastUsedAt=\").append(lastUsedAt);\n sb.append(\", userDn='\").append(userDn).append('\\'');\n sb.append(\", authenticationTime=\").append(authenticationTime);\n sb.append(\", permissionGranted=\").append(permissionGranted);\n sb.append(\", sessionAttributes=\").append(sessionAttributes);\n sb.append(\", persisted=\").append(persisted);\n sb.append('}');\n return sb.toString();\n }\n\n}\n"},"new_file":{"kind":"string","value":"oxLdapSample/src/main/java/org/gluu/ldap/model/SimpleSessionState.java"},"old_contents":{"kind":"string","value":"/*\n * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.\n *\n * Copyright (c) 2014, Gluu\n */\n\npackage org.gluu.ldap.model;\n\nimport java.io.Serializable;\nimport java.util.Date;\nimport java.util.Map;\n\nimport javax.persistence.Transient;\n\nimport org.apache.commons.collections.map.HashedMap;\nimport org.gluu.site.ldap.persistence.annotation.LdapAttribute;\nimport org.gluu.site.ldap.persistence.annotation.LdapDN;\nimport org.gluu.site.ldap.persistence.annotation.LdapEntry;\nimport org.gluu.site.ldap.persistence.annotation.LdapJsonObject;\nimport org.gluu.site.ldap.persistence.annotation.LdapObjectClass;\n\n/**\n * @author Yuriy Zabrovarnyy\n * @author Javier Rojas Blum\n * @version December 15, 2015\n */\n@LdapEntry\n@LdapObjectClass(values = { \"top\", \"oxAuthSessionId\" })\npublic class SimpleSessionState implements Serializable {\n\n private static final long serialVersionUID = -237476411915686378L;\n\n @LdapDN\n private String dn;\n\n @LdapAttribute(name = \"uniqueIdentifier\")\n private String id;\n\n @LdapAttribute(name = \"oxLastAccessTime\")\n private Date lastUsedAt;\n\n @LdapAttribute(name = \"oxAuthUserDN\")\n private String userDn;\n\n @LdapAttribute(name = \"oxAuthAuthenticationTime\")\n private Date authenticationTime;\n\n @LdapAttribute(name = \"oxAuthSessionState\")\n private Boolean permissionGranted;\n\n @LdapAttribute(name = \"oxAsJwt\")\n private Boolean isJwt = false;\n\n @LdapAttribute(name = \"oxJwt\")\n private String jwt;\n\n @LdapJsonObject\n @LdapAttribute(name = \"oxAuthSessionAttribute\")\n private Map sessionAttributes;\n\n @Transient\n private transient boolean persisted;\n\n public String getDn() {\n return dn;\n }\n\n public void setDn(String dn) {\n this.dn = dn;\n }\n\n public String getJwt() {\n return jwt;\n }\n\n public void setJwt(String jwt) {\n this.jwt = jwt;\n }\n\n public Boolean getIsJwt() {\n return isJwt;\n }\n\n public void setIsJwt(Boolean isJwt) {\n this.isJwt = isJwt;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public Date getLastUsedAt() {\n return lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null;\n }\n\n public void setLastUsedAt(Date lastUsedAt) {\n this.lastUsedAt = lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null;\n }\n\n public String getUserDn() {\n return userDn;\n }\n\n public void setUserDn(String userDn) {\n this.userDn = userDn != null ? userDn : \"\";\n }\n\n public Date getAuthenticationTime() {\n return authenticationTime != null ? new Date(authenticationTime.getTime()) : null;\n }\n\n public void setAuthenticationTime(Date authenticationTime) {\n this.authenticationTime = authenticationTime != null ? new Date(authenticationTime.getTime()) : null;\n }\n\n public Boolean getPermissionGranted() {\n return permissionGranted;\n }\n\n public void setPermissionGranted(Boolean permissionGranted) {\n this.permissionGranted = permissionGranted;\n }\n\n public Map getSessionAttributes() {\n if (sessionAttributes == null) {\n sessionAttributes = new HashedMap();\n }\n return sessionAttributes;\n }\n\n public void setSessionAttributes(Map sessionAttributes) {\n this.sessionAttributes = sessionAttributes;\n }\n\n public boolean isPersisted() {\n return persisted;\n }\n\n public void setPersisted(boolean persisted) {\n this.persisted = persisted;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n SimpleSessionState id1 = (SimpleSessionState) o;\n\n return !(id != null ? !id.equals(id1.id) : id1.id != null);\n }\n\n @Override\n public int hashCode() {\n return id != null ? id.hashCode() : 0;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(\"SessionState\");\n sb.append(\", dn='\").append(dn).append('\\'');\n sb.append(\", id='\").append(id).append('\\'');\n sb.append(\", isJwt=\").append(isJwt);\n sb.append(\", lastUsedAt=\").append(lastUsedAt);\n sb.append(\", userDn='\").append(userDn).append('\\'');\n sb.append(\", authenticationTime=\").append(authenticationTime);\n sb.append(\", permissionGranted=\").append(permissionGranted);\n sb.append(\", sessionAttributes=\").append(sessionAttributes);\n sb.append(\", persisted=\").append(persisted);\n sb.append('}');\n return sb.toString();\n }\n\n}\n"},"message":{"kind":"string","value":"Fix Map type"},"old_file":{"kind":"string","value":"oxLdapSample/src/main/java/org/gluu/ldap/model/SimpleSessionState.java"},"subject":{"kind":"string","value":"Fix Map type"}}},{"rowIdx":1275,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"df5744bcd336c2d6b99fccd3bd21142781fc0d0b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable"},"new_contents":{"kind":"string","value":"\npackage org.broadinstitute.sting.gatk.walkers.indels;\n\nimport org.broadinstitute.sting.gatk.refdata.*;\nimport org.broadinstitute.sting.gatk.contexts.AlignmentContext;\nimport org.broadinstitute.sting.gatk.contexts.ReferenceContext;\nimport org.broadinstitute.sting.utils.*;\nimport org.broadinstitute.sting.gatk.walkers.*;\nimport org.broadinstitute.sting.utils.cmdLine.Argument;\n\n@WalkerName(\"SNPClusters\")\n@Requires(value={DataSource.REFERENCE},referenceMetaData={@RMD(name=\"snps\",type=AllelicVariant.class)})\npublic class SNPClusterWalker extends RefWalker {\n @Argument(fullName=\"windowSize\", shortName=\"window\", doc=\"window size for calculating clusters\", required=false)\n int windowSize = 10;\n\n public void initialize() {\n if ( windowSize < 1)\n throw new RuntimeException(\"Window Size must be a positive integer\");\n }\n\n public GenomeLoc map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {\n AllelicVariant snp = (AllelicVariant)tracker.lookup(\"snps\", null);\n return (snp != null && snp.isSNP()) ? context.getLocation() : null;\n }\n\n public void onTraversalDone(GenomeLoc sum) {\n if ( sum != null && sum.getStart() != sum.getStop() )\n out.println(sum);\n }\n\n public GenomeLoc reduceInit() {\n return null;\n }\n\n public GenomeLoc reduce(GenomeLoc value, GenomeLoc sum) {\n // ignore non-SNP variants\n if ( value == null )\n return sum;\n\n // if we have no previous SNPs start with the new location\n if ( sum == null )\n return value;\n\n // if we hit a new contig, emit and start with the new location\n if ( sum.getContigIndex() != value.getContigIndex() ) {\n if ( sum.getStart() != sum.getStop() )\n out.println(sum);\n return value;\n }\n\n // if the last SNP location was within a window, merge them\n if ( value.getStart() - sum.getStop() <= windowSize ) {\n sum = GenomeLocParser.setStop(sum,value.getStart()); \n return sum;\n }\n\n // otherwise, emit and start with the new location\n if ( sum.getStart() != sum.getStop() )\n out.println(sum);\n return value;\n }\n}"},"new_file":{"kind":"string","value":"java/src/org/broadinstitute/sting/gatk/walkers/indels/SNPClusterWalker.java"},"old_contents":{"kind":"string","value":"\npackage org.broadinstitute.sting.gatk.walkers.indels;\n\nimport org.broadinstitute.sting.gatk.refdata.*;\nimport org.broadinstitute.sting.gatk.contexts.AlignmentContext;\nimport org.broadinstitute.sting.gatk.contexts.ReferenceContext;\nimport org.broadinstitute.sting.utils.*;\nimport org.broadinstitute.sting.gatk.walkers.*;\nimport org.broadinstitute.sting.utils.cmdLine.Argument;\n\n@WalkerName(\"SNPClusters\")\n@By(DataSource.REFERENCE)\n@Requires(DataSource.REFERENCE)\n@Allows(DataSource.REFERENCE)\npublic class SNPClusterWalker extends RefWalker {\n @Argument(fullName=\"windowSize\", shortName=\"window\", doc=\"window size for calculating clusters\", required=false)\n int windowSize = 10;\n\n public void initialize() {\n if ( windowSize < 1)\n throw new RuntimeException(\"Window Size must be a positive integer\");\n }\n\n public GenomeLoc map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {\n AllelicVariant eval = (AllelicVariant)tracker.lookup(\"eval\", null);\n if ( eval instanceof SNPCallFromGenotypes )\n return context.getLocation();\n return null;\n }\n\n public void onTraversalDone(GenomeLoc sum) {\n if ( sum != null && sum.getStart() != sum.getStop() )\n out.println(sum);\n }\n\n public GenomeLoc reduceInit() {\n return null;\n }\n\n public GenomeLoc reduce(GenomeLoc value, GenomeLoc sum) {\n // ignore non-SNP variants\n if ( value == null )\n return sum;\n\n // if we have no previous SNPs start with the new location\n if ( sum == null )\n return value;\n\n // if we hit a new contig, emit and start with the new location\n if ( sum.getContigIndex() != value.getContigIndex() ) {\n if ( sum.getStart() != sum.getStop() )\n out.println(sum);\n return value;\n }\n\n // if the last SNP location was within a window, merge them\n if ( value.getStart() - sum.getStop() <= windowSize ) {\n sum = GenomeLocParser.setStop(sum,value.getStart()); \n return sum;\n }\n\n // otherwise, emit and start with the new location\n if ( sum.getStart() != sum.getStop() )\n out.println(sum);\n return value;\n }\n}"},"message":{"kind":"string","value":"update this walker so any variants can be passed in\n\n\ngit-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@1426 348d0f76-0448-11de-a6fe-93d51630548a\n"},"old_file":{"kind":"string","value":"java/src/org/broadinstitute/sting/gatk/walkers/indels/SNPClusterWalker.java"},"subject":{"kind":"string","value":"update this walker so any variants can be passed in"}}},{"rowIdx":1276,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"epl-1.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8d6c5ddba550aa81914eeb63b2a2ca54b75c1a77"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"minecrafter/SuperbVote,minecrafter/SuperbVote"},"new_contents":{"kind":"string","value":"package io.minimum.minecraft.superbvote.signboard;\n\nimport io.minimum.minecraft.superbvote.SuperbVote;\nimport io.minimum.minecraft.superbvote.configuration.message.MessageContext;\nimport io.minimum.minecraft.superbvote.configuration.message.PlainStringMessage;\nimport io.minimum.minecraft.superbvote.util.PlayerVotes;\nimport lombok.RequiredArgsConstructor;\nimport org.bukkit.Bukkit;\nimport org.bukkit.Material;\nimport org.bukkit.SkullType;\nimport org.bukkit.block.Block;\nimport org.bukkit.block.BlockFace;\nimport org.bukkit.block.Sign;\nimport org.bukkit.block.Skull;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.UUID;\n\n@RequiredArgsConstructor\npublic class TopPlayerSignUpdater implements Runnable {\n private final List toUpdate;\n private final List top;\n\n private static final UUID QUESTION_MARK_HEAD = UUID.fromString(\"606e2ff0-ed77-4842-9d6c-e1d3321c7838\");\n static final BlockFace[] FACES = {BlockFace.SELF, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST};\n\n public static Optional findSkullBlock(Block origin) {\n Block at = origin.getRelative(BlockFace.UP);\n for (BlockFace face : FACES) {\n Block b = at.getRelative(face);\n if (b.getType() == Material.PLAYER_HEAD || b.getType() == Material.PLAYER_WALL_HEAD)\n return Optional.of(b);\n }\n return Optional.empty();\n }\n\n @Override\n public void run() {\n for (TopPlayerSign sign : toUpdate) {\n Block block = sign.getSign().getBukkitLocation().getBlock();\n if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN) {\n Sign worldSign = (Sign) block.getState();\n // TODO: Formatting\n if (sign.getPosition() > top.size()) {\n for (int i = 0; i < 4; i++) {\n worldSign.setLine(i, \"???\");\n }\n } else {\n int lines = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().size();\n for (int i = 0; i < Math.min(4, lines); i++) {\n PlainStringMessage m = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().get(i);\n PlayerVotes pv = top.get(sign.getPosition() - 1);\n worldSign.setLine(i, m.getWithOfflinePlayer(null,\n new MessageContext(null, pv, null)).replace(\"%num%\", Integer.toString(sign.getPosition())));\n }\n for (int i = lines; i < 4; i++) {\n worldSign.setLine(i, \"\");\n }\n }\n worldSign.update();\n\n // If a head location is also present, set the location for that.\n Optional headBlock = findSkullBlock(sign.getSign().getBukkitLocation().getBlock());\n if (headBlock.isPresent()) {\n Block head = headBlock.get();\n Skull skull = (Skull) head.getState();\n skull.setOwningPlayer(Bukkit.getOfflinePlayer(sign.getPosition() > top.size() ? QUESTION_MARK_HEAD :\n top.get(sign.getPosition() - 1).getUuid()));\n skull.update();\n }\n }\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/io/minimum/minecraft/superbvote/signboard/TopPlayerSignUpdater.java"},"old_contents":{"kind":"string","value":"package io.minimum.minecraft.superbvote.signboard;\n\nimport io.minimum.minecraft.superbvote.SuperbVote;\nimport io.minimum.minecraft.superbvote.configuration.message.MessageContext;\nimport io.minimum.minecraft.superbvote.configuration.message.PlainStringMessage;\nimport io.minimum.minecraft.superbvote.util.PlayerVotes;\nimport lombok.RequiredArgsConstructor;\nimport org.bukkit.Bukkit;\nimport org.bukkit.Material;\nimport org.bukkit.SkullType;\nimport org.bukkit.block.Block;\nimport org.bukkit.block.BlockFace;\nimport org.bukkit.block.Sign;\nimport org.bukkit.block.Skull;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.UUID;\n\n@RequiredArgsConstructor\npublic class TopPlayerSignUpdater implements Runnable {\n private final List toUpdate;\n private final List top;\n\n private static final UUID QUESTION_MARK_HEAD = UUID.fromString(\"606e2ff0-ed77-4842-9d6c-e1d3321c7838\");\n static final BlockFace[] FACES = {BlockFace.SELF, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST};\n\n public static Optional findSkullBlock(Block origin) {\n Block at = origin.getRelative(BlockFace.UP);\n for (BlockFace face : FACES) {\n Block b = at.getRelative(face);\n System.out.println(\"at \" + face + \" block is \" + b.getType());\n if (b.getType() == Material.PLAYER_HEAD || b.getType() == Material.PLAYER_WALL_HEAD)\n return Optional.of(b);\n }\n return Optional.empty();\n }\n\n @Override\n public void run() {\n for (TopPlayerSign sign : toUpdate) {\n Block block = sign.getSign().getBukkitLocation().getBlock();\n System.out.println(block.getType());\n if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN) {\n Sign worldSign = (Sign) block.getState();\n // TODO: Formatting\n if (sign.getPosition() > top.size()) {\n for (int i = 0; i < 4; i++) {\n worldSign.setLine(i, \"???\");\n }\n } else {\n int lines = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().size();\n for (int i = 0; i < Math.min(4, lines); i++) {\n PlainStringMessage m = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().get(i);\n PlayerVotes pv = top.get(sign.getPosition() - 1);\n worldSign.setLine(i, m.getWithOfflinePlayer(null,\n new MessageContext(null, pv, null)).replace(\"%num%\", Integer.toString(sign.getPosition())));\n }\n for (int i = lines; i < 4; i++) {\n worldSign.setLine(i, \"\");\n }\n }\n worldSign.update();\n\n // If a head location is also present, set the location for that.\n Optional headBlock = findSkullBlock(sign.getSign().getBukkitLocation().getBlock());\n if (headBlock.isPresent()) {\n Block head = headBlock.get();\n Skull skull = (Skull) head.getState();\n skull.setOwningPlayer(Bukkit.getOfflinePlayer(sign.getPosition() > top.size() ? QUESTION_MARK_HEAD :\n top.get(sign.getPosition() - 1).getUuid()));\n skull.update();\n }\n }\n }\n }\n}\n"},"message":{"kind":"string","value":"Remove debug artifacts.\n"},"old_file":{"kind":"string","value":"src/main/java/io/minimum/minecraft/superbvote/signboard/TopPlayerSignUpdater.java"},"subject":{"kind":"string","value":"Remove debug artifacts."}}},{"rowIdx":1277,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mpl-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"789981a9f35da05fa384c67aa56e300505ebaa7b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"crankycoder/MozStumbler,cascheberg/MozStumbler,priyankvex/MozStumbler,cascheberg/MozStumbler,crankycoder/MozStumbler,petercpg/MozStumbler,priyankvex/MozStumbler,petercpg/MozStumbler,cascheberg/MozStumbler,petercpg/MozStumbler,MozillaCZ/MozStumbler,MozillaCZ/MozStumbler,priyankvex/MozStumbler,crankycoder/MozStumbler,MozillaCZ/MozStumbler"},"new_contents":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\npackage org.mozilla.mozstumbler.client.navdrawer;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.CheckBox;\nimport android.widget.CompoundButton;\nimport android.widget.ImageButton;\nimport android.widget.TextView;\n\nimport com.ocpsoft.pretty.time.PrettyTime;\n\nimport org.mozilla.mozstumbler.R;\nimport org.mozilla.mozstumbler.client.ClientPrefs;\nimport org.mozilla.mozstumbler.client.DateTimeUtils;\nimport org.mozilla.mozstumbler.service.AppGlobals;\nimport org.mozilla.mozstumbler.service.Prefs;\nimport org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageContract;\nimport org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageManager;\nimport org.mozilla.mozstumbler.service.uploadthread.AsyncUploadParam;\nimport org.mozilla.mozstumbler.service.uploadthread.AsyncUploader;\n\nimport java.io.IOException;\nimport java.lang.ref.WeakReference;\nimport java.util.Date;\nimport java.util.Locale;\nimport java.util.Properties;\n\npublic class MetricsView {\n\n public interface IMapLayerToggleListener {\n public void setShowMLS(boolean isOn);\n }\n\n private static final String LOG_TAG = AppGlobals.LOG_PREFIX + MetricsView.class.getSimpleName();\n\n private final TextView\n mLastUpdateTimeView,\n mAllTimeObservationsSentView,\n mAllTimeCellsSentView,\n mAllTimeWifisSentView,\n mQueuedObservationsView,\n mQueuedCellsView,\n mQueuedWifisView,\n mThisSessionObservationsView;\n\n private final CheckBox mOnMapShowMLS;\n\n private WeakReference mMapLayerToggleListener = new WeakReference(null);\n\n private final Handler mHandler = new Handler(Looper.getMainLooper());\n private final long FREQ_UPDATE_UPLOADTIME = 10 * 1000;\n\n private ImageButton mUploadButton;\n private final View mView;\n private long mTotalBytesUploadedThisSession_lastDisplayed = -1;\n private long mLastUploadTime = 0;\n private final String mObservationAndSize = \"%1$d %2$s\";\n\n private boolean mHasQueuedObservations;\n\n private static int mThisSessionObservationsCount;\n\n public MetricsView(View view) {\n mView = view;\n\n mOnMapShowMLS = (CheckBox) mView.findViewById(R.id.checkBox_show_mls);\n mOnMapShowMLS.setVisibility(View.GONE);\n mOnMapShowMLS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n ClientPrefs.getInstance().setOnMapShowMLS(mOnMapShowMLS.isChecked());\n if (mMapLayerToggleListener.get() != null) {\n mMapLayerToggleListener.get().setShowMLS(mOnMapShowMLS.isChecked());\n }\n }\n });\n\n mLastUpdateTimeView = (TextView) mView.findViewById(R.id.last_upload_time_value);\n mAllTimeObservationsSentView = (TextView) mView.findViewById(R.id.observations_sent_value);\n mAllTimeCellsSentView = (TextView) mView.findViewById(R.id.cells_sent_value);\n mAllTimeWifisSentView = (TextView) mView.findViewById(R.id.wifis_sent_value);\n mQueuedObservationsView = (TextView) mView.findViewById(R.id.observations_queued_value);\n mQueuedCellsView = (TextView) mView.findViewById(R.id.cells_queued_value);\n mQueuedWifisView = (TextView) mView.findViewById(R.id.wifis_queued_value);\n mThisSessionObservationsView = (TextView) mView.findViewById(R.id.this_session_observations_value);\n\n mUploadButton = (ImageButton) mView.findViewById(R.id.upload_observations_button);\n mUploadButton.setEnabled(false);\n mUploadButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!mHasQueuedObservations) {\n return;\n }\n\n // @TODO: Emit a signal here to initiate an upload\n // and have it handled by MainApp\n AsyncUploader uploader = new AsyncUploader();\n AsyncUploadParam param = new AsyncUploadParam(false /* useWifiOnly */,\n Prefs.getInstance().getNickname(),\n Prefs.getInstance().getEmail());\n uploader.execute(param);\n\n setUploadButtonToSyncing(true);\n }\n });\n\n mHandler.postDelayed(mUpdateLastUploadedLabel, FREQ_UPDATE_UPLOADTIME);\n }\n\n public void setMapLayerToggleListener(IMapLayerToggleListener listener) {\n mMapLayerToggleListener = new WeakReference(listener);\n mOnMapShowMLS.setChecked(ClientPrefs.getInstance().getOnMapShowMLS());\n }\n\n\n private boolean buttonIsSyncIcon;\n private void updateUploadButtonEnabled() {\n if (buttonIsSyncIcon) {\n mUploadButton.setEnabled(false);\n } else {\n mUploadButton.setEnabled(mHasQueuedObservations);\n }\n }\n\n private void setUploadButtonToSyncing(boolean isSyncing) {\n if (isSyncing) {\n mUploadButton.setImageResource(android.R.drawable.ic_popup_sync);\n } else {\n mUploadButton.setImageResource(R.drawable.ic_action_upload);\n }\n\n buttonIsSyncIcon = isSyncing;\n updateUploadButtonEnabled();\n }\n\n public void setUploadState(boolean isUploadingObservations) {\n updateUiThread();\n }\n\n private void updateUiThread() {\n mHandler.post(new Runnable() {\n @Override\n public void run() {\n update();\n }\n });\n }\n\n public void update() {\n DataStorageManager dm = DataStorageManager.getInstance();\n if (dm == null) {\n return;\n }\n\n updateQueuedStats(dm);\n updateSentStats(dm);\n updateThisSessionStats();\n\n setUploadButtonToSyncing(AsyncUploader.isUploading.get());\n }\n\n public void onOpened() {\n if (ClientPrefs.getInstance().isOptionEnabledToShowMLSOnMap()) {\n mOnMapShowMLS.setVisibility(View.VISIBLE);\n } else {\n mOnMapShowMLS.setVisibility(View.GONE);\n }\n update();\n }\n\n private void updateThisSessionStats() {\n if (mThisSessionObservationsCount < 1) {\n mThisSessionObservationsView.setText(\"0\");\n return;\n }\n\n long bytesUploadedThisSession = AsyncUploader.sTotalBytesUploadedThisSession.get();\n String val = String.format(mObservationAndSize, mThisSessionObservationsCount, formatKb(bytesUploadedThisSession));\n mThisSessionObservationsView.setText(val);\n }\n\n String formatKb(long bytes) {\n float kb = bytes / 1000.0f;\n if (kb < 0.1) {\n return \"\"; // don't show 0.0 for size.\n }\n return \"(\" + (Math.round(kb * 10.0f) / 10.0f) + \" KB)\";\n }\n\n private final Runnable mUpdateLastUploadedLabel = new Runnable() {\n @Override\n public void run() {\n updateLastUploadedLabel();\n mHandler.postDelayed(mUpdateLastUploadedLabel, FREQ_UPDATE_UPLOADTIME);\n }\n };\n\n private void updateLastUploadedLabel() {\n String value = (String) mView.getContext().getText(R.string.metrics_observations_last_upload_time_never);\n if (mLastUploadTime > 0) {\n if (Locale.getDefault().getLanguage().equals(\"en\")) {\n value = new PrettyTime().format(new Date(mLastUploadTime));\n } else {\n value = DateTimeUtils.formatTimeForLocale(mLastUploadTime);\n }\n }\n mLastUpdateTimeView.setText(value);\n }\n\n private void updateSentStats(DataStorageManager dataStorageManager) {\n\n final long bytesUploadedThisSession = AsyncUploader.sTotalBytesUploadedThisSession.get();\n\n if (mTotalBytesUploadedThisSession_lastDisplayed == bytesUploadedThisSession) {\n // no need to update\n return;\n }\n mTotalBytesUploadedThisSession_lastDisplayed = bytesUploadedThisSession;\n\n try {\n Properties props = dataStorageManager.readSyncStats();\n String value;\n value = props.getProperty(DataStorageContract.Stats.KEY_CELLS_SENT, \"0\");\n mAllTimeCellsSentView.setText(String.valueOf(value));\n value = props.getProperty(DataStorageContract.Stats.KEY_WIFIS_SENT, \"0\");\n mAllTimeWifisSentView.setText(String.valueOf(value));\n value = props.getProperty(DataStorageContract.Stats.KEY_OBSERVATIONS_SENT, \"0\");\n String bytes = props.getProperty(DataStorageContract.Stats.KEY_BYTES_SENT, \"0\");\n value = String.format(mObservationAndSize, Integer.parseInt(value), formatKb(Long.parseLong(bytes)));\n mAllTimeObservationsSentView.setText(value);\n\n mLastUploadTime = Long.parseLong(props.getProperty(DataStorageContract.Stats.KEY_LAST_UPLOAD_TIME, \"0\"));\n updateLastUploadedLabel();\n } catch (IOException ex) {\n Log.e(LOG_TAG, \"Exception in updateSentStats()\", ex);\n }\n }\n\n private void updateQueuedStats(DataStorageManager dataStorageManager) {\n DataStorageManager.QueuedCounts q = dataStorageManager.getQueuedCounts();\n mQueuedCellsView.setText(String.valueOf(q.mCellCount));\n mQueuedWifisView.setText(String.valueOf(q.mWifiCount));\n\n String val = String.format(mObservationAndSize, q.mReportCount, formatKb(q.mBytes));\n mQueuedObservationsView.setText(val);\n\n mHasQueuedObservations = q.mReportCount > 0;\n updateUploadButtonEnabled();\n }\n\n public void setObservationCount(int count) {\n mThisSessionObservationsCount = count;\n updateThisSessionStats();\n }\n}\n"},"new_file":{"kind":"string","value":"android/src/main/java/org/mozilla/mozstumbler/client/navdrawer/MetricsView.java"},"old_contents":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\npackage org.mozilla.mozstumbler.client.navdrawer;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.CheckBox;\nimport android.widget.CompoundButton;\nimport android.widget.ImageButton;\nimport android.widget.TextView;\n\nimport com.ocpsoft.pretty.time.PrettyTime;\n\nimport org.mozilla.mozstumbler.R;\nimport org.mozilla.mozstumbler.client.ClientPrefs;\nimport org.mozilla.mozstumbler.client.DateTimeUtils;\nimport org.mozilla.mozstumbler.service.AppGlobals;\nimport org.mozilla.mozstumbler.service.Prefs;\nimport org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageContract;\nimport org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageManager;\nimport org.mozilla.mozstumbler.service.uploadthread.AsyncUploadParam;\nimport org.mozilla.mozstumbler.service.uploadthread.AsyncUploader;\n\nimport java.io.IOException;\nimport java.lang.ref.WeakReference;\nimport java.util.Date;\nimport java.util.Locale;\nimport java.util.Properties;\n\npublic class MetricsView {\n\n public interface IMapLayerToggleListener {\n public void setShowMLS(boolean isOn);\n }\n\n private static final String LOG_TAG = AppGlobals.LOG_PREFIX + MetricsView.class.getSimpleName();\n\n private final TextView\n mLastUpdateTimeView,\n mAllTimeObservationsSentView,\n mAllTimeCellsSentView,\n mAllTimeWifisSentView,\n mQueuedObservationsView,\n mQueuedCellsView,\n mQueuedWifisView,\n mThisSessionObservationsView;\n\n private final CheckBox mOnMapShowMLS;\n\n private WeakReference mMapLayerToggleListener = new WeakReference(null);\n\n private ImageButton mUploadButton;\n private final View mView;\n private long mTotalBytesUploaded_lastDisplayed = -1;\n private final String mObservationAndSize = \"%1$d %2$s\";\n\n private boolean mHasQueuedObservations;\n\n private static int mThisSessionObservationsCount;\n\n public MetricsView(View view) {\n mView = view;\n\n mOnMapShowMLS = (CheckBox) mView.findViewById(R.id.checkBox_show_mls);\n mOnMapShowMLS.setVisibility(View.GONE);\n mOnMapShowMLS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n ClientPrefs.getInstance().setOnMapShowMLS(mOnMapShowMLS.isChecked());\n if (mMapLayerToggleListener.get() != null) {\n mMapLayerToggleListener.get().setShowMLS(mOnMapShowMLS.isChecked());\n }\n }\n });\n\n mLastUpdateTimeView = (TextView) mView.findViewById(R.id.last_upload_time_value);\n mAllTimeObservationsSentView = (TextView) mView.findViewById(R.id.observations_sent_value);\n mAllTimeCellsSentView = (TextView) mView.findViewById(R.id.cells_sent_value);\n mAllTimeWifisSentView = (TextView) mView.findViewById(R.id.wifis_sent_value);\n mQueuedObservationsView = (TextView) mView.findViewById(R.id.observations_queued_value);\n mQueuedCellsView = (TextView) mView.findViewById(R.id.cells_queued_value);\n mQueuedWifisView = (TextView) mView.findViewById(R.id.wifis_queued_value);\n mThisSessionObservationsView = (TextView) mView.findViewById(R.id.this_session_observations_value);\n\n mUploadButton = (ImageButton) mView.findViewById(R.id.upload_observations_button);\n mUploadButton.setEnabled(false);\n mUploadButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!mHasQueuedObservations) {\n return;\n }\n \n // @TODO: Emit a signal here to initiate an upload\n // and have it handled by MainApp\n AsyncUploader uploader = new AsyncUploader();\n AsyncUploadParam param = new AsyncUploadParam(false /* useWifiOnly */,\n Prefs.getInstance().getNickname(),\n Prefs.getInstance().getEmail());\n uploader.execute(param);\n\n setUploadButtonToSyncing(true);\n }\n });\n }\n\n public void setMapLayerToggleListener(IMapLayerToggleListener listener) {\n mMapLayerToggleListener = new WeakReference(listener);\n mOnMapShowMLS.setChecked(ClientPrefs.getInstance().getOnMapShowMLS());\n }\n\n\n private boolean buttonIsSyncIcon;\n private void updateUploadButtonEnabled() {\n if (buttonIsSyncIcon) {\n mUploadButton.setEnabled(false);\n } else {\n mUploadButton.setEnabled(mHasQueuedObservations);\n }\n }\n\n private void setUploadButtonToSyncing(boolean isSyncing) {\n if (isSyncing) {\n mUploadButton.setImageResource(android.R.drawable.ic_popup_sync);\n } else {\n mUploadButton.setImageResource(R.drawable.ic_action_upload);\n }\n\n buttonIsSyncIcon = isSyncing;\n updateUploadButtonEnabled();\n }\n\n public void setUploadState(boolean isUploadingObservations) {\n updateUiThread();\n }\n\n private void updateUiThread() {\n Handler h = new Handler(Looper.getMainLooper());\n h.post(new Runnable() {\n @Override\n public void run() {\n update();\n }\n });\n }\n\n public void update() {\n DataStorageManager dm = DataStorageManager.getInstance();\n if (dm == null) {\n return;\n }\n\n updateQueuedStats(dm);\n updateSentStats(dm);\n updateThisSessionStats();\n\n setUploadButtonToSyncing(AsyncUploader.isUploading.get());\n }\n\n public void onOpened() {\n if (ClientPrefs.getInstance().isOptionEnabledToShowMLSOnMap()) {\n mOnMapShowMLS.setVisibility(View.VISIBLE);\n } else {\n mOnMapShowMLS.setVisibility(View.GONE);\n }\n update();\n }\n\n private void updateThisSessionStats() {\n if (mThisSessionObservationsCount < 1) {\n mThisSessionObservationsView.setText(\"0\");\n return;\n }\n\n long bytesUploadedThisSession = AsyncUploader.sTotalBytesUploadedThisSession.get();\n String val = String.format(mObservationAndSize, mThisSessionObservationsCount, formatKb(bytesUploadedThisSession));\n mThisSessionObservationsView.setText(val);\n }\n\n String formatKb(long bytes) {\n float kb = bytes / 1000.0f;\n if (kb < 0.1) {\n return \"\"; // don't show 0.0 for size.\n }\n return \"(\" + (Math.round(kb * 10.0f) / 10.0f) + \" KB)\";\n }\n\n private void updateSentStats(DataStorageManager dataStorageManager) {\n try {\n Properties props = dataStorageManager.readSyncStats();\n\n String value = (String) mView.getContext().getText(R.string.metrics_observations_last_upload_time_never);\n final long lastUploadTime = Long.parseLong(props.getProperty(DataStorageContract.Stats.KEY_LAST_UPLOAD_TIME, \"0\"));\n if (lastUploadTime > 0) {\n if (Locale.getDefault().getLanguage().equals(\"en\")) {\n value = new PrettyTime().format(new Date(lastUploadTime));\n } else {\n value = DateTimeUtils.formatTimeForLocale(lastUploadTime);\n }\n }\n mLastUpdateTimeView.setText(value);\n\n final long bytes = Long.parseLong(props.getProperty(DataStorageContract.Stats.KEY_BYTES_SENT, \"0\"));\n if (mTotalBytesUploaded_lastDisplayed != -1 &&\n mTotalBytesUploaded_lastDisplayed == bytes) {\n // no need to update\n return;\n }\n mTotalBytesUploaded_lastDisplayed = bytes;\n\n value = props.getProperty(DataStorageContract.Stats.KEY_CELLS_SENT, \"0\");\n mAllTimeCellsSentView.setText(String.valueOf(value));\n value = props.getProperty(DataStorageContract.Stats.KEY_WIFIS_SENT, \"0\");\n mAllTimeWifisSentView.setText(String.valueOf(value));\n value = props.getProperty(DataStorageContract.Stats.KEY_OBSERVATIONS_SENT, \"0\");\n value = String.format(mObservationAndSize, Integer.parseInt(value), formatKb(bytes));\n mAllTimeObservationsSentView.setText(value);\n } catch (IOException ex) {\n Log.e(LOG_TAG, \"Exception in updateSentStats()\", ex);\n }\n }\n\n private void updateQueuedStats(DataStorageManager dataStorageManager) {\n DataStorageManager.QueuedCounts q = dataStorageManager.getQueuedCounts();\n mQueuedCellsView.setText(String.valueOf(q.mCellCount));\n mQueuedWifisView.setText(String.valueOf(q.mWifiCount));\n\n String val = String.format(mObservationAndSize, q.mReportCount, formatKb(q.mBytes));\n mQueuedObservationsView.setText(val);\n\n mHasQueuedObservations = q.mReportCount > 0;\n updateUploadButtonEnabled();\n }\n\n public void setObservationCount(int count) {\n mThisSessionObservationsCount = count;\n updateThisSessionStats();\n }\n}\n"},"message":{"kind":"string","value":"periodically update metrics last upload time\n"},"old_file":{"kind":"string","value":"android/src/main/java/org/mozilla/mozstumbler/client/navdrawer/MetricsView.java"},"subject":{"kind":"string","value":"periodically update metrics last upload time"}}},{"rowIdx":1278,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9f05d97e93e479f1329efd871ced90566b24c6c5"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jspacco/CloudCoder,x77686d/CloudCoder,jspacco/CloudCoder2,daveho/CloudCoder,daveho/CloudCoder,cloudcoderdotorg/CloudCoder,cloudcoderdotorg/CloudCoder,vjpudelski/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder2,cloudcoderdotorg/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,cloudcoderdotorg/CloudCoder,vjpudelski/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder,cloudcoderdotorg/CloudCoder,jspacco/CloudCoder2,wicky-info/CloudCoder,csirkeee/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder,csirkeee/CloudCoder,wicky-info/CloudCoder,cloudcoderdotorg/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder2,vjpudelski/CloudCoder,vjpudelski/CloudCoder,vjpudelski/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder2,jspacco/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,csirkeee/CloudCoder,jspacco/CloudCoder2,csirkeee/CloudCoder,wicky-info/CloudCoder,wicky-info/CloudCoder,daveho/CloudCoder,vjpudelski/CloudCoder,x77686d/CloudCoder,x77686d/CloudCoder,jspacco/CloudCoder2,wicky-info/CloudCoder,x77686d/CloudCoder,wicky-info/CloudCoder,vjpudelski/CloudCoder,wicky-info/CloudCoder,cloudcoderdotorg/CloudCoder,daveho/CloudCoder"},"new_contents":{"kind":"string","value":"// CloudCoder - a web-based pedagogical programming environment\n// Copyright (C) 2011-2012, Jaime Spacco \n// Copyright (C) 2011-2012, David H. Hovemeyer \n// Copyright (C) 2013, York College of Pennsylvania\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see .\n\npackage org.cloudcoder.builder2.csandbox;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.StringWriter;\nimport java.util.Properties;\n\nimport org.cloudcoder.builder2.ccompiler.Compiler;\nimport org.cloudcoder.builder2.util.DeleteDirectoryRecursively;\nimport org.cloudcoder.builder2.util.FileUtil;\nimport org.cloudcoder.builder2.util.SingletonHolder;\nimport org.cloudcoder.daemon.IOUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Compile the EasySandbox shared library.\n * This is a singleton object that can be used by many threads.\n * Some code in the overall process should guarantee that\n * the {@link #cleanup()} method is called on the singleton instance\n * before the process exits.\n * \n * @author David Hovemeyer\n */\npublic class EasySandboxSharedLibrary {\n\tprivate static Logger logger = LoggerFactory.getLogger(EasySandboxSharedLibrary.class);\n\t\n\tprivate static SingletonHolder holder = new SingletonHolder() {\n\t\t@Override\n\t\tprotected EasySandboxSharedLibrary onCreate(Properties arg) {\n\t\t\treturn new EasySandboxSharedLibrary(arg);\n\t\t}\n\t};\n\t\n\t/**\n\t * Get the singleton instance.\n\t * \n\t * @return the singleton instance\n\t */\n\tpublic static EasySandboxSharedLibrary getInstance(Properties config) {\n\t\treturn holder.get(config);\n\t}\n\t\n\t/**\n\t * Check whether or not the singleton instance was created.\n\t * \n\t * @return true if the singleton instance was created, false if not\n\t */\n\tpublic static boolean isCreated() {\n\t\treturn holder.isCreated();\n\t}\n\t\n\t// Fields\n\tprivate File tempDir;\n\tprivate String sharedLibraryPath;\n\t\n\t/**\n\t * Constructor.\n\t */\n\tprivate EasySandboxSharedLibrary(Properties config) {\n\t\ttry {\n\t\t\tbuild(config);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Could not build EasySandbox shared library\", e);\n\t\t}\n\t}\n\t\n\tprivate void build(Properties config) throws IOException {\n\t\t// Get source code for the EasySandbox source files\n\t\tString source1 = sourceResourceToString(\"EasySandbox.c\");\n\t\tString source2 = sourceResourceToString(\"malloc.c\");\n\t\t\n\t\tthis.tempDir = FileUtil.makeTempDir(config);\n\t\t\n\t\t// Compile the code and link it into a shared library\n\t\tCompiler compiler = new Compiler(tempDir, \"EasySandbox.so\");\n\t\tcompiler.addModule(\"EasySandbox.c\", source1);\n\t\tcompiler.addModule(\"malloc.c\", source2);\n\t\tcompiler.addFlag(\"-fPIC\");\n\t\tcompiler.addFlag(\"-shared\");\n\t\tcompiler.addEndFlag(\"-ldl\");\n\t\t\n\t\tif (!compiler.compile()) {\n\t\t\tfor (String err : compiler.getCompilerOutput()) {\n\t\t\t\tlogger.error(\"Compile error: {}\", err);\n\t\t\t}\n\t\t\tthrow new IOException(\"Error compiling EasySandbox shared library\");\n\t\t}\n\t\t\n\t\tsharedLibraryPath = tempDir.getAbsolutePath() + \"/EasySandbox.so\";\n\t}\n\t\n\t/**\n\t * Get the path of the shared library.\n\t * \n\t * @return the path of the shared library, or null if the shared library is not available\n\t */\n\tpublic String getSharedLibraryPath() {\n\t\treturn sharedLibraryPath;\n\t}\n\t\n\t/**\n\t * Clean up.\n\t */\n\tpublic void cleanup() {\n\t\tif (tempDir != null) {\n\t\t\tnew DeleteDirectoryRecursively(tempDir).delete();\n\t\t}\n\t}\n\t\n\tprivate String sourceResourceToString(String sourceFileName) throws IOException {\n\t\tInputStream in = null;\n\t\ttry {\n\t\t\tin = this.getClass().getClassLoader().getResourceAsStream(\"org/cloudcoder/builder2/csandbox/res/\" + sourceFileName);\n\t\t\tInputStreamReader r = new InputStreamReader(in);\n\t\t\tStringWriter sw = new StringWriter();\n\t\t\tIOUtil.copy(r, sw);\n\t\t\treturn sw.toString();\n\t\t} finally {\n\t\t\tIOUtil.closeQuietly(in);\n\t\t}\n\t}\n\t\n}\n"},"new_file":{"kind":"string","value":"CloudCoderBuilder2/src/org/cloudcoder/builder2/csandbox/EasySandboxSharedLibrary.java"},"old_contents":{"kind":"string","value":"// CloudCoder - a web-based pedagogical programming environment\n// Copyright (C) 2011-2012, Jaime Spacco \n// Copyright (C) 2011-2012, David H. Hovemeyer \n// Copyright (C) 2013, York College of Pennsylvania\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see .\n\npackage org.cloudcoder.builder2.csandbox;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.StringWriter;\nimport java.util.Properties;\n\nimport jline.internal.Log;\n\nimport org.cloudcoder.builder2.ccompiler.Compiler;\nimport org.cloudcoder.builder2.util.DeleteDirectoryRecursively;\nimport org.cloudcoder.builder2.util.FileUtil;\nimport org.cloudcoder.builder2.util.SingletonHolder;\nimport org.cloudcoder.daemon.IOUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Compile the EasySandbox shared library.\n * This is a singleton object that can be used by many threads.\n * Some code in the overall process should guarantee that\n * the {@link #cleanup()} method is called on the singleton instance\n * before the process exits.\n * \n * @author David Hovemeyer\n */\npublic class EasySandboxSharedLibrary {\n\tprivate static Logger logger = LoggerFactory.getLogger(EasySandboxSharedLibrary.class);\n\t\n\tprivate static SingletonHolder holder = new SingletonHolder() {\n\t\t@Override\n\t\tprotected EasySandboxSharedLibrary onCreate(Properties arg) {\n\t\t\treturn new EasySandboxSharedLibrary(arg);\n\t\t}\n\t};\n\t\n\t/**\n\t * Get the singleton instance.\n\t * \n\t * @return the singleton instance\n\t */\n\tpublic static EasySandboxSharedLibrary getInstance(Properties config) {\n\t\treturn holder.get(config);\n\t}\n\t\n\t/**\n\t * Check whether or not the singleton instance was created.\n\t * \n\t * @return true if the singleton instance was created, false if not\n\t */\n\tpublic static boolean isCreated() {\n\t\treturn holder.isCreated();\n\t}\n\t\n\t// Fields\n\tprivate File tempDir;\n\tprivate String sharedLibraryPath;\n\t\n\t/**\n\t * Constructor.\n\t */\n\tprivate EasySandboxSharedLibrary(Properties config) {\n\t\ttry {\n\t\t\tbuild(config);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Could not build EasySandbox shared library\", e);\n\t\t}\n\t}\n\t\n\tprivate void build(Properties config) throws IOException {\n\t\t// Get source code for the EasySandbox source files\n\t\tString source1 = sourceResourceToString(\"EasySandbox.c\");\n\t\tString source2 = sourceResourceToString(\"malloc.c\");\n\t\t\n\t\tthis.tempDir = FileUtil.makeTempDir(config);\n\t\t\n\t\t// Compile the code and link it into a shared library\n\t\tCompiler compiler = new Compiler(tempDir, \"EasySandbox.so\");\n\t\tcompiler.addModule(\"EasySandbox.c\", source1);\n\t\tcompiler.addModule(\"malloc.c\", source2);\n\t\tcompiler.addFlag(\"-fPIC\");\n\t\tcompiler.addFlag(\"-shared\");\n\t\tcompiler.addEndFlag(\"-ldl\");\n\t\t\n\t\tif (!compiler.compile()) {\n\t\t\tfor (String err : compiler.getCompilerOutput()) {\n\t\t\t\tLog.error(\"Compile error: {}\", err);\n\t\t\t}\n\t\t\tthrow new IOException(\"Error compiling EasySandbox shared library\");\n\t\t}\n\t\t\n\t\tsharedLibraryPath = tempDir.getAbsolutePath() + \"/EasySandbox.so\";\n\t}\n\t\n\t/**\n\t * Get the path of the shared library.\n\t * \n\t * @return the path of the shared library, or null if the shared library is not available\n\t */\n\tpublic String getSharedLibraryPath() {\n\t\treturn sharedLibraryPath;\n\t}\n\t\n\t/**\n\t * Clean up.\n\t */\n\tpublic void cleanup() {\n\t\tif (tempDir != null) {\n\t\t\tnew DeleteDirectoryRecursively(tempDir).delete();\n\t\t}\n\t}\n\t\n\tprivate String sourceResourceToString(String sourceFileName) throws IOException {\n\t\tInputStream in = null;\n\t\ttry {\n\t\t\tin = this.getClass().getClassLoader().getResourceAsStream(\"org/cloudcoder/builder2/csandbox/res/\" + sourceFileName);\n\t\t\tInputStreamReader r = new InputStreamReader(in);\n\t\t\tStringWriter sw = new StringWriter();\n\t\t\tIOUtil.copy(r, sw);\n\t\t\treturn sw.toString();\n\t\t} finally {\n\t\t\tIOUtil.closeQuietly(in);\n\t\t}\n\t}\n\t\n}\n"},"message":{"kind":"string","value":"fixed logging of compile errors"},"old_file":{"kind":"string","value":"CloudCoderBuilder2/src/org/cloudcoder/builder2/csandbox/EasySandboxSharedLibrary.java"},"subject":{"kind":"string","value":"fixed logging of compile errors"}}},{"rowIdx":1279,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"4ad151a17a9169870f8420ec8cff9a54a9da05a4"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"skylow95/libreplan,LibrePlan/libreplan,skylow95/libreplan,dgray16/libreplan,skylow95/libreplan,dgray16/libreplan,dgray16/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,poum/libreplan,poum/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,dgray16/libreplan,Marine-22/libre,PaulLuchyn/libreplan,Marine-22/libre,poum/libreplan,poum/libreplan,LibrePlan/libreplan,Marine-22/libre,dgray16/libreplan,Marine-22/libre,PaulLuchyn/libreplan,poum/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,poum/libreplan,skylow95/libreplan,skylow95/libreplan,dgray16/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,Marine-22/libre,dgray16/libreplan,PaulLuchyn/libreplan,Marine-22/libre"},"new_contents":{"kind":"string","value":"/*\n * This file is part of LibrePlan\n *\n * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e\n * Desenvolvemento Tecnolóxico de Galicia\n * Copyright (C) 2010-2011 Igalia, S.L.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n */\n\npackage org.libreplan.business.workreports.daos;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.hibernate.Criteria;\nimport org.hibernate.Query;\nimport org.hibernate.criterion.Restrictions;\nimport org.libreplan.business.common.daos.IntegrationEntityDAO;\nimport org.libreplan.business.orders.entities.OrderElement;\nimport org.libreplan.business.reports.dtos.WorkReportLineDTO;\nimport org.libreplan.business.resources.entities.Resource;\nimport org.libreplan.business.workreports.entities.WorkReportLine;\nimport org.springframework.beans.factory.config.BeanDefinition;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.stereotype.Repository;\nimport org.springframework.transaction.annotation.Transactional;\n\n/**\n * Dao for {@link WorkReportLineDAO}\n *\n * @author Diego Pino García \n * @author Susana Montes Pedreira \n */\n\n@Repository\n@Scope(BeanDefinition.SCOPE_SINGLETON)\npublic class WorkReportLineDAO extends IntegrationEntityDAO\n implements IWorkReportLineDAO {\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public List findByOrderElement(OrderElement orderElement){\n Criteria c = getSession().createCriteria(WorkReportLine.class).createCriteria(\"orderElement\");\n c.add(Restrictions.idEq(orderElement.getId()));\n return (List) c.list();\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public List findByOrderElementGroupByResourceAndHourTypeAndDate(\n OrderElement orderElement) {\n\n String strQuery = \"SELECT new org.libreplan.business.reports.dtos.WorkReportLineDTO(wrl.resource, wrl.typeOfWorkHours, wrl.date, SUM(wrl.effort)) \"\n + \"FROM WorkReportLine wrl \"\n + \"LEFT OUTER JOIN wrl.orderElement orderElement \"\n + \"WHERE orderElement = :orderElement \"\n + \"GROUP BY wrl.resource, wrl.typeOfWorkHours, wrl.date \"\n + \"ORDER BY wrl.resource, wrl.typeOfWorkHours, wrl.date\";\n\n // Set parameters\n Query query = getSession().createQuery(strQuery);\n query.setParameter(\"orderElement\", orderElement);\n\n return (List) query.list();\n }\n\n @Override\n public List findByOrderElementAndChildren(\n OrderElement orderElement) {\n if (orderElement.isNewObject()) {\n return new ArrayList();\n }\n return findByOrderElementAndChildren(orderElement, false);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n @Transactional(readOnly=true)\n public List findByOrderElementAndChildren(OrderElement orderElement, boolean sortByDate) {\n // Create collection with current orderElement and all its children\n Collection orderElements = orderElement.getAllChildren();\n orderElements.add(orderElement);\n\n // Prepare criteria\n final Criteria criteria = getSession().createCriteria(WorkReportLine.class);\n criteria.add(Restrictions.in(\"orderElement\", orderElements));\n if (sortByDate) {\n criteria.addOrder(org.hibernate.criterion.Order.asc(\"date\"));\n }\n return criteria.list();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public List findFilteredByDate(Date start, Date end) {\n Criteria criteria = getSession().createCriteria(WorkReportLine.class);\n if(start != null) {\n criteria.add(Restrictions.ge(\"date\", start));\n }\n if(end != null) {\n criteria.add(Restrictions.le(\"date\", end));\n }\n return criteria.list();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public List findByResources(List resourcesList) {\n if (resourcesList.isEmpty()) {\n return Collections.emptyList();\n }\n return getSession().createCriteria(WorkReportLine.class).add(\n Restrictions.in(\"resource\", resourcesList)).list();\n }\n\n}\n"},"new_file":{"kind":"string","value":"libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportLineDAO.java"},"old_contents":{"kind":"string","value":"/*\n * This file is part of LibrePlan\n *\n * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e\n * Desenvolvemento Tecnolóxico de Galicia\n * Copyright (C) 2010-2011 Igalia, S.L.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n */\n\npackage org.libreplan.business.workreports.daos;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.hibernate.Criteria;\nimport org.hibernate.Query;\nimport org.hibernate.criterion.Restrictions;\nimport org.libreplan.business.common.daos.IntegrationEntityDAO;\nimport org.libreplan.business.orders.entities.OrderElement;\nimport org.libreplan.business.reports.dtos.WorkReportLineDTO;\nimport org.libreplan.business.resources.entities.Resource;\nimport org.libreplan.business.workreports.entities.WorkReportLine;\nimport org.springframework.beans.factory.config.BeanDefinition;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.stereotype.Repository;\n\n/**\n * Dao for {@link WorkReportLineDAO}\n *\n * @author Diego Pino García \n * @author Susana Montes Pedreira \n */\n\n@Repository\n@Scope(BeanDefinition.SCOPE_SINGLETON)\npublic class WorkReportLineDAO extends IntegrationEntityDAO\n implements IWorkReportLineDAO {\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public List findByOrderElement(OrderElement orderElement){\n Criteria c = getSession().createCriteria(WorkReportLine.class).createCriteria(\"orderElement\");\n c.add(Restrictions.idEq(orderElement.getId()));\n return (List) c.list();\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public List findByOrderElementGroupByResourceAndHourTypeAndDate(\n OrderElement orderElement) {\n\n String strQuery = \"SELECT new org.libreplan.business.reports.dtos.WorkReportLineDTO(wrl.resource, wrl.typeOfWorkHours, wrl.date, SUM(wrl.effort)) \"\n + \"FROM WorkReportLine wrl \"\n + \"LEFT OUTER JOIN wrl.orderElement orderElement \"\n + \"WHERE orderElement = :orderElement \"\n + \"GROUP BY wrl.resource, wrl.typeOfWorkHours, wrl.date \"\n + \"ORDER BY wrl.resource, wrl.typeOfWorkHours, wrl.date\";\n\n // Set parameters\n Query query = getSession().createQuery(strQuery);\n query.setParameter(\"orderElement\", orderElement);\n\n return (List) query.list();\n }\n\n @Override\n public List findByOrderElementAndChildren(\n OrderElement orderElement) {\n if (orderElement.isNewObject()) {\n return new ArrayList();\n }\n return findByOrderElementAndChildren(orderElement, false);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public List findByOrderElementAndChildren(OrderElement orderElement, boolean sortByDate) {\n // Create collection with current orderElement and all its children\n Collection orderElements = orderElement.getAllChildren();\n orderElements.add(orderElement);\n\n // Prepare criteria\n final Criteria criteria = getSession().createCriteria(WorkReportLine.class);\n criteria.add(Restrictions.in(\"orderElement\", orderElements));\n if (sortByDate) {\n criteria.addOrder(org.hibernate.criterion.Order.asc(\"date\"));\n }\n return criteria.list();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public List findFilteredByDate(Date start, Date end) {\n Criteria criteria = getSession().createCriteria(WorkReportLine.class);\n if(start != null) {\n criteria.add(Restrictions.ge(\"date\", start));\n }\n if(end != null) {\n criteria.add(Restrictions.le(\"date\", end));\n }\n return criteria.list();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public List findByResources(List resourcesList) {\n if (resourcesList.isEmpty()) {\n return Collections.emptyList();\n }\n return getSession().createCriteria(WorkReportLine.class).add(\n Restrictions.in(\"resource\", resourcesList)).list();\n }\n\n}\n"},"message":{"kind":"string","value":"Set a method transactional.\n\nFEA: ItEr75S27PerProjectDashboard\n"},"old_file":{"kind":"string","value":"libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportLineDAO.java"},"subject":{"kind":"string","value":"Set a method transactional."}}},{"rowIdx":1280,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f465518593eb7aca8de023674a78ab8ace24be9a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"lespea/Java-CEF,cmcotton/Java-CEF"},"new_contents":{"kind":"string","value":"/**\n * Extension.java 2011-09-06\n *\n * Copyright 2011, Adam Lesperance\n *\n * This library is free software; you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation; either version 2.1 of the License, or (at your option)\n * any later version.\n *\n * This library is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n * details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n\n\npackage com.lespea.cef;\n\n//~--- non-JDK imports --------------------------------------------------------\n\nimport com.lespea.cef.utils.StringUtils;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n//~--- JDK imports ------------------------------------------------------------\n\nimport java.io.Serializable;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n\n//~--- classes ----------------------------------------------------------------\n\n/**\n * Object that holds the mapping of all the elements that are part of the CEF extension.\n *

\n * This object is immutable and once created no changes can be made!\n *\n * @version 1.0, 2011-09-06\n * @author Adam Lesperance\n */\npublic class Extension implements Serializable {\n\n /**\n * Logger object\n */\n private static final Logger LOG = LoggerFactory.getLogger( Extension.class );\n\n /** Field description */\n private static final long serialVersionUID = 1L;\n\n //~--- fields -------------------------------------------------------------\n\n /** Field description */\n private final String asString;\n\n /** Field description */\n private final Map fields;\n\n /** Field description */\n private final int hashCode;\n\n\n //~--- constructors -------------------------------------------------------\n\n /**\n * Create a new extension object using the provided map. All of the key/value pairs are checked\n * to ensure they are valid and the map is made read-only.\n *\n * @param extensionFields\n * the mapping of extension keys and their values\n * @throws InvalidExtensionKey\n * if one of the provided keys is invalid\n */\n public Extension( final Map extensionFields ) throws InvalidExtensionKey {\n\n // Use the # of pairs * 20 as an initial best-guess for the builder size\n final StringBuilder sb = new StringBuilder( extensionFields.size() * 20 );\n Boolean first = true;\n\n /*\n * Loop over all of the element pairs and add them to the string builder. Conveniently when\n * we escape the keys/values we also check to make sure they're valid and if they aren't an\n * exception will be thrown. So we not only ensure everything is okay at creation, but we\n * also pre-calculate the string variable so future calls are instant for the small price of\n * memory space.\n */\n for (final Entry entry : extensionFields.entrySet()) {\n if (first) {\n first = false;\n }\n else {\n sb.append( \" \" );\n }\n\n\n sb.append( StringUtils.escapeExtensionKey( entry.getKey() ) );\n sb.append( \"=\" );\n sb.append( StringUtils.escapeExtensionValue( entry.getValue() ) );\n }\n\n\n Extension.LOG.debug( \"The map was valid and turned into an unmodifiable collection\" );\n\n // Should be changeable but cast it anyway\n fields = Collections.unmodifiableMap( extensionFields );\n\n Extension.LOG.debug( \"The extension's string was calculated as {}\", sb.toString() );\n\n asString = sb.toString();\n hashCode = fields.hashCode();\n }\n\n\n //~--- methods ------------------------------------------------------------\n\n @Override\n public boolean equals( final Object obj ) {\n if (this == obj) {\n return true;\n }\n else if (obj == null) {\n return false;\n }\n else if (this.getClass() != obj.getClass()) {\n return false;\n }\n else if (hashCode != obj.hashCode()) {\n return false;\n }\n else if (!fields.equals( ((Extension) obj).getFields() )) {\n return false;\n }\n\n\n return true;\n }\n\n\n @Override\n public int hashCode() {\n return hashCode;\n }\n\n\n @Override\n public String toString() {\n return asString;\n }\n\n\n //~--- get methods --------------------------------------------------------\n\n /**\n * @return a copy of the fields present in the extension\n */\n public Map getFields() {\n return new HashMap( fields );\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/lespea/cef/Extension.java"},"old_contents":{"kind":"string","value":"/**\n * Extension.java 2011-09-06\n *\n * Copyright 2011, Adam Lesperance\n *\n * This library is free software; you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation; either version 2.1 of the License, or (at your option)\n * any later version.\n *\n * This library is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n * details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n\n\npackage com.lespea.cef;\n\n//~--- non-JDK imports --------------------------------------------------------\n\nimport com.lespea.cef.utils.StringUtils;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n//~--- JDK imports ------------------------------------------------------------\n\nimport java.io.Serializable;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n\n//~--- classes ----------------------------------------------------------------\n\n/**\n * Object that holds the mapping of all the elements that are part of the CEF extension.\n *

\n * This object is immutable and once created no changes can be made!\n *\n * @version 1.0, 2011-09-06\n * @author Adam Lesperance\n */\npublic class Extension implements Serializable {\n\n /**\n * Logger object\n */\n private static final Logger LOG = LoggerFactory.getLogger( Extension.class );\n\n /** Field description */\n private static final long serialVersionUID = 1L;\n\n //~--- fields -------------------------------------------------------------\n\n /** Field description */\n private final String asString;\n\n /** Field description */\n private final Map fields;\n\n\n //~--- constructors -------------------------------------------------------\n\n /**\n * Create a new extension object using the provided map. All of the key/value pairs are checked\n * to ensure they are valid and the map is made read-only.\n *\n * @param extensionFields\n * the mapping of extension keys and their values\n * @throws InvalidExtensionKey\n * if one of the provided keys is invalid\n */\n public Extension( final Map extensionFields ) throws InvalidExtensionKey {\n\n // Use the # of pairs * 20 as an initial best-guess for the builder size\n final StringBuilder sb = new StringBuilder( extensionFields.size() * 20 );\n Boolean first = true;\n\n /*\n * Loop over all of the element pairs and add them to the string builder. Conveniently when\n * we escape the keys/values we also check to make sure they're valid and if they aren't an\n * exception will be thrown. So we not only ensure everything is okay at creation, but we\n * also pre-calculate the string variable so future calls are instant for the small price of\n * memory space.\n */\n for (final Entry entry : extensionFields.entrySet()) {\n if (first) {\n first = false;\n }\n else {\n sb.append( \" \" );\n }\n\n\n sb.append( StringUtils.escapeExtensionKey( entry.getKey() ) );\n sb.append( \"=\" );\n sb.append( StringUtils.escapeExtensionValue( entry.getValue() ) );\n }\n\n\n Extension.LOG.debug( \"The map was valid and turned into an unmodifiable collection\" );\n\n // Should be changeable but cast it anyway\n fields = Collections.unmodifiableMap( extensionFields );\n\n Extension.LOG.debug( \"The extension's string was calculated as {}\", sb.toString() );\n\n asString = sb.toString();\n }\n\n\n //~--- methods ------------------------------------------------------------\n\n @Override\n public boolean equals( final Object obj ) {\n if (this == obj) {\n return true;\n }\n else if (obj == null) {\n return false;\n }\n else if (this.getClass() != obj.getClass()) {\n return false;\n }\n else if (!fields.equals( ((Extension) obj).getFields() )) {\n return false;\n }\n\n\n return true;\n }\n\n\n @Override\n public int hashCode() {\n return fields.hashCode();\n }\n\n\n @Override\n public String toString() {\n return asString;\n }\n\n\n //~--- get methods --------------------------------------------------------\n\n /**\n * @return a copy of the fields present in the extension\n */\n public Map getFields() {\n return new HashMap( fields );\n }\n}\n"},"message":{"kind":"string","value":"Precompute the hashcode as well and use it in equals to possibly save a\nlot of checks"},"old_file":{"kind":"string","value":"src/main/java/com/lespea/cef/Extension.java"},"subject":{"kind":"string","value":"Precompute the hashcode as well and use it in equals to possibly save a lot of checks"}}},{"rowIdx":1281,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"534e1190ecaa30d78a513829be8fc26b9f3d2a38"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"hal/core,hal/core,hal/core,hal/core,hal/core"},"new_contents":{"kind":"string","value":"package org.jboss.as.console.client.shared.subsys.jca;\n\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.user.client.ui.VerticalPanel;\nimport com.google.gwt.user.client.ui.Widget;\nimport org.jboss.as.console.client.Console;\nimport org.jboss.as.console.client.shared.help.FormHelpPanel;\nimport org.jboss.as.console.client.shared.subsys.Baseadress;\nimport org.jboss.as.console.client.shared.subsys.jca.model.ResourceAdapter;\nimport org.jboss.ballroom.client.widgets.forms.ComboBoxItem;\nimport org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer;\nimport org.jboss.ballroom.client.widgets.forms.Form;\nimport org.jboss.ballroom.client.widgets.forms.TextBoxItem;\nimport org.jboss.ballroom.client.widgets.forms.TextItem;\nimport org.jboss.ballroom.client.widgets.tools.ToolButton;\nimport org.jboss.ballroom.client.widgets.tools.ToolStrip;\nimport org.jboss.ballroom.client.widgets.window.Feedback;\nimport org.jboss.dmr.client.ModelNode;\n\n/**\n * @author Heiko Braun\n * @date 7/19/11\n */\npublic class AdapterDetails {\n\n private VerticalPanel layout;\n private Form form;\n private ToolButton editBtn;\n private ResourceAdapterPresenter presenter;\n\n public AdapterDetails(final ResourceAdapterPresenter presenter) {\n\n this.presenter = presenter;\n\n layout = new VerticalPanel();\n layout.setStyleName(\"fill-layout-width\");\n\n form = new Form(ResourceAdapter.class);\n form.setNumColumns(2);\n\n ToolStrip detailToolStrip = new ToolStrip();\n editBtn = new ToolButton(Console.CONSTANTS.common_label_edit());\n ClickHandler editHandler = new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n\n\n if(null == form.getEditedEntity())\n return;\n\n if(editBtn.getText().equals(Console.CONSTANTS.common_label_edit()))\n presenter.onEdit(form.getEditedEntity());\n else\n presenter.onSave(form.getEditedEntity().getName(), form.getChangedValues());\n }\n };\n editBtn.addClickHandler(editHandler);\n detailToolStrip.addToolButton(editBtn);\n\n\n ClickHandler clickHandler = new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n\n final ResourceAdapter ra = form.getEditedEntity();\n\n Feedback.confirm(\n \"Delete Resource Adapter\",\n \"Really delete Adapter '\" + ra.getName() + \"' ?\",\n new Feedback.ConfirmationHandler() {\n @Override\n public void onConfirmation(boolean isConfirmed) {\n if (isConfirmed) {\n presenter.onDelete(ra);\n }\n }\n });\n }\n };\n ToolButton deleteBtn = new ToolButton(Console.CONSTANTS.common_label_delete());\n deleteBtn.addClickHandler(clickHandler);\n detailToolStrip.addToolButton(deleteBtn);\n\n layout.add(detailToolStrip);\n\n // ----\n\n TextItem nameItem = new TextItem(\"name\", \"Name\");\n TextBoxItem poolItem = new TextBoxItem(\"poolName\", \"Pool\");\n TextBoxItem jndiItem = new TextBoxItem(\"jndiName\", \"JNDI\");\n TextItem archiveItem = new TextItem(\"archive\", \"Archive\");\n\n ComboBoxItem txItem = new ComboBoxItem(\"transactionSupport\", \"TX\");\n txItem.setDefaultToFirstOption(true);\n txItem.setValueMap(new String[]{\"NoTransaction\", \"LocalTransaction\", \"XATransaction\"});\n\n TextBoxItem classItem = new TextBoxItem(\"connectionClass\", \"Connection Class\");\n\n\n form.setFields(nameItem, jndiItem, poolItem, archiveItem);\n form.setFieldsInGroup(\"Advanced\", new DisclosureGroupRenderer(), txItem, classItem);\n\n final FormHelpPanel helpPanel = new FormHelpPanel(\n new FormHelpPanel.AddressCallback() {\n @Override\n public ModelNode getAddress() {\n ModelNode address = Baseadress.get();\n address.add(\"subsystem\", \"resource-adapters\");\n address.add(\"resource-adapter\", \"*\");\n return address;\n }\n }, form\n );\n layout.add(helpPanel.asWidget());\n\n layout.add(form.asWidget());\n\n form.setEnabled(false );\n\n }\n\n Widget asWidget() {\n return layout;\n }\n\n public Form getForm() {\n return form;\n }\n\n public void setEnabled(boolean b) {\n form.setEnabled(b);\n\n if(!b)\n editBtn.setText(\"Edit\");\n else\n editBtn.setText(\"Save\");\n }\n}\n"},"new_file":{"kind":"string","value":"gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/AdapterDetails.java"},"old_contents":{"kind":"string","value":"package org.jboss.as.console.client.shared.subsys.jca;\n\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.user.client.ui.VerticalPanel;\nimport com.google.gwt.user.client.ui.Widget;\nimport org.jboss.as.console.client.Console;\nimport org.jboss.as.console.client.shared.help.FormHelpPanel;\nimport org.jboss.as.console.client.shared.subsys.Baseadress;\nimport org.jboss.as.console.client.shared.subsys.jca.model.ResourceAdapter;\nimport org.jboss.ballroom.client.widgets.forms.ComboBoxItem;\nimport org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer;\nimport org.jboss.ballroom.client.widgets.forms.Form;\nimport org.jboss.ballroom.client.widgets.forms.TextBoxItem;\nimport org.jboss.ballroom.client.widgets.forms.TextItem;\nimport org.jboss.ballroom.client.widgets.tools.ToolButton;\nimport org.jboss.ballroom.client.widgets.tools.ToolStrip;\nimport org.jboss.ballroom.client.widgets.window.Feedback;\nimport org.jboss.dmr.client.ModelNode;\n\n/**\n * @author Heiko Braun\n * @date 7/19/11\n */\npublic class AdapterDetails {\n\n private VerticalPanel layout;\n private Form form;\n private ToolButton editBtn;\n private ResourceAdapterPresenter presenter;\n\n public AdapterDetails(final ResourceAdapterPresenter presenter) {\n\n this.presenter = presenter;\n\n layout = new VerticalPanel();\n layout.setStyleName(\"fill-layout-width\");\n\n form = new Form(ResourceAdapter.class);\n form.setNumColumns(2);\n\n ToolStrip detailToolStrip = new ToolStrip();\n editBtn = new ToolButton(Console.CONSTANTS.common_label_edit());\n ClickHandler editHandler = new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n if(editBtn.getText().equals(Console.CONSTANTS.common_label_edit()))\n presenter.onEdit(form.getEditedEntity());\n else\n presenter.onSave(form.getEditedEntity().getName(), form.getChangedValues());\n }\n };\n editBtn.addClickHandler(editHandler);\n detailToolStrip.addToolButton(editBtn);\n\n\n ClickHandler clickHandler = new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n\n final ResourceAdapter ra = form.getEditedEntity();\n\n Feedback.confirm(\n \"Delete Resource Adapter\",\n \"Really delete Adapter '\" + ra.getName() + \"' ?\",\n new Feedback.ConfirmationHandler() {\n @Override\n public void onConfirmation(boolean isConfirmed) {\n if (isConfirmed) {\n presenter.onDelete(ra);\n }\n }\n });\n }\n };\n ToolButton deleteBtn = new ToolButton(Console.CONSTANTS.common_label_delete());\n deleteBtn.addClickHandler(clickHandler);\n detailToolStrip.addToolButton(deleteBtn);\n\n layout.add(detailToolStrip);\n\n // ----\n\n TextItem nameItem = new TextItem(\"name\", \"Name\");\n TextBoxItem poolItem = new TextBoxItem(\"poolName\", \"Pool\");\n TextBoxItem jndiItem = new TextBoxItem(\"jndiName\", \"JNDI\");\n TextItem archiveItem = new TextItem(\"archive\", \"Archive\");\n\n ComboBoxItem txItem = new ComboBoxItem(\"transactionSupport\", \"TX\");\n txItem.setDefaultToFirstOption(true);\n txItem.setValueMap(new String[]{\"NoTransaction\", \"LocalTransaction\", \"XATransaction\"});\n\n TextBoxItem classItem = new TextBoxItem(\"connectionClass\", \"Connection Class\");\n\n\n form.setFields(nameItem, jndiItem, poolItem, archiveItem);\n form.setFieldsInGroup(\"Advanced\", new DisclosureGroupRenderer(), txItem, classItem);\n\n final FormHelpPanel helpPanel = new FormHelpPanel(\n new FormHelpPanel.AddressCallback() {\n @Override\n public ModelNode getAddress() {\n ModelNode address = Baseadress.get();\n address.add(\"subsystem\", \"resource-adapters\");\n address.add(\"resource-adapter\", \"*\");\n return address;\n }\n }, form\n );\n layout.add(helpPanel.asWidget());\n\n layout.add(form.asWidget());\n\n form.setEnabled(false );\n\n }\n\n Widget asWidget() {\n return layout;\n }\n\n public Form getForm() {\n return form;\n }\n\n public void setEnabled(boolean b) {\n form.setEnabled(b);\n\n if(!b)\n editBtn.setText(\"Edit\");\n else\n editBtn.setText(\"Save\");\n }\n}\n"},"message":{"kind":"string","value":"prevent edit when no entity selected"},"old_file":{"kind":"string","value":"gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/AdapterDetails.java"},"subject":{"kind":"string","value":"prevent edit when no entity selected"}}},{"rowIdx":1282,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"6d4d3fc90da3a4d8c1f36edc9898df5b3b883000"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"picketbox/picketbox,picketbox/picketbox,picketbox/picketbox"},"new_contents":{"kind":"string","value":"/*\n* JBoss, Home of Professional Open Source\n* Copyright 2005, JBoss Inc., and individual contributors as indicated\n* by the @authors tag. See the copyright.txt in the distribution for a\n* full listing of individual contributors.\n*\n* This is free software; you can redistribute it and/or modify it\n* under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation; either version 2.1 of\n* the License, or (at your option) any later version.\n*\n* This software is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this software; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n* 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n*/\npackage org.jboss.security.auth.spi;\n\nimport java.io.IOException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.Principal;\nimport java.security.acl.Group;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.Map;\n\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\nimport javax.security.auth.Subject;\nimport javax.security.auth.callback.Callback;\nimport javax.security.auth.callback.CallbackHandler;\nimport javax.security.auth.callback.NameCallback;\nimport javax.security.auth.callback.UnsupportedCallbackException;\nimport javax.security.auth.login.FailedLoginException;\nimport javax.security.auth.login.LoginException;\n\nimport org.jboss.security.SecurityDomain;\nimport org.jboss.security.auth.callback.ObjectCallback;\nimport org.jboss.security.auth.certs.X509CertificateVerifier;\n\n/**\n * Base Login Module that uses X509Certificates as credentials for\n * authentication.\n *\n * This login module uses X509Certificates as a\n * credential. It takes the cert as an object and checks to see if the alias in\n * the truststore/keystore contains the same certificate. Subclasses of this\n * module should implement the getRoleSets() method defined by\n * AbstractServerLoginModule. Much of this module was patterned after the\n * UserNamePasswordLoginModule.\n *\n * @author Jason Essington\n * @author Scott.Stark@jboss.org\n * @version $Revision$\n */\npublic class BaseCertLoginModule extends AbstractServerLoginModule\n{\n /** A principal derived from the certificate alias */\n private Principal identity;\n /** The client certificate */\n private X509Certificate credential;\n /** The SecurityDomain to obtain the KeyStore/TrustStore from */\n private SecurityDomain domain = null;\n /** An option certificate verifier */\n private X509CertificateVerifier verifier; \n\n /** Override the super version to pickup the following options after first\n * calling the super method.\n *\n * option: securityDomain - the name of the SecurityDomain to obtain the\n * trust and keystore from.\n * option: verifier - the class name of the X509CertificateVerifier to use\n * for verification of the login certificate\n *\n * @see SecurityDomain\n * @see X509CertificateVerifier\n *\n * @param subject the Subject to update after a successful login.\n * @param callbackHandler the CallbackHandler that will be used to obtain the\n * the user identity and credentials.\n * @param sharedState a Map shared between all configured login module instances\n * @param options the parameters passed to the login module.\n */\n public void initialize(Subject subject, CallbackHandler callbackHandler,\n Map sharedState, Map options)\n {\n super.initialize(subject, callbackHandler, sharedState, options);\n trace = log.isTraceEnabled();\n\n // Get the security domain and default to \"other\"\n String sd = (String) options.get(\"securityDomain\");\n if (sd == null)\n sd = \"java:/jaas/other\";\n\n if( trace )\n log.trace(\"securityDomain=\" + sd);\n\n try\n {\n Object tempDomain = new InitialContext().lookup(sd);\n if (tempDomain instanceof SecurityDomain)\n {\n domain = (SecurityDomain) tempDomain;\n if( trace )\n {\n if (domain != null)\n log.trace(\"found domain: \" + domain.getClass().getName());\n else\n log.trace(\"the domain \" + sd + \" is null!\");\n }\n }\n else\n {\n log.error(\"The domain \" + sd + \" is not a SecurityDomain. All authentication using this module will fail!\");\n }\n }\n catch (NamingException e)\n {\n log.error(\"Unable to find the securityDomain named: \" + sd, e);\n }\n\n String option = (String) options.get(\"verifier\");\n if( option != null )\n {\n try\n {\n ClassLoader loader = SecurityActions.getContextClassLoader();\n Class verifierClass = loader.loadClass(option);\n verifier = (X509CertificateVerifier) verifierClass.newInstance();\n }\n catch(Throwable e)\n {\n if( trace )\n log.trace(\"Failed to create X509CertificateVerifier\", e);\n IllegalArgumentException ex = new IllegalArgumentException(\"Invalid verifier: \"+option);\n ex.initCause(e);\n }\n }\n\n if( trace )\n log.trace(\"exit: initialize(Subject, CallbackHandler, Map, Map)\");\n }\n\n /**\n * Perform the authentication of the username and password.\n */\n @SuppressWarnings(\"unchecked\")\n public boolean login() throws LoginException\n {\n if( trace )\n log.trace(\"enter: login()\");\n // See if shared credentials exist\n if (super.login() == true)\n {\n // Setup our view of the user\n Object username = sharedState.get(\"javax.security.auth.login.name\");\n if( username instanceof Principal )\n identity = (Principal) username;\n else\n {\n String name = username.toString();\n try\n {\n identity = createIdentity(name);\n }\n catch(Exception e)\n {\n log.debug(\"Failed to create principal\", e);\n throw new LoginException(\"Failed to create principal: \"+ e.getMessage());\n }\n }\n\n Object password = sharedState.get(\"javax.security.auth.login.password\");\n if (password instanceof X509Certificate)\n credential = (X509Certificate) password;\n else if (password != null)\n {\n log.debug(\"javax.security.auth.login.password is not X509Certificate\");\n super.loginOk = false;\n return false;\n }\n return true;\n }\n\n super.loginOk = false;\n Object[] info = getAliasAndCert();\n String alias = (String) info[0];\n credential = (X509Certificate) info[1];\n\n if (alias == null && credential == null)\n {\n identity = unauthenticatedIdentity;\n super.log.trace(\"Authenticating as unauthenticatedIdentity=\" + identity);\n }\n\n if (identity == null)\n {\n try\n {\n identity = createIdentity(alias);\n }\n catch(Exception e)\n {\n log.debug(\"Failed to create identity for alias:\"+alias, e);\n }\n\n if (!validateCredential(alias, credential))\n {\n log.debug(\"Bad credential for alias=\" + alias);\n throw new FailedLoginException(\"Supplied Credential did not match existing credential for \" + alias);\n }\n }\n\n if (getUseFirstPass() == true)\n {\n // Add authentication info to shared state map\n sharedState.put(\"javax.security.auth.login.name\", alias);\n sharedState.put(\"javax.security.auth.login.password\", credential);\n }\n super.loginOk = true;\n if( trace )\n {\n log.trace(\"User '\" + identity + \"' authenticated, loginOk=\" + loginOk);\n log.debug(\"exit: login()\");\n }\n return true;\n }\n\n /** Override to add the X509Certificate to the public credentials\n * @return\n * @throws LoginException\n */\n public boolean commit() throws LoginException\n {\n boolean ok = super.commit();\n if( ok == true )\n {\n // Add the cert to the public credentials\n if (credential != null)\n {\n subject.getPublicCredentials().add(credential);\n }\n }\n return ok;\n }\n\n /** Subclasses need to override this to provide the roles for authorization\n * @return\n * @throws LoginException\n */\n protected Group[] getRoleSets() throws LoginException\n {\n return new Group[0];\n }\n\n protected Principal getIdentity()\n {\n return identity;\n }\n protected Object getCredentials()\n {\n return credential;\n }\n protected String getUsername()\n {\n String username = null;\n if (getIdentity() != null)\n username = getIdentity().getName();\n return username;\n }\n\n protected Object[] getAliasAndCert() throws LoginException\n {\n if( trace )\n log.trace(\"enter: getAliasAndCert()\");\n Object[] info = { null, null };\n // prompt for a username and password\n if (callbackHandler == null)\n {\n throw new LoginException(\"Error: no CallbackHandler available to collect authentication information\");\n }\n NameCallback nc = new NameCallback(\"Alias: \");\n ObjectCallback oc = new ObjectCallback(\"Certificate: \");\n Callback[] callbacks = { nc, oc };\n String alias = null;\n X509Certificate cert = null;\n X509Certificate[] certChain;\n try\n {\n callbackHandler.handle(callbacks);\n alias = nc.getName();\n Object tmpCert = oc.getCredential();\n if (tmpCert != null)\n {\n if (tmpCert instanceof X509Certificate)\n {\n cert = (X509Certificate) tmpCert;\n if( trace )\n log.trace(\"found cert \" + cert.getSerialNumber().toString(16) + \":\" + cert.getSubjectDN().getName());\n }\n else if( tmpCert instanceof X509Certificate[] )\n {\n certChain = (X509Certificate[]) tmpCert;\n if( certChain.length > 0 )\n cert = certChain[0];\n }\n else\n {\n String msg = \"Don't know how to obtain X509Certificate from: \"\n +tmpCert.getClass();\n log.warn(msg);\n throw new LoginException(msg);\n }\n }\n else\n {\n log.warn(\"CallbackHandler did not provide a certificate\");\n }\n }\n catch (IOException e)\n {\n log.debug(\"Failed to invoke callback\", e);\n throw new LoginException(\"Failed to invoke callback: \"+e.toString());\n }\n catch (UnsupportedCallbackException uce)\n {\n throw new LoginException(\"CallbackHandler does not support: \"\n + uce.getCallback());\n }\n\n info[0] = alias;\n info[1] = cert;\n if( trace )\n log.trace(\"exit: getAliasAndCert()\");\n return info;\n }\n\n protected boolean validateCredential(String alias, X509Certificate cert)\n {\n if( trace )\n log.trace(\"enter: validateCredentail(String, X509Certificate)\");\n boolean isValid = false;\n\n // if we don't have a trust store, we'll just use the key store.\n KeyStore keyStore = null;\n KeyStore trustStore = null;\n if( domain != null )\n {\n keyStore = domain.getKeyStore();\n trustStore = domain.getTrustStore();\n }\n if( trustStore == null )\n trustStore = keyStore;\n\n if( verifier != null )\n {\n // Have the verifier validate the cert\n if( trace )\n log.trace(\"Validating cert using: \"+verifier);\n isValid = verifier.verify(cert, alias, keyStore, trustStore);\n }\n else if (trustStore != null && cert != null)\n {\n // Look for the cert in the truststore using the alias\n X509Certificate storeCert = null;\n try\n {\n storeCert = (X509Certificate) trustStore.getCertificate(alias);\n if( trace )\n {\n StringBuffer buf = new StringBuffer(\"\\n\\tSupplied Credential: \");\n buf.append(cert.getSerialNumber().toString(16));\n buf.append(\"\\n\\t\\t\");\n buf.append(cert.getSubjectDN().getName());\n buf.append(\"\\n\\n\\tExisting Credential: \");\n if( storeCert != null )\n {\n buf.append(storeCert.getSerialNumber().toString(16));\n buf.append(\"\\n\\t\\t\");\n buf.append(storeCert.getSubjectDN().getName());\n buf.append(\"\\n\");\n }\n else\n {\n ArrayList aliases = new ArrayList();\n Enumeration en = trustStore.aliases();\n while (en.hasMoreElements())\n {\n aliases.add(en.nextElement());\n }\n buf.append(\"No match for alias: \"+alias+\", we have aliases \" + aliases);\n }\n log.trace(buf.toString());\n }\n }\n catch (KeyStoreException e)\n {\n log.warn(\"failed to find the certificate for \" + alias, e);\n }\n // Ensure that the two certs are equal\n if (cert.equals(storeCert))\n isValid = true;\n }\n else\n {\n log.warn(\"Domain, KeyStore, or cert is null. Unable to validate the certificate.\");\n }\n\n if( trace )\n {\n log.trace(\"The supplied certificate \"\n + (isValid ? \"matched\" : \"DID NOT match\")\n + \" the certificate in the keystore.\");\n\n log.trace(\"exit: validateCredentail(String, X509Certificate)\");\n }\n return isValid;\n }\n\n}"},"new_file":{"kind":"string","value":"security-jboss-sx/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java"},"old_contents":{"kind":"string","value":"/*\n* JBoss, Home of Professional Open Source\n* Copyright 2005, JBoss Inc., and individual contributors as indicated\n* by the @authors tag. See the copyright.txt in the distribution for a\n* full listing of individual contributors.\n*\n* This is free software; you can redistribute it and/or modify it\n* under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation; either version 2.1 of\n* the License, or (at your option) any later version.\n*\n* This software is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this software; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n* 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n*/\npackage org.jboss.security.auth.spi;\n\nimport java.io.IOException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.Principal;\nimport java.security.acl.Group;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.Map;\n\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\nimport javax.security.auth.Subject;\nimport javax.security.auth.callback.Callback;\nimport javax.security.auth.callback.CallbackHandler;\nimport javax.security.auth.callback.NameCallback;\nimport javax.security.auth.callback.UnsupportedCallbackException;\nimport javax.security.auth.login.FailedLoginException;\nimport javax.security.auth.login.LoginException;\n\nimport org.jboss.security.SecurityDomain;\nimport org.jboss.security.auth.callback.ObjectCallback;\nimport org.jboss.security.auth.certs.X509CertificateVerifier;\n\n/**\n * Base Login Module that uses X509Certificates as credentials for\n * authentication.\n *\n * This login module uses X509Certificates as a\n * credential. It takes the cert as an object and checks to see if the alias in\n * the truststore/keystore contains the same certificate. Subclasses of this\n * module should implement the getRoleSets() method defined by\n * AbstractServerLoginModule. Much of this module was patterned after the\n * UserNamePasswordLoginModule.\n *\n * @author Jason Essington\n * @author Scott.Stark@jboss.org\n * @version $Revision$\n */\npublic class BaseCertLoginModule extends AbstractServerLoginModule\n{\n /** A principal derived from the certificate alias */\n private Principal identity;\n /** The client certificate */\n private X509Certificate credential;\n /** The SecurityDomain to obtain the KeyStore/TrustStore from */\n private SecurityDomain domain = null;\n /** An option certificate verifier */\n private X509CertificateVerifier verifier; \n\n /** Override the super version to pickup the following options after first\n * calling the super method.\n *\n * option: securityDomain - the name of the SecurityDomain to obtain the\n * trust and keystore from.\n * option: verifier - the class name of the X509CertificateVerifier to use\n * for verification of the login certificate\n *\n * @see SecurityDomain\n * @see X509CertificateVerifier\n *\n * @param subject the Subject to update after a successful login.\n * @param callbackHandler the CallbackHandler that will be used to obtain the\n * the user identity and credentials.\n * @param sharedState a Map shared between all configured login module instances\n * @param options the parameters passed to the login module.\n */\n public void initialize(Subject subject, CallbackHandler callbackHandler,\n Map sharedState, Map options)\n {\n super.initialize(subject, callbackHandler, sharedState, options);\n trace = log.isTraceEnabled();\n\n // Get the security domain and default to \"other\"\n String sd = (String) options.get(\"securityDomain\");\n if (sd == null)\n sd = \"java:/jaas/other\";\n\n if( trace )\n log.trace(\"securityDomain=\" + sd);\n\n try\n {\n Object tempDomain = new InitialContext().lookup(sd);\n if (tempDomain instanceof SecurityDomain)\n {\n domain = (SecurityDomain) tempDomain;\n if( trace )\n {\n if (domain != null)\n log.trace(\"found domain: \" + domain.getClass().getName());\n else\n log.trace(\"the domain \" + sd + \" is null!\");\n }\n }\n else\n {\n log.error(\"The domain \" + sd + \" is not a SecurityDomain. All authentication using this module will fail!\");\n }\n }\n catch (NamingException e)\n {\n log.error(\"Unable to find the securityDomain named: \" + sd, e);\n }\n\n String option = (String) options.get(\"verifier\");\n if( option != null )\n {\n try\n {\n ClassLoader loader = SecurityActions.getContextClassLoader();\n Class verifierClass = loader.loadClass(option);\n verifier = (X509CertificateVerifier) verifierClass.newInstance();\n }\n catch(Throwable e)\n {\n if( trace )\n log.trace(\"Failed to create X509CertificateVerifier\", e);\n IllegalArgumentException ex = new IllegalArgumentException(\"Invalid verifier: \"+option);\n ex.initCause(e);\n }\n }\n\n if( trace )\n log.trace(\"exit: initialize(Subject, CallbackHandler, Map, Map)\");\n }\n\n /**\n * Perform the authentication of the username and password.\n */\n @SuppressWarnings(\"unchecked\")\n public boolean login() throws LoginException\n {\n if( trace )\n log.trace(\"enter: login()\");\n // See if shared credentials exist\n if (super.login() == true)\n {\n // Setup our view of the user\n Object username = sharedState.get(\"javax.security.auth.login.name\");\n if( username instanceof Principal )\n identity = (Principal) username;\n else\n {\n String name = username.toString();\n try\n {\n identity = createIdentity(name);\n }\n catch(Exception e)\n {\n log.debug(\"Failed to create principal\", e);\n throw new LoginException(\"Failed to create principal: \"+ e.getMessage());\n }\n }\n\n Object password = sharedState.get(\"javax.security.auth.login.password\");\n if (password instanceof X509Certificate)\n credential = (X509Certificate) password;\n else if (password != null)\n {\n log.debug(\"javax.security.auth.login.password is not X509Certificate\");\n super.loginOk = false;\n return false;\n }\n return true;\n }\n\n super.loginOk = false;\n Object[] info = getAliasAndCert();\n String alias = (String) info[0];\n credential = (X509Certificate) info[1];\n\n if (alias == null && credential == null)\n {\n identity = unauthenticatedIdentity;\n super.log.trace(\"Authenticating as unauthenticatedIdentity=\" + identity);\n }\n\n if (identity == null)\n {\n try\n {\n identity = createIdentity(alias);\n }\n catch(Exception e)\n {\n log.debug(\"Failed to create identity for alias:\"+alias, e);\n }\n\n if (!validateCredential(alias, credential))\n {\n log.debug(\"Bad credential for alias=\" + alias);\n throw new FailedLoginException(\"Supplied Credential did not match existing credential for \" + alias);\n }\n }\n\n if (getUseFirstPass() == true)\n {\n // Add authentication info to shared state map\n sharedState.put(\"javax.security.auth.login.name\", alias);\n sharedState.put(\"javax.security.auth.login.password\", credential);\n }\n super.loginOk = true;\n if( trace )\n {\n log.trace(\"User '\" + identity + \"' authenticated, loginOk=\" + loginOk);\n log.debug(\"exit: login()\");\n }\n return true;\n }\n\n /** Override to add the X509Certificate to the public credentials\n * @return\n * @throws LoginException\n */\n public boolean commit() throws LoginException\n {\n boolean ok = super.commit();\n if( ok == true )\n {\n // Add the cert to the public credentials\n if (credential != null)\n {\n subject.getPublicCredentials().add(credential);\n }\n }\n return ok;\n }\n\n /** Subclasses need to override this to provide the roles for authorization\n * @return\n * @throws LoginException\n */\n protected Group[] getRoleSets() throws LoginException\n {\n return new Group[0];\n }\n\n protected Principal getIdentity()\n {\n return identity;\n }\n protected Object getCredentials()\n {\n return credential;\n }\n protected String getUsername()\n {\n String username = null;\n if (getIdentity() != null)\n username = getIdentity().getName();\n return username;\n }\n\n protected Object[] getAliasAndCert() throws LoginException\n {\n if( trace )\n log.trace(\"enter: getAliasAndCert()\");\n Object[] info = { null, null };\n // prompt for a username and password\n if (callbackHandler == null)\n {\n throw new LoginException(\"Error: no CallbackHandler available to collect authentication information\");\n }\n NameCallback nc = new NameCallback(\"Alias: \");\n ObjectCallback oc = new ObjectCallback(\"Certificate: \");\n Callback[] callbacks = { nc, oc };\n String alias = null;\n X509Certificate cert = null;\n X509Certificate[] certChain;\n try\n {\n callbackHandler.handle(callbacks);\n alias = nc.getName();\n Object tmpCert = oc.getCredential();\n if (tmpCert != null)\n {\n if (tmpCert instanceof X509Certificate)\n {\n cert = (X509Certificate) tmpCert;\n if( trace )\n log.trace(\"found cert \" + cert.getSerialNumber().toString(16) + \":\" + cert.getSubjectDN().getName());\n }\n else if( tmpCert instanceof X509Certificate[] )\n {\n certChain = (X509Certificate[]) tmpCert;\n if( certChain.length > 0 )\n cert = certChain[0];\n }\n else\n {\n String msg = \"Don't know how to obtain X509Certificate from: \"\n +tmpCert.getClass();\n log.warn(msg);\n throw new LoginException(msg);\n }\n }\n else\n {\n log.warn(\"CallbackHandler did not provide a certificate\");\n }\n }\n catch (IOException e)\n {\n log.debug(\"Failed to invoke callback\", e);\n throw new LoginException(\"Failed to invoke callback: \"+e.toString());\n }\n catch (UnsupportedCallbackException uce)\n {\n throw new LoginException(\"CallbackHandler does not support: \"\n + uce.getCallback());\n }\n\n info[0] = alias;\n info[1] = cert;\n if( trace )\n log.trace(\"exit: getAliasAndCert()\");\n return info;\n }\n\n protected boolean validateCredential(String alias, X509Certificate cert)\n {\n if( trace )\n log.trace(\"enter: validateCredentail(String, X509Certificate)\");\n boolean isValid = false;\n\n // if we don't have a trust store, we'll just use the key store.\n KeyStore keyStore = null;\n KeyStore trustStore = null;\n if( domain != null )\n {\n keyStore = domain.getKeyStore();\n trustStore = domain.getTrustStore();\n }\n if( trustStore == null )\n trustStore = keyStore;\n\n if( verifier != null )\n {\n // Have the verifier validate the cert\n if( trace )\n log.trace(\"Validating cert using: \"+verifier);\n isValid = verifier.verify(cert, alias, keyStore, trustStore);\n }\n else if (keyStore != null && cert != null)\n {\n // Look for the cert in the keystore using the alias\n X509Certificate storeCert = null;\n try\n {\n storeCert = (X509Certificate) keyStore.getCertificate(alias);\n if( trace )\n {\n StringBuffer buf = new StringBuffer(\"\\n\\tSupplied Credential: \");\n buf.append(cert.getSerialNumber().toString(16));\n buf.append(\"\\n\\t\\t\");\n buf.append(cert.getSubjectDN().getName());\n buf.append(\"\\n\\n\\tExisting Credential: \");\n if( storeCert != null )\n {\n buf.append(storeCert.getSerialNumber().toString(16));\n buf.append(\"\\n\\t\\t\");\n buf.append(storeCert.getSubjectDN().getName());\n buf.append(\"\\n\");\n }\n else\n {\n ArrayList aliases = new ArrayList();\n Enumeration en = keyStore.aliases();\n while (en.hasMoreElements())\n {\n aliases.add(en.nextElement());\n }\n buf.append(\"No match for alias: \"+alias+\", we have aliases \" + aliases);\n }\n log.trace(buf.toString());\n }\n }\n catch (KeyStoreException e)\n {\n log.warn(\"failed to find the certificate for \" + alias, e);\n }\n // Ensure that the two certs are equal\n if (cert.equals(storeCert))\n isValid = true;\n }\n else\n {\n log.warn(\"Domain, KeyStore, or cert is null. Unable to validate the certificate.\");\n }\n\n if( trace )\n {\n log.trace(\"The supplied certificate \"\n + (isValid ? \"matched\" : \"DID NOT match\")\n + \" the certificate in the keystore.\");\n\n log.trace(\"exit: validateCredentail(String, X509Certificate)\");\n }\n return isValid;\n }\n\n}"},"message":{"kind":"string","value":"SECURITY-558: use truststore by default and fallback to keystore\n"},"old_file":{"kind":"string","value":"security-jboss-sx/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java"},"subject":{"kind":"string","value":"SECURITY-558: use truststore by default and fallback to keystore"}}},{"rowIdx":1283,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"81eb7b4a3366ca2fe9325c49fcaa5ae94497fd39"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"exedio/copernica,exedio/copernica,exedio/copernica"},"new_contents":{"kind":"string","value":"\npackage com.exedio.cope.lib;\n\nimport java.io.File;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.math.BigDecimal;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nimport bak.pcj.list.IntArrayList;\n\npublic abstract class Database\n{\n\tpublic static final Database theInstance = createInstance();\n\t\n\tprivate static final Database createInstance()\n\t{\n\t\tfinal String databaseName = Properties.getInstance().getDatabase();\n\n\t\tfinal Class databaseClass;\n\t\ttry\n\t\t{\n\t\t\tdatabaseClass = Class.forName(databaseName);\n\t\t}\n\t\tcatch(ClassNotFoundException e)\n\t\t{\n\t\t\tfinal String m = \"ERROR: class \"+databaseName+\" from cope.properties not found.\";\n\t\t\tSystem.err.println(m);\n\t\t\tthrow new RuntimeException(m);\n\t\t}\n\t\t\n\t\tif(!Database.class.isAssignableFrom(databaseClass))\n\t\t{\n\t\t\tfinal String m = \"ERROR: class \"+databaseName+\" from cope.properties not a subclass of \"+Database.class.getName()+\".\";\n\t\t\tSystem.err.println(m);\n\t\t\tthrow new RuntimeException(m);\n\t\t}\n\n\t\tfinal Constructor constructor;\n\t\ttry\n\t\t{\n\t\t\tconstructor = databaseClass.getDeclaredConstructor(new Class[]{});\n\t\t}\n\t\tcatch(NoSuchMethodException e)\n\t\t{\n\t\t\tfinal String m = \"ERROR: class \"+databaseName+\" from cope.properties has no default constructor.\";\n\t\t\tSystem.err.println(m);\n\t\t\tthrow new RuntimeException(m);\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\treturn (Database)constructor.newInstance(new Object[]{});\n\t\t}\n\t\tcatch(InstantiationException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t\tcatch(IllegalAccessException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t\tcatch(InvocationTargetException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate final boolean useDefineColumnTypes;\n\t\n\tprotected Database()\n\t{\n\t\tthis.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable;\n\t\t//System.out.println(\"using database \"+getClass());\n\t}\n\t\n\tprivate final Statement createStatement()\n\t{\n\t\treturn new Statement(useDefineColumnTypes);\n\t}\n\t\n\t//private static int createTableTime = 0, dropTableTime = 0, checkEmptyTableTime = 0;\n\t\n\tpublic void createDatabase()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t\tcreateTable((Table)i.next());\n\n\t\tfor(Iterator i = Type.getTypes().iterator(); i.hasNext(); )\n\t\t\tcreateMediaDirectories((Type)i.next());\n\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t\tcreateForeignKeyConstraints((Table)i.next());\n\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//createTableTime += amount;\n\t\t//System.out.println(\"CREATE TABLES \"+amount+\"ms accumulated \"+createTableTime);\n\t}\n\n\t//private static int checkTableTime = 0;\n\n\t/**\n\t * Checks the database,\n\t * whether the database tables representing the types do exist.\n\t * Issues a single database statement,\n\t * that touches all tables and columns,\n\t * that would have been created by\n\t * {@link #createDatabase()}.\n\t * @throws SystemException\n\t * \tif something is wrong with the database.\n\t * \tTODO: use a more specific exception.\n\t */\n\tpublic void checkDatabase()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"select count(*) from \").defineColumnInteger();\n\t\tboolean first = true;\n\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\n\t\t\tfinal Table table = (Table)i.next();\n\t\t\tbf.append(table.protectedID);\n\t\t}\n\t\t\n\t\tfinal Long testDate = new Long(System.currentTimeMillis());\n\t\t\n\t\tbf.append(\" where \");\n\t\tfirst = true;\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(\" and \");\n\n\t\t\tfinal Table table = (Table)i.next();\n\n\t\t\tfinal Column primaryKey = table.primaryKey;\n\t\t\tbf.append(table.protectedID).\n\t\t\t\tappend('.').\n\t\t\t\tappend(primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(Type.NOT_A_PK);\n\t\t\t\n\t\t\tfor(Iterator j = table.getColumns().iterator(); j.hasNext(); )\n\t\t\t{\n\t\t\t\tfinal Column column = (Column)j.next();\n\t\t\t\tbf.append(\" and \").\n\t\t\t\t\tappend(table.protectedID).\n\t\t\t\t\tappend('.').\n\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\tappend('=');\n\n\t\t\t\tif(column instanceof IntegerColumn)\n\t\t\t\t\tbf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1));\n\t\t\t\telse if(column instanceof DoubleColumn)\n\t\t\t\t\tbf.appendValue(column, new Double(2.2));\n\t\t\t\telse if(column instanceof StringColumn)\n\t\t\t\t\tbf.appendValue(column, \"z\");\n\t\t\t\telse if(column instanceof TimestampColumn)\n\t\t\t\t\tbf.appendValue(column, testDate);\n\t\t\t\telse\n\t\t\t\t\tthrow new RuntimeException(column.toString());\n\t\t\t}\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\t//System.out.println(\"checkDatabase:\"+bf.toString());\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//checkTableTime += amount;\n\t\t//System.out.println(\"CHECK TABLES \"+amount+\"ms accumulated \"+checkTableTime);\n\t}\n\n\tpublic void dropDatabase()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\t{\n\t\t\tfinal List types = Type.getTypes();\n\t\t\tfor(ListIterator i = types.listIterator(types.size()); i.hasPrevious(); )\n\t\t\t\t((Type)i.previous()).onDropTable();\n\t\t}\n\t\t{\n\t\t\tfinal List tables = Table.getTables();\n\t\t\t// must delete in reverse order, to obey integrity constraints\n\t\t\tfor(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); )\n\t\t\t\tdropForeignKeyConstraints((Table)i.previous());\n\t\t\tfor(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); )\n\t\t\t\tdropTable((Table)i.previous());\n\t\t}\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//dropTableTime += amount;\n\t\t//System.out.println(\"DROP TABLES \"+amount+\"ms accumulated \"+dropTableTime);\n\t}\n\t\n\tpublic void tearDownDatabase()\n\t{\n\t\tSystem.err.println(\"TEAR DOWN ALL DATABASE\");\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfinal Table table = (Table)i.next();\n\t\t\t\tSystem.err.print(\"DROPPING FOREIGN KEY CONSTRAINTS \"+table+\"... \");\n\t\t\t\tdropForeignKeyConstraints(table);\n\t\t\t\tSystem.err.println(\"done.\");\n\t\t\t}\n\t\t\tcatch(SystemException e2)\n\t\t\t{\n\t\t\t\tSystem.err.println(\"failed:\"+e2.getMessage());\n\t\t\t}\n\t\t}\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfinal Table table = (Table)i.next();\n\t\t\t\tSystem.err.print(\"DROPPING TABLE \"+table+\" ... \");\n\t\t\t\tdropTable(table);\n\t\t\t\tSystem.err.println(\"done.\");\n\t\t\t}\n\t\t\tcatch(SystemException e2)\n\t\t\t{\n\t\t\t\tSystem.err.println(\"failed:\"+e2.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkEmptyTables()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\tfor(Iterator i = Type.getTypes().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Type type = (Type)i.next();\n\t\t\tfinal int count = countTable(type);\n\t\t\tif(count>0)\n\t\t\t\tthrow new RuntimeException(\"there are \"+count+\" items left for type \"+type); \n\t\t}\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//checkEmptyTableTime += amount;\n\t\t//System.out.println(\"CHECK EMPTY TABLES \"+amount+\"ms accumulated \"+checkEmptyTableTime);\n\t}\n\t\n\tfinal IntArrayList search(final Query query)\n\t{\n\t\tfinal Table selectTable = query.selectType.table;\n\t\tfinal Statement bf = createStatement();\n\n\t\tbf.append(\"select \").\n\t\t\tappend(selectTable.protectedID).\n\t\t\tappend('.').\n\t\t\tappend(selectTable.primaryKey.protectedID).defineColumnInteger().\n\t\t\tappend(\" from \");\n\n\t\tboolean first = true;\n\t\tfor(Iterator i = query.fromTypes.iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\n\t\t\tbf.append(((Type)i.next()).table.protectedID);\n\t\t}\n\n\t\tif(query.condition!=null)\n\t\t{\n\t\t\tbf.append(\" where \");\n\t\t\tquery.condition.appendStatement(bf);\n\t\t}\n\t\t\n\t\tif(query.orderBy!=null)\n\t\t{\n\t\t\tbf.append(\" order by \").\n\t\t\t\tappend(query.orderBy);\n\t\t\tif(!query.orderAscending)\n\t\t\t\tbf.append(\" desc\");\n\t\t}\n\t\t\n\t\t//System.out.println(\"searching \"+bf.toString());\n\t\ttry\n\t\t{\n\t\t\tfinal QueryResultSetHandler handler = new QueryResultSetHandler(query.start, query.count);\n\t\t\texecuteSQL(bf, handler);\n\t\t\treturn handler.result;\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\n\tvoid load(final Row row)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"select \");\n\n\t\tboolean first = true;\n\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t{\n\t\t\tfinal Table table = type.table;\n\t\t\tfinal List columns = table.getColumns();\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tif(first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tbf.append(',');\n\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tbf.append(table.protectedID).\n\t\t\t\t\tappend('.').\n\t\t\t\t\tappend(column.protectedID).defineColumn(column);\n\t\t\t}\n\t\t}\n\n\t\tbf.append(\" from \");\n\t\tfirst = true;\n\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\n\t\t\tbf.append(type.table.protectedID);\n\t\t}\n\t\t\t\n\t\tbf.append(\" where \");\n\t\tfirst = true;\n\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(\" and \");\n\n\t\t\tfinal Table table = type.table;\n\t\t\tbf.append(table.protectedID).\n\t\t\t\tappend('.').\n\t\t\t\tappend(table.primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(row.pk);\n\t\t}\n\n\t\t//System.out.println(\"loading \"+bf.toString());\n\t\ttry\n\t\t{\n\t\t\texecuteSQL(bf, new LoadResultSetHandler(row));\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\n\tvoid store(final Row row)\n\t\t\tthrows UniqueViolationException\n\t{\n\t\tstore(row, row.type);\n\t}\n\n\tprivate void store(final Row row, final Type theType) // TODO: rename to type\n\t\t\tthrows UniqueViolationException\n\t{\n\t\tfinal Type supertype = theType.getSupertype();\n\t\tif(supertype!=null)\n\t\t\tstore(row, supertype);\n\t\t\t\n\t\tfinal Table type = theType.table; // TODO: rename to table\n\n\t\tfinal List columns = type.getColumns();\n\n\t\tfinal Statement bf = createStatement();\n\t\tif(row.present)\n\t\t{\n\t\t\tbf.append(\"update \").\n\t\t\t\tappend(type.protectedID).\n\t\t\t\tappend(\" set \");\n\n\t\t\tboolean first = true;\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tif(first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tbf.append(',');\n\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tbf.append(column.protectedID).\n\t\t\t\t\tappend('=');\n\n\t\t\t\tfinal Object value = row.store(column);\n\t\t\t\tbf.append(column.cacheToDatabase(value));\n\t\t\t}\n\t\t\tbf.append(\" where \").\n\t\t\t\tappend(type.primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(row.pk);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbf.append(\"insert into \").\n\t\t\t\tappend(type.protectedID).\n\t\t\t\tappend(\"(\").\n\t\t\t\tappend(type.primaryKey.protectedID);\n\n\t\t\tboolean first = true;\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tbf.append(',');\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tbf.append(column.protectedID);\n\t\t\t}\n\n\t\t\tbf.append(\")values(\").\n\t\t\t\tappend(row.pk);\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tbf.append(',');\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tfinal Object value = row.store(column);\n\t\t\t\tbf.append(column.cacheToDatabase(value));\n\t\t\t}\n\t\t\tbf.append(')');\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//System.out.println(\"storing \"+bf.toString());\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(UniqueViolationException e)\n\t\t{\n\t\t\tthrow e;\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\n\tvoid delete(final Type type, final int pk)\n\t\t\tthrows IntegrityViolationException\n\t{\n\t\tfor(Type currentType = type; currentType!=null; currentType = currentType.getSupertype())\n\t\t{\n\t\t\tfinal Table currentTable = currentType.table;\n\t\t\tfinal Statement bf = createStatement();\n\t\t\tbf.append(\"delete from \").\n\t\t\t\tappend(currentTable.protectedID).\n\t\t\t\tappend(\" where \").\n\t\t\t\tappend(currentTable.primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(pk);\n\n\t\t\t//System.out.println(\"deleting \"+bf.toString());\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t\t}\n\t\t\tcatch(IntegrityViolationException e)\n\t\t\t{\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tcatch(ConstraintViolationException e)\n\t\t\t{\n\t\t\t\tthrow new SystemException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static interface ResultSetHandler\n\t{\n\t\tpublic void run(ResultSet resultSet) throws SQLException;\n\t}\n\n\tprivate static final ResultSetHandler EMPTY_RESULT_SET_HANDLER = new ResultSetHandler()\n\t{\n\t\tpublic void run(ResultSet resultSet)\n\t\t{\n\t\t}\n\t};\n\t\t\n\tprivate static class QueryResultSetHandler implements ResultSetHandler\n\t{\n\t\tprivate final int start;\n\t\tprivate final int count;\n\t\tprivate final IntArrayList result = new IntArrayList();\n\t\t\n\t\tQueryResultSetHandler(final int start, final int count)\n\t\t{\n\t\t\tthis.start = start;\n\t\t\tthis.count = count;\n\t\t\tif(start<0)\n\t\t\t\tthrow new RuntimeException();\n\t\t}\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(start>0)\n\t\t\t{\n\t\t\t\t// TODO: ResultSet.relative\n\t\t\t\t// Would like to use\n\t\t\t\t// resultSet.relative(start+1);\n\t\t\t\t// but this throws a java.sql.SQLException:\n\t\t\t\t// Invalid operation for forward only resultset : relative\n\t\t\t\tfor(int i = start; i>0; i--)\n\t\t\t\t\tresultSet.next();\n\t\t\t}\n\t\t\t\t\n\t\t\tint i = (count>=0 ? count : Integer.MAX_VALUE);\n\n\t\t\twhile(resultSet.next() && (--i)>=0)\n\t\t\t{\n\t\t\t\tfinal int pk = resultSet.getInt(1);\n\t\t\t\t//System.out.println(\"pk:\"+pk);\n\t\t\t\tresult.add(pk);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static class LoadResultSetHandler implements ResultSetHandler\n\t{\n\t\tprivate final Row row;\n\n\t\tLoadResultSetHandler(final Row row)\n\t\t{\n\t\t\tthis.row = row;\n\t\t}\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(!resultSet.next())\n\t\t\t\tthrow new RuntimeException(\"no such pk\"); // TODO use some better exception\n\t\t\tint columnIndex = 1;\n\t\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t\t{\n\t\t\t\tfor(Iterator i = type.table.getColumns().iterator(); i.hasNext(); )\n\t\t\t\t\t((Column)i.next()).load(resultSet, columnIndex++, row);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tprivate final static int convertSQLResult(final Object sqlInteger)\n\t{\n\t\t// IMPLEMENTATION NOTE for Oracle\n\t\t// Whether the returned object is an Integer or a BigDecimal,\n\t\t// depends on whether OracleStatement.defineColumnType is used or not,\n\t\t// so we support both here.\n\t\tif(sqlInteger instanceof BigDecimal)\n\t\t\treturn ((BigDecimal)sqlInteger).intValue();\n\t\telse\n\t\t\treturn ((Integer)sqlInteger).intValue();\n\t}\n\n\tprivate static class IntegerResultSetHandler implements ResultSetHandler\n\t{\n\t\tint result;\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(!resultSet.next())\n\t\t\t\tthrow new RuntimeException();\n\n\t\t\tresult = convertSQLResult(resultSet.getObject(1));\n\t\t}\n\t}\n\n\tprivate static class NextPKResultSetHandler implements ResultSetHandler\n\t{\n\t\tint resultLo;\n\t\tint resultHi;\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(!resultSet.next())\n\t\t\t\tthrow new RuntimeException();\n\t\t\tfinal Object oLo = resultSet.getObject(1);\n\t\t\tif(oLo==null)\n\t\t\t{\n\t\t\t\tresultLo = -1;\n\t\t\t\tresultHi = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tresultLo = convertSQLResult(oLo)-1;\n\t\t\t\tfinal Object oHi = resultSet.getObject(2);\n\t\t\t\tresultHi = convertSQLResult(oHi)+1;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//private static int timeExecuteQuery = 0;\n\n\tprivate void executeSQL(final Statement statement, final ResultSetHandler resultSetHandler)\n\t\t\tthrows ConstraintViolationException\n\t{\n\t\tfinal ConnectionPool connectionPool = ConnectionPool.getInstance();\n\t\t\n\t\tConnection connection = null;\n\t\tjava.sql.Statement sqlStatement = null;\n\t\tResultSet resultSet = null;\n\t\ttry\n\t\t{\n\t\t\tconnection = connectionPool.getConnection();\n\t\t\t// TODO: use prepared statements and reuse the statement.\n\t\t\tsqlStatement = connection.createStatement();\n\t\t\tfinal String sqlText = statement.getText();\n\t\t\tif(!sqlText.startsWith(\"select \"))\n\t\t\t{\n\t\t\t\tfinal int rows = sqlStatement.executeUpdate(sqlText);\n\t\t\t\t//System.out.println(\"(\"+rows+\"): \"+statement.getText());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//long time = System.currentTimeMillis();\n\t\t\t\tif(useDefineColumnTypes)\n\t\t\t\t\t((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement);\n\t\t\t\tresultSet = sqlStatement.executeQuery(sqlText);\n\t\t\t\t//long interval = System.currentTimeMillis() - time;\n\t\t\t\t//timeExecuteQuery += interval;\n\t\t\t\t//System.out.println(\"executeQuery: \"+interval+\"ms sum \"+timeExecuteQuery+\"ms\");\n\t\t\t\tresultSetHandler.run(resultSet);\n\t\t\t}\n\t\t}\n\t\tcatch(SQLException e)\n\t\t{\n\t\t\tfinal ConstraintViolationException wrappedException = wrapException(e);\n\t\t\tif(wrappedException!=null)\n\t\t\t\tthrow wrappedException;\n\t\t\telse\n\t\t\t\tthrow new SystemException(e, statement.toString());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tif(resultSet!=null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tresultSet.close();\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e)\n\t\t\t\t{\n\t\t\t\t\t// exception is already thrown\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(sqlStatement!=null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tsqlStatement.close();\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e)\n\t\t\t\t{\n\t\t\t\t\t// exception is already thrown\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(connection!=null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tconnectionPool.putConnection(connection);\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e)\n\t\t\t\t{\n\t\t\t\t\t// exception is already thrown\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected abstract String extractUniqueConstraintName(SQLException e);\n\tprotected abstract String extractIntegrityConstraintName(SQLException e);\n\n\tprivate final ConstraintViolationException wrapException(final SQLException e)\n\t{\n\t\t{\t\t\n\t\t\tfinal String uniqueConstraintID = extractUniqueConstraintName(e);\n\t\t\tif(uniqueConstraintID!=null)\n\t\t\t{\n\t\t\t\tfinal UniqueConstraint constraint = UniqueConstraint.findByID(uniqueConstraintID, e);\n\t\t\t\treturn new UniqueViolationException(e, null, constraint);\n\t\t\t}\n\t\t}\n\t\t{\t\t\n\t\t\tfinal String integrityConstraintName = extractIntegrityConstraintName(e);\n\t\t\tif(integrityConstraintName!=null)\n\t\t\t{\n\t\t\t\tfinal ItemAttribute attribute = ItemAttribute.getItemAttributeByIntegrityConstraintName(integrityConstraintName, e);\n\t\t\t\treturn new IntegrityViolationException(e, null, attribute);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected static final String trimString(final String longString, final int maxLength)\n\t{\n\t\tif(maxLength<=0)\n\t\t\tthrow new RuntimeException(\"maxLength must be greater zero\");\n\t\tif(longString.length()==0)\n\t\t\tthrow new RuntimeException(\"longString must not be empty\");\n\n\t\tif(longString.length()<=maxLength)\n\t\t\treturn longString;\n\n\t\tint longStringLength = longString.length();\n\t\tfinal int[] trimPotential = new int[maxLength];\n\t\tfinal ArrayList words = new ArrayList();\n\t\t{\n\t\t\tfinal StringBuffer buf = new StringBuffer();\n\t\t\tfor(int i=0; i0)\n\t\t\t\t{\n\t\t\t\t\twords.add(buf.toString());\n\t\t\t\t\tint potential = 1;\n\t\t\t\t\tfor(int j = buf.length()-1; j>=0; j--, potential++)\n\t\t\t\t\t\ttrimPotential[j] += potential; \n\t\t\t\t\tbuf.setLength(0);\n\t\t\t\t}\n\t\t\t\tif(buf.length()0)\n\t\t\t{\n\t\t\t\twords.add(buf.toString());\n\t\t\t\tint potential = 1;\n\t\t\t\tfor(int j = buf.length()-1; j>=0; j--, potential++)\n\t\t\t\t\ttrimPotential[j] += potential; \n\t\t\t\tbuf.setLength(0);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfinal int expectedTrimPotential = longStringLength - maxLength;\n\t\t//System.out.println(\"expected trim potential = \"+expectedTrimPotential);\n\n\t\tint wordLength;\n\t\tint remainder = 0;\n\t\tfor(wordLength = trimPotential.length-1; wordLength>=0; wordLength--)\n\t\t{\n\t\t\t//System.out.println(\"trim potential [\"+wordLength+\"] = \"+trimPotential[wordLength]);\n\t\t\tremainder = trimPotential[wordLength] - expectedTrimPotential;\n\t\t\tif(remainder>=0)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tfinal StringBuffer result = new StringBuffer(longStringLength);\n\t\tfor(Iterator i = words.iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal String word = (String)i.next();\n\t\t\t//System.out.println(\"word \"+word+\" remainder:\"+remainder);\n\t\t\tif((word.length()>wordLength) && remainder>0)\n\t\t\t{\n\t\t\t\tresult.append(word.substring(0, wordLength+1));\n\t\t\t\tremainder--;\n\t\t\t}\n\t\t\telse if(word.length()>wordLength)\n\t\t\t\tresult.append(word.substring(0, wordLength));\n\t\t\telse\n\t\t\t\tresult.append(word);\n\t\t}\n\t\t//System.out.println(\"---- trimName(\"+longString+\",\"+maxLength+\") == \"+result+\" --- \"+words);\n\n\t\tif(result.length()!=maxLength)\n\t\t\tthrow new RuntimeException(result.toString()+maxLength);\n\n\t\treturn result.toString();\n\t}\n\t\n\tString trimName(final Type type)\n\t{\n\t\tfinal String className = type.getJavaClass().getName();\n\t\tfinal int pos = className.lastIndexOf('.');\n\t\treturn trimString(className.substring(pos+1), 25);\n\t}\n\t\n\t/**\n\t * Trims a name to length for being be a suitable qualifier for database entities,\n\t * such as tables, columns, indexes, constraints, partitions etc.\n\t */\n\tString trimName(final String longName)\n\t{\n\t\treturn trimString(longName, 25);\n\t}\n\n\t/**\n\t * Protects a database name from being interpreted as a SQL keyword.\n\t * This is usually done by enclosing the name with some (database specific) delimiters.\n\t * The default implementation uses double quotes as delimiter.\n\t */\n\tprotected String protectName(String name)\n\t{\n\t\treturn '\"' + name + '\"';\n\t}\n\n\tabstract String getIntegerType(int precision);\n\tabstract String getDoubleType(int precision);\n\tabstract String getStringType(int maxLength);\n\tabstract String getDateTimestampType();\n\t\n\tprivate void createTable(final Table table)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"create table \").\n\t\t\tappend(table.protectedID).\n\t\t\tappend('(');\n\n\t\tboolean firstColumn = true;\n\t\tfor(Iterator i = table.getAllColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(firstColumn)\n\t\t\t\tfirstColumn = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\t\t\t\n\t\t\tfinal Column column = (Column)i.next();\n\t\t\tbf.append(column.protectedID).\n\t\t\t\tappend(' ').\n\t\t\t\tappend(column.databaseType);\n\n\t\t\tif(column.primaryKey)\n\t\t\t{\n\t\t\t\tbf.append(\" primary key\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(column.notNull)\n\t\t\t\t\tbf.append(\" not null\");\n\t\t\t}\n\t\t}\n\t\t\n\t\t// attribute constraints\t\t\n\t\tfor(Iterator i = table.getColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Column column = (Column)i.next();\n\n\t\t\tif(column instanceof StringColumn)\n\t\t\t{\n\t\t\t\tfinal StringColumn stringColumn = (StringColumn)column;\n\t\t\t\tif(stringColumn.minimumLengthID!=null)\n\t\t\t\t{\n\t\t\t\t\tbf.append(\",constraint \").\n\t\t\t\t\t\tappend(protectName(stringColumn.minimumLengthID)).\n\t\t\t\t\t\tappend(\" check(length(\").\n\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\tappend(\")>=\").\n\t\t\t\t\t\tappend(stringColumn.minimumLength);\n\n\t\t\t\t\tif(!column.notNull)\n\t\t\t\t\t{\n\t\t\t\t\t\tbf.append(\" or \").\n\t\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\t\tappend(\" is null\");\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\t\t\t\t}\n\t\t\t\tif(stringColumn.maximumLengthID!=null)\n\t\t\t\t{\n\t\t\t\t\tbf.append(\",constraint \").\n\t\t\t\t\t\tappend(protectName(stringColumn.maximumLengthID)).\n\t\t\t\t\t\tappend(\" check(length(\").\n\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\tappend(\")<=\").\n\t\t\t\t\t\tappend(stringColumn.maximumLength);\n\n\t\t\t\t\tif(!column.notNull)\n\t\t\t\t\t{\n\t\t\t\t\t\tbf.append(\" or \").\n\t\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\t\tappend(\" is null\");\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(column instanceof IntegerColumn)\n\t\t\t{\n\t\t\t\tfinal IntegerColumn intColumn = (IntegerColumn)column;\n\t\t\t\tfinal int[] allowedValues = intColumn.allowedValues;\n\t\t\t\tif(allowedValues!=null)\n\t\t\t\t{\n\t\t\t\t\tbf.append(\",constraint \").\n\t\t\t\t\t\tappend(protectName(intColumn.allowedValuesID)).\n\t\t\t\t\t\tappend(\" check(\").\n\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\tappend(\" in (\");\n\n\t\t\t\t\tfor(int j = 0; j0)\n\t\t\t\t\t\t\tbf.append(',');\n\t\t\t\t\t\tbf.append(allowedValues[j]);\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\n\t\t\t\t\tif(!column.notNull)\n\t\t\t\t\t{\n\t\t\t\t\t\tbf.append(\" or \").\n\t\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\t\tappend(\" is null\");\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor(Iterator i = table.getUniqueConstraints().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal UniqueConstraint uniqueConstraint = (UniqueConstraint)i.next();\n\t\t\tbf.append(\",constraint \").\n\t\t\t\tappend(uniqueConstraint.getProtectedID()).\n\t\t\t\tappend(\" unique(\");\n\t\t\tboolean first = true;\n\t\t\tfor(Iterator j = uniqueConstraint.getUniqueAttributes().iterator(); j.hasNext(); )\n\t\t\t{\n\t\t\t\tif(first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tbf.append(',');\n\t\t\t\tfinal Attribute uniqueAttribute = (Attribute)j.next();\n\t\t\t\tbf.append(uniqueAttribute.getMainColumn().protectedID);\n\t\t\t}\n\t\t\tbf.append(')');\n\t\t}\n\t\t\n\t\tbf.append(')');\n\n\t\ttry\n\t\t{\n\t\t\t//System.out.println(\"createTable:\"+bf.toString());\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate void createForeignKeyConstraints(final Table type) // TODO: rename to table\n\t{\n\t\t//System.out.println(\"createForeignKeyConstraints:\"+bf);\n\n\t\tfor(Iterator i = type.getAllColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Column column = (Column)i.next();\n\t\t\t//System.out.println(\"createForeignKeyConstraints(\"+column+\"):\"+bf);\n\t\t\tif(column instanceof ItemColumn)\n\t\t\t{\n\t\t\t\tfinal ItemColumn itemColumn = (ItemColumn)column;\n\t\t\t\tfinal Statement bf = createStatement();\n\t\t\t\tbf.append(\"alter table \").\n\t\t\t\t\tappend(type.protectedID).\n\t\t\t\t\tappend(\" add constraint \").\n\t\t\t\t\tappend(Database.theInstance.protectName(itemColumn.integrityConstraintName)).\n\t\t\t\t\tappend(\" foreign key (\").\n\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\tappend(\") references \").\n\t\t\t\t\tappend(itemColumn.getForeignTableNameProtected());\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t//System.out.println(\"createForeignKeyConstraints:\"+bf);\n\t\t\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t\t\t}\n\t\t\t\tcatch(ConstraintViolationException e)\n\t\t\t\t{\n\t\t\t\t\tthrow new SystemException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void createMediaDirectories(final Type type)\n\t{\n\t\tFile typeDirectory = null;\n\n\t\tfor(Iterator i = type.getAttributes().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Attribute attribute = (Attribute)i.next();\n\t\t\tif(attribute instanceof MediaAttribute)\n\t\t\t{\n\t\t\t\tif(typeDirectory==null)\n\t\t\t\t{\n\t\t\t\t\tfinal File directory = Properties.getInstance().getMediaDirectory();\n\t\t\t\t\ttypeDirectory = new File(directory, type.id);\n\t\t\t\t\ttypeDirectory.mkdir();\n\t\t\t\t}\n\t\t\t\tfinal File attributeDirectory = new File(typeDirectory, attribute.getName());\n\t\t\t\tattributeDirectory.mkdir();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void dropTable(final Table type) // TODO: rename to table\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"drop table \").\n\t\t\tappend(type.protectedID);\n\n\t\ttry\n\t\t{\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate int countTable(final Type type)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"select count(*) from \").defineColumnInteger().\n\t\t\tappend(type.table.protectedID);\n\n\t\ttry\n\t\t{\n\t\t\tfinal IntegerResultSetHandler handler = new IntegerResultSetHandler();\n\t\t\texecuteSQL(bf, handler);\n\t\t\treturn handler.result;\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate void dropForeignKeyConstraints(final Table type) // TODO: rename to table\n\t{\n\t\tfor(Iterator i = type.getColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Column column = (Column)i.next();\n\t\t\t//System.out.println(\"dropForeignKeyConstraints(\"+column+\")\");\n\t\t\tif(column instanceof ItemColumn)\n\t\t\t{\n\t\t\t\tfinal ItemColumn itemColumn = (ItemColumn)column;\n\t\t\t\tfinal Statement bf = createStatement();\n\t\t\t\tboolean hasOne = false;\n\n\t\t\t\tbf.append(\"alter table \").\n\t\t\t\t\tappend(type.protectedID).\n\t\t\t\t\tappend(\" drop constraint \").\n\t\t\t\t\tappend(Database.theInstance.protectName(itemColumn.integrityConstraintName));\n\n\t\t\t\t//System.out.println(\"dropForeignKeyConstraints:\"+bf);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t\t\t}\n\t\t\t\tcatch(ConstraintViolationException e)\n\t\t\t\t{\n\t\t\t\t\tthrow new SystemException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint[] getNextPK(final Type type)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tfinal Table table = type.table;\n\t\tfinal String primaryKeyProtectedID = table.primaryKey.protectedID;\n\t\tbf.append(\"select min(\").\n\t\t\tappend(primaryKeyProtectedID).defineColumnInteger().\n\t\t\tappend(\"),max(\").\n\t\t\tappend(primaryKeyProtectedID).defineColumnInteger().\n\t\t\tappend(\") from \").\n\t\t\tappend(table.protectedID);\n\t\t\t\n\t\ttry\n\t\t{\n\t\t\tfinal NextPKResultSetHandler handler = new NextPKResultSetHandler();\n\t\t\texecuteSQL(bf, handler);\n\t\t\t//System.err.println(\"select max(\"+type.primaryKey.trimmedName+\") from \"+type.trimmedName+\" : \"+handler.result);\n\t\t\treturn new int[] {handler.resultLo, handler.resultHi};\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n}\n"},"new_file":{"kind":"string","value":"lib/src/com/exedio/cope/lib/Database.java"},"old_contents":{"kind":"string","value":"\npackage com.exedio.cope.lib;\n\nimport java.io.File;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.math.BigDecimal;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nimport bak.pcj.list.IntArrayList;\n\npublic abstract class Database\n{\n\tpublic static final Database theInstance = createInstance();\n\t\n\tprivate static final Database createInstance()\n\t{\n\t\tfinal String databaseName = Properties.getInstance().getDatabase();\n\n\t\tfinal Class databaseClass;\n\t\ttry\n\t\t{\n\t\t\tdatabaseClass = Class.forName(databaseName);\n\t\t}\n\t\tcatch(ClassNotFoundException e)\n\t\t{\n\t\t\tfinal String m = \"ERROR: class \"+databaseName+\" from cope.properties not found.\";\n\t\t\tSystem.err.println(m);\n\t\t\tthrow new RuntimeException(m);\n\t\t}\n\t\t\n\t\tif(!Database.class.isAssignableFrom(databaseClass))\n\t\t{\n\t\t\tfinal String m = \"ERROR: class \"+databaseName+\" from cope.properties not a subclass of \"+Database.class.getName()+\".\";\n\t\t\tSystem.err.println(m);\n\t\t\tthrow new RuntimeException(m);\n\t\t}\n\n\t\tfinal Constructor constructor;\n\t\ttry\n\t\t{\n\t\t\tconstructor = databaseClass.getDeclaredConstructor(new Class[]{});\n\t\t}\n\t\tcatch(NoSuchMethodException e)\n\t\t{\n\t\t\tfinal String m = \"ERROR: class \"+databaseName+\" from cope.properties has no default constructor.\";\n\t\t\tSystem.err.println(m);\n\t\t\tthrow new RuntimeException(m);\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\treturn (Database)constructor.newInstance(new Object[]{});\n\t\t}\n\t\tcatch(InstantiationException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t\tcatch(IllegalAccessException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t\tcatch(InvocationTargetException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate final boolean useDefineColumnTypes;\n\t\n\tprotected Database()\n\t{\n\t\tthis.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable;\n\t\t//System.out.println(\"using database \"+getClass());\n\t}\n\t\n\tprivate final Statement createStatement()\n\t{\n\t\treturn new Statement(useDefineColumnTypes);\n\t}\n\t\n\t//private static int createTableTime = 0, dropTableTime = 0, checkEmptyTableTime = 0;\n\t\n\tpublic void createDatabase()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t\tcreateTable((Table)i.next());\n\n\t\tfor(Iterator i = Type.getTypes().iterator(); i.hasNext(); )\n\t\t\tcreateMediaDirectories((Type)i.next());\n\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t\tcreateForeignKeyConstraints((Table)i.next());\n\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//createTableTime += amount;\n\t\t//System.out.println(\"CREATE TABLES \"+amount+\"ms accumulated \"+createTableTime);\n\t}\n\n\t//private static int checkTableTime = 0;\n\n\t/**\n\t * Checks the database,\n\t * whether the database tables representing the types do exist.\n\t * Issues a single database statement,\n\t * that touches all tables and columns,\n\t * that would have been created by\n\t * {@link #createDatabase()}.\n\t * @throws SystemException\n\t * \tif something is wrong with the database.\n\t * \tTODO: use a more specific exception.\n\t */\n\tpublic void checkDatabase()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"select count(*) from \").defineColumnInteger();\n\t\tboolean first = true;\n\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\n\t\t\tfinal Table table = (Table)i.next();\n\t\t\tbf.append(table.protectedID);\n\t\t}\n\t\t\n\t\tfinal Long testDate = new Long(System.currentTimeMillis());\n\t\t\n\t\tbf.append(\" where \");\n\t\tfirst = true;\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(\" and \");\n\n\t\t\tfinal Table table = (Table)i.next();\n\n\t\t\tfinal Column primaryKey = table.primaryKey;\n\t\t\tbf.append(table.protectedID).\n\t\t\t\tappend('.').\n\t\t\t\tappend(primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(Type.NOT_A_PK);\n\t\t\t\n\t\t\tfor(Iterator j = table.getColumns().iterator(); j.hasNext(); )\n\t\t\t{\n\t\t\t\tfinal Column column = (Column)j.next();\n\t\t\t\tbf.append(\" and \").\n\t\t\t\t\tappend(table.protectedID).\n\t\t\t\t\tappend('.').\n\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\tappend('=');\n\n\t\t\t\tif(column instanceof IntegerColumn)\n\t\t\t\t\tbf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1));\n\t\t\t\telse if(column instanceof DoubleColumn)\n\t\t\t\t\tbf.appendValue(column, new Double(2.2));\n\t\t\t\telse if(column instanceof StringColumn)\n\t\t\t\t\tbf.appendValue(column, \"z\");\n\t\t\t\telse if(column instanceof TimestampColumn)\n\t\t\t\t\tbf.appendValue(column, testDate);\n\t\t\t\telse\n\t\t\t\t\tthrow new RuntimeException(column.toString());\n\t\t\t}\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\t//System.out.println(\"checkDatabase:\"+bf.toString());\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//checkTableTime += amount;\n\t\t//System.out.println(\"CHECK TABLES \"+amount+\"ms accumulated \"+checkTableTime);\n\t}\n\n\tpublic void dropDatabase()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\t{\n\t\t\tfinal List types = Type.getTypes();\n\t\t\tfor(ListIterator i = types.listIterator(types.size()); i.hasPrevious(); )\n\t\t\t\t((Type)i.previous()).onDropTable();\n\t\t}\n\t\t{\n\t\t\tfinal List tables = Table.getTables();\n\t\t\t// must delete in reverse order, to obey integrity constraints\n\t\t\tfor(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); )\n\t\t\t\tdropForeignKeyConstraints((Table)i.previous());\n\t\t\tfor(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); )\n\t\t\t\tdropTable((Table)i.previous());\n\t\t}\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//dropTableTime += amount;\n\t\t//System.out.println(\"DROP TABLES \"+amount+\"ms accumulated \"+dropTableTime);\n\t}\n\t\n\tpublic void tearDownDatabase()\n\t{\n\t\tSystem.err.println(\"TEAR DOWN ALL DATABASE\");\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfinal Table table = (Table)i.next();\n\t\t\t\tSystem.err.print(\"DROPPING FOREIGN KEY CONSTRAINTS \"+table+\"... \");\n\t\t\t\tdropForeignKeyConstraints(table);\n\t\t\t\tSystem.err.println(\"done.\");\n\t\t\t}\n\t\t\tcatch(SystemException e2)\n\t\t\t{\n\t\t\t\tSystem.err.println(\"failed:\"+e2.getMessage());\n\t\t\t}\n\t\t}\n\t\tfor(Iterator i = Table.getTables().iterator(); i.hasNext(); )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfinal Table table = (Table)i.next();\n\t\t\t\tSystem.err.print(\"DROPPING TABLE \"+table+\" ... \");\n\t\t\t\tdropTable(table);\n\t\t\t\tSystem.err.println(\"done.\");\n\t\t\t}\n\t\t\tcatch(SystemException e2)\n\t\t\t{\n\t\t\t\tSystem.err.println(\"failed:\"+e2.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkEmptyTables()\n\t{\n\t\t//final long time = System.currentTimeMillis();\n\t\tfor(Iterator i = Type.getTypes().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Type type = (Type)i.next();\n\t\t\tfinal int count = countTable(type);\n\t\t\tif(count>0)\n\t\t\t\tthrow new RuntimeException(\"there are \"+count+\" items left for type \"+type); \n\t\t}\n\t\t//final long amount = (System.currentTimeMillis()-time);\n\t\t//checkEmptyTableTime += amount;\n\t\t//System.out.println(\"CHECK EMPTY TABLES \"+amount+\"ms accumulated \"+checkEmptyTableTime);\n\t}\n\t\n\tfinal IntArrayList search(final Query query)\n\t{\n\t\tfinal Table selectType = query.selectType.table; // TODO: rename to selectTable\n\t\tfinal Statement bf = createStatement();\n\n\t\tbf.append(\"select \").\n\t\t\tappend(selectType.protectedID).\n\t\t\tappend('.').\n\t\t\tappend(selectType.primaryKey.protectedID).defineColumnInteger().\n\t\t\tappend(\" from \");\n\n\t\tboolean first = true;\n\t\tfor(Iterator i = query.fromTypes.iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\n\t\t\tbf.append(((Type)i.next()).table.protectedID);\n\t\t}\n\n\t\tif(query.condition!=null)\n\t\t{\n\t\t\tbf.append(\" where \");\n\t\t\tquery.condition.appendStatement(bf);\n\t\t}\n\t\t\n\t\tif(query.orderBy!=null)\n\t\t{\n\t\t\tbf.append(\" order by \").\n\t\t\t\tappend(query.orderBy);\n\t\t\tif(!query.orderAscending)\n\t\t\t\tbf.append(\" desc\");\n\t\t}\n\t\t\n\t\t//System.out.println(\"searching \"+bf.toString());\n\t\ttry\n\t\t{\n\t\t\tfinal QueryResultSetHandler handler = new QueryResultSetHandler(query.start, query.count);\n\t\t\texecuteSQL(bf, handler);\n\t\t\treturn handler.result;\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\n\tvoid load(final Row row)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"select \");\n\n\t\tboolean first = true;\n\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t{\n\t\t\tfinal Table table = type.table;\n\t\t\tfinal List columns = table.getColumns();\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tif(first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tbf.append(',');\n\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tbf.append(table.protectedID).\n\t\t\t\t\tappend('.').\n\t\t\t\t\tappend(column.protectedID).defineColumn(column);\n\t\t\t}\n\t\t}\n\n\t\tbf.append(\" from \");\n\t\tfirst = true;\n\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\n\t\t\tbf.append(type.table.protectedID);\n\t\t}\n\t\t\t\n\t\tbf.append(\" where \");\n\t\tfirst = true;\n\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t{\n\t\t\tif(first)\n\t\t\t\tfirst = false;\n\t\t\telse\n\t\t\t\tbf.append(\" and \");\n\n\t\t\tfinal Table table = type.table;\n\t\t\tbf.append(table.protectedID).\n\t\t\t\tappend('.').\n\t\t\t\tappend(table.primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(row.pk);\n\t\t}\n\n\t\t//System.out.println(\"loading \"+bf.toString());\n\t\ttry\n\t\t{\n\t\t\texecuteSQL(bf, new LoadResultSetHandler(row));\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\n\tvoid store(final Row row)\n\t\t\tthrows UniqueViolationException\n\t{\n\t\tstore(row, row.type);\n\t}\n\n\tprivate void store(final Row row, final Type theType) // TODO: rename to type\n\t\t\tthrows UniqueViolationException\n\t{\n\t\tfinal Type supertype = theType.getSupertype();\n\t\tif(supertype!=null)\n\t\t\tstore(row, supertype);\n\t\t\t\n\t\tfinal Table type = theType.table; // TODO: rename to table\n\n\t\tfinal List columns = type.getColumns();\n\n\t\tfinal Statement bf = createStatement();\n\t\tif(row.present)\n\t\t{\n\t\t\tbf.append(\"update \").\n\t\t\t\tappend(type.protectedID).\n\t\t\t\tappend(\" set \");\n\n\t\t\tboolean first = true;\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tif(first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tbf.append(',');\n\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tbf.append(column.protectedID).\n\t\t\t\t\tappend('=');\n\n\t\t\t\tfinal Object value = row.store(column);\n\t\t\t\tbf.append(column.cacheToDatabase(value));\n\t\t\t}\n\t\t\tbf.append(\" where \").\n\t\t\t\tappend(type.primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(row.pk);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbf.append(\"insert into \").\n\t\t\t\tappend(type.protectedID).\n\t\t\t\tappend(\"(\").\n\t\t\t\tappend(type.primaryKey.protectedID);\n\n\t\t\tboolean first = true;\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tbf.append(',');\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tbf.append(column.protectedID);\n\t\t\t}\n\n\t\t\tbf.append(\")values(\").\n\t\t\t\tappend(row.pk);\n\t\t\tfor(Iterator i = columns.iterator(); i.hasNext(); )\n\t\t\t{\n\t\t\t\tbf.append(',');\n\t\t\t\tfinal Column column = (Column)i.next();\n\t\t\t\tfinal Object value = row.store(column);\n\t\t\t\tbf.append(column.cacheToDatabase(value));\n\t\t\t}\n\t\t\tbf.append(')');\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//System.out.println(\"storing \"+bf.toString());\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(UniqueViolationException e)\n\t\t{\n\t\t\tthrow e;\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\n\tvoid delete(final Type type, final int pk)\n\t\t\tthrows IntegrityViolationException\n\t{\n\t\tfor(Type currentType = type; currentType!=null; currentType = currentType.getSupertype())\n\t\t{\n\t\t\tfinal Table currentTable = currentType.table;\n\t\t\tfinal Statement bf = createStatement();\n\t\t\tbf.append(\"delete from \").\n\t\t\t\tappend(currentTable.protectedID).\n\t\t\t\tappend(\" where \").\n\t\t\t\tappend(currentTable.primaryKey.protectedID).\n\t\t\t\tappend('=').\n\t\t\t\tappend(pk);\n\n\t\t\t//System.out.println(\"deleting \"+bf.toString());\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t\t}\n\t\t\tcatch(IntegrityViolationException e)\n\t\t\t{\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tcatch(ConstraintViolationException e)\n\t\t\t{\n\t\t\t\tthrow new SystemException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static interface ResultSetHandler\n\t{\n\t\tpublic void run(ResultSet resultSet) throws SQLException;\n\t}\n\n\tprivate static final ResultSetHandler EMPTY_RESULT_SET_HANDLER = new ResultSetHandler()\n\t{\n\t\tpublic void run(ResultSet resultSet)\n\t\t{\n\t\t}\n\t};\n\t\t\n\tprivate static class QueryResultSetHandler implements ResultSetHandler\n\t{\n\t\tprivate final int start;\n\t\tprivate final int count;\n\t\tprivate final IntArrayList result = new IntArrayList();\n\t\t\n\t\tQueryResultSetHandler(final int start, final int count)\n\t\t{\n\t\t\tthis.start = start;\n\t\t\tthis.count = count;\n\t\t\tif(start<0)\n\t\t\t\tthrow new RuntimeException();\n\t\t}\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(start>0)\n\t\t\t{\n\t\t\t\t// TODO: ResultSet.relative\n\t\t\t\t// Would like to use\n\t\t\t\t// resultSet.relative(start+1);\n\t\t\t\t// but this throws a java.sql.SQLException:\n\t\t\t\t// Invalid operation for forward only resultset : relative\n\t\t\t\tfor(int i = start; i>0; i--)\n\t\t\t\t\tresultSet.next();\n\t\t\t}\n\t\t\t\t\n\t\t\tint i = (count>=0 ? count : Integer.MAX_VALUE);\n\n\t\t\twhile(resultSet.next() && (--i)>=0)\n\t\t\t{\n\t\t\t\tfinal int pk = resultSet.getInt(1);\n\t\t\t\t//System.out.println(\"pk:\"+pk);\n\t\t\t\tresult.add(pk);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static class LoadResultSetHandler implements ResultSetHandler\n\t{\n\t\tprivate final Row row;\n\n\t\tLoadResultSetHandler(final Row row)\n\t\t{\n\t\t\tthis.row = row;\n\t\t}\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(!resultSet.next())\n\t\t\t\tthrow new RuntimeException(\"no such pk\"); // TODO use some better exception\n\t\t\tint columnIndex = 1;\n\t\t\tfor(Type type = row.type; type!=null; type = type.getSupertype())\n\t\t\t{\n\t\t\t\tfor(Iterator i = type.table.getColumns().iterator(); i.hasNext(); )\n\t\t\t\t\t((Column)i.next()).load(resultSet, columnIndex++, row);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tprivate final static int convertSQLResult(final Object sqlInteger)\n\t{\n\t\t// IMPLEMENTATION NOTE for Oracle\n\t\t// Whether the returned object is an Integer or a BigDecimal,\n\t\t// depends on whether OracleStatement.defineColumnType is used or not,\n\t\t// so we support both here.\n\t\tif(sqlInteger instanceof BigDecimal)\n\t\t\treturn ((BigDecimal)sqlInteger).intValue();\n\t\telse\n\t\t\treturn ((Integer)sqlInteger).intValue();\n\t}\n\n\tprivate static class IntegerResultSetHandler implements ResultSetHandler\n\t{\n\t\tint result;\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(!resultSet.next())\n\t\t\t\tthrow new RuntimeException();\n\n\t\t\tresult = convertSQLResult(resultSet.getObject(1));\n\t\t}\n\t}\n\n\tprivate static class NextPKResultSetHandler implements ResultSetHandler\n\t{\n\t\tint resultLo;\n\t\tint resultHi;\n\n\t\tpublic void run(ResultSet resultSet) throws SQLException\n\t\t{\n\t\t\tif(!resultSet.next())\n\t\t\t\tthrow new RuntimeException();\n\t\t\tfinal Object oLo = resultSet.getObject(1);\n\t\t\tif(oLo==null)\n\t\t\t{\n\t\t\t\tresultLo = -1;\n\t\t\t\tresultHi = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tresultLo = convertSQLResult(oLo)-1;\n\t\t\t\tfinal Object oHi = resultSet.getObject(2);\n\t\t\t\tresultHi = convertSQLResult(oHi)+1;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//private static int timeExecuteQuery = 0;\n\n\tprivate void executeSQL(final Statement statement, final ResultSetHandler resultSetHandler)\n\t\t\tthrows ConstraintViolationException\n\t{\n\t\tfinal ConnectionPool connectionPool = ConnectionPool.getInstance();\n\t\t\n\t\tConnection connection = null;\n\t\tjava.sql.Statement sqlStatement = null;\n\t\tResultSet resultSet = null;\n\t\ttry\n\t\t{\n\t\t\tconnection = connectionPool.getConnection();\n\t\t\t// TODO: use prepared statements and reuse the statement.\n\t\t\tsqlStatement = connection.createStatement();\n\t\t\tfinal String sqlText = statement.getText();\n\t\t\tif(!sqlText.startsWith(\"select \"))\n\t\t\t{\n\t\t\t\tfinal int rows = sqlStatement.executeUpdate(sqlText);\n\t\t\t\t//System.out.println(\"(\"+rows+\"): \"+statement.getText());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//long time = System.currentTimeMillis();\n\t\t\t\tif(useDefineColumnTypes)\n\t\t\t\t\t((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement);\n\t\t\t\tresultSet = sqlStatement.executeQuery(sqlText);\n\t\t\t\t//long interval = System.currentTimeMillis() - time;\n\t\t\t\t//timeExecuteQuery += interval;\n\t\t\t\t//System.out.println(\"executeQuery: \"+interval+\"ms sum \"+timeExecuteQuery+\"ms\");\n\t\t\t\tresultSetHandler.run(resultSet);\n\t\t\t}\n\t\t}\n\t\tcatch(SQLException e)\n\t\t{\n\t\t\tfinal ConstraintViolationException wrappedException = wrapException(e);\n\t\t\tif(wrappedException!=null)\n\t\t\t\tthrow wrappedException;\n\t\t\telse\n\t\t\t\tthrow new SystemException(e, statement.toString());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tif(resultSet!=null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tresultSet.close();\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e)\n\t\t\t\t{\n\t\t\t\t\t// exception is already thrown\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(sqlStatement!=null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tsqlStatement.close();\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e)\n\t\t\t\t{\n\t\t\t\t\t// exception is already thrown\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(connection!=null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tconnectionPool.putConnection(connection);\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e)\n\t\t\t\t{\n\t\t\t\t\t// exception is already thrown\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected abstract String extractUniqueConstraintName(SQLException e);\n\tprotected abstract String extractIntegrityConstraintName(SQLException e);\n\n\tprivate final ConstraintViolationException wrapException(final SQLException e)\n\t{\n\t\t{\t\t\n\t\t\tfinal String uniqueConstraintID = extractUniqueConstraintName(e);\n\t\t\tif(uniqueConstraintID!=null)\n\t\t\t{\n\t\t\t\tfinal UniqueConstraint constraint = UniqueConstraint.findByID(uniqueConstraintID, e);\n\t\t\t\treturn new UniqueViolationException(e, null, constraint);\n\t\t\t}\n\t\t}\n\t\t{\t\t\n\t\t\tfinal String integrityConstraintName = extractIntegrityConstraintName(e);\n\t\t\tif(integrityConstraintName!=null)\n\t\t\t{\n\t\t\t\tfinal ItemAttribute attribute = ItemAttribute.getItemAttributeByIntegrityConstraintName(integrityConstraintName, e);\n\t\t\t\treturn new IntegrityViolationException(e, null, attribute);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected static final String trimString(final String longString, final int maxLength)\n\t{\n\t\tif(maxLength<=0)\n\t\t\tthrow new RuntimeException(\"maxLength must be greater zero\");\n\t\tif(longString.length()==0)\n\t\t\tthrow new RuntimeException(\"longString must not be empty\");\n\n\t\tif(longString.length()<=maxLength)\n\t\t\treturn longString;\n\n\t\tint longStringLength = longString.length();\n\t\tfinal int[] trimPotential = new int[maxLength];\n\t\tfinal ArrayList words = new ArrayList();\n\t\t{\n\t\t\tfinal StringBuffer buf = new StringBuffer();\n\t\t\tfor(int i=0; i0)\n\t\t\t\t{\n\t\t\t\t\twords.add(buf.toString());\n\t\t\t\t\tint potential = 1;\n\t\t\t\t\tfor(int j = buf.length()-1; j>=0; j--, potential++)\n\t\t\t\t\t\ttrimPotential[j] += potential; \n\t\t\t\t\tbuf.setLength(0);\n\t\t\t\t}\n\t\t\t\tif(buf.length()0)\n\t\t\t{\n\t\t\t\twords.add(buf.toString());\n\t\t\t\tint potential = 1;\n\t\t\t\tfor(int j = buf.length()-1; j>=0; j--, potential++)\n\t\t\t\t\ttrimPotential[j] += potential; \n\t\t\t\tbuf.setLength(0);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfinal int expectedTrimPotential = longStringLength - maxLength;\n\t\t//System.out.println(\"expected trim potential = \"+expectedTrimPotential);\n\n\t\tint wordLength;\n\t\tint remainder = 0;\n\t\tfor(wordLength = trimPotential.length-1; wordLength>=0; wordLength--)\n\t\t{\n\t\t\t//System.out.println(\"trim potential [\"+wordLength+\"] = \"+trimPotential[wordLength]);\n\t\t\tremainder = trimPotential[wordLength] - expectedTrimPotential;\n\t\t\tif(remainder>=0)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tfinal StringBuffer result = new StringBuffer(longStringLength);\n\t\tfor(Iterator i = words.iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal String word = (String)i.next();\n\t\t\t//System.out.println(\"word \"+word+\" remainder:\"+remainder);\n\t\t\tif((word.length()>wordLength) && remainder>0)\n\t\t\t{\n\t\t\t\tresult.append(word.substring(0, wordLength+1));\n\t\t\t\tremainder--;\n\t\t\t}\n\t\t\telse if(word.length()>wordLength)\n\t\t\t\tresult.append(word.substring(0, wordLength));\n\t\t\telse\n\t\t\t\tresult.append(word);\n\t\t}\n\t\t//System.out.println(\"---- trimName(\"+longString+\",\"+maxLength+\") == \"+result+\" --- \"+words);\n\n\t\tif(result.length()!=maxLength)\n\t\t\tthrow new RuntimeException(result.toString()+maxLength);\n\n\t\treturn result.toString();\n\t}\n\t\n\tString trimName(final Type type)\n\t{\n\t\tfinal String className = type.getJavaClass().getName();\n\t\tfinal int pos = className.lastIndexOf('.');\n\t\treturn trimString(className.substring(pos+1), 25);\n\t}\n\t\n\t/**\n\t * Trims a name to length for being be a suitable qualifier for database entities,\n\t * such as tables, columns, indexes, constraints, partitions etc.\n\t */\n\tString trimName(final String longName)\n\t{\n\t\treturn trimString(longName, 25);\n\t}\n\n\t/**\n\t * Protects a database name from being interpreted as a SQL keyword.\n\t * This is usually done by enclosing the name with some (database specific) delimiters.\n\t * The default implementation uses double quotes as delimiter.\n\t */\n\tprotected String protectName(String name)\n\t{\n\t\treturn '\"' + name + '\"';\n\t}\n\n\tabstract String getIntegerType(int precision);\n\tabstract String getDoubleType(int precision);\n\tabstract String getStringType(int maxLength);\n\tabstract String getDateTimestampType();\n\t\n\tprivate void createTable(final Table table)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"create table \").\n\t\t\tappend(table.protectedID).\n\t\t\tappend('(');\n\n\t\tboolean firstColumn = true;\n\t\tfor(Iterator i = table.getAllColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tif(firstColumn)\n\t\t\t\tfirstColumn = false;\n\t\t\telse\n\t\t\t\tbf.append(',');\n\t\t\t\n\t\t\tfinal Column column = (Column)i.next();\n\t\t\tbf.append(column.protectedID).\n\t\t\t\tappend(' ').\n\t\t\t\tappend(column.databaseType);\n\n\t\t\tif(column.primaryKey)\n\t\t\t{\n\t\t\t\tbf.append(\" primary key\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(column.notNull)\n\t\t\t\t\tbf.append(\" not null\");\n\t\t\t}\n\t\t}\n\t\t\n\t\t// attribute constraints\t\t\n\t\tfor(Iterator i = table.getColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Column column = (Column)i.next();\n\n\t\t\tif(column instanceof StringColumn)\n\t\t\t{\n\t\t\t\tfinal StringColumn stringColumn = (StringColumn)column;\n\t\t\t\tif(stringColumn.minimumLengthID!=null)\n\t\t\t\t{\n\t\t\t\t\tbf.append(\",constraint \").\n\t\t\t\t\t\tappend(protectName(stringColumn.minimumLengthID)).\n\t\t\t\t\t\tappend(\" check(length(\").\n\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\tappend(\")>=\").\n\t\t\t\t\t\tappend(stringColumn.minimumLength);\n\n\t\t\t\t\tif(!column.notNull)\n\t\t\t\t\t{\n\t\t\t\t\t\tbf.append(\" or \").\n\t\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\t\tappend(\" is null\");\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\t\t\t\t}\n\t\t\t\tif(stringColumn.maximumLengthID!=null)\n\t\t\t\t{\n\t\t\t\t\tbf.append(\",constraint \").\n\t\t\t\t\t\tappend(protectName(stringColumn.maximumLengthID)).\n\t\t\t\t\t\tappend(\" check(length(\").\n\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\tappend(\")<=\").\n\t\t\t\t\t\tappend(stringColumn.maximumLength);\n\n\t\t\t\t\tif(!column.notNull)\n\t\t\t\t\t{\n\t\t\t\t\t\tbf.append(\" or \").\n\t\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\t\tappend(\" is null\");\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(column instanceof IntegerColumn)\n\t\t\t{\n\t\t\t\tfinal IntegerColumn intColumn = (IntegerColumn)column;\n\t\t\t\tfinal int[] allowedValues = intColumn.allowedValues;\n\t\t\t\tif(allowedValues!=null)\n\t\t\t\t{\n\t\t\t\t\tbf.append(\",constraint \").\n\t\t\t\t\t\tappend(protectName(intColumn.allowedValuesID)).\n\t\t\t\t\t\tappend(\" check(\").\n\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\tappend(\" in (\");\n\n\t\t\t\t\tfor(int j = 0; j0)\n\t\t\t\t\t\t\tbf.append(',');\n\t\t\t\t\t\tbf.append(allowedValues[j]);\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\n\t\t\t\t\tif(!column.notNull)\n\t\t\t\t\t{\n\t\t\t\t\t\tbf.append(\" or \").\n\t\t\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\t\t\tappend(\" is null\");\n\t\t\t\t\t}\n\t\t\t\t\tbf.append(')');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor(Iterator i = table.getUniqueConstraints().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal UniqueConstraint uniqueConstraint = (UniqueConstraint)i.next();\n\t\t\tbf.append(\",constraint \").\n\t\t\t\tappend(uniqueConstraint.getProtectedID()).\n\t\t\t\tappend(\" unique(\");\n\t\t\tboolean first = true;\n\t\t\tfor(Iterator j = uniqueConstraint.getUniqueAttributes().iterator(); j.hasNext(); )\n\t\t\t{\n\t\t\t\tif(first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tbf.append(',');\n\t\t\t\tfinal Attribute uniqueAttribute = (Attribute)j.next();\n\t\t\t\tbf.append(uniqueAttribute.getMainColumn().protectedID);\n\t\t\t}\n\t\t\tbf.append(')');\n\t\t}\n\t\t\n\t\tbf.append(')');\n\n\t\ttry\n\t\t{\n\t\t\t//System.out.println(\"createTable:\"+bf.toString());\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate void createForeignKeyConstraints(final Table type) // TODO: rename to table\n\t{\n\t\t//System.out.println(\"createForeignKeyConstraints:\"+bf);\n\n\t\tfor(Iterator i = type.getAllColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Column column = (Column)i.next();\n\t\t\t//System.out.println(\"createForeignKeyConstraints(\"+column+\"):\"+bf);\n\t\t\tif(column instanceof ItemColumn)\n\t\t\t{\n\t\t\t\tfinal ItemColumn itemColumn = (ItemColumn)column;\n\t\t\t\tfinal Statement bf = createStatement();\n\t\t\t\tbf.append(\"alter table \").\n\t\t\t\t\tappend(type.protectedID).\n\t\t\t\t\tappend(\" add constraint \").\n\t\t\t\t\tappend(Database.theInstance.protectName(itemColumn.integrityConstraintName)).\n\t\t\t\t\tappend(\" foreign key (\").\n\t\t\t\t\tappend(column.protectedID).\n\t\t\t\t\tappend(\") references \").\n\t\t\t\t\tappend(itemColumn.getForeignTableNameProtected());\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t//System.out.println(\"createForeignKeyConstraints:\"+bf);\n\t\t\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t\t\t}\n\t\t\t\tcatch(ConstraintViolationException e)\n\t\t\t\t{\n\t\t\t\t\tthrow new SystemException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void createMediaDirectories(final Type type)\n\t{\n\t\tFile typeDirectory = null;\n\n\t\tfor(Iterator i = type.getAttributes().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Attribute attribute = (Attribute)i.next();\n\t\t\tif(attribute instanceof MediaAttribute)\n\t\t\t{\n\t\t\t\tif(typeDirectory==null)\n\t\t\t\t{\n\t\t\t\t\tfinal File directory = Properties.getInstance().getMediaDirectory();\n\t\t\t\t\ttypeDirectory = new File(directory, type.id);\n\t\t\t\t\ttypeDirectory.mkdir();\n\t\t\t\t}\n\t\t\t\tfinal File attributeDirectory = new File(typeDirectory, attribute.getName());\n\t\t\t\tattributeDirectory.mkdir();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void dropTable(final Table type) // TODO: rename to table\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"drop table \").\n\t\t\tappend(type.protectedID);\n\n\t\ttry\n\t\t{\n\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate int countTable(final Type type)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tbf.append(\"select count(*) from \").defineColumnInteger().\n\t\t\tappend(type.table.protectedID);\n\n\t\ttry\n\t\t{\n\t\t\tfinal IntegerResultSetHandler handler = new IntegerResultSetHandler();\n\t\t\texecuteSQL(bf, handler);\n\t\t\treturn handler.result;\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n\tprivate void dropForeignKeyConstraints(final Table type) // TODO: rename to table\n\t{\n\t\tfor(Iterator i = type.getColumns().iterator(); i.hasNext(); )\n\t\t{\n\t\t\tfinal Column column = (Column)i.next();\n\t\t\t//System.out.println(\"dropForeignKeyConstraints(\"+column+\")\");\n\t\t\tif(column instanceof ItemColumn)\n\t\t\t{\n\t\t\t\tfinal ItemColumn itemColumn = (ItemColumn)column;\n\t\t\t\tfinal Statement bf = createStatement();\n\t\t\t\tboolean hasOne = false;\n\n\t\t\t\tbf.append(\"alter table \").\n\t\t\t\t\tappend(type.protectedID).\n\t\t\t\t\tappend(\" drop constraint \").\n\t\t\t\t\tappend(Database.theInstance.protectName(itemColumn.integrityConstraintName));\n\n\t\t\t\t//System.out.println(\"dropForeignKeyConstraints:\"+bf);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\texecuteSQL(bf, EMPTY_RESULT_SET_HANDLER);\n\t\t\t\t}\n\t\t\t\tcatch(ConstraintViolationException e)\n\t\t\t\t{\n\t\t\t\t\tthrow new SystemException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint[] getNextPK(final Type type)\n\t{\n\t\tfinal Statement bf = createStatement();\n\t\tfinal Table table = type.table;\n\t\tfinal String primaryKeyProtectedID = table.primaryKey.protectedID;\n\t\tbf.append(\"select min(\").\n\t\t\tappend(primaryKeyProtectedID).defineColumnInteger().\n\t\t\tappend(\"),max(\").\n\t\t\tappend(primaryKeyProtectedID).defineColumnInteger().\n\t\t\tappend(\") from \").\n\t\t\tappend(table.protectedID);\n\t\t\t\n\t\ttry\n\t\t{\n\t\t\tfinal NextPKResultSetHandler handler = new NextPKResultSetHandler();\n\t\t\texecuteSQL(bf, handler);\n\t\t\t//System.err.println(\"select max(\"+type.primaryKey.trimmedName+\") from \"+type.trimmedName+\" : \"+handler.result);\n\t\t\treturn new int[] {handler.resultLo, handler.resultHi};\n\t\t}\n\t\tcatch(ConstraintViolationException e)\n\t\t{\n\t\t\tthrow new SystemException(e);\n\t\t}\n\t}\n\t\n}\n"},"message":{"kind":"string","value":"rename selectType to selectTable\n\n\ngit-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@1091 e7d4fc99-c606-0410-b9bf-843393a9eab7\n"},"old_file":{"kind":"string","value":"lib/src/com/exedio/cope/lib/Database.java"},"subject":{"kind":"string","value":"rename selectType to selectTable"}}},{"rowIdx":1284,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"68014bf3b3a0027b5fde22c7d2a194af60dd01fa"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ImmobilienScout24/deadcode4j"},"new_contents":{"kind":"string","value":"package de.is24.deadcode4j.analyzer.webxml;\n\nimport de.is24.deadcode4j.AnalysisContext;\nimport de.is24.deadcode4j.analyzer.XmlAnalyzer;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.helpers.DefaultHandler;\n\nimport javax.annotation.Nonnull;\nimport java.util.*;\n\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static com.google.common.collect.Iterables.elementsEqual;\nimport static java.util.Arrays.asList;\n\n/**\n * Parses {@code web.xml} and translates XML events into {@code web.xml}\n * specific events that can be consumed by a {@link WebXmlHandler}. It only\n * creates events for {@code web.xml} nodes that are needed by existing\n * {@link de.is24.deadcode4j.Analyzer}s. Please add further events if needed.\n *\n * @since 2.1.0\n */\npublic abstract class BaseWebXmlAnalyzer extends XmlAnalyzer {\n protected BaseWebXmlAnalyzer() {\n super(\"web.xml\");\n }\n\n /**\n * This method is called to provide a WebXmlHandler for each file being processed.\n */\n @Nonnull\n protected abstract WebXmlHandler createWebXmlHandlerFor(@Nonnull AnalysisContext analysisContext);\n\n @Nonnull\n @Override\n protected DefaultHandler createHandlerFor(@Nonnull AnalysisContext analysisContext) {\n WebXmlHandler webXmlHandler = createWebXmlHandlerFor(analysisContext);\n return new WebXmlAdapter(webXmlHandler);\n }\n\n // Translates XML events into web.xml events that can be consumed by a WebXmlHandler\n private static class WebXmlAdapter extends DefaultHandler {\n @SuppressWarnings(\"unchecked\")\n static final Collection> NODES_WITH_TEXT = asList(\n asList(\"web-app\", \"context-param\", \"param-name\"),\n asList(\"web-app\", \"context-param\", \"param-value\"),\n asList(\"web-app\", \"filter\", \"filter-class\"),\n asList(\"web-app\", \"filter\", \"init-param\", \"param-name\"),\n asList(\"web-app\", \"filter\", \"init-param\", \"param-value\"),\n asList(\"web-app\", \"listener\", \"listener-class\"),\n asList(\"web-app\", \"servlet\", \"servlet-class\"),\n asList(\"web-app\", \"servlet\", \"init-param\", \"param-name\"),\n asList(\"web-app\", \"servlet\", \"init-param\", \"param-value\"));\n static final Collection CONTEXT_PARAM_PATH = asList(\"web-app\", \"context-param\");\n static final Collection FILTER_PATH = asList(\"web-app\", \"filter\");\n static final Collection FILTER_INIT_PARAM_PATH = asList(\"web-app\", \"filter\", \"init-param\");\n static final Collection LISTENER_PATH = asList(\"web-app\", \"listener\");\n static final Collection SERVLET_INIT_PARAM_PATH = asList(\"web-app\", \"servlet\", \"init-param\");\n static final Collection SERVLET_PATH = asList(\"web-app\", \"servlet\");\n\n final Deque deque = new ArrayDeque();\n final List initParams = new ArrayList();\n final Map texts = new HashMap();\n StringBuilder buffer;\n final WebXmlHandler webXmlHandler;\n\n WebXmlAdapter(WebXmlHandler webXmlHandler) {\n this.webXmlHandler = webXmlHandler;\n }\n\n @Override\n public void startElement(String uri, String localName, String qName, Attributes attributes) {\n deque.add(localName);\n if (isNodeWithText()) {\n buffer = new StringBuilder(128);\n }\n }\n\n @Override\n public void characters(char[] ch, int start, int length) {\n if (isNodeWithText()) {\n buffer.append(new String(ch, start, length).trim());\n }\n }\n\n @Override\n public void endElement(String uri, String localName, String qName) {\n if (isNodeWithText()) {\n storeCharacters(localName);\n } else if (matchesPath(CONTEXT_PARAM_PATH)) {\n reportContextParam();\n } else if (matchesPath(FILTER_INIT_PARAM_PATH)) {\n storeInitParam();\n } else if (matchesPath(FILTER_PATH)) {\n reportFilter();\n } else if (matchesPath(LISTENER_PATH)) {\n reportListener();\n } else if (matchesPath(SERVLET_INIT_PARAM_PATH)) {\n storeInitParam();\n } else if (matchesPath(SERVLET_PATH)) {\n reportServlet();\n }\n deque.removeLast();\n }\n\n boolean isNodeWithText() {\n for (List candidate : NODES_WITH_TEXT) {\n if (matchesPath(candidate)) {\n return true;\n }\n }\n return false;\n }\n\n void reportContextParam() {\n webXmlHandler.contextParam(createParam());\n }\n\n void storeInitParam() {\n initParams.add(createParam());\n }\n\n Param createParam() {\n return new Param(getText(\"param-name\"), getText(\"param-value\"));\n }\n\n void reportFilter() {\n webXmlHandler.filter(\n getText(\"filter-class\"),\n new ArrayList(initParams));\n initParams.clear();\n }\n\n void reportListener() {\n webXmlHandler.listener(getText(\"listener-class\"));\n }\n\n void reportServlet() {\n webXmlHandler.servlet(\n getText(\"servlet-class\"),\n new ArrayList(initParams));\n initParams.clear();\n }\n\n boolean matchesPath(Collection path) {\n return path.size() == deque.size() && elementsEqual(path, deque);\n }\n\n void storeCharacters(String localName) {\n texts.put(localName, buffer.toString());\n }\n\n String getText(String localName) {\n String text = texts.remove(localName);\n return nullToEmpty(text);\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/de/is24/deadcode4j/analyzer/webxml/BaseWebXmlAnalyzer.java"},"old_contents":{"kind":"string","value":"package de.is24.deadcode4j.analyzer.webxml;\n\nimport de.is24.deadcode4j.AnalysisContext;\nimport de.is24.deadcode4j.analyzer.XmlAnalyzer;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.helpers.DefaultHandler;\n\nimport javax.annotation.Nonnull;\nimport java.util.*;\n\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static com.google.common.collect.Iterables.elementsEqual;\nimport static java.util.Arrays.asList;\n\n/**\n * Parses {@code web.xml} and translates XML events into {@code web.xml}\n * specific events that can be consumed by a {@link WebXmlHandler}. It only\n * creates events for {@code web.xml} nodes that are needed by existing\n * {@link de.is24.deadcode4j.Analyzer}s. Please add further events if needed.\n *\n * @since 2.1.0\n */\npublic abstract class BaseWebXmlAnalyzer extends XmlAnalyzer {\n protected BaseWebXmlAnalyzer() {\n super(\"web.xml\");\n }\n\n /**\n * This method is called to provide a WebXmlHandler for each file being processed.\n */\n @Nonnull\n protected abstract WebXmlHandler createWebXmlHandlerFor(@Nonnull AnalysisContext analysisContext);\n\n @Nonnull\n @Override\n protected DefaultHandler createHandlerFor(@Nonnull AnalysisContext analysisContext) {\n WebXmlHandler webXmlHandler = createWebXmlHandlerFor(analysisContext);\n return new WebXmlAdapter(webXmlHandler);\n }\n\n // Translates XML events into web.xml events that can be consumed by a WebXmlHandler\n private static class WebXmlAdapter extends DefaultHandler {\n static final Collection> NODES_WITH_TEXT = asList(\n asList(\"web-app\", \"context-param\", \"param-name\"),\n asList(\"web-app\", \"context-param\", \"param-value\"),\n asList(\"web-app\", \"filter\", \"filter-class\"),\n asList(\"web-app\", \"filter\", \"init-param\", \"param-name\"),\n asList(\"web-app\", \"filter\", \"init-param\", \"param-value\"),\n asList(\"web-app\", \"listener\", \"listener-class\"),\n asList(\"web-app\", \"servlet\", \"servlet-class\"),\n asList(\"web-app\", \"servlet\", \"init-param\", \"param-name\"),\n asList(\"web-app\", \"servlet\", \"init-param\", \"param-value\"));\n static final Collection CONTEXT_PARAM_PATH = asList(\"web-app\", \"context-param\");\n static final Collection FILTER_PATH = asList(\"web-app\", \"filter\");\n static final Collection FILTER_INIT_PARAM_PATH = asList(\"web-app\", \"filter\", \"init-param\");\n static final Collection LISTENER_PATH = asList(\"web-app\", \"listener\");\n static final Collection SERVLET_INIT_PARAM_PATH = asList(\"web-app\", \"servlet\", \"init-param\");\n static final Collection SERVLET_PATH = asList(\"web-app\", \"servlet\");\n\n final Deque deque = new ArrayDeque();\n final List initParams = new ArrayList();\n final Map texts = new HashMap();\n StringBuilder buffer;\n final WebXmlHandler webXmlHandler;\n\n WebXmlAdapter(WebXmlHandler webXmlHandler) {\n this.webXmlHandler = webXmlHandler;\n }\n\n @Override\n public void startElement(String uri, String localName, String qName, Attributes attributes) {\n deque.add(localName);\n if (isNodeWithText()) {\n buffer = new StringBuilder(128);\n }\n }\n\n @Override\n public void characters(char[] ch, int start, int length) {\n if (isNodeWithText()) {\n buffer.append(new String(ch, start, length).trim());\n }\n }\n\n @Override\n public void endElement(String uri, String localName, String qName) {\n if (isNodeWithText()) {\n storeCharacters(localName);\n } else if (matchesPath(CONTEXT_PARAM_PATH)) {\n reportContextParam();\n } else if (matchesPath(FILTER_INIT_PARAM_PATH)) {\n storeInitParam();\n } else if (matchesPath(FILTER_PATH)) {\n reportFilter();\n } else if (matchesPath(LISTENER_PATH)) {\n reportListener();\n } else if (matchesPath(SERVLET_INIT_PARAM_PATH)) {\n storeInitParam();\n } else if (matchesPath(SERVLET_PATH)) {\n reportServlet();\n }\n deque.removeLast();\n }\n\n boolean isNodeWithText() {\n for (List candidate : NODES_WITH_TEXT) {\n if (matchesPath(candidate)) {\n return true;\n }\n }\n return false;\n }\n\n void reportContextParam() {\n webXmlHandler.contextParam(createParam());\n }\n\n void storeInitParam() {\n initParams.add(createParam());\n }\n\n Param createParam() {\n return new Param(getText(\"param-name\"), getText(\"param-value\"));\n }\n\n void reportFilter() {\n webXmlHandler.filter(\n getText(\"filter-class\"),\n new ArrayList(initParams));\n initParams.clear();\n }\n\n void reportListener() {\n webXmlHandler.listener(getText(\"listener-class\"));\n }\n\n void reportServlet() {\n webXmlHandler.servlet(\n getText(\"servlet-class\"),\n new ArrayList(initParams));\n initParams.clear();\n }\n\n boolean matchesPath(Collection path) {\n return path.size() == deque.size() && elementsEqual(path, deque);\n }\n\n void storeCharacters(String localName) {\n texts.put(localName, buffer.toString());\n }\n\n String getText(String localName) {\n String text = texts.remove(localName);\n return nullToEmpty(text);\n }\n }\n}\n"},"message":{"kind":"string","value":"suppress unchecked warning\n"},"old_file":{"kind":"string","value":"src/main/java/de/is24/deadcode4j/analyzer/webxml/BaseWebXmlAnalyzer.java"},"subject":{"kind":"string","value":"suppress unchecked warning"}}},{"rowIdx":1285,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24e296b86971d8e075cba241bbb44fe6f76b472a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sdnwiselab/onos,mengmoya/onos,opennetworkinglab/onos,osinstom/onos,LorenzReinhart/ONOSnew,osinstom/onos,maheshraju-Huawei/actn,opennetworkinglab/onos,VinodKumarS-Huawei/ietf96yang,VinodKumarS-Huawei/ietf96yang,sonu283304/onos,maheshraju-Huawei/actn,y-higuchi/onos,kuujo/onos,sdnwiselab/onos,y-higuchi/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,kuujo/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,opennetworkinglab/onos,sdnwiselab/onos,Shashikanth-Huawei/bmp,lsinfo3/onos,kuujo/onos,kuujo/onos,oplinkoms/onos,mengmoya/onos,lsinfo3/onos,kuujo/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,donNewtonAlpha/onos,donNewtonAlpha/onos,sdnwiselab/onos,mengmoya/onos,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,sonu283304/onos,donNewtonAlpha/onos,oplinkoms/onos,gkatsikas/onos,donNewtonAlpha/onos,gkatsikas/onos,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,mengmoya/onos,y-higuchi/onos,kuujo/onos,osinstom/onos,lsinfo3/onos,Shashikanth-Huawei/bmp,sonu283304/onos,sdnwiselab/onos,osinstom/onos,sonu283304/onos,LorenzReinhart/ONOSnew,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,oplinkoms/onos,oplinkoms/onos,oplinkoms/onos,osinstom/onos,kuujo/onos,opennetworkinglab/onos,y-higuchi/onos,gkatsikas/onos,sdnwiselab/onos,y-higuchi/onos,donNewtonAlpha/onos,maheshraju-Huawei/actn,mengmoya/onos,lsinfo3/onos"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2014 Open Networking Laboratory\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 */\npackage org.onosproject.net.flow;\n\nimport com.google.common.annotations.Beta;\nimport org.onosproject.core.ApplicationId;\nimport org.onosproject.core.DefaultGroupId;\nimport org.onosproject.core.GroupId;\nimport org.onosproject.net.DeviceId;\n\nimport java.util.Objects;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic class DefaultFlowRule implements FlowRule {\n\n private final DeviceId deviceId;\n private final int priority;\n private final TrafficSelector selector;\n private final TrafficTreatment treatment;\n private final long created;\n\n private final FlowId id;\n\n private final Short appId;\n\n private final int timeout;\n private final boolean permanent;\n private final GroupId groupId;\n\n private final Integer tableId;\n private final FlowRuleExtPayLoad payLoad;\n\n public DefaultFlowRule(FlowRule rule) {\n this.deviceId = rule.deviceId();\n this.priority = rule.priority();\n this.selector = rule.selector();\n this.treatment = rule.treatment();\n this.appId = rule.appId();\n this.groupId = rule.groupId();\n this.id = rule.id();\n this.timeout = rule.timeout();\n this.permanent = rule.isPermanent();\n this.created = System.currentTimeMillis();\n this.tableId = rule.tableId();\n this.payLoad = rule.payLoad();\n }\n\n private DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,\n TrafficTreatment treatment, Integer priority,\n FlowId flowId, Boolean permanent, Integer timeout,\n Integer tableId) {\n\n this.deviceId = deviceId;\n this.selector = selector;\n this.treatment = treatment;\n this.priority = priority;\n this.appId = (short) (flowId.value() >>> 48);\n this.id = flowId;\n this.permanent = permanent;\n this.timeout = timeout;\n this.tableId = tableId;\n this.created = System.currentTimeMillis();\n\n\n //FIXME: fields below will be removed.\n this.groupId = new DefaultGroupId(0);\n this.payLoad = null;\n }\n\n /**\n * Support for the third party flow rule. Creates a flow rule of flow table.\n *\n * @param deviceId the identity of the device where this rule applies\n * @param selector the traffic selector that identifies what traffic this\n * rule\n * @param treatment the traffic treatment that applies to selected traffic\n * @param priority the flow rule priority given in natural order\n * @param appId the application id of this flow\n * @param timeout the timeout for this flow requested by an application\n * @param permanent whether the flow is permanent i.e. does not time out\n * @param payLoad 3rd-party origin private flow\n */\n public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,\n TrafficTreatment treatment, int priority,\n ApplicationId appId, int timeout, boolean permanent,\n FlowRuleExtPayLoad payLoad) {\n\n if (priority < FlowRule.MIN_PRIORITY) {\n throw new IllegalArgumentException(\"Priority cannot be less than \"\n + MIN_PRIORITY);\n }\n\n this.deviceId = deviceId;\n this.priority = priority;\n this.selector = selector;\n this.treatment = treatment;\n this.appId = appId.id();\n this.groupId = new DefaultGroupId(0);\n this.timeout = timeout;\n this.permanent = permanent;\n this.tableId = 0;\n this.created = System.currentTimeMillis();\n this.payLoad = payLoad;\n\n /*\n * id consists of the following. | appId (16 bits) | groupId (16 bits) |\n * flowId (32 bits) |\n */\n this.id = FlowId.valueOf((((long) this.appId) << 48)\n | (((long) this.groupId.id()) << 32)\n | (this.hash() & 0xffffffffL));\n }\n\n /**\n * Support for the third party flow rule. Creates a flow rule of group\n * table.\n *\n * @param deviceId the identity of the device where this rule applies\n * @param selector the traffic selector that identifies what traffic this\n * rule\n * @param treatment the traffic treatment that applies to selected traffic\n * @param priority the flow rule priority given in natural order\n * @param appId the application id of this flow\n * @param groupId the group id of this flow\n * @param timeout the timeout for this flow requested by an application\n * @param permanent whether the flow is permanent i.e. does not time out\n * @param payLoad 3rd-party origin private flow\n *\n */\n public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,\n TrafficTreatment treatment, int priority,\n ApplicationId appId, GroupId groupId, int timeout,\n boolean permanent, FlowRuleExtPayLoad payLoad) {\n\n if (priority < FlowRule.MIN_PRIORITY) {\n throw new IllegalArgumentException(\"Priority cannot be less than \"\n + MIN_PRIORITY);\n }\n\n this.deviceId = deviceId;\n this.priority = priority;\n this.selector = selector;\n this.treatment = treatment;\n this.appId = appId.id();\n this.groupId = groupId;\n this.timeout = timeout;\n this.permanent = permanent;\n this.created = System.currentTimeMillis();\n this.tableId = 0;\n this.payLoad = payLoad;\n\n /*\n * id consists of the following. | appId (16 bits) | groupId (16 bits) |\n * flowId (32 bits) |\n */\n this.id = FlowId.valueOf((((long) this.appId) << 48)\n | (((long) this.groupId.id()) << 32)\n | (this.hash() & 0xffffffffL));\n }\n\n @Override\n public FlowId id() {\n return id;\n }\n\n @Override\n public short appId() {\n return appId;\n }\n\n @Override\n public GroupId groupId() {\n return groupId;\n }\n\n @Override\n public int priority() {\n return priority;\n }\n\n @Override\n public DeviceId deviceId() {\n return deviceId;\n }\n\n @Override\n public TrafficSelector selector() {\n return selector;\n }\n\n @Override\n public TrafficTreatment treatment() {\n return treatment;\n }\n\n @Override\n /*\n * The priority and statistics can change on a given treatment and selector\n *\n * (non-Javadoc)\n *\n * @see java.lang.Object#equals(java.lang.Object)\n */\n public int hashCode() {\n return Objects.hash(deviceId, selector, tableId, payLoad);\n }\n\n //FIXME do we need this method in addition to hashCode()?\n private int hash() {\n return Objects.hash(deviceId, selector, tableId, payLoad);\n }\n\n @Override\n /*\n * The priority and statistics can change on a given treatment and selector\n *\n * (non-Javadoc)\n *\n * @see java.lang.Object#equals(java.lang.Object)\n */\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj instanceof DefaultFlowRule) {\n DefaultFlowRule that = (DefaultFlowRule) obj;\n return Objects.equals(deviceId, that.deviceId) &&\n Objects.equals(priority, that.priority) &&\n Objects.equals(selector, that.selector) &&\n Objects.equals(tableId, that.tableId)\n && Objects.equals(payLoad, that.payLoad);\n }\n return false;\n }\n\n @Override\n public boolean exactMatch(FlowRule rule) {\n return this.equals(rule) &&\n Objects.equals(this.id, rule.id()) &&\n Objects.equals(this.treatment, rule.treatment());\n }\n\n @Override\n public String toString() {\n return toStringHelper(this)\n .add(\"id\", Long.toHexString(id.value()))\n .add(\"deviceId\", deviceId)\n .add(\"priority\", priority)\n .add(\"selector\", selector.criteria())\n .add(\"treatment\", treatment == null ? \"N/A\" : treatment.allInstructions())\n .add(\"tableId\", tableId)\n .add(\"created\", created)\n .add(\"payLoad\", payLoad)\n .toString();\n }\n\n @Override\n public int timeout() {\n return timeout;\n }\n\n @Override\n public boolean isPermanent() {\n return permanent;\n }\n\n @Override\n public int tableId() {\n return tableId;\n }\n\n @Beta\n public long created() {\n return created;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static final class Builder implements FlowRule.Builder {\n\n private FlowId flowId;\n private ApplicationId appId;\n private Integer priority;\n private DeviceId deviceId;\n private Integer tableId = 0;\n private TrafficSelector selector = DefaultTrafficSelector.builder().build();\n private TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();\n private Integer timeout;\n private Boolean permanent;\n\n @Override\n public FlowRule.Builder withCookie(long cookie) {\n this.flowId = FlowId.valueOf(cookie);\n return this;\n }\n\n @Override\n public FlowRule.Builder fromApp(ApplicationId appId) {\n this.appId = appId;\n return this;\n }\n\n @Override\n public FlowRule.Builder withPriority(int priority) {\n this.priority = priority;\n return this;\n }\n\n @Override\n public FlowRule.Builder forDevice(DeviceId deviceId) {\n this.deviceId = deviceId;\n return this;\n }\n\n @Override\n public FlowRule.Builder forTable(int tableId) {\n this.tableId = tableId;\n return this;\n }\n\n @Override\n public FlowRule.Builder withSelector(TrafficSelector selector) {\n this.selector = selector;\n return this;\n }\n\n @Override\n public FlowRule.Builder withTreatment(TrafficTreatment treatment) {\n this.treatment = checkNotNull(treatment);\n return this;\n }\n\n @Override\n public FlowRule.Builder makePermanent() {\n this.timeout = 0;\n this.permanent = true;\n return this;\n }\n\n @Override\n public FlowRule.Builder makeTemporary(int timeout) {\n this.permanent = false;\n this.timeout = timeout;\n return this;\n }\n\n @Override\n public FlowRule build() {\n checkArgument(flowId != null || appId != null, \"Either an application\" +\n \" id or a cookie must be supplied\");\n checkNotNull(selector, \"Traffic selector cannot be null\");\n checkArgument(timeout != null || permanent != null, \"Must either have \" +\n \"a timeout or be permanent\");\n checkNotNull(deviceId, \"Must refer to a device\");\n checkNotNull(priority, \"Priority cannot be null\");\n checkArgument(priority >= MIN_PRIORITY, \"Priority cannot be less than \" +\n MIN_PRIORITY);\n\n // Computing a flow ID based on appId takes precedence over setting\n // the flow ID directly\n if (appId != null) {\n flowId = computeFlowId(appId);\n }\n\n return new DefaultFlowRule(deviceId, selector, treatment, priority,\n flowId, permanent, timeout, tableId);\n }\n\n private FlowId computeFlowId(ApplicationId appId) {\n return FlowId.valueOf((((long) appId.id()) << 48)\n | (hash() & 0xffffffffL));\n }\n\n private int hash() {\n return Objects.hash(deviceId, priority, selector, tableId);\n }\n\n }\n\n @Override\n public FlowRuleExtPayLoad payLoad() {\n return payLoad;\n }\n\n}\n"},"new_file":{"kind":"string","value":"core/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2014 Open Networking Laboratory\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 */\npackage org.onosproject.net.flow;\n\nimport com.google.common.annotations.Beta;\nimport org.onosproject.core.ApplicationId;\nimport org.onosproject.core.DefaultGroupId;\nimport org.onosproject.core.GroupId;\nimport org.onosproject.net.DeviceId;\n\nimport java.util.Objects;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic class DefaultFlowRule implements FlowRule {\n\n private final DeviceId deviceId;\n private final int priority;\n private final TrafficSelector selector;\n private final TrafficTreatment treatment;\n private final long created;\n\n private final FlowId id;\n\n private final Short appId;\n\n private final int timeout;\n private final boolean permanent;\n private final GroupId groupId;\n\n private final Integer tableId;\n private final FlowRuleExtPayLoad payLoad;\n\n public DefaultFlowRule(FlowRule rule) {\n this.deviceId = rule.deviceId();\n this.priority = rule.priority();\n this.selector = rule.selector();\n this.treatment = rule.treatment();\n this.appId = rule.appId();\n this.groupId = rule.groupId();\n this.id = rule.id();\n this.timeout = rule.timeout();\n this.permanent = rule.isPermanent();\n this.created = System.currentTimeMillis();\n this.tableId = rule.tableId();\n this.payLoad = rule.payLoad();\n }\n\n private DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,\n TrafficTreatment treatment, Integer priority,\n FlowId flowId, Boolean permanent, Integer timeout,\n Integer tableId) {\n\n this.deviceId = deviceId;\n this.selector = selector;\n this.treatment = treatment;\n this.priority = priority;\n this.appId = (short) (flowId.value() >>> 48);\n this.id = flowId;\n this.permanent = permanent;\n this.timeout = timeout;\n this.tableId = tableId;\n this.created = System.currentTimeMillis();\n\n\n //FIXME: fields below will be removed.\n this.groupId = new DefaultGroupId(0);\n this.payLoad = null;\n }\n\n /**\n * Support for the third party flow rule. Creates a flow rule of flow table.\n *\n * @param deviceId the identity of the device where this rule applies\n * @param selector the traffic selector that identifies what traffic this\n * rule\n * @param treatment the traffic treatment that applies to selected traffic\n * @param priority the flow rule priority given in natural order\n * @param appId the application id of this flow\n * @param timeout the timeout for this flow requested by an application\n * @param permanent whether the flow is permanent i.e. does not time out\n * @param payLoad 3rd-party origin private flow\n */\n public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,\n TrafficTreatment treatment, int priority,\n ApplicationId appId, int timeout, boolean permanent,\n FlowRuleExtPayLoad payLoad) {\n\n if (priority < FlowRule.MIN_PRIORITY) {\n throw new IllegalArgumentException(\"Priority cannot be less than \"\n + MIN_PRIORITY);\n }\n\n this.deviceId = deviceId;\n this.priority = priority;\n this.selector = selector;\n this.treatment = treatment;\n this.appId = appId.id();\n this.groupId = new DefaultGroupId(0);\n this.timeout = timeout;\n this.permanent = permanent;\n this.tableId = 0;\n this.created = System.currentTimeMillis();\n this.payLoad = payLoad;\n\n /*\n * id consists of the following. | appId (16 bits) | groupId (16 bits) |\n * flowId (32 bits) |\n */\n this.id = FlowId.valueOf((((long) this.appId) << 48)\n | (((long) this.groupId.id()) << 32)\n | (this.hash() & 0xffffffffL));\n }\n\n /**\n * Support for the third party flow rule. Creates a flow rule of group\n * table.\n *\n * @param deviceId the identity of the device where this rule applies\n * @param selector the traffic selector that identifies what traffic this\n * rule\n * @param treatment the traffic treatment that applies to selected traffic\n * @param priority the flow rule priority given in natural order\n * @param appId the application id of this flow\n * @param groupId the group id of this flow\n * @param timeout the timeout for this flow requested by an application\n * @param permanent whether the flow is permanent i.e. does not time out\n * @param payLoad 3rd-party origin private flow\n *\n */\n public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector,\n TrafficTreatment treatment, int priority,\n ApplicationId appId, GroupId groupId, int timeout,\n boolean permanent, FlowRuleExtPayLoad payLoad) {\n\n if (priority < FlowRule.MIN_PRIORITY) {\n throw new IllegalArgumentException(\"Priority cannot be less than \"\n + MIN_PRIORITY);\n }\n\n this.deviceId = deviceId;\n this.priority = priority;\n this.selector = selector;\n this.treatment = treatment;\n this.appId = appId.id();\n this.groupId = groupId;\n this.timeout = timeout;\n this.permanent = permanent;\n this.created = System.currentTimeMillis();\n this.tableId = 0;\n this.payLoad = payLoad;\n\n /*\n * id consists of the following. | appId (16 bits) | groupId (16 bits) |\n * flowId (32 bits) |\n */\n this.id = FlowId.valueOf((((long) this.appId) << 48)\n | (((long) this.groupId.id()) << 32)\n | (this.hash() & 0xffffffffL));\n }\n\n @Override\n public FlowId id() {\n return id;\n }\n\n @Override\n public short appId() {\n return appId;\n }\n\n @Override\n public GroupId groupId() {\n return groupId;\n }\n\n @Override\n public int priority() {\n return priority;\n }\n\n @Override\n public DeviceId deviceId() {\n return deviceId;\n }\n\n @Override\n public TrafficSelector selector() {\n return selector;\n }\n\n @Override\n public TrafficTreatment treatment() {\n return treatment;\n }\n\n @Override\n /*\n * The priority and statistics can change on a given treatment and selector\n *\n * (non-Javadoc)\n *\n * @see java.lang.Object#equals(java.lang.Object)\n */\n public int hashCode() {\n return Objects.hash(deviceId, selector, tableId, payLoad);\n }\n\n //FIXME do we need this method in addition to hashCode()?\n private int hash() {\n return Objects.hash(deviceId, selector, tableId, payLoad);\n }\n\n @Override\n /*\n * The priority and statistics can change on a given treatment and selector\n *\n * (non-Javadoc)\n *\n * @see java.lang.Object#equals(java.lang.Object)\n */\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj instanceof DefaultFlowRule) {\n DefaultFlowRule that = (DefaultFlowRule) obj;\n return Objects.equals(deviceId, that.deviceId) &&\n Objects.equals(priority, that.priority) &&\n Objects.equals(selector, that.selector) &&\n Objects.equals(tableId, that.tableId)\n && Objects.equals(payLoad, that.payLoad);\n }\n return false;\n }\n\n @Override\n public boolean exactMatch(FlowRule rule) {\n return this.equals(rule) &&\n Objects.equals(this.id, rule.id()) &&\n Objects.equals(this.treatment, rule.treatment());\n }\n\n @Override\n public String toString() {\n return toStringHelper(this)\n .add(\"id\", Long.toHexString(id.value()))\n .add(\"deviceId\", deviceId)\n .add(\"priority\", priority)\n .add(\"selector\", selector.criteria())\n .add(\"treatment\", treatment == null ? \"N/A\" : treatment.allInstructions())\n .add(\"tableId\", tableId)\n .add(\"created\", created)\n .add(\"payLoad\", payLoad)\n .toString();\n }\n\n @Override\n public int timeout() {\n return timeout;\n }\n\n @Override\n public boolean isPermanent() {\n return permanent;\n }\n\n @Override\n public int tableId() {\n return tableId;\n }\n\n @Beta\n public long created() {\n return created;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static final class Builder implements FlowRule.Builder {\n\n private FlowId flowId;\n private ApplicationId appId;\n private Integer priority;\n private DeviceId deviceId;\n private Integer tableId = 0;\n private TrafficSelector selector = DefaultTrafficSelector.builder().build();\n private TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();\n private Integer timeout;\n private Boolean permanent;\n\n @Override\n public FlowRule.Builder withCookie(long cookie) {\n this.flowId = FlowId.valueOf(cookie);\n return this;\n }\n\n @Override\n public FlowRule.Builder fromApp(ApplicationId appId) {\n this.appId = appId;\n return this;\n }\n\n @Override\n public FlowRule.Builder withPriority(int priority) {\n this.priority = priority;\n return this;\n }\n\n @Override\n public FlowRule.Builder forDevice(DeviceId deviceId) {\n this.deviceId = deviceId;\n return this;\n }\n\n @Override\n public FlowRule.Builder forTable(int tableId) {\n this.tableId = tableId;\n return this;\n }\n\n @Override\n public FlowRule.Builder withSelector(TrafficSelector selector) {\n this.selector = selector;\n return this;\n }\n\n @Override\n public FlowRule.Builder withTreatment(TrafficTreatment treatment) {\n this.treatment = treatment;\n return this;\n }\n\n @Override\n public FlowRule.Builder makePermanent() {\n this.timeout = 0;\n this.permanent = true;\n return this;\n }\n\n @Override\n public FlowRule.Builder makeTemporary(int timeout) {\n this.permanent = false;\n this.timeout = timeout;\n return this;\n }\n\n @Override\n public FlowRule build() {\n checkArgument(flowId != null || appId != null, \"Either an application\" +\n \" id or a cookie must be supplied\");\n checkNotNull(selector, \"Traffic selector cannot be null\");\n checkArgument(timeout != null || permanent != null, \"Must either have \" +\n \"a timeout or be permanent\");\n checkNotNull(deviceId, \"Must refer to a device\");\n checkNotNull(priority, \"Priority cannot be null\");\n checkArgument(priority >= MIN_PRIORITY, \"Priority cannot be less than \" +\n MIN_PRIORITY);\n\n // Computing a flow ID based on appId takes precedence over setting\n // the flow ID directly\n if (appId != null) {\n flowId = computeFlowId(appId);\n }\n\n return new DefaultFlowRule(deviceId, selector, treatment, priority,\n flowId, permanent, timeout, tableId);\n }\n\n private FlowId computeFlowId(ApplicationId appId) {\n return FlowId.valueOf((((long) appId.id()) << 48)\n | (hash() & 0xffffffffL));\n }\n\n private int hash() {\n return Objects.hash(deviceId, priority, selector, tableId);\n }\n\n }\n\n @Override\n public FlowRuleExtPayLoad payLoad() {\n return payLoad;\n }\n\n}\n"},"message":{"kind":"string","value":"Prevent null treatments\n\nChange-Id: Icd40ab7f986f9738d0445428cd1f0c9053ed4e88\n"},"old_file":{"kind":"string","value":"core/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java"},"subject":{"kind":"string","value":"Prevent null treatments"}}},{"rowIdx":1286,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"11e5c67356852b144e67d701eeed4f950cc8cc0a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"google/ExoPlayer,google/ExoPlayer,androidx/media,google/ExoPlayer,androidx/media,androidx/media"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2016 The Android Open Source Project\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 */\npackage androidx.media3.exoplayer;\n\nimport static androidx.media3.common.C.TRACK_TYPE_AUDIO;\nimport static androidx.media3.common.C.TRACK_TYPE_CAMERA_MOTION;\nimport static androidx.media3.common.C.TRACK_TYPE_VIDEO;\nimport static androidx.media3.common.Player.COMMAND_ADJUST_DEVICE_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_CHANGE_MEDIA_ITEMS;\nimport static androidx.media3.common.Player.COMMAND_GET_AUDIO_ATTRIBUTES;\nimport static androidx.media3.common.Player.COMMAND_GET_CURRENT_MEDIA_ITEM;\nimport static androidx.media3.common.Player.COMMAND_GET_DEVICE_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_GET_MEDIA_ITEMS_METADATA;\nimport static androidx.media3.common.Player.COMMAND_GET_TEXT;\nimport static androidx.media3.common.Player.COMMAND_GET_TIMELINE;\nimport static androidx.media3.common.Player.COMMAND_GET_TRACK_INFOS;\nimport static androidx.media3.common.Player.COMMAND_GET_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_PLAY_PAUSE;\nimport static androidx.media3.common.Player.COMMAND_PREPARE;\nimport static androidx.media3.common.Player.COMMAND_SEEK_TO_DEFAULT_POSITION;\nimport static androidx.media3.common.Player.COMMAND_SEEK_TO_MEDIA_ITEM;\nimport static androidx.media3.common.Player.COMMAND_SET_DEVICE_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_SET_MEDIA_ITEMS_METADATA;\nimport static androidx.media3.common.Player.COMMAND_SET_REPEAT_MODE;\nimport static androidx.media3.common.Player.COMMAND_SET_SHUFFLE_MODE;\nimport static androidx.media3.common.Player.COMMAND_SET_SPEED_AND_PITCH;\nimport static androidx.media3.common.Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS;\nimport static androidx.media3.common.Player.COMMAND_SET_VIDEO_SURFACE;\nimport static androidx.media3.common.Player.COMMAND_SET_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_STOP;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_AUTO_TRANSITION;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_INTERNAL;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_REMOVE;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_SEEK;\nimport static androidx.media3.common.Player.EVENT_MEDIA_METADATA_CHANGED;\nimport static androidx.media3.common.Player.EVENT_PLAYLIST_METADATA_CHANGED;\nimport static androidx.media3.common.Player.EVENT_TRACK_SELECTION_PARAMETERS_CHANGED;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_AUTO;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_SEEK;\nimport static androidx.media3.common.Player.PLAYBACK_SUPPRESSION_REASON_NONE;\nimport static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS;\nimport static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;\nimport static androidx.media3.common.Player.STATE_BUFFERING;\nimport static androidx.media3.common.Player.STATE_ENDED;\nimport static androidx.media3.common.Player.STATE_IDLE;\nimport static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED;\nimport static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_SOURCE_UPDATE;\nimport static androidx.media3.common.util.Assertions.checkNotNull;\nimport static androidx.media3.common.util.Assertions.checkState;\nimport static androidx.media3.common.util.Util.castNonNull;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_ATTRIBUTES;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_SESSION_ID;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_AUX_EFFECT_INFO;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_CAMERA_MOTION_LISTENER;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_SCALING_MODE;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_SKIP_SILENCE_ENABLED;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_OUTPUT;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_VOLUME;\nimport static java.lang.Math.max;\nimport static java.lang.Math.min;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.graphics.Rect;\nimport android.graphics.SurfaceTexture;\nimport android.media.AudioFormat;\nimport android.media.AudioTrack;\nimport android.media.MediaFormat;\nimport android.media.metrics.LogSessionId;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Pair;\nimport android.view.Surface;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.TextureView;\nimport androidx.annotation.DoNotInline;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.media3.common.AudioAttributes;\nimport androidx.media3.common.AuxEffectInfo;\nimport androidx.media3.common.C;\nimport androidx.media3.common.DeviceInfo;\nimport androidx.media3.common.Format;\nimport androidx.media3.common.IllegalSeekPositionException;\nimport androidx.media3.common.MediaItem;\nimport androidx.media3.common.MediaLibraryInfo;\nimport androidx.media3.common.MediaMetadata;\nimport androidx.media3.common.Metadata;\nimport androidx.media3.common.PlaybackException;\nimport androidx.media3.common.PlaybackParameters;\nimport androidx.media3.common.Player;\nimport androidx.media3.common.Player.Commands;\nimport androidx.media3.common.Player.DiscontinuityReason;\nimport androidx.media3.common.Player.Events;\nimport androidx.media3.common.Player.Listener;\nimport androidx.media3.common.Player.PlayWhenReadyChangeReason;\nimport androidx.media3.common.Player.PlaybackSuppressionReason;\nimport androidx.media3.common.Player.PositionInfo;\nimport androidx.media3.common.Player.RepeatMode;\nimport androidx.media3.common.Player.State;\nimport androidx.media3.common.Player.TimelineChangeReason;\nimport androidx.media3.common.PriorityTaskManager;\nimport androidx.media3.common.Timeline;\nimport androidx.media3.common.TrackGroup;\nimport androidx.media3.common.TrackGroupArray;\nimport androidx.media3.common.TrackSelectionArray;\nimport androidx.media3.common.TrackSelectionParameters;\nimport androidx.media3.common.TracksInfo;\nimport androidx.media3.common.VideoSize;\nimport androidx.media3.common.text.Cue;\nimport androidx.media3.common.util.Assertions;\nimport androidx.media3.common.util.Clock;\nimport androidx.media3.common.util.ConditionVariable;\nimport androidx.media3.common.util.HandlerWrapper;\nimport androidx.media3.common.util.ListenerSet;\nimport androidx.media3.common.util.Log;\nimport androidx.media3.common.util.Util;\nimport androidx.media3.exoplayer.ExoPlayer.AudioOffloadListener;\nimport androidx.media3.exoplayer.PlayerMessage.Target;\nimport androidx.media3.exoplayer.Renderer.MessageType;\nimport androidx.media3.exoplayer.analytics.AnalyticsCollector;\nimport androidx.media3.exoplayer.analytics.AnalyticsListener;\nimport androidx.media3.exoplayer.analytics.PlayerId;\nimport androidx.media3.exoplayer.audio.AudioRendererEventListener;\nimport androidx.media3.exoplayer.metadata.MetadataOutput;\nimport androidx.media3.exoplayer.source.MediaSource;\nimport androidx.media3.exoplayer.source.MediaSource.MediaPeriodId;\nimport androidx.media3.exoplayer.source.ShuffleOrder;\nimport androidx.media3.exoplayer.text.TextOutput;\nimport androidx.media3.exoplayer.trackselection.ExoTrackSelection;\nimport androidx.media3.exoplayer.trackselection.TrackSelector;\nimport androidx.media3.exoplayer.trackselection.TrackSelectorResult;\nimport androidx.media3.exoplayer.upstream.BandwidthMeter;\nimport androidx.media3.exoplayer.video.VideoDecoderOutputBufferRenderer;\nimport androidx.media3.exoplayer.video.VideoFrameMetadataListener;\nimport androidx.media3.exoplayer.video.VideoRendererEventListener;\nimport androidx.media3.exoplayer.video.spherical.CameraMotionListener;\nimport androidx.media3.exoplayer.video.spherical.SphericalGLSurfaceView;\nimport com.google.common.collect.ImmutableList;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.CopyOnWriteArraySet;\nimport java.util.concurrent.TimeoutException;\n\n/** A helper class for the {@link SimpleExoPlayer} implementation of {@link ExoPlayer}. */\n/* package */ final class ExoPlayerImpl {\n\n static {\n MediaLibraryInfo.registerModule(\"media3.exoplayer\");\n }\n\n private static final String TAG = \"ExoPlayerImpl\";\n\n /**\n * This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult}\n * when the player does not have any track selection made (such as when player is reset, or when\n * player seeks to an unprepared period). It will not be used as result of any {@link\n * TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)}\n * operation.\n */\n /* package */ final TrackSelectorResult emptyTrackSelectorResult;\n /* package */ final Commands permanentAvailableCommands;\n\n private final ConditionVariable constructorFinished;\n private final Context applicationContext;\n private final Player wrappingPlayer;\n private final Renderer[] renderers;\n private final TrackSelector trackSelector;\n private final HandlerWrapper playbackInfoUpdateHandler;\n private final ExoPlayerImplInternal.PlaybackInfoUpdateListener playbackInfoUpdateListener;\n private final ExoPlayerImplInternal internalPlayer;\n\n private final ListenerSet listeners;\n // TODO(b/187152483): Remove this once all events are dispatched via ListenerSet.\n private final CopyOnWriteArraySet listenerArraySet;\n private final CopyOnWriteArraySet audioOffloadListeners;\n private final Timeline.Period period;\n private final Timeline.Window window;\n private final List mediaSourceHolderSnapshots;\n private final boolean useLazyPreparation;\n private final MediaSource.Factory mediaSourceFactory;\n private final AnalyticsCollector analyticsCollector;\n private final Looper applicationLooper;\n private final BandwidthMeter bandwidthMeter;\n private final long seekBackIncrementMs;\n private final long seekForwardIncrementMs;\n private final Clock clock;\n private final ComponentListener componentListener;\n private final FrameMetadataListener frameMetadataListener;\n private final AudioBecomingNoisyManager audioBecomingNoisyManager;\n private final AudioFocusManager audioFocusManager;\n private final StreamVolumeManager streamVolumeManager;\n private final WakeLockManager wakeLockManager;\n private final WifiLockManager wifiLockManager;\n private final long detachSurfaceTimeoutMs;\n\n private @RepeatMode int repeatMode;\n private boolean shuffleModeEnabled;\n private int pendingOperationAcks;\n private @DiscontinuityReason int pendingDiscontinuityReason;\n private boolean pendingDiscontinuity;\n private @PlayWhenReadyChangeReason int pendingPlayWhenReadyChangeReason;\n private boolean foregroundMode;\n private SeekParameters seekParameters;\n private ShuffleOrder shuffleOrder;\n private boolean pauseAtEndOfMediaItems;\n private Commands availableCommands;\n private MediaMetadata mediaMetadata;\n private MediaMetadata playlistMetadata;\n @Nullable private Format videoFormat;\n @Nullable private Format audioFormat;\n @Nullable private AudioTrack keepSessionIdAudioTrack;\n @Nullable private Object videoOutput;\n @Nullable private Surface ownedSurface;\n @Nullable private SurfaceHolder surfaceHolder;\n @Nullable private SphericalGLSurfaceView sphericalGLSurfaceView;\n private boolean surfaceHolderSurfaceIsVideoOutput;\n @Nullable private TextureView textureView;\n private @C.VideoScalingMode int videoScalingMode;\n private @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy;\n private int surfaceWidth;\n private int surfaceHeight;\n @Nullable private DecoderCounters videoDecoderCounters;\n @Nullable private DecoderCounters audioDecoderCounters;\n private int audioSessionId;\n private AudioAttributes audioAttributes;\n private float volume;\n private boolean skipSilenceEnabled;\n private List currentCues;\n @Nullable private VideoFrameMetadataListener videoFrameMetadataListener;\n @Nullable private CameraMotionListener cameraMotionListener;\n private boolean throwsWhenUsingWrongThread;\n private boolean hasNotifiedFullWrongThreadWarning;\n @Nullable private PriorityTaskManager priorityTaskManager;\n private boolean isPriorityTaskManagerRegistered;\n private boolean playerReleased;\n private DeviceInfo deviceInfo;\n private VideoSize videoSize;\n\n // MediaMetadata built from static (TrackGroup Format) and dynamic (onMetadata(Metadata)) metadata\n // sources.\n private MediaMetadata staticAndDynamicMediaMetadata;\n\n // Playback information when there is no pending seek/set source operation.\n private PlaybackInfo playbackInfo;\n\n // Playback information when there is a pending seek/set source operation.\n private int maskingWindowIndex;\n private int maskingPeriodIndex;\n private long maskingWindowPositionMs;\n\n @SuppressLint(\"HandlerLeak\")\n public ExoPlayerImpl(ExoPlayer.Builder builder, Player wrappingPlayer) {\n constructorFinished = new ConditionVariable();\n try {\n Log.i(\n TAG,\n \"Init \"\n + Integer.toHexString(System.identityHashCode(this))\n + \" [\"\n + MediaLibraryInfo.VERSION_SLASHY\n + \"] [\"\n + Util.DEVICE_DEBUG_INFO\n + \"]\");\n applicationContext = builder.context.getApplicationContext();\n analyticsCollector = builder.analyticsCollectorSupplier.get();\n priorityTaskManager = builder.priorityTaskManager;\n audioAttributes = builder.audioAttributes;\n videoScalingMode = builder.videoScalingMode;\n videoChangeFrameRateStrategy = builder.videoChangeFrameRateStrategy;\n skipSilenceEnabled = builder.skipSilenceEnabled;\n detachSurfaceTimeoutMs = builder.detachSurfaceTimeoutMs;\n componentListener = new ComponentListener();\n frameMetadataListener = new FrameMetadataListener();\n Handler eventHandler = new Handler(builder.looper);\n renderers =\n builder\n .renderersFactorySupplier\n .get()\n .createRenderers(\n eventHandler,\n componentListener,\n componentListener,\n componentListener,\n componentListener);\n checkState(renderers.length > 0);\n this.trackSelector = builder.trackSelectorSupplier.get();\n this.mediaSourceFactory = builder.mediaSourceFactorySupplier.get();\n this.bandwidthMeter = builder.bandwidthMeterSupplier.get();\n this.useLazyPreparation = builder.useLazyPreparation;\n this.seekParameters = builder.seekParameters;\n this.seekBackIncrementMs = builder.seekBackIncrementMs;\n this.seekForwardIncrementMs = builder.seekForwardIncrementMs;\n this.pauseAtEndOfMediaItems = builder.pauseAtEndOfMediaItems;\n this.applicationLooper = builder.looper;\n this.clock = builder.clock;\n this.wrappingPlayer = wrappingPlayer;\n listeners =\n new ListenerSet<>(\n applicationLooper,\n clock,\n (listener, flags) -> listener.onEvents(wrappingPlayer, new Events(flags)));\n listenerArraySet = new CopyOnWriteArraySet<>();\n audioOffloadListeners = new CopyOnWriteArraySet<>();\n mediaSourceHolderSnapshots = new ArrayList<>();\n shuffleOrder = new ShuffleOrder.DefaultShuffleOrder(/* length= */ 0);\n emptyTrackSelectorResult =\n new TrackSelectorResult(\n new RendererConfiguration[renderers.length],\n new ExoTrackSelection[renderers.length],\n TracksInfo.EMPTY,\n /* info= */ null);\n period = new Timeline.Period();\n window = new Timeline.Window();\n permanentAvailableCommands =\n new Commands.Builder()\n .addAll(\n COMMAND_PLAY_PAUSE,\n COMMAND_PREPARE,\n COMMAND_STOP,\n COMMAND_SET_SPEED_AND_PITCH,\n COMMAND_SET_SHUFFLE_MODE,\n COMMAND_SET_REPEAT_MODE,\n COMMAND_GET_CURRENT_MEDIA_ITEM,\n COMMAND_GET_TIMELINE,\n COMMAND_GET_MEDIA_ITEMS_METADATA,\n COMMAND_SET_MEDIA_ITEMS_METADATA,\n COMMAND_CHANGE_MEDIA_ITEMS,\n COMMAND_GET_TRACK_INFOS,\n COMMAND_GET_AUDIO_ATTRIBUTES,\n COMMAND_GET_VOLUME,\n COMMAND_GET_DEVICE_VOLUME,\n COMMAND_SET_VOLUME,\n COMMAND_SET_DEVICE_VOLUME,\n COMMAND_ADJUST_DEVICE_VOLUME,\n COMMAND_SET_VIDEO_SURFACE,\n COMMAND_GET_TEXT)\n .addIf(\n COMMAND_SET_TRACK_SELECTION_PARAMETERS, trackSelector.isSetParametersSupported())\n .build();\n availableCommands =\n new Commands.Builder()\n .addAll(permanentAvailableCommands)\n .add(COMMAND_SEEK_TO_DEFAULT_POSITION)\n .add(COMMAND_SEEK_TO_MEDIA_ITEM)\n .build();\n playbackInfoUpdateHandler = clock.createHandler(applicationLooper, /* callback= */ null);\n playbackInfoUpdateListener =\n playbackInfoUpdate ->\n playbackInfoUpdateHandler.post(() -> handlePlaybackInfo(playbackInfoUpdate));\n playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult);\n analyticsCollector.setPlayer(wrappingPlayer, applicationLooper);\n PlayerId playerId = Util.SDK_INT < 31 ? new PlayerId() : Api31.createPlayerId();\n internalPlayer =\n new ExoPlayerImplInternal(\n renderers,\n trackSelector,\n emptyTrackSelectorResult,\n builder.loadControlSupplier.get(),\n bandwidthMeter,\n repeatMode,\n shuffleModeEnabled,\n analyticsCollector,\n seekParameters,\n builder.livePlaybackSpeedControl,\n builder.releaseTimeoutMs,\n pauseAtEndOfMediaItems,\n applicationLooper,\n clock,\n playbackInfoUpdateListener,\n playerId);\n\n volume = 1;\n repeatMode = Player.REPEAT_MODE_OFF;\n mediaMetadata = MediaMetadata.EMPTY;\n playlistMetadata = MediaMetadata.EMPTY;\n staticAndDynamicMediaMetadata = MediaMetadata.EMPTY;\n maskingWindowIndex = C.INDEX_UNSET;\n if (Util.SDK_INT < 21) {\n audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET);\n } else {\n audioSessionId = Util.generateAudioSessionIdV21(applicationContext);\n }\n currentCues = ImmutableList.of();\n throwsWhenUsingWrongThread = true;\n\n listeners.add(analyticsCollector);\n bandwidthMeter.addEventListener(new Handler(applicationLooper), analyticsCollector);\n addAudioOffloadListener(componentListener);\n if (builder.foregroundModeTimeoutMs > 0) {\n experimentalSetForegroundModeTimeoutMs(builder.foregroundModeTimeoutMs);\n }\n\n audioBecomingNoisyManager =\n new AudioBecomingNoisyManager(builder.context, eventHandler, componentListener);\n audioBecomingNoisyManager.setEnabled(builder.handleAudioBecomingNoisy);\n audioFocusManager = new AudioFocusManager(builder.context, eventHandler, componentListener);\n audioFocusManager.setAudioAttributes(builder.handleAudioFocus ? audioAttributes : null);\n streamVolumeManager =\n new StreamVolumeManager(builder.context, eventHandler, componentListener);\n streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage));\n wakeLockManager = new WakeLockManager(builder.context);\n wakeLockManager.setEnabled(builder.wakeMode != C.WAKE_MODE_NONE);\n wifiLockManager = new WifiLockManager(builder.context);\n wifiLockManager.setEnabled(builder.wakeMode == C.WAKE_MODE_NETWORK);\n deviceInfo = createDeviceInfo(streamVolumeManager);\n videoSize = VideoSize.UNKNOWN;\n\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes);\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode);\n sendRendererMessage(\n TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy);\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled);\n sendRendererMessage(\n TRACK_TYPE_VIDEO, MSG_SET_VIDEO_FRAME_METADATA_LISTENER, frameMetadataListener);\n sendRendererMessage(\n TRACK_TYPE_CAMERA_MOTION, MSG_SET_CAMERA_MOTION_LISTENER, frameMetadataListener);\n } finally {\n constructorFinished.open();\n }\n }\n\n /**\n * Sets a limit on the time a call to {@link #setForegroundMode} can spend. If a call to {@link\n * #setForegroundMode} takes more than {@code timeoutMs} milliseconds to complete, the player will\n * raise an error via {@link Player.Listener#onPlayerError}.\n *\n *

This method is experimental, and will be renamed or removed in a future release. It should\n * only be called before the player is used.\n *\n * @param timeoutMs The time limit in milliseconds.\n */\n public void experimentalSetForegroundModeTimeoutMs(long timeoutMs) {\n internalPlayer.experimentalSetForegroundModeTimeoutMs(timeoutMs);\n }\n\n public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) {\n verifyApplicationThread();\n internalPlayer.experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled);\n }\n\n public boolean experimentalIsSleepingForOffload() {\n verifyApplicationThread();\n return playbackInfo.sleepingForOffload;\n }\n\n public Looper getPlaybackLooper() {\n // Don't verify application thread. We allow calls to this method from any thread.\n return internalPlayer.getPlaybackLooper();\n }\n\n public Looper getApplicationLooper() {\n // Don't verify application thread. We allow calls to this method from any thread.\n return applicationLooper;\n }\n\n public Clock getClock() {\n // Don't verify application thread. We allow calls to this method from any thread.\n return clock;\n }\n\n public void addAudioOffloadListener(AudioOffloadListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n audioOffloadListeners.add(listener);\n }\n\n public void removeAudioOffloadListener(AudioOffloadListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n audioOffloadListeners.remove(listener);\n }\n\n public Commands getAvailableCommands() {\n verifyApplicationThread();\n return availableCommands;\n }\n\n public @State int getPlaybackState() {\n verifyApplicationThread();\n return playbackInfo.playbackState;\n }\n\n public @PlaybackSuppressionReason int getPlaybackSuppressionReason() {\n verifyApplicationThread();\n return playbackInfo.playbackSuppressionReason;\n }\n\n @Nullable\n public ExoPlaybackException getPlayerError() {\n verifyApplicationThread();\n return playbackInfo.playbackError;\n }\n\n /** @deprecated Use {@link #prepare()} instead. */\n @Deprecated\n public void retry() {\n prepare();\n }\n\n public void prepare() {\n verifyApplicationThread();\n boolean playWhenReady = getPlayWhenReady();\n @AudioFocusManager.PlayerCommand\n int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, Player.STATE_BUFFERING);\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n if (playbackInfo.playbackState != Player.STATE_IDLE) {\n return;\n }\n PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlaybackError(null);\n playbackInfo =\n playbackInfo.copyWithPlaybackState(\n playbackInfo.timeline.isEmpty() ? STATE_ENDED : STATE_BUFFERING);\n // Trigger internal prepare first before updating the playback info and notifying external\n // listeners to ensure that new operations issued in the listener notifications reach the\n // player after this prepare. The internal player can't change the playback info immediately\n // because it uses a callback.\n pendingOperationAcks++;\n internalPlayer.prepare();\n updatePlaybackInfo(\n playbackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_SOURCE_UPDATE,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n /**\n * @deprecated Use {@link #setMediaSource(MediaSource)} and {@link ExoPlayer#prepare()} instead.\n */\n @Deprecated\n public void prepare(MediaSource mediaSource) {\n verifyApplicationThread();\n setMediaSource(mediaSource);\n prepare();\n }\n\n /**\n * @deprecated Use {@link #setMediaSource(MediaSource, boolean)} and {@link ExoPlayer#prepare()}\n * instead.\n */\n @Deprecated\n public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) {\n verifyApplicationThread();\n setMediaSource(mediaSource, resetPosition);\n prepare();\n }\n\n public void setMediaItems(List mediaItems, boolean resetPosition) {\n verifyApplicationThread();\n setMediaSources(createMediaSources(mediaItems), resetPosition);\n }\n\n public void setMediaItems(List mediaItems, int startIndex, long startPositionMs) {\n verifyApplicationThread();\n setMediaSources(createMediaSources(mediaItems), startIndex, startPositionMs);\n }\n\n public void setMediaSource(MediaSource mediaSource) {\n verifyApplicationThread();\n setMediaSources(Collections.singletonList(mediaSource));\n }\n\n public void setMediaSource(MediaSource mediaSource, long startPositionMs) {\n verifyApplicationThread();\n setMediaSources(\n Collections.singletonList(mediaSource), /* startWindowIndex= */ 0, startPositionMs);\n }\n\n public void setMediaSource(MediaSource mediaSource, boolean resetPosition) {\n verifyApplicationThread();\n setMediaSources(Collections.singletonList(mediaSource), resetPosition);\n }\n\n public void setMediaSources(List mediaSources) {\n verifyApplicationThread();\n setMediaSources(mediaSources, /* resetPosition= */ true);\n }\n\n public void setMediaSources(List mediaSources, boolean resetPosition) {\n verifyApplicationThread();\n setMediaSourcesInternal(\n mediaSources,\n /* startWindowIndex= */ C.INDEX_UNSET,\n /* startPositionMs= */ C.TIME_UNSET,\n /* resetToDefaultPosition= */ resetPosition);\n }\n\n public void setMediaSources(\n List mediaSources, int startWindowIndex, long startPositionMs) {\n verifyApplicationThread();\n setMediaSourcesInternal(\n mediaSources, startWindowIndex, startPositionMs, /* resetToDefaultPosition= */ false);\n }\n\n public void addMediaItems(int index, List mediaItems) {\n verifyApplicationThread();\n index = min(index, mediaSourceHolderSnapshots.size());\n addMediaSources(index, createMediaSources(mediaItems));\n }\n\n public void addMediaSource(MediaSource mediaSource) {\n verifyApplicationThread();\n addMediaSources(Collections.singletonList(mediaSource));\n }\n\n public void addMediaSource(int index, MediaSource mediaSource) {\n verifyApplicationThread();\n addMediaSources(index, Collections.singletonList(mediaSource));\n }\n\n public void addMediaSources(List mediaSources) {\n verifyApplicationThread();\n addMediaSources(/* index= */ mediaSourceHolderSnapshots.size(), mediaSources);\n }\n\n public void addMediaSources(int index, List mediaSources) {\n verifyApplicationThread();\n Assertions.checkArgument(index >= 0);\n Timeline oldTimeline = getCurrentTimeline();\n pendingOperationAcks++;\n List holders = addMediaSourceHolders(index, mediaSources);\n Timeline newTimeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n newTimeline,\n getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));\n internalPlayer.addMediaSources(index, holders, shuffleOrder);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void removeMediaItems(int fromIndex, int toIndex) {\n verifyApplicationThread();\n toIndex = min(toIndex, mediaSourceHolderSnapshots.size());\n PlaybackInfo newPlaybackInfo = removeMediaItemsInternal(fromIndex, toIndex);\n boolean positionDiscontinuity =\n !newPlaybackInfo.periodId.periodUid.equals(playbackInfo.periodId.periodUid);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n positionDiscontinuity,\n DISCONTINUITY_REASON_REMOVE,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void moveMediaItems(int fromIndex, int toIndex, int newFromIndex) {\n verifyApplicationThread();\n Assertions.checkArgument(\n fromIndex >= 0\n && fromIndex <= toIndex\n && toIndex <= mediaSourceHolderSnapshots.size()\n && newFromIndex >= 0);\n Timeline oldTimeline = getCurrentTimeline();\n pendingOperationAcks++;\n newFromIndex = min(newFromIndex, mediaSourceHolderSnapshots.size() - (toIndex - fromIndex));\n Util.moveItems(mediaSourceHolderSnapshots, fromIndex, toIndex, newFromIndex);\n Timeline newTimeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n newTimeline,\n getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));\n internalPlayer.moveMediaSources(fromIndex, toIndex, newFromIndex, shuffleOrder);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void setShuffleOrder(ShuffleOrder shuffleOrder) {\n verifyApplicationThread();\n Timeline timeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n timeline,\n maskWindowPositionMsOrGetPeriodPositionUs(\n timeline, getCurrentMediaItemIndex(), getCurrentPosition()));\n pendingOperationAcks++;\n this.shuffleOrder = shuffleOrder;\n internalPlayer.setShuffleOrder(shuffleOrder);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void setPauseAtEndOfMediaItems(boolean pauseAtEndOfMediaItems) {\n verifyApplicationThread();\n if (this.pauseAtEndOfMediaItems == pauseAtEndOfMediaItems) {\n return;\n }\n this.pauseAtEndOfMediaItems = pauseAtEndOfMediaItems;\n internalPlayer.setPauseAtEndOfWindow(pauseAtEndOfMediaItems);\n }\n\n public boolean getPauseAtEndOfMediaItems() {\n verifyApplicationThread();\n return pauseAtEndOfMediaItems;\n }\n\n public void setPlayWhenReady(boolean playWhenReady) {\n verifyApplicationThread();\n @AudioFocusManager.PlayerCommand\n int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState());\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n }\n\n public void setPlayWhenReady(\n boolean playWhenReady,\n @PlaybackSuppressionReason int playbackSuppressionReason,\n @PlayWhenReadyChangeReason int playWhenReadyChangeReason) {\n if (playbackInfo.playWhenReady == playWhenReady\n && playbackInfo.playbackSuppressionReason == playbackSuppressionReason) {\n return;\n }\n pendingOperationAcks++;\n PlaybackInfo playbackInfo =\n this.playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason);\n internalPlayer.setPlayWhenReady(playWhenReady, playbackSuppressionReason);\n updatePlaybackInfo(\n playbackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n playWhenReadyChangeReason,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public boolean getPlayWhenReady() {\n verifyApplicationThread();\n return playbackInfo.playWhenReady;\n }\n\n public void setRepeatMode(@RepeatMode int repeatMode) {\n verifyApplicationThread();\n if (this.repeatMode != repeatMode) {\n this.repeatMode = repeatMode;\n internalPlayer.setRepeatMode(repeatMode);\n listeners.queueEvent(\n Player.EVENT_REPEAT_MODE_CHANGED, listener -> listener.onRepeatModeChanged(repeatMode));\n updateAvailableCommands();\n listeners.flushEvents();\n }\n }\n\n public @RepeatMode int getRepeatMode() {\n verifyApplicationThread();\n return repeatMode;\n }\n\n public void setShuffleModeEnabled(boolean shuffleModeEnabled) {\n verifyApplicationThread();\n if (this.shuffleModeEnabled != shuffleModeEnabled) {\n this.shuffleModeEnabled = shuffleModeEnabled;\n internalPlayer.setShuffleModeEnabled(shuffleModeEnabled);\n listeners.queueEvent(\n Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED,\n listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled));\n updateAvailableCommands();\n listeners.flushEvents();\n }\n }\n\n public boolean getShuffleModeEnabled() {\n verifyApplicationThread();\n return shuffleModeEnabled;\n }\n\n public boolean isLoading() {\n verifyApplicationThread();\n return playbackInfo.isLoading;\n }\n\n public void seekTo(int mediaItemIndex, long positionMs) {\n verifyApplicationThread();\n analyticsCollector.notifySeekStarted();\n Timeline timeline = playbackInfo.timeline;\n if (mediaItemIndex < 0\n || (!timeline.isEmpty() && mediaItemIndex >= timeline.getWindowCount())) {\n throw new IllegalSeekPositionException(timeline, mediaItemIndex, positionMs);\n }\n pendingOperationAcks++;\n if (isPlayingAd()) {\n // TODO: Investigate adding support for seeking during ads. This is complicated to do in\n // general because the midroll ad preceding the seek destination must be played before the\n // content position can be played, if a different ad is playing at the moment.\n Log.w(TAG, \"seekTo ignored because an ad is playing\");\n ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate =\n new ExoPlayerImplInternal.PlaybackInfoUpdate(this.playbackInfo);\n playbackInfoUpdate.incrementPendingOperationAcks(1);\n playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate);\n return;\n }\n @Player.State\n int newPlaybackState =\n getPlaybackState() == Player.STATE_IDLE ? Player.STATE_IDLE : STATE_BUFFERING;\n int oldMaskingMediaItemIndex = getCurrentMediaItemIndex();\n PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackState(newPlaybackState);\n newPlaybackInfo =\n maskTimelineAndPosition(\n newPlaybackInfo,\n timeline,\n maskWindowPositionMsOrGetPeriodPositionUs(timeline, mediaItemIndex, positionMs));\n internalPlayer.seekTo(timeline, mediaItemIndex, Util.msToUs(positionMs));\n updatePlaybackInfo(\n newPlaybackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ true,\n /* positionDiscontinuity= */ true,\n /* positionDiscontinuityReason= */ DISCONTINUITY_REASON_SEEK,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),\n oldMaskingMediaItemIndex);\n }\n\n public long getSeekBackIncrement() {\n verifyApplicationThread();\n return seekBackIncrementMs;\n }\n\n public long getSeekForwardIncrement() {\n verifyApplicationThread();\n return seekForwardIncrementMs;\n }\n\n public long getMaxSeekToPreviousPosition() {\n verifyApplicationThread();\n return C.DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS;\n }\n\n public void setPlaybackParameters(PlaybackParameters playbackParameters) {\n verifyApplicationThread();\n if (playbackParameters == null) {\n playbackParameters = PlaybackParameters.DEFAULT;\n }\n if (playbackInfo.playbackParameters.equals(playbackParameters)) {\n return;\n }\n PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters);\n pendingOperationAcks++;\n internalPlayer.setPlaybackParameters(playbackParameters);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public PlaybackParameters getPlaybackParameters() {\n verifyApplicationThread();\n return playbackInfo.playbackParameters;\n }\n\n public void setSeekParameters(@Nullable SeekParameters seekParameters) {\n verifyApplicationThread();\n if (seekParameters == null) {\n seekParameters = SeekParameters.DEFAULT;\n }\n if (!this.seekParameters.equals(seekParameters)) {\n this.seekParameters = seekParameters;\n internalPlayer.setSeekParameters(seekParameters);\n }\n }\n\n public SeekParameters getSeekParameters() {\n verifyApplicationThread();\n return seekParameters;\n }\n\n public void setForegroundMode(boolean foregroundMode) {\n verifyApplicationThread();\n if (this.foregroundMode != foregroundMode) {\n this.foregroundMode = foregroundMode;\n if (!internalPlayer.setForegroundMode(foregroundMode)) {\n // One of the renderers timed out releasing its resources.\n stop(\n /* reset= */ false,\n ExoPlaybackException.createForUnexpected(\n new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_SET_FOREGROUND_MODE),\n PlaybackException.ERROR_CODE_TIMEOUT));\n }\n }\n }\n\n public void stop() {\n stop(/* reset= */ false);\n }\n\n public void stop(boolean reset) {\n verifyApplicationThread();\n audioFocusManager.updateAudioFocus(getPlayWhenReady(), Player.STATE_IDLE);\n stop(reset, /* error= */ null);\n currentCues = ImmutableList.of();\n }\n\n /**\n * Stops the player.\n *\n * @param reset Whether the playlist should be cleared and whether the playback position and\n * playback error should be reset.\n * @param error An optional {@link ExoPlaybackException} to set.\n */\n public void stop(boolean reset, @Nullable ExoPlaybackException error) {\n PlaybackInfo playbackInfo;\n if (reset) {\n playbackInfo =\n removeMediaItemsInternal(\n /* fromIndex= */ 0, /* toIndex= */ mediaSourceHolderSnapshots.size());\n playbackInfo = playbackInfo.copyWithPlaybackError(null);\n } else {\n playbackInfo = this.playbackInfo.copyWithLoadingMediaPeriodId(this.playbackInfo.periodId);\n playbackInfo.bufferedPositionUs = playbackInfo.positionUs;\n playbackInfo.totalBufferedDurationUs = 0;\n }\n playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE);\n if (error != null) {\n playbackInfo = playbackInfo.copyWithPlaybackError(error);\n }\n pendingOperationAcks++;\n internalPlayer.stop();\n boolean positionDiscontinuity =\n playbackInfo.timeline.isEmpty() && !this.playbackInfo.timeline.isEmpty();\n updatePlaybackInfo(\n playbackInfo,\n TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n positionDiscontinuity,\n DISCONTINUITY_REASON_REMOVE,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(playbackInfo),\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void release() {\n Log.i(\n TAG,\n \"Release \"\n + Integer.toHexString(System.identityHashCode(this))\n + \" [\"\n + MediaLibraryInfo.VERSION_SLASHY\n + \"] [\"\n + Util.DEVICE_DEBUG_INFO\n + \"] [\"\n + MediaLibraryInfo.registeredModules()\n + \"]\");\n verifyApplicationThread();\n if (Util.SDK_INT < 21 && keepSessionIdAudioTrack != null) {\n keepSessionIdAudioTrack.release();\n keepSessionIdAudioTrack = null;\n }\n audioBecomingNoisyManager.setEnabled(false);\n streamVolumeManager.release();\n wakeLockManager.setStayAwake(false);\n wifiLockManager.setStayAwake(false);\n audioFocusManager.release();\n if (!internalPlayer.release()) {\n // One of the renderers timed out releasing its resources.\n listeners.sendEvent(\n Player.EVENT_PLAYER_ERROR,\n listener ->\n listener.onPlayerError(\n ExoPlaybackException.createForUnexpected(\n new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_RELEASE),\n PlaybackException.ERROR_CODE_TIMEOUT)));\n }\n listeners.release();\n playbackInfoUpdateHandler.removeCallbacksAndMessages(null);\n bandwidthMeter.removeEventListener(analyticsCollector);\n playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE);\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(playbackInfo.periodId);\n playbackInfo.bufferedPositionUs = playbackInfo.positionUs;\n playbackInfo.totalBufferedDurationUs = 0;\n analyticsCollector.release();\n removeSurfaceCallbacks();\n if (ownedSurface != null) {\n ownedSurface.release();\n ownedSurface = null;\n }\n if (isPriorityTaskManagerRegistered) {\n checkNotNull(priorityTaskManager).remove(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = false;\n }\n currentCues = ImmutableList.of();\n playerReleased = true;\n }\n\n public PlayerMessage createMessage(Target target) {\n verifyApplicationThread();\n return createMessageInternal(target);\n }\n\n public int getCurrentPeriodIndex() {\n verifyApplicationThread();\n if (playbackInfo.timeline.isEmpty()) {\n return maskingPeriodIndex;\n } else {\n return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid);\n }\n }\n\n public int getCurrentMediaItemIndex() {\n verifyApplicationThread();\n int currentWindowIndex = getCurrentWindowIndexInternal();\n return currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex;\n }\n\n public long getDuration() {\n verifyApplicationThread();\n if (isPlayingAd()) {\n MediaPeriodId periodId = playbackInfo.periodId;\n playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);\n long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup);\n return Util.usToMs(adDurationUs);\n }\n return getContentDuration();\n }\n\n private long getContentDuration() {\n Timeline timeline = getCurrentTimeline();\n return timeline.isEmpty()\n ? C.TIME_UNSET\n : timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs();\n }\n\n public long getCurrentPosition() {\n verifyApplicationThread();\n return Util.usToMs(getCurrentPositionUsInternal(playbackInfo));\n }\n\n public long getBufferedPosition() {\n verifyApplicationThread();\n if (isPlayingAd()) {\n return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)\n ? Util.usToMs(playbackInfo.bufferedPositionUs)\n : getDuration();\n }\n return getContentBufferedPosition();\n }\n\n public long getTotalBufferedDuration() {\n verifyApplicationThread();\n return Util.usToMs(playbackInfo.totalBufferedDurationUs);\n }\n\n public boolean isPlayingAd() {\n verifyApplicationThread();\n return playbackInfo.periodId.isAd();\n }\n\n public int getCurrentAdGroupIndex() {\n verifyApplicationThread();\n return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET;\n }\n\n public int getCurrentAdIndexInAdGroup() {\n verifyApplicationThread();\n return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET;\n }\n\n public long getContentPosition() {\n verifyApplicationThread();\n if (isPlayingAd()) {\n playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);\n return playbackInfo.requestedContentPositionUs == C.TIME_UNSET\n ? playbackInfo\n .timeline\n .getWindow(getCurrentMediaItemIndex(), window)\n .getDefaultPositionMs()\n : period.getPositionInWindowMs() + Util.usToMs(playbackInfo.requestedContentPositionUs);\n } else {\n return getCurrentPosition();\n }\n }\n\n public long getContentBufferedPosition() {\n verifyApplicationThread();\n if (playbackInfo.timeline.isEmpty()) {\n return maskingWindowPositionMs;\n }\n if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber\n != playbackInfo.periodId.windowSequenceNumber) {\n return playbackInfo.timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs();\n }\n long contentBufferedPositionUs = playbackInfo.bufferedPositionUs;\n if (playbackInfo.loadingMediaPeriodId.isAd()) {\n Timeline.Period loadingPeriod =\n playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period);\n contentBufferedPositionUs =\n loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex);\n if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) {\n contentBufferedPositionUs = loadingPeriod.durationUs;\n }\n }\n return Util.usToMs(\n periodPositionUsToWindowPositionUs(\n playbackInfo.timeline, playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs));\n }\n\n public int getRendererCount() {\n verifyApplicationThread();\n return renderers.length;\n }\n\n public @C.TrackType int getRendererType(int index) {\n verifyApplicationThread();\n return renderers[index].getTrackType();\n }\n\n public Renderer getRenderer(int index) {\n verifyApplicationThread();\n return renderers[index];\n }\n\n public TrackSelector getTrackSelector() {\n verifyApplicationThread();\n return trackSelector;\n }\n\n public TrackGroupArray getCurrentTrackGroups() {\n verifyApplicationThread();\n return playbackInfo.trackGroups;\n }\n\n public TrackSelectionArray getCurrentTrackSelections() {\n verifyApplicationThread();\n return new TrackSelectionArray(playbackInfo.trackSelectorResult.selections);\n }\n\n public TracksInfo getCurrentTracksInfo() {\n verifyApplicationThread();\n return playbackInfo.trackSelectorResult.tracksInfo;\n }\n\n public TrackSelectionParameters getTrackSelectionParameters() {\n verifyApplicationThread();\n return trackSelector.getParameters();\n }\n\n public void setTrackSelectionParameters(TrackSelectionParameters parameters) {\n verifyApplicationThread();\n if (!trackSelector.isSetParametersSupported()\n || parameters.equals(trackSelector.getParameters())) {\n return;\n }\n trackSelector.setParameters(parameters);\n listeners.queueEvent(\n EVENT_TRACK_SELECTION_PARAMETERS_CHANGED,\n listener -> listener.onTrackSelectionParametersChanged(parameters));\n }\n\n public MediaMetadata getMediaMetadata() {\n verifyApplicationThread();\n return mediaMetadata;\n }\n\n private void onMetadata(Metadata metadata) {\n staticAndDynamicMediaMetadata =\n staticAndDynamicMediaMetadata.buildUpon().populateFromMetadata(metadata).build();\n\n MediaMetadata newMediaMetadata = buildUpdatedMediaMetadata();\n\n if (newMediaMetadata.equals(mediaMetadata)) {\n return;\n }\n mediaMetadata = newMediaMetadata;\n listeners.sendEvent(\n EVENT_MEDIA_METADATA_CHANGED, listener -> listener.onMediaMetadataChanged(mediaMetadata));\n }\n\n public MediaMetadata getPlaylistMetadata() {\n verifyApplicationThread();\n return playlistMetadata;\n }\n\n public void setPlaylistMetadata(MediaMetadata playlistMetadata) {\n verifyApplicationThread();\n checkNotNull(playlistMetadata);\n if (playlistMetadata.equals(this.playlistMetadata)) {\n return;\n }\n this.playlistMetadata = playlistMetadata;\n listeners.sendEvent(\n EVENT_PLAYLIST_METADATA_CHANGED,\n listener -> listener.onPlaylistMetadataChanged(this.playlistMetadata));\n }\n\n public Timeline getCurrentTimeline() {\n verifyApplicationThread();\n return playbackInfo.timeline;\n }\n\n public void setVideoScalingMode(@C.VideoScalingMode int videoScalingMode) {\n verifyApplicationThread();\n this.videoScalingMode = videoScalingMode;\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode);\n }\n\n public @C.VideoScalingMode int getVideoScalingMode() {\n return videoScalingMode;\n }\n\n public void setVideoChangeFrameRateStrategy(\n @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy) {\n verifyApplicationThread();\n if (this.videoChangeFrameRateStrategy == videoChangeFrameRateStrategy) {\n return;\n }\n this.videoChangeFrameRateStrategy = videoChangeFrameRateStrategy;\n sendRendererMessage(\n TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy);\n }\n\n public @C.VideoChangeFrameRateStrategy int getVideoChangeFrameRateStrategy() {\n return videoChangeFrameRateStrategy;\n }\n\n public VideoSize getVideoSize() {\n return videoSize;\n }\n\n public void clearVideoSurface() {\n verifyApplicationThread();\n removeSurfaceCallbacks();\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n\n public void clearVideoSurface(@Nullable Surface surface) {\n verifyApplicationThread();\n if (surface != null && surface == videoOutput) {\n clearVideoSurface();\n }\n }\n\n public void setVideoSurface(@Nullable Surface surface) {\n verifyApplicationThread();\n removeSurfaceCallbacks();\n setVideoOutputInternal(surface);\n int newSurfaceSize = surface == null ? 0 : C.LENGTH_UNSET;\n maybeNotifySurfaceSizeChanged(/* width= */ newSurfaceSize, /* height= */ newSurfaceSize);\n }\n\n public void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) {\n verifyApplicationThread();\n if (surfaceHolder == null) {\n clearVideoSurface();\n } else {\n removeSurfaceCallbacks();\n this.surfaceHolderSurfaceIsVideoOutput = true;\n this.surfaceHolder = surfaceHolder;\n surfaceHolder.addCallback(componentListener);\n Surface surface = surfaceHolder.getSurface();\n if (surface != null && surface.isValid()) {\n setVideoOutputInternal(surface);\n Rect surfaceSize = surfaceHolder.getSurfaceFrame();\n maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height());\n } else {\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n }\n }\n\n public void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) {\n verifyApplicationThread();\n if (surfaceHolder != null && surfaceHolder == this.surfaceHolder) {\n clearVideoSurface();\n }\n }\n\n public void setVideoSurfaceView(@Nullable SurfaceView surfaceView) {\n verifyApplicationThread();\n if (surfaceView instanceof VideoDecoderOutputBufferRenderer) {\n removeSurfaceCallbacks();\n setVideoOutputInternal(surfaceView);\n setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder());\n } else if (surfaceView instanceof SphericalGLSurfaceView) {\n removeSurfaceCallbacks();\n sphericalGLSurfaceView = (SphericalGLSurfaceView) surfaceView;\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW)\n .setPayload(sphericalGLSurfaceView)\n .send();\n sphericalGLSurfaceView.addVideoSurfaceListener(componentListener);\n setVideoOutputInternal(sphericalGLSurfaceView.getVideoSurface());\n setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder());\n } else {\n setVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());\n }\n }\n\n public void clearVideoSurfaceView(@Nullable SurfaceView surfaceView) {\n verifyApplicationThread();\n clearVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());\n }\n\n public void setVideoTextureView(@Nullable TextureView textureView) {\n verifyApplicationThread();\n if (textureView == null) {\n clearVideoSurface();\n } else {\n removeSurfaceCallbacks();\n this.textureView = textureView;\n if (textureView.getSurfaceTextureListener() != null) {\n Log.w(TAG, \"Replacing existing SurfaceTextureListener.\");\n }\n textureView.setSurfaceTextureListener(componentListener);\n @Nullable\n SurfaceTexture surfaceTexture =\n textureView.isAvailable() ? textureView.getSurfaceTexture() : null;\n if (surfaceTexture == null) {\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n } else {\n setSurfaceTextureInternal(surfaceTexture);\n maybeNotifySurfaceSizeChanged(textureView.getWidth(), textureView.getHeight());\n }\n }\n }\n\n public void clearVideoTextureView(@Nullable TextureView textureView) {\n verifyApplicationThread();\n if (textureView != null && textureView == this.textureView) {\n clearVideoSurface();\n }\n }\n\n public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) {\n verifyApplicationThread();\n if (playerReleased) {\n return;\n }\n if (!Util.areEqual(this.audioAttributes, audioAttributes)) {\n this.audioAttributes = audioAttributes;\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes);\n streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage));\n analyticsCollector.onAudioAttributesChanged(audioAttributes);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onAudioAttributesChanged(audioAttributes);\n }\n }\n\n audioFocusManager.setAudioAttributes(handleAudioFocus ? audioAttributes : null);\n boolean playWhenReady = getPlayWhenReady();\n @AudioFocusManager.PlayerCommand\n int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState());\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n }\n\n public AudioAttributes getAudioAttributes() {\n return audioAttributes;\n }\n\n public void setAudioSessionId(int audioSessionId) {\n verifyApplicationThread();\n if (this.audioSessionId == audioSessionId) {\n return;\n }\n if (audioSessionId == C.AUDIO_SESSION_ID_UNSET) {\n if (Util.SDK_INT < 21) {\n audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET);\n } else {\n audioSessionId = Util.generateAudioSessionIdV21(applicationContext);\n }\n } else if (Util.SDK_INT < 21) {\n // We need to re-initialize keepSessionIdAudioTrack to make sure the session is kept alive for\n // as long as the player is using it.\n initializeKeepSessionIdAudioTrack(audioSessionId);\n }\n this.audioSessionId = audioSessionId;\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n analyticsCollector.onAudioSessionIdChanged(audioSessionId);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onAudioSessionIdChanged(audioSessionId);\n }\n }\n\n public int getAudioSessionId() {\n return audioSessionId;\n }\n\n public void setAuxEffectInfo(AuxEffectInfo auxEffectInfo) {\n verifyApplicationThread();\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUX_EFFECT_INFO, auxEffectInfo);\n }\n\n public void clearAuxEffectInfo() {\n setAuxEffectInfo(new AuxEffectInfo(AuxEffectInfo.NO_AUX_EFFECT_ID, /* sendLevel= */ 0f));\n }\n\n public void setVolume(float volume) {\n verifyApplicationThread();\n volume = Util.constrainValue(volume, /* min= */ 0, /* max= */ 1);\n if (this.volume == volume) {\n return;\n }\n this.volume = volume;\n sendVolumeToRenderers();\n analyticsCollector.onVolumeChanged(volume);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onVolumeChanged(volume);\n }\n }\n\n public float getVolume() {\n return volume;\n }\n\n public boolean getSkipSilenceEnabled() {\n return skipSilenceEnabled;\n }\n\n public void setSkipSilenceEnabled(boolean skipSilenceEnabled) {\n verifyApplicationThread();\n if (this.skipSilenceEnabled == skipSilenceEnabled) {\n return;\n }\n this.skipSilenceEnabled = skipSilenceEnabled;\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled);\n notifySkipSilenceEnabledChanged();\n }\n\n public AnalyticsCollector getAnalyticsCollector() {\n return analyticsCollector;\n }\n\n public void addAnalyticsListener(AnalyticsListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n checkNotNull(listener);\n analyticsCollector.addListener(listener);\n }\n\n public void removeAnalyticsListener(AnalyticsListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n analyticsCollector.removeListener(listener);\n }\n\n public void setHandleAudioBecomingNoisy(boolean handleAudioBecomingNoisy) {\n verifyApplicationThread();\n if (playerReleased) {\n return;\n }\n audioBecomingNoisyManager.setEnabled(handleAudioBecomingNoisy);\n }\n\n public void setPriorityTaskManager(@Nullable PriorityTaskManager priorityTaskManager) {\n verifyApplicationThread();\n if (Util.areEqual(this.priorityTaskManager, priorityTaskManager)) {\n return;\n }\n if (isPriorityTaskManagerRegistered) {\n checkNotNull(this.priorityTaskManager).remove(C.PRIORITY_PLAYBACK);\n }\n if (priorityTaskManager != null && isLoading()) {\n priorityTaskManager.add(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = true;\n } else {\n isPriorityTaskManagerRegistered = false;\n }\n this.priorityTaskManager = priorityTaskManager;\n }\n\n @Nullable\n public Format getVideoFormat() {\n return videoFormat;\n }\n\n @Nullable\n public Format getAudioFormat() {\n return audioFormat;\n }\n\n @Nullable\n public DecoderCounters getVideoDecoderCounters() {\n return videoDecoderCounters;\n }\n\n @Nullable\n public DecoderCounters getAudioDecoderCounters() {\n return audioDecoderCounters;\n }\n\n public void setVideoFrameMetadataListener(VideoFrameMetadataListener listener) {\n verifyApplicationThread();\n videoFrameMetadataListener = listener;\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER)\n .setPayload(listener)\n .send();\n }\n\n public void clearVideoFrameMetadataListener(VideoFrameMetadataListener listener) {\n verifyApplicationThread();\n if (videoFrameMetadataListener != listener) {\n return;\n }\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER)\n .setPayload(null)\n .send();\n }\n\n public void setCameraMotionListener(CameraMotionListener listener) {\n verifyApplicationThread();\n cameraMotionListener = listener;\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER)\n .setPayload(listener)\n .send();\n }\n\n public void clearCameraMotionListener(CameraMotionListener listener) {\n verifyApplicationThread();\n if (cameraMotionListener != listener) {\n return;\n }\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER)\n .setPayload(null)\n .send();\n }\n\n public List getCurrentCues() {\n verifyApplicationThread();\n return currentCues;\n }\n\n public void addListener(Listener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n checkNotNull(listener);\n listeners.add(listener);\n listenerArraySet.add(listener);\n }\n\n public void removeListener(Listener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n checkNotNull(listener);\n listeners.remove(listener);\n listenerArraySet.remove(listener);\n }\n\n public void setHandleWakeLock(boolean handleWakeLock) {\n setWakeMode(handleWakeLock ? C.WAKE_MODE_LOCAL : C.WAKE_MODE_NONE);\n }\n\n public void setWakeMode(@C.WakeMode int wakeMode) {\n verifyApplicationThread();\n switch (wakeMode) {\n case C.WAKE_MODE_NONE:\n wakeLockManager.setEnabled(false);\n wifiLockManager.setEnabled(false);\n break;\n case C.WAKE_MODE_LOCAL:\n wakeLockManager.setEnabled(true);\n wifiLockManager.setEnabled(false);\n break;\n case C.WAKE_MODE_NETWORK:\n wakeLockManager.setEnabled(true);\n wifiLockManager.setEnabled(true);\n break;\n default:\n break;\n }\n }\n\n public DeviceInfo getDeviceInfo() {\n verifyApplicationThread();\n return deviceInfo;\n }\n\n public int getDeviceVolume() {\n verifyApplicationThread();\n return streamVolumeManager.getVolume();\n }\n\n public boolean isDeviceMuted() {\n verifyApplicationThread();\n return streamVolumeManager.isMuted();\n }\n\n public void setDeviceVolume(int volume) {\n verifyApplicationThread();\n streamVolumeManager.setVolume(volume);\n }\n\n public void increaseDeviceVolume() {\n verifyApplicationThread();\n streamVolumeManager.increaseVolume();\n }\n\n public void decreaseDeviceVolume() {\n verifyApplicationThread();\n streamVolumeManager.decreaseVolume();\n }\n\n public void setDeviceMuted(boolean muted) {\n verifyApplicationThread();\n streamVolumeManager.setMuted(muted);\n }\n\n /* package */ void setThrowsWhenUsingWrongThread(boolean throwsWhenUsingWrongThread) {\n this.throwsWhenUsingWrongThread = throwsWhenUsingWrongThread;\n }\n\n private int getCurrentWindowIndexInternal() {\n if (playbackInfo.timeline.isEmpty()) {\n return maskingWindowIndex;\n } else {\n return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period)\n .windowIndex;\n }\n }\n\n private long getCurrentPositionUsInternal(PlaybackInfo playbackInfo) {\n if (playbackInfo.timeline.isEmpty()) {\n return Util.msToUs(maskingWindowPositionMs);\n } else if (playbackInfo.periodId.isAd()) {\n return playbackInfo.positionUs;\n } else {\n return periodPositionUsToWindowPositionUs(\n playbackInfo.timeline, playbackInfo.periodId, playbackInfo.positionUs);\n }\n }\n\n private List createMediaSources(List mediaItems) {\n List mediaSources = new ArrayList<>();\n for (int i = 0; i < mediaItems.size(); i++) {\n mediaSources.add(mediaSourceFactory.createMediaSource(mediaItems.get(i)));\n }\n return mediaSources;\n }\n\n private void handlePlaybackInfo(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate) {\n pendingOperationAcks -= playbackInfoUpdate.operationAcks;\n if (playbackInfoUpdate.positionDiscontinuity) {\n pendingDiscontinuityReason = playbackInfoUpdate.discontinuityReason;\n pendingDiscontinuity = true;\n }\n if (playbackInfoUpdate.hasPlayWhenReadyChangeReason) {\n pendingPlayWhenReadyChangeReason = playbackInfoUpdate.playWhenReadyChangeReason;\n }\n if (pendingOperationAcks == 0) {\n Timeline newTimeline = playbackInfoUpdate.playbackInfo.timeline;\n if (!this.playbackInfo.timeline.isEmpty() && newTimeline.isEmpty()) {\n // Update the masking variables, which are used when the timeline becomes empty because a\n // ConcatenatingMediaSource has been cleared.\n maskingWindowIndex = C.INDEX_UNSET;\n maskingWindowPositionMs = 0;\n maskingPeriodIndex = 0;\n }\n if (!newTimeline.isEmpty()) {\n List timelines = ((PlaylistTimeline) newTimeline).getChildTimelines();\n checkState(timelines.size() == mediaSourceHolderSnapshots.size());\n for (int i = 0; i < timelines.size(); i++) {\n mediaSourceHolderSnapshots.get(i).timeline = timelines.get(i);\n }\n }\n boolean positionDiscontinuity = false;\n long discontinuityWindowStartPositionUs = C.TIME_UNSET;\n if (pendingDiscontinuity) {\n positionDiscontinuity =\n !playbackInfoUpdate.playbackInfo.periodId.equals(playbackInfo.periodId)\n || playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs\n != playbackInfo.positionUs;\n if (positionDiscontinuity) {\n discontinuityWindowStartPositionUs =\n newTimeline.isEmpty() || playbackInfoUpdate.playbackInfo.periodId.isAd()\n ? playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs\n : periodPositionUsToWindowPositionUs(\n newTimeline,\n playbackInfoUpdate.playbackInfo.periodId,\n playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs);\n }\n }\n pendingDiscontinuity = false;\n updatePlaybackInfo(\n playbackInfoUpdate.playbackInfo,\n TIMELINE_CHANGE_REASON_SOURCE_UPDATE,\n pendingPlayWhenReadyChangeReason,\n /* seekProcessed= */ false,\n positionDiscontinuity,\n pendingDiscontinuityReason,\n discontinuityWindowStartPositionUs,\n /* ignored */ C.INDEX_UNSET);\n }\n }\n\n // Calling deprecated listeners.\n @SuppressWarnings(\"deprecation\")\n private void updatePlaybackInfo(\n PlaybackInfo playbackInfo,\n @TimelineChangeReason int timelineChangeReason,\n @PlayWhenReadyChangeReason int playWhenReadyChangeReason,\n boolean seekProcessed,\n boolean positionDiscontinuity,\n @DiscontinuityReason int positionDiscontinuityReason,\n long discontinuityWindowStartPositionUs,\n int oldMaskingMediaItemIndex) {\n\n // Assign playback info immediately such that all getters return the right values, but keep\n // snapshot of previous and new state so that listener invocations are triggered correctly.\n PlaybackInfo previousPlaybackInfo = this.playbackInfo;\n PlaybackInfo newPlaybackInfo = playbackInfo;\n this.playbackInfo = playbackInfo;\n\n Pair mediaItemTransitionInfo =\n evaluateMediaItemTransitionReason(\n newPlaybackInfo,\n previousPlaybackInfo,\n positionDiscontinuity,\n positionDiscontinuityReason,\n !previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline));\n boolean mediaItemTransitioned = mediaItemTransitionInfo.first;\n int mediaItemTransitionReason = mediaItemTransitionInfo.second;\n MediaMetadata newMediaMetadata = mediaMetadata;\n @Nullable MediaItem mediaItem = null;\n if (mediaItemTransitioned) {\n if (!newPlaybackInfo.timeline.isEmpty()) {\n int windowIndex =\n newPlaybackInfo.timeline.getPeriodByUid(newPlaybackInfo.periodId.periodUid, period)\n .windowIndex;\n mediaItem = newPlaybackInfo.timeline.getWindow(windowIndex, window).mediaItem;\n }\n staticAndDynamicMediaMetadata = MediaMetadata.EMPTY;\n }\n if (mediaItemTransitioned\n || !previousPlaybackInfo.staticMetadata.equals(newPlaybackInfo.staticMetadata)) {\n staticAndDynamicMediaMetadata =\n staticAndDynamicMediaMetadata\n .buildUpon()\n .populateFromMetadata(newPlaybackInfo.staticMetadata)\n .build();\n newMediaMetadata = buildUpdatedMediaMetadata();\n }\n boolean metadataChanged = !newMediaMetadata.equals(mediaMetadata);\n mediaMetadata = newMediaMetadata;\n boolean playWhenReadyChanged =\n previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady;\n boolean playbackStateChanged =\n previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState;\n if (playbackStateChanged || playWhenReadyChanged) {\n updateWakeAndWifiLock();\n }\n boolean isLoadingChanged = previousPlaybackInfo.isLoading != newPlaybackInfo.isLoading;\n if (isLoadingChanged) {\n updatePriorityTaskManagerForIsLoadingChange(newPlaybackInfo.isLoading);\n }\n\n if (!previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline)) {\n listeners.queueEvent(\n Player.EVENT_TIMELINE_CHANGED,\n listener -> listener.onTimelineChanged(newPlaybackInfo.timeline, timelineChangeReason));\n }\n if (positionDiscontinuity) {\n PositionInfo previousPositionInfo =\n getPreviousPositionInfo(\n positionDiscontinuityReason, previousPlaybackInfo, oldMaskingMediaItemIndex);\n PositionInfo positionInfo = getPositionInfo(discontinuityWindowStartPositionUs);\n listeners.queueEvent(\n Player.EVENT_POSITION_DISCONTINUITY,\n listener -> {\n listener.onPositionDiscontinuity(positionDiscontinuityReason);\n listener.onPositionDiscontinuity(\n previousPositionInfo, positionInfo, positionDiscontinuityReason);\n });\n }\n if (mediaItemTransitioned) {\n @Nullable final MediaItem finalMediaItem = mediaItem;\n listeners.queueEvent(\n Player.EVENT_MEDIA_ITEM_TRANSITION,\n listener -> listener.onMediaItemTransition(finalMediaItem, mediaItemTransitionReason));\n }\n if (previousPlaybackInfo.playbackError != newPlaybackInfo.playbackError) {\n listeners.queueEvent(\n Player.EVENT_PLAYER_ERROR,\n listener -> listener.onPlayerErrorChanged(newPlaybackInfo.playbackError));\n if (newPlaybackInfo.playbackError != null) {\n listeners.queueEvent(\n Player.EVENT_PLAYER_ERROR,\n listener -> listener.onPlayerError(newPlaybackInfo.playbackError));\n }\n }\n if (previousPlaybackInfo.trackSelectorResult != newPlaybackInfo.trackSelectorResult) {\n trackSelector.onSelectionActivated(newPlaybackInfo.trackSelectorResult.info);\n TrackSelectionArray newSelection =\n new TrackSelectionArray(newPlaybackInfo.trackSelectorResult.selections);\n listeners.queueEvent(\n Player.EVENT_TRACKS_CHANGED,\n listener -> listener.onTracksChanged(newPlaybackInfo.trackGroups, newSelection));\n listeners.queueEvent(\n Player.EVENT_TRACKS_CHANGED,\n listener -> listener.onTracksInfoChanged(newPlaybackInfo.trackSelectorResult.tracksInfo));\n }\n if (metadataChanged) {\n final MediaMetadata finalMediaMetadata = mediaMetadata;\n listeners.queueEvent(\n EVENT_MEDIA_METADATA_CHANGED,\n listener -> listener.onMediaMetadataChanged(finalMediaMetadata));\n }\n if (isLoadingChanged) {\n listeners.queueEvent(\n Player.EVENT_IS_LOADING_CHANGED,\n listener -> {\n listener.onLoadingChanged(newPlaybackInfo.isLoading);\n listener.onIsLoadingChanged(newPlaybackInfo.isLoading);\n });\n }\n if (playbackStateChanged || playWhenReadyChanged) {\n listeners.queueEvent(\n /* eventFlag= */ C.INDEX_UNSET,\n listener ->\n listener.onPlayerStateChanged(\n newPlaybackInfo.playWhenReady, newPlaybackInfo.playbackState));\n }\n if (playbackStateChanged) {\n listeners.queueEvent(\n Player.EVENT_PLAYBACK_STATE_CHANGED,\n listener -> listener.onPlaybackStateChanged(newPlaybackInfo.playbackState));\n }\n if (playWhenReadyChanged) {\n listeners.queueEvent(\n Player.EVENT_PLAY_WHEN_READY_CHANGED,\n listener ->\n listener.onPlayWhenReadyChanged(\n newPlaybackInfo.playWhenReady, playWhenReadyChangeReason));\n }\n if (previousPlaybackInfo.playbackSuppressionReason\n != newPlaybackInfo.playbackSuppressionReason) {\n listeners.queueEvent(\n Player.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED,\n listener ->\n listener.onPlaybackSuppressionReasonChanged(\n newPlaybackInfo.playbackSuppressionReason));\n }\n if (isPlaying(previousPlaybackInfo) != isPlaying(newPlaybackInfo)) {\n listeners.queueEvent(\n Player.EVENT_IS_PLAYING_CHANGED,\n listener -> listener.onIsPlayingChanged(isPlaying(newPlaybackInfo)));\n }\n if (!previousPlaybackInfo.playbackParameters.equals(newPlaybackInfo.playbackParameters)) {\n listeners.queueEvent(\n Player.EVENT_PLAYBACK_PARAMETERS_CHANGED,\n listener -> listener.onPlaybackParametersChanged(newPlaybackInfo.playbackParameters));\n }\n if (seekProcessed) {\n listeners.queueEvent(/* eventFlag= */ C.INDEX_UNSET, Listener::onSeekProcessed);\n }\n updateAvailableCommands();\n listeners.flushEvents();\n\n if (previousPlaybackInfo.offloadSchedulingEnabled != newPlaybackInfo.offloadSchedulingEnabled) {\n for (AudioOffloadListener listener : audioOffloadListeners) {\n listener.onExperimentalOffloadSchedulingEnabledChanged(\n newPlaybackInfo.offloadSchedulingEnabled);\n }\n }\n if (previousPlaybackInfo.sleepingForOffload != newPlaybackInfo.sleepingForOffload) {\n for (AudioOffloadListener listener : audioOffloadListeners) {\n listener.onExperimentalSleepingForOffloadChanged(newPlaybackInfo.sleepingForOffload);\n }\n }\n }\n\n private PositionInfo getPreviousPositionInfo(\n @DiscontinuityReason int positionDiscontinuityReason,\n PlaybackInfo oldPlaybackInfo,\n int oldMaskingMediaItemIndex) {\n @Nullable Object oldWindowUid = null;\n @Nullable Object oldPeriodUid = null;\n int oldMediaItemIndex = oldMaskingMediaItemIndex;\n int oldPeriodIndex = C.INDEX_UNSET;\n @Nullable MediaItem oldMediaItem = null;\n Timeline.Period oldPeriod = new Timeline.Period();\n if (!oldPlaybackInfo.timeline.isEmpty()) {\n oldPeriodUid = oldPlaybackInfo.periodId.periodUid;\n oldPlaybackInfo.timeline.getPeriodByUid(oldPeriodUid, oldPeriod);\n oldMediaItemIndex = oldPeriod.windowIndex;\n oldPeriodIndex = oldPlaybackInfo.timeline.getIndexOfPeriod(oldPeriodUid);\n oldWindowUid = oldPlaybackInfo.timeline.getWindow(oldMediaItemIndex, window).uid;\n oldMediaItem = window.mediaItem;\n }\n long oldPositionUs;\n long oldContentPositionUs;\n if (positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) {\n if (oldPlaybackInfo.periodId.isAd()) {\n // The old position is the end of the previous ad.\n oldPositionUs =\n oldPeriod.getAdDurationUs(\n oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup);\n // The ad cue point is stored in the old requested content position.\n oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo);\n } else if (oldPlaybackInfo.periodId.nextAdGroupIndex != C.INDEX_UNSET) {\n // The old position is the end of a clipped content before an ad group. Use the exact ad\n // cue point as the transition position.\n oldPositionUs = getRequestedContentPositionUs(playbackInfo);\n oldContentPositionUs = oldPositionUs;\n } else {\n // The old position is the end of a Timeline period. Use the exact duration.\n oldPositionUs = oldPeriod.positionInWindowUs + oldPeriod.durationUs;\n oldContentPositionUs = oldPositionUs;\n }\n } else if (oldPlaybackInfo.periodId.isAd()) {\n oldPositionUs = oldPlaybackInfo.positionUs;\n oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo);\n } else {\n oldPositionUs = oldPeriod.positionInWindowUs + oldPlaybackInfo.positionUs;\n oldContentPositionUs = oldPositionUs;\n }\n return new PositionInfo(\n oldWindowUid,\n oldMediaItemIndex,\n oldMediaItem,\n oldPeriodUid,\n oldPeriodIndex,\n Util.usToMs(oldPositionUs),\n Util.usToMs(oldContentPositionUs),\n oldPlaybackInfo.periodId.adGroupIndex,\n oldPlaybackInfo.periodId.adIndexInAdGroup);\n }\n\n private PositionInfo getPositionInfo(long discontinuityWindowStartPositionUs) {\n @Nullable Object newWindowUid = null;\n @Nullable Object newPeriodUid = null;\n int newMediaItemIndex = getCurrentMediaItemIndex();\n int newPeriodIndex = C.INDEX_UNSET;\n @Nullable MediaItem newMediaItem = null;\n if (!playbackInfo.timeline.isEmpty()) {\n newPeriodUid = playbackInfo.periodId.periodUid;\n playbackInfo.timeline.getPeriodByUid(newPeriodUid, period);\n newPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(newPeriodUid);\n newWindowUid = playbackInfo.timeline.getWindow(newMediaItemIndex, window).uid;\n newMediaItem = window.mediaItem;\n }\n long positionMs = Util.usToMs(discontinuityWindowStartPositionUs);\n return new PositionInfo(\n newWindowUid,\n newMediaItemIndex,\n newMediaItem,\n newPeriodUid,\n newPeriodIndex,\n positionMs,\n /* contentPositionMs= */ playbackInfo.periodId.isAd()\n ? Util.usToMs(getRequestedContentPositionUs(playbackInfo))\n : positionMs,\n playbackInfo.periodId.adGroupIndex,\n playbackInfo.periodId.adIndexInAdGroup);\n }\n\n private static long getRequestedContentPositionUs(PlaybackInfo playbackInfo) {\n Timeline.Window window = new Timeline.Window();\n Timeline.Period period = new Timeline.Period();\n playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);\n return playbackInfo.requestedContentPositionUs == C.TIME_UNSET\n ? playbackInfo.timeline.getWindow(period.windowIndex, window).getDefaultPositionUs()\n : period.getPositionInWindowUs() + playbackInfo.requestedContentPositionUs;\n }\n\n private Pair evaluateMediaItemTransitionReason(\n PlaybackInfo playbackInfo,\n PlaybackInfo oldPlaybackInfo,\n boolean positionDiscontinuity,\n @DiscontinuityReason int positionDiscontinuityReason,\n boolean timelineChanged) {\n\n Timeline oldTimeline = oldPlaybackInfo.timeline;\n Timeline newTimeline = playbackInfo.timeline;\n if (newTimeline.isEmpty() && oldTimeline.isEmpty()) {\n return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET);\n } else if (newTimeline.isEmpty() != oldTimeline.isEmpty()) {\n return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED);\n }\n\n int oldWindowIndex =\n oldTimeline.getPeriodByUid(oldPlaybackInfo.periodId.periodUid, period).windowIndex;\n Object oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid;\n int newWindowIndex =\n newTimeline.getPeriodByUid(playbackInfo.periodId.periodUid, period).windowIndex;\n Object newWindowUid = newTimeline.getWindow(newWindowIndex, window).uid;\n if (!oldWindowUid.equals(newWindowUid)) {\n @Player.MediaItemTransitionReason int transitionReason;\n if (positionDiscontinuity\n && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) {\n transitionReason = MEDIA_ITEM_TRANSITION_REASON_AUTO;\n } else if (positionDiscontinuity\n && positionDiscontinuityReason == DISCONTINUITY_REASON_SEEK) {\n transitionReason = MEDIA_ITEM_TRANSITION_REASON_SEEK;\n } else if (timelineChanged) {\n transitionReason = MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED;\n } else {\n // A change in window uid must be justified by one of the reasons above.\n throw new IllegalStateException();\n }\n return new Pair<>(/* isTransitioning */ true, transitionReason);\n } else if (positionDiscontinuity\n && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION\n && oldPlaybackInfo.periodId.windowSequenceNumber\n < playbackInfo.periodId.windowSequenceNumber) {\n return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_REPEAT);\n }\n return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET);\n }\n\n private void updateAvailableCommands() {\n Commands previousAvailableCommands = availableCommands;\n availableCommands = Util.getAvailableCommands(wrappingPlayer, permanentAvailableCommands);\n if (!availableCommands.equals(previousAvailableCommands)) {\n listeners.queueEvent(\n Player.EVENT_AVAILABLE_COMMANDS_CHANGED,\n listener -> listener.onAvailableCommandsChanged(availableCommands));\n }\n }\n\n private void setMediaSourcesInternal(\n List mediaSources,\n int startWindowIndex,\n long startPositionMs,\n boolean resetToDefaultPosition) {\n int currentWindowIndex = getCurrentWindowIndexInternal();\n long currentPositionMs = getCurrentPosition();\n pendingOperationAcks++;\n if (!mediaSourceHolderSnapshots.isEmpty()) {\n removeMediaSourceHolders(\n /* fromIndex= */ 0, /* toIndexExclusive= */ mediaSourceHolderSnapshots.size());\n }\n List holders =\n addMediaSourceHolders(/* index= */ 0, mediaSources);\n Timeline timeline = createMaskingTimeline();\n if (!timeline.isEmpty() && startWindowIndex >= timeline.getWindowCount()) {\n throw new IllegalSeekPositionException(timeline, startWindowIndex, startPositionMs);\n }\n // Evaluate the actual start position.\n if (resetToDefaultPosition) {\n startWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled);\n startPositionMs = C.TIME_UNSET;\n } else if (startWindowIndex == C.INDEX_UNSET) {\n startWindowIndex = currentWindowIndex;\n startPositionMs = currentPositionMs;\n }\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n timeline,\n maskWindowPositionMsOrGetPeriodPositionUs(timeline, startWindowIndex, startPositionMs));\n // Mask the playback state.\n int maskingPlaybackState = newPlaybackInfo.playbackState;\n if (startWindowIndex != C.INDEX_UNSET && newPlaybackInfo.playbackState != STATE_IDLE) {\n // Position reset to startWindowIndex (results in pending initial seek).\n if (timeline.isEmpty() || startWindowIndex >= timeline.getWindowCount()) {\n // Setting an empty timeline or invalid seek transitions to ended.\n maskingPlaybackState = STATE_ENDED;\n } else {\n maskingPlaybackState = STATE_BUFFERING;\n }\n }\n newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(maskingPlaybackState);\n internalPlayer.setMediaSources(\n holders, startWindowIndex, Util.msToUs(startPositionMs), shuffleOrder);\n boolean positionDiscontinuity =\n !playbackInfo.periodId.periodUid.equals(newPlaybackInfo.periodId.periodUid)\n && !playbackInfo.timeline.isEmpty();\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ positionDiscontinuity,\n DISCONTINUITY_REASON_REMOVE,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),\n /* ignored */ C.INDEX_UNSET);\n }\n\n private List addMediaSourceHolders(\n int index, List mediaSources) {\n List holders = new ArrayList<>();\n for (int i = 0; i < mediaSources.size(); i++) {\n MediaSourceList.MediaSourceHolder holder =\n new MediaSourceList.MediaSourceHolder(mediaSources.get(i), useLazyPreparation);\n holders.add(holder);\n mediaSourceHolderSnapshots.add(\n i + index, new MediaSourceHolderSnapshot(holder.uid, holder.mediaSource.getTimeline()));\n }\n shuffleOrder =\n shuffleOrder.cloneAndInsert(\n /* insertionIndex= */ index, /* insertionCount= */ holders.size());\n return holders;\n }\n\n private PlaybackInfo removeMediaItemsInternal(int fromIndex, int toIndex) {\n Assertions.checkArgument(\n fromIndex >= 0 && toIndex >= fromIndex && toIndex <= mediaSourceHolderSnapshots.size());\n int currentIndex = getCurrentMediaItemIndex();\n Timeline oldTimeline = getCurrentTimeline();\n int currentMediaSourceCount = mediaSourceHolderSnapshots.size();\n pendingOperationAcks++;\n removeMediaSourceHolders(fromIndex, /* toIndexExclusive= */ toIndex);\n Timeline newTimeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n newTimeline,\n getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));\n // Player transitions to STATE_ENDED if the current index is part of the removed tail.\n final boolean transitionsToEnded =\n newPlaybackInfo.playbackState != STATE_IDLE\n && newPlaybackInfo.playbackState != STATE_ENDED\n && fromIndex < toIndex\n && toIndex == currentMediaSourceCount\n && currentIndex >= newPlaybackInfo.timeline.getWindowCount();\n if (transitionsToEnded) {\n newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(STATE_ENDED);\n }\n internalPlayer.removeMediaSources(fromIndex, toIndex, shuffleOrder);\n return newPlaybackInfo;\n }\n\n private void removeMediaSourceHolders(int fromIndex, int toIndexExclusive) {\n for (int i = toIndexExclusive - 1; i >= fromIndex; i--) {\n mediaSourceHolderSnapshots.remove(i);\n }\n shuffleOrder = shuffleOrder.cloneAndRemove(fromIndex, toIndexExclusive);\n }\n\n private Timeline createMaskingTimeline() {\n return new PlaylistTimeline(mediaSourceHolderSnapshots, shuffleOrder);\n }\n\n private PlaybackInfo maskTimelineAndPosition(\n PlaybackInfo playbackInfo, Timeline timeline, @Nullable Pair periodPositionUs) {\n Assertions.checkArgument(timeline.isEmpty() || periodPositionUs != null);\n Timeline oldTimeline = playbackInfo.timeline;\n // Mask the timeline.\n playbackInfo = playbackInfo.copyWithTimeline(timeline);\n\n if (timeline.isEmpty()) {\n // Reset periodId and loadingPeriodId.\n MediaPeriodId dummyMediaPeriodId = PlaybackInfo.getDummyPeriodForEmptyTimeline();\n long positionUs = Util.msToUs(maskingWindowPositionMs);\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n dummyMediaPeriodId,\n positionUs,\n /* requestedContentPositionUs= */ positionUs,\n /* discontinuityStartPositionUs= */ positionUs,\n /* totalBufferedDurationUs= */ 0,\n TrackGroupArray.EMPTY,\n emptyTrackSelectorResult,\n /* staticMetadata= */ ImmutableList.of());\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(dummyMediaPeriodId);\n playbackInfo.bufferedPositionUs = playbackInfo.positionUs;\n return playbackInfo;\n }\n\n Object oldPeriodUid = playbackInfo.periodId.periodUid;\n boolean playingPeriodChanged = !oldPeriodUid.equals(castNonNull(periodPositionUs).first);\n MediaPeriodId newPeriodId =\n playingPeriodChanged ? new MediaPeriodId(periodPositionUs.first) : playbackInfo.periodId;\n long newContentPositionUs = periodPositionUs.second;\n long oldContentPositionUs = Util.msToUs(getContentPosition());\n if (!oldTimeline.isEmpty()) {\n oldContentPositionUs -=\n oldTimeline.getPeriodByUid(oldPeriodUid, period).getPositionInWindowUs();\n }\n\n if (playingPeriodChanged || newContentPositionUs < oldContentPositionUs) {\n checkState(!newPeriodId.isAd());\n // The playing period changes or a backwards seek within the playing period occurs.\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n newPeriodId,\n /* positionUs= */ newContentPositionUs,\n /* requestedContentPositionUs= */ newContentPositionUs,\n /* discontinuityStartPositionUs= */ newContentPositionUs,\n /* totalBufferedDurationUs= */ 0,\n playingPeriodChanged ? TrackGroupArray.EMPTY : playbackInfo.trackGroups,\n playingPeriodChanged ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult,\n playingPeriodChanged ? ImmutableList.of() : playbackInfo.staticMetadata);\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId);\n playbackInfo.bufferedPositionUs = newContentPositionUs;\n } else if (newContentPositionUs == oldContentPositionUs) {\n // Period position remains unchanged.\n int loadingPeriodIndex =\n timeline.getIndexOfPeriod(playbackInfo.loadingMediaPeriodId.periodUid);\n if (loadingPeriodIndex == C.INDEX_UNSET\n || timeline.getPeriod(loadingPeriodIndex, period).windowIndex\n != timeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex) {\n // Discard periods after the playing period, if the loading period is discarded or the\n // playing and loading period are not in the same window.\n timeline.getPeriodByUid(newPeriodId.periodUid, period);\n long maskedBufferedPositionUs =\n newPeriodId.isAd()\n ? period.getAdDurationUs(newPeriodId.adGroupIndex, newPeriodId.adIndexInAdGroup)\n : period.durationUs;\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n newPeriodId,\n /* positionUs= */ playbackInfo.positionUs,\n /* requestedContentPositionUs= */ playbackInfo.positionUs,\n playbackInfo.discontinuityStartPositionUs,\n /* totalBufferedDurationUs= */ maskedBufferedPositionUs - playbackInfo.positionUs,\n playbackInfo.trackGroups,\n playbackInfo.trackSelectorResult,\n playbackInfo.staticMetadata);\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId);\n playbackInfo.bufferedPositionUs = maskedBufferedPositionUs;\n }\n } else {\n checkState(!newPeriodId.isAd());\n // A forward seek within the playing period (timeline did not change).\n long maskedTotalBufferedDurationUs =\n max(\n 0,\n playbackInfo.totalBufferedDurationUs - (newContentPositionUs - oldContentPositionUs));\n long maskedBufferedPositionUs = playbackInfo.bufferedPositionUs;\n if (playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)) {\n maskedBufferedPositionUs = newContentPositionUs + maskedTotalBufferedDurationUs;\n }\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n newPeriodId,\n /* positionUs= */ newContentPositionUs,\n /* requestedContentPositionUs= */ newContentPositionUs,\n /* discontinuityStartPositionUs= */ newContentPositionUs,\n maskedTotalBufferedDurationUs,\n playbackInfo.trackGroups,\n playbackInfo.trackSelectorResult,\n playbackInfo.staticMetadata);\n playbackInfo.bufferedPositionUs = maskedBufferedPositionUs;\n }\n return playbackInfo;\n }\n\n @Nullable\n private Pair getPeriodPositionUsAfterTimelineChanged(\n Timeline oldTimeline, Timeline newTimeline) {\n long currentPositionMs = getContentPosition();\n if (oldTimeline.isEmpty() || newTimeline.isEmpty()) {\n boolean isCleared = !oldTimeline.isEmpty() && newTimeline.isEmpty();\n return maskWindowPositionMsOrGetPeriodPositionUs(\n newTimeline,\n isCleared ? C.INDEX_UNSET : getCurrentWindowIndexInternal(),\n isCleared ? C.TIME_UNSET : currentPositionMs);\n }\n int currentMediaItemIndex = getCurrentMediaItemIndex();\n @Nullable\n Pair oldPeriodPositionUs =\n oldTimeline.getPeriodPositionUs(\n window, period, currentMediaItemIndex, Util.msToUs(currentPositionMs));\n Object periodUid = castNonNull(oldPeriodPositionUs).first;\n if (newTimeline.getIndexOfPeriod(periodUid) != C.INDEX_UNSET) {\n // The old period position is still available in the new timeline.\n return oldPeriodPositionUs;\n }\n // Period uid not found in new timeline. Try to get subsequent period.\n @Nullable\n Object nextPeriodUid =\n ExoPlayerImplInternal.resolveSubsequentPeriod(\n window, period, repeatMode, shuffleModeEnabled, periodUid, oldTimeline, newTimeline);\n if (nextPeriodUid != null) {\n // Reset position to the default position of the window of the subsequent period.\n newTimeline.getPeriodByUid(nextPeriodUid, period);\n return maskWindowPositionMsOrGetPeriodPositionUs(\n newTimeline,\n period.windowIndex,\n newTimeline.getWindow(period.windowIndex, window).getDefaultPositionMs());\n } else {\n // No subsequent period found and the new timeline is not empty. Use the default position.\n return maskWindowPositionMsOrGetPeriodPositionUs(\n newTimeline, /* windowIndex= */ C.INDEX_UNSET, /* windowPositionMs= */ C.TIME_UNSET);\n }\n }\n\n @Nullable\n private Pair maskWindowPositionMsOrGetPeriodPositionUs(\n Timeline timeline, int windowIndex, long windowPositionMs) {\n if (timeline.isEmpty()) {\n // If empty we store the initial seek in the masking variables.\n maskingWindowIndex = windowIndex;\n maskingWindowPositionMs = windowPositionMs == C.TIME_UNSET ? 0 : windowPositionMs;\n maskingPeriodIndex = 0;\n return null;\n }\n if (windowIndex == C.INDEX_UNSET || windowIndex >= timeline.getWindowCount()) {\n // Use default position of timeline if window index still unset or if a previous initial seek\n // now turns out to be invalid.\n windowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled);\n windowPositionMs = timeline.getWindow(windowIndex, window).getDefaultPositionMs();\n }\n return timeline.getPeriodPositionUs(window, period, windowIndex, Util.msToUs(windowPositionMs));\n }\n\n private long periodPositionUsToWindowPositionUs(\n Timeline timeline, MediaPeriodId periodId, long positionUs) {\n timeline.getPeriodByUid(periodId.periodUid, period);\n positionUs += period.getPositionInWindowUs();\n return positionUs;\n }\n\n private PlayerMessage createMessageInternal(Target target) {\n int currentWindowIndex = getCurrentWindowIndexInternal();\n return new PlayerMessage(\n internalPlayer,\n target,\n playbackInfo.timeline,\n currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex,\n clock,\n internalPlayer.getPlaybackLooper());\n }\n\n /**\n * Builds a {@link MediaMetadata} from the main sources.\n *\n *

{@link MediaItem} {@link MediaMetadata} is prioritized, with any gaps/missing fields\n * populated by metadata from static ({@link TrackGroup} {@link Format}) and dynamic ({@link\n * #onMetadata(Metadata)}) sources.\n */\n private MediaMetadata buildUpdatedMediaMetadata() {\n Timeline timeline = getCurrentTimeline();\n if (timeline.isEmpty()) {\n return staticAndDynamicMediaMetadata;\n }\n MediaItem mediaItem = timeline.getWindow(getCurrentMediaItemIndex(), window).mediaItem;\n // MediaItem metadata is prioritized over metadata within the media.\n return staticAndDynamicMediaMetadata.buildUpon().populate(mediaItem.mediaMetadata).build();\n }\n\n private void removeSurfaceCallbacks() {\n if (sphericalGLSurfaceView != null) {\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW)\n .setPayload(null)\n .send();\n sphericalGLSurfaceView.removeVideoSurfaceListener(componentListener);\n sphericalGLSurfaceView = null;\n }\n if (textureView != null) {\n if (textureView.getSurfaceTextureListener() != componentListener) {\n Log.w(TAG, \"SurfaceTextureListener already unset or replaced.\");\n } else {\n textureView.setSurfaceTextureListener(null);\n }\n textureView = null;\n }\n if (surfaceHolder != null) {\n surfaceHolder.removeCallback(componentListener);\n surfaceHolder = null;\n }\n }\n\n private void setSurfaceTextureInternal(SurfaceTexture surfaceTexture) {\n Surface surface = new Surface(surfaceTexture);\n setVideoOutputInternal(surface);\n ownedSurface = surface;\n }\n\n private void setVideoOutputInternal(@Nullable Object videoOutput) {\n // Note: We don't turn this method into a no-op if the output is being replaced with itself so\n // as to ensure onRenderedFirstFrame callbacks are still called in this case.\n List messages = new ArrayList<>();\n for (Renderer renderer : renderers) {\n if (renderer.getTrackType() == TRACK_TYPE_VIDEO) {\n messages.add(\n createMessageInternal(renderer)\n .setType(MSG_SET_VIDEO_OUTPUT)\n .setPayload(videoOutput)\n .send());\n }\n }\n boolean messageDeliveryTimedOut = false;\n if (this.videoOutput != null && this.videoOutput != videoOutput) {\n // We're replacing an output. Block to ensure that this output will not be accessed by the\n // renderers after this method returns.\n try {\n for (PlayerMessage message : messages) {\n message.blockUntilDelivered(detachSurfaceTimeoutMs);\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n } catch (TimeoutException e) {\n messageDeliveryTimedOut = true;\n }\n if (this.videoOutput == ownedSurface) {\n // We're replacing a surface that we are responsible for releasing.\n ownedSurface.release();\n ownedSurface = null;\n }\n }\n this.videoOutput = videoOutput;\n if (messageDeliveryTimedOut) {\n stop(\n /* reset= */ false,\n ExoPlaybackException.createForUnexpected(\n new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_DETACH_SURFACE),\n PlaybackException.ERROR_CODE_TIMEOUT));\n }\n }\n\n /**\n * Sets the holder of the surface that will be displayed to the user, but which should\n * not be the output for video renderers. This case occurs when video frames need to be\n * rendered to an intermediate surface (which is not the one held by the provided holder).\n *\n * @param nonVideoOutputSurfaceHolder The holder of the surface that will eventually be displayed\n * to the user.\n */\n private void setNonVideoOutputSurfaceHolderInternal(SurfaceHolder nonVideoOutputSurfaceHolder) {\n // Although we won't use the view's surface directly as the video output, still use the holder\n // to query the surface size, to be informed in changes to the size via componentListener, and\n // for equality checking in clearVideoSurfaceHolder.\n surfaceHolderSurfaceIsVideoOutput = false;\n surfaceHolder = nonVideoOutputSurfaceHolder;\n surfaceHolder.addCallback(componentListener);\n Surface surface = surfaceHolder.getSurface();\n if (surface != null && surface.isValid()) {\n Rect surfaceSize = surfaceHolder.getSurfaceFrame();\n maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height());\n } else {\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n }\n\n private void maybeNotifySurfaceSizeChanged(int width, int height) {\n if (width != surfaceWidth || height != surfaceHeight) {\n surfaceWidth = width;\n surfaceHeight = height;\n analyticsCollector.onSurfaceSizeChanged(width, height);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onSurfaceSizeChanged(width, height);\n }\n }\n }\n\n private void sendVolumeToRenderers() {\n float scaledVolume = volume * audioFocusManager.getVolumeMultiplier();\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_VOLUME, scaledVolume);\n }\n\n private void notifySkipSilenceEnabledChanged() {\n analyticsCollector.onSkipSilenceEnabledChanged(skipSilenceEnabled);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onSkipSilenceEnabledChanged(skipSilenceEnabled);\n }\n }\n\n private void updatePlayWhenReady(\n boolean playWhenReady,\n @AudioFocusManager.PlayerCommand int playerCommand,\n @Player.PlayWhenReadyChangeReason int playWhenReadyChangeReason) {\n playWhenReady = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY;\n @PlaybackSuppressionReason\n int playbackSuppressionReason =\n playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY\n ? Player.PLAYBACK_SUPPRESSION_REASON_TRANSIENT_AUDIO_FOCUS_LOSS\n : Player.PLAYBACK_SUPPRESSION_REASON_NONE;\n setPlayWhenReady(playWhenReady, playbackSuppressionReason, playWhenReadyChangeReason);\n }\n\n private void updateWakeAndWifiLock() {\n @State int playbackState = getPlaybackState();\n switch (playbackState) {\n case Player.STATE_READY:\n case Player.STATE_BUFFERING:\n boolean isSleeping = experimentalIsSleepingForOffload();\n wakeLockManager.setStayAwake(getPlayWhenReady() && !isSleeping);\n // The wifi lock is not released while sleeping to avoid interrupting downloads.\n wifiLockManager.setStayAwake(getPlayWhenReady());\n break;\n case Player.STATE_ENDED:\n case Player.STATE_IDLE:\n wakeLockManager.setStayAwake(false);\n wifiLockManager.setStayAwake(false);\n break;\n default:\n throw new IllegalStateException();\n }\n }\n\n private void verifyApplicationThread() {\n // The constructor may be executed on a background thread. Wait with accessing the player from\n // the app thread until the constructor finished executing.\n constructorFinished.blockUninterruptible();\n if (Thread.currentThread() != getApplicationLooper().getThread()) {\n String message =\n Util.formatInvariant(\n \"Player is accessed on the wrong thread.\\n\"\n + \"Current thread: '%s'\\n\"\n + \"Expected thread: '%s'\\n\"\n + \"See https://exoplayer.dev/issues/player-accessed-on-wrong-thread\",\n Thread.currentThread().getName(), getApplicationLooper().getThread().getName());\n if (throwsWhenUsingWrongThread) {\n throw new IllegalStateException(message);\n }\n Log.w(TAG, message, hasNotifiedFullWrongThreadWarning ? null : new IllegalStateException());\n hasNotifiedFullWrongThreadWarning = true;\n }\n }\n\n private void sendRendererMessage(\n @C.TrackType int trackType, int messageType, @Nullable Object payload) {\n for (Renderer renderer : renderers) {\n if (renderer.getTrackType() == trackType) {\n createMessageInternal(renderer).setType(messageType).setPayload(payload).send();\n }\n }\n }\n\n /**\n * Initializes {@link #keepSessionIdAudioTrack} to keep an audio session ID alive. If the audio\n * session ID is {@link C#AUDIO_SESSION_ID_UNSET} then a new audio session ID is generated.\n *\n *

Use of this method is only required on API level 21 and earlier.\n *\n * @param audioSessionId The audio session ID, or {@link C#AUDIO_SESSION_ID_UNSET} to generate a\n * new one.\n * @return The audio session ID.\n */\n private int initializeKeepSessionIdAudioTrack(int audioSessionId) {\n if (keepSessionIdAudioTrack != null\n && keepSessionIdAudioTrack.getAudioSessionId() != audioSessionId) {\n keepSessionIdAudioTrack.release();\n keepSessionIdAudioTrack = null;\n }\n if (keepSessionIdAudioTrack == null) {\n int sampleRate = 4000; // Minimum sample rate supported by the platform.\n int channelConfig = AudioFormat.CHANNEL_OUT_MONO;\n @C.PcmEncoding int encoding = C.ENCODING_PCM_16BIT;\n int bufferSize = 2; // Use a two byte buffer, as it is not actually used for playback.\n keepSessionIdAudioTrack =\n new AudioTrack(\n C.STREAM_TYPE_DEFAULT,\n sampleRate,\n channelConfig,\n encoding,\n bufferSize,\n AudioTrack.MODE_STATIC,\n audioSessionId);\n }\n return keepSessionIdAudioTrack.getAudioSessionId();\n }\n\n private void updatePriorityTaskManagerForIsLoadingChange(boolean isLoading) {\n if (priorityTaskManager != null) {\n if (isLoading && !isPriorityTaskManagerRegistered) {\n priorityTaskManager.add(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = true;\n } else if (!isLoading && isPriorityTaskManagerRegistered) {\n priorityTaskManager.remove(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = false;\n }\n }\n }\n\n private static DeviceInfo createDeviceInfo(StreamVolumeManager streamVolumeManager) {\n return new DeviceInfo(\n DeviceInfo.PLAYBACK_TYPE_LOCAL,\n streamVolumeManager.getMinVolume(),\n streamVolumeManager.getMaxVolume());\n }\n\n private static int getPlayWhenReadyChangeReason(boolean playWhenReady, int playerCommand) {\n return playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY\n ? PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS\n : PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;\n }\n\n private static boolean isPlaying(PlaybackInfo playbackInfo) {\n return playbackInfo.playbackState == Player.STATE_READY\n && playbackInfo.playWhenReady\n && playbackInfo.playbackSuppressionReason == PLAYBACK_SUPPRESSION_REASON_NONE;\n }\n\n private static final class MediaSourceHolderSnapshot implements MediaSourceInfoHolder {\n\n private final Object uid;\n\n private Timeline timeline;\n\n public MediaSourceHolderSnapshot(Object uid, Timeline timeline) {\n this.uid = uid;\n this.timeline = timeline;\n }\n\n @Override\n public Object getUid() {\n return uid;\n }\n\n @Override\n public Timeline getTimeline() {\n return timeline;\n }\n }\n\n private final class ComponentListener\n implements VideoRendererEventListener,\n AudioRendererEventListener,\n TextOutput,\n MetadataOutput,\n SurfaceHolder.Callback,\n TextureView.SurfaceTextureListener,\n SphericalGLSurfaceView.VideoSurfaceListener,\n AudioFocusManager.PlayerControl,\n AudioBecomingNoisyManager.EventListener,\n StreamVolumeManager.Listener,\n AudioOffloadListener {\n\n // VideoRendererEventListener implementation\n\n @Override\n public void onVideoEnabled(DecoderCounters counters) {\n videoDecoderCounters = counters;\n analyticsCollector.onVideoEnabled(counters);\n }\n\n @Override\n public void onVideoDecoderInitialized(\n String decoderName, long initializedTimestampMs, long initializationDurationMs) {\n analyticsCollector.onVideoDecoderInitialized(\n decoderName, initializedTimestampMs, initializationDurationMs);\n }\n\n @Override\n public void onVideoInputFormatChanged(\n Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) {\n videoFormat = format;\n analyticsCollector.onVideoInputFormatChanged(format, decoderReuseEvaluation);\n }\n\n @Override\n public void onDroppedFrames(int count, long elapsed) {\n analyticsCollector.onDroppedFrames(count, elapsed);\n }\n\n @Override\n public void onVideoSizeChanged(VideoSize videoSize) {\n ExoPlayerImpl.this.videoSize = videoSize;\n analyticsCollector.onVideoSizeChanged(videoSize);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onVideoSizeChanged(videoSize);\n }\n }\n\n @Override\n public void onRenderedFirstFrame(Object output, long renderTimeMs) {\n analyticsCollector.onRenderedFirstFrame(output, renderTimeMs);\n if (videoOutput == output) {\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onRenderedFirstFrame();\n }\n }\n }\n\n @Override\n public void onVideoDecoderReleased(String decoderName) {\n analyticsCollector.onVideoDecoderReleased(decoderName);\n }\n\n @Override\n public void onVideoDisabled(DecoderCounters counters) {\n analyticsCollector.onVideoDisabled(counters);\n videoFormat = null;\n videoDecoderCounters = null;\n }\n\n @Override\n public void onVideoFrameProcessingOffset(long totalProcessingOffsetUs, int frameCount) {\n analyticsCollector.onVideoFrameProcessingOffset(totalProcessingOffsetUs, frameCount);\n }\n\n @Override\n public void onVideoCodecError(Exception videoCodecError) {\n analyticsCollector.onVideoCodecError(videoCodecError);\n }\n\n // AudioRendererEventListener implementation\n\n @Override\n public void onAudioEnabled(DecoderCounters counters) {\n audioDecoderCounters = counters;\n analyticsCollector.onAudioEnabled(counters);\n }\n\n @Override\n public void onAudioDecoderInitialized(\n String decoderName, long initializedTimestampMs, long initializationDurationMs) {\n analyticsCollector.onAudioDecoderInitialized(\n decoderName, initializedTimestampMs, initializationDurationMs);\n }\n\n @Override\n public void onAudioInputFormatChanged(\n Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) {\n audioFormat = format;\n analyticsCollector.onAudioInputFormatChanged(format, decoderReuseEvaluation);\n }\n\n @Override\n public void onAudioPositionAdvancing(long playoutStartSystemTimeMs) {\n analyticsCollector.onAudioPositionAdvancing(playoutStartSystemTimeMs);\n }\n\n @Override\n public void onAudioUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) {\n analyticsCollector.onAudioUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs);\n }\n\n @Override\n public void onAudioDecoderReleased(String decoderName) {\n analyticsCollector.onAudioDecoderReleased(decoderName);\n }\n\n @Override\n public void onAudioDisabled(DecoderCounters counters) {\n analyticsCollector.onAudioDisabled(counters);\n audioFormat = null;\n audioDecoderCounters = null;\n }\n\n @Override\n public void onSkipSilenceEnabledChanged(boolean skipSilenceEnabled) {\n if (ExoPlayerImpl.this.skipSilenceEnabled == skipSilenceEnabled) {\n return;\n }\n ExoPlayerImpl.this.skipSilenceEnabled = skipSilenceEnabled;\n notifySkipSilenceEnabledChanged();\n }\n\n @Override\n public void onAudioSinkError(Exception audioSinkError) {\n analyticsCollector.onAudioSinkError(audioSinkError);\n }\n\n @Override\n public void onAudioCodecError(Exception audioCodecError) {\n analyticsCollector.onAudioCodecError(audioCodecError);\n }\n\n // TextOutput implementation\n\n @Override\n public void onCues(List cues) {\n currentCues = cues;\n analyticsCollector.onCues(cues);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listeners : listenerArraySet) {\n listeners.onCues(cues);\n }\n }\n\n // MetadataOutput implementation\n\n @Override\n public void onMetadata(Metadata metadata) {\n analyticsCollector.onMetadata(metadata);\n ExoPlayerImpl.this.onMetadata(metadata);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onMetadata(metadata);\n }\n }\n\n // SurfaceHolder.Callback implementation\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n if (surfaceHolderSurfaceIsVideoOutput) {\n setVideoOutputInternal(holder.getSurface());\n }\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n maybeNotifySurfaceSizeChanged(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n if (surfaceHolderSurfaceIsVideoOutput) {\n setVideoOutputInternal(/* videoOutput= */ null);\n }\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n\n // TextureView.SurfaceTextureListener implementation\n\n @Override\n public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {\n setSurfaceTextureInternal(surfaceTexture);\n maybeNotifySurfaceSizeChanged(width, height);\n }\n\n @Override\n public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {\n maybeNotifySurfaceSizeChanged(width, height);\n }\n\n @Override\n public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n return true;\n }\n\n @Override\n public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {\n // Do nothing.\n }\n\n // SphericalGLSurfaceView.VideoSurfaceListener\n\n @Override\n public void onVideoSurfaceCreated(Surface surface) {\n setVideoOutputInternal(surface);\n }\n\n @Override\n public void onVideoSurfaceDestroyed(Surface surface) {\n setVideoOutputInternal(/* videoOutput= */ null);\n }\n\n // AudioFocusManager.PlayerControl implementation\n\n @Override\n public void setVolumeMultiplier(float volumeMultiplier) {\n sendVolumeToRenderers();\n }\n\n @Override\n public void executePlayerCommand(@AudioFocusManager.PlayerCommand int playerCommand) {\n boolean playWhenReady = getPlayWhenReady();\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n }\n\n // AudioBecomingNoisyManager.EventListener implementation.\n\n @Override\n public void onAudioBecomingNoisy() {\n updatePlayWhenReady(\n /* playWhenReady= */ false,\n AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY,\n Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY);\n }\n\n // StreamVolumeManager.Listener implementation.\n\n @Override\n public void onStreamTypeChanged(@C.StreamType int streamType) {\n DeviceInfo deviceInfo = createDeviceInfo(streamVolumeManager);\n if (!deviceInfo.equals(ExoPlayerImpl.this.deviceInfo)) {\n ExoPlayerImpl.this.deviceInfo = deviceInfo;\n analyticsCollector.onDeviceInfoChanged(deviceInfo);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onDeviceInfoChanged(deviceInfo);\n }\n }\n }\n\n @Override\n public void onStreamVolumeChanged(int streamVolume, boolean streamMuted) {\n analyticsCollector.onDeviceVolumeChanged(streamVolume, streamMuted);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onDeviceVolumeChanged(streamVolume, streamMuted);\n }\n }\n\n // Player.AudioOffloadListener implementation.\n\n @Override\n public void onExperimentalSleepingForOffloadChanged(boolean sleepingForOffload) {\n updateWakeAndWifiLock();\n }\n }\n\n /** Listeners that are called on the playback thread. */\n private static final class FrameMetadataListener\n implements VideoFrameMetadataListener, CameraMotionListener, PlayerMessage.Target {\n\n public static final @MessageType int MSG_SET_VIDEO_FRAME_METADATA_LISTENER =\n Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER;\n\n public static final @MessageType int MSG_SET_CAMERA_MOTION_LISTENER =\n Renderer.MSG_SET_CAMERA_MOTION_LISTENER;\n\n public static final @MessageType int MSG_SET_SPHERICAL_SURFACE_VIEW = Renderer.MSG_CUSTOM_BASE;\n\n @Nullable private VideoFrameMetadataListener videoFrameMetadataListener;\n @Nullable private CameraMotionListener cameraMotionListener;\n @Nullable private VideoFrameMetadataListener internalVideoFrameMetadataListener;\n @Nullable private CameraMotionListener internalCameraMotionListener;\n\n @Override\n public void handleMessage(@MessageType int messageType, @Nullable Object message) {\n switch (messageType) {\n case MSG_SET_VIDEO_FRAME_METADATA_LISTENER:\n videoFrameMetadataListener = (VideoFrameMetadataListener) message;\n break;\n case MSG_SET_CAMERA_MOTION_LISTENER:\n cameraMotionListener = (CameraMotionListener) message;\n break;\n case MSG_SET_SPHERICAL_SURFACE_VIEW:\n @Nullable SphericalGLSurfaceView surfaceView = (SphericalGLSurfaceView) message;\n if (surfaceView == null) {\n internalVideoFrameMetadataListener = null;\n internalCameraMotionListener = null;\n } else {\n internalVideoFrameMetadataListener = surfaceView.getVideoFrameMetadataListener();\n internalCameraMotionListener = surfaceView.getCameraMotionListener();\n }\n break;\n case Renderer.MSG_SET_AUDIO_ATTRIBUTES:\n case Renderer.MSG_SET_AUDIO_SESSION_ID:\n case Renderer.MSG_SET_AUX_EFFECT_INFO:\n case Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY:\n case Renderer.MSG_SET_SCALING_MODE:\n case Renderer.MSG_SET_SKIP_SILENCE_ENABLED:\n case Renderer.MSG_SET_VIDEO_OUTPUT:\n case Renderer.MSG_SET_VOLUME:\n case Renderer.MSG_SET_WAKEUP_LISTENER:\n default:\n break;\n }\n }\n\n // VideoFrameMetadataListener\n\n @Override\n public void onVideoFrameAboutToBeRendered(\n long presentationTimeUs,\n long releaseTimeNs,\n Format format,\n @Nullable MediaFormat mediaFormat) {\n if (internalVideoFrameMetadataListener != null) {\n internalVideoFrameMetadataListener.onVideoFrameAboutToBeRendered(\n presentationTimeUs, releaseTimeNs, format, mediaFormat);\n }\n if (videoFrameMetadataListener != null) {\n videoFrameMetadataListener.onVideoFrameAboutToBeRendered(\n presentationTimeUs, releaseTimeNs, format, mediaFormat);\n }\n }\n\n // CameraMotionListener\n\n @Override\n public void onCameraMotion(long timeUs, float[] rotation) {\n if (internalCameraMotionListener != null) {\n internalCameraMotionListener.onCameraMotion(timeUs, rotation);\n }\n if (cameraMotionListener != null) {\n cameraMotionListener.onCameraMotion(timeUs, rotation);\n }\n }\n\n @Override\n public void onCameraMotionReset() {\n if (internalCameraMotionListener != null) {\n internalCameraMotionListener.onCameraMotionReset();\n }\n if (cameraMotionListener != null) {\n cameraMotionListener.onCameraMotionReset();\n }\n }\n }\n\n @RequiresApi(31)\n private static final class Api31 {\n private Api31() {}\n\n @DoNotInline\n public static PlayerId createPlayerId() {\n // TODO: Create a MediaMetricsListener and obtain LogSessionId from it.\n return new PlayerId(LogSessionId.LOG_SESSION_ID_NONE);\n }\n }\n}\n"},"new_file":{"kind":"string","value":"libraries/exoplayer/src/main/java/androidx/media3/exoplayer/ExoPlayerImpl.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2016 The Android Open Source Project\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 */\npackage androidx.media3.exoplayer;\n\nimport static androidx.media3.common.C.TRACK_TYPE_AUDIO;\nimport static androidx.media3.common.C.TRACK_TYPE_CAMERA_MOTION;\nimport static androidx.media3.common.C.TRACK_TYPE_VIDEO;\nimport static androidx.media3.common.Player.COMMAND_ADJUST_DEVICE_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_CHANGE_MEDIA_ITEMS;\nimport static androidx.media3.common.Player.COMMAND_GET_AUDIO_ATTRIBUTES;\nimport static androidx.media3.common.Player.COMMAND_GET_CURRENT_MEDIA_ITEM;\nimport static androidx.media3.common.Player.COMMAND_GET_DEVICE_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_GET_MEDIA_ITEMS_METADATA;\nimport static androidx.media3.common.Player.COMMAND_GET_TEXT;\nimport static androidx.media3.common.Player.COMMAND_GET_TIMELINE;\nimport static androidx.media3.common.Player.COMMAND_GET_TRACK_INFOS;\nimport static androidx.media3.common.Player.COMMAND_GET_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_PLAY_PAUSE;\nimport static androidx.media3.common.Player.COMMAND_PREPARE;\nimport static androidx.media3.common.Player.COMMAND_SEEK_TO_DEFAULT_POSITION;\nimport static androidx.media3.common.Player.COMMAND_SEEK_TO_MEDIA_ITEM;\nimport static androidx.media3.common.Player.COMMAND_SET_DEVICE_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_SET_MEDIA_ITEMS_METADATA;\nimport static androidx.media3.common.Player.COMMAND_SET_REPEAT_MODE;\nimport static androidx.media3.common.Player.COMMAND_SET_SHUFFLE_MODE;\nimport static androidx.media3.common.Player.COMMAND_SET_SPEED_AND_PITCH;\nimport static androidx.media3.common.Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS;\nimport static androidx.media3.common.Player.COMMAND_SET_VIDEO_SURFACE;\nimport static androidx.media3.common.Player.COMMAND_SET_VOLUME;\nimport static androidx.media3.common.Player.COMMAND_STOP;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_AUTO_TRANSITION;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_INTERNAL;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_REMOVE;\nimport static androidx.media3.common.Player.DISCONTINUITY_REASON_SEEK;\nimport static androidx.media3.common.Player.EVENT_MEDIA_METADATA_CHANGED;\nimport static androidx.media3.common.Player.EVENT_PLAYLIST_METADATA_CHANGED;\nimport static androidx.media3.common.Player.EVENT_TRACK_SELECTION_PARAMETERS_CHANGED;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_AUTO;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT;\nimport static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_SEEK;\nimport static androidx.media3.common.Player.PLAYBACK_SUPPRESSION_REASON_NONE;\nimport static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS;\nimport static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;\nimport static androidx.media3.common.Player.STATE_BUFFERING;\nimport static androidx.media3.common.Player.STATE_ENDED;\nimport static androidx.media3.common.Player.STATE_IDLE;\nimport static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED;\nimport static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_SOURCE_UPDATE;\nimport static androidx.media3.common.util.Assertions.checkNotNull;\nimport static androidx.media3.common.util.Assertions.checkState;\nimport static androidx.media3.common.util.Util.castNonNull;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_ATTRIBUTES;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_SESSION_ID;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_AUX_EFFECT_INFO;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_CAMERA_MOTION_LISTENER;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_SCALING_MODE;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_SKIP_SILENCE_ENABLED;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_OUTPUT;\nimport static androidx.media3.exoplayer.Renderer.MSG_SET_VOLUME;\nimport static java.lang.Math.max;\nimport static java.lang.Math.min;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.graphics.Rect;\nimport android.graphics.SurfaceTexture;\nimport android.media.AudioFormat;\nimport android.media.AudioTrack;\nimport android.media.MediaFormat;\nimport android.media.metrics.LogSessionId;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Pair;\nimport android.view.Surface;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.TextureView;\nimport androidx.annotation.DoNotInline;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.media3.common.AudioAttributes;\nimport androidx.media3.common.AuxEffectInfo;\nimport androidx.media3.common.C;\nimport androidx.media3.common.DeviceInfo;\nimport androidx.media3.common.Format;\nimport androidx.media3.common.IllegalSeekPositionException;\nimport androidx.media3.common.MediaItem;\nimport androidx.media3.common.MediaLibraryInfo;\nimport androidx.media3.common.MediaMetadata;\nimport androidx.media3.common.Metadata;\nimport androidx.media3.common.PlaybackException;\nimport androidx.media3.common.PlaybackParameters;\nimport androidx.media3.common.Player;\nimport androidx.media3.common.Player.Commands;\nimport androidx.media3.common.Player.DiscontinuityReason;\nimport androidx.media3.common.Player.Events;\nimport androidx.media3.common.Player.Listener;\nimport androidx.media3.common.Player.PlayWhenReadyChangeReason;\nimport androidx.media3.common.Player.PlaybackSuppressionReason;\nimport androidx.media3.common.Player.PositionInfo;\nimport androidx.media3.common.Player.RepeatMode;\nimport androidx.media3.common.Player.State;\nimport androidx.media3.common.Player.TimelineChangeReason;\nimport androidx.media3.common.PriorityTaskManager;\nimport androidx.media3.common.Timeline;\nimport androidx.media3.common.TrackGroup;\nimport androidx.media3.common.TrackGroupArray;\nimport androidx.media3.common.TrackSelectionArray;\nimport androidx.media3.common.TrackSelectionParameters;\nimport androidx.media3.common.TracksInfo;\nimport androidx.media3.common.VideoSize;\nimport androidx.media3.common.text.Cue;\nimport androidx.media3.common.util.Assertions;\nimport androidx.media3.common.util.Clock;\nimport androidx.media3.common.util.ConditionVariable;\nimport androidx.media3.common.util.HandlerWrapper;\nimport androidx.media3.common.util.ListenerSet;\nimport androidx.media3.common.util.Log;\nimport androidx.media3.common.util.Util;\nimport androidx.media3.exoplayer.ExoPlayer.AudioOffloadListener;\nimport androidx.media3.exoplayer.PlayerMessage.Target;\nimport androidx.media3.exoplayer.Renderer.MessageType;\nimport androidx.media3.exoplayer.analytics.AnalyticsCollector;\nimport androidx.media3.exoplayer.analytics.AnalyticsListener;\nimport androidx.media3.exoplayer.analytics.PlayerId;\nimport androidx.media3.exoplayer.audio.AudioRendererEventListener;\nimport androidx.media3.exoplayer.metadata.MetadataOutput;\nimport androidx.media3.exoplayer.source.MediaSource;\nimport androidx.media3.exoplayer.source.MediaSource.MediaPeriodId;\nimport androidx.media3.exoplayer.source.ShuffleOrder;\nimport androidx.media3.exoplayer.text.TextOutput;\nimport androidx.media3.exoplayer.trackselection.ExoTrackSelection;\nimport androidx.media3.exoplayer.trackselection.TrackSelector;\nimport androidx.media3.exoplayer.trackselection.TrackSelectorResult;\nimport androidx.media3.exoplayer.upstream.BandwidthMeter;\nimport androidx.media3.exoplayer.video.VideoDecoderOutputBufferRenderer;\nimport androidx.media3.exoplayer.video.VideoFrameMetadataListener;\nimport androidx.media3.exoplayer.video.VideoRendererEventListener;\nimport androidx.media3.exoplayer.video.spherical.CameraMotionListener;\nimport androidx.media3.exoplayer.video.spherical.SphericalGLSurfaceView;\nimport com.google.common.collect.ImmutableList;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.CopyOnWriteArraySet;\nimport java.util.concurrent.TimeoutException;\n\n/** A helper class for the {@link SimpleExoPlayer} implementation of {@link ExoPlayer}. */\n/* package */ final class ExoPlayerImpl {\n\n static {\n MediaLibraryInfo.registerModule(\"media3.exoplayer\");\n }\n\n private static final String TAG = \"ExoPlayerImpl\";\n\n /**\n * This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult}\n * when the player does not have any track selection made (such as when player is reset, or when\n * player seeks to an unprepared period). It will not be used as result of any {@link\n * TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)}\n * operation.\n */\n /* package */ final TrackSelectorResult emptyTrackSelectorResult;\n /* package */ final Commands permanentAvailableCommands;\n\n private final ConditionVariable constructorFinished;\n private final Context applicationContext;\n private final Player wrappingPlayer;\n private final Renderer[] renderers;\n private final TrackSelector trackSelector;\n private final HandlerWrapper playbackInfoUpdateHandler;\n private final ExoPlayerImplInternal.PlaybackInfoUpdateListener playbackInfoUpdateListener;\n private final ExoPlayerImplInternal internalPlayer;\n\n private final ListenerSet listeners;\n // TODO(b/187152483): Remove this once all events are dispatched via ListenerSet.\n private final CopyOnWriteArraySet listenerArraySet;\n private final CopyOnWriteArraySet audioOffloadListeners;\n private final Timeline.Period period;\n private final Timeline.Window window;\n private final List mediaSourceHolderSnapshots;\n private final boolean useLazyPreparation;\n private final MediaSource.Factory mediaSourceFactory;\n private final AnalyticsCollector analyticsCollector;\n private final Looper applicationLooper;\n private final BandwidthMeter bandwidthMeter;\n private final long seekBackIncrementMs;\n private final long seekForwardIncrementMs;\n private final Clock clock;\n private final ComponentListener componentListener;\n private final FrameMetadataListener frameMetadataListener;\n private final AudioBecomingNoisyManager audioBecomingNoisyManager;\n private final AudioFocusManager audioFocusManager;\n private final StreamVolumeManager streamVolumeManager;\n private final WakeLockManager wakeLockManager;\n private final WifiLockManager wifiLockManager;\n private final long detachSurfaceTimeoutMs;\n\n private @RepeatMode int repeatMode;\n private boolean shuffleModeEnabled;\n private int pendingOperationAcks;\n private @DiscontinuityReason int pendingDiscontinuityReason;\n private boolean pendingDiscontinuity;\n private @PlayWhenReadyChangeReason int pendingPlayWhenReadyChangeReason;\n private boolean foregroundMode;\n private SeekParameters seekParameters;\n private ShuffleOrder shuffleOrder;\n private boolean pauseAtEndOfMediaItems;\n private Commands availableCommands;\n private MediaMetadata mediaMetadata;\n private MediaMetadata playlistMetadata;\n @Nullable private Format videoFormat;\n @Nullable private Format audioFormat;\n @Nullable private AudioTrack keepSessionIdAudioTrack;\n @Nullable private Object videoOutput;\n @Nullable private Surface ownedSurface;\n @Nullable private SurfaceHolder surfaceHolder;\n @Nullable private SphericalGLSurfaceView sphericalGLSurfaceView;\n private boolean surfaceHolderSurfaceIsVideoOutput;\n @Nullable private TextureView textureView;\n private @C.VideoScalingMode int videoScalingMode;\n private @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy;\n private int surfaceWidth;\n private int surfaceHeight;\n @Nullable private DecoderCounters videoDecoderCounters;\n @Nullable private DecoderCounters audioDecoderCounters;\n private int audioSessionId;\n private AudioAttributes audioAttributes;\n private float volume;\n private boolean skipSilenceEnabled;\n private List currentCues;\n @Nullable private VideoFrameMetadataListener videoFrameMetadataListener;\n @Nullable private CameraMotionListener cameraMotionListener;\n private boolean throwsWhenUsingWrongThread;\n private boolean hasNotifiedFullWrongThreadWarning;\n @Nullable private PriorityTaskManager priorityTaskManager;\n private boolean isPriorityTaskManagerRegistered;\n private boolean playerReleased;\n private DeviceInfo deviceInfo;\n private VideoSize videoSize;\n\n // MediaMetadata built from static (TrackGroup Format) and dynamic (onMetadata(Metadata)) metadata\n // sources.\n private MediaMetadata staticAndDynamicMediaMetadata;\n\n // Playback information when there is no pending seek/set source operation.\n private PlaybackInfo playbackInfo;\n\n // Playback information when there is a pending seek/set source operation.\n private int maskingWindowIndex;\n private int maskingPeriodIndex;\n private long maskingWindowPositionMs;\n\n @SuppressLint(\"HandlerLeak\")\n public ExoPlayerImpl(ExoPlayer.Builder builder, Player wrappingPlayer) {\n constructorFinished = new ConditionVariable();\n try {\n Log.i(\n TAG,\n \"Init \"\n + Integer.toHexString(System.identityHashCode(this))\n + \" [\"\n + MediaLibraryInfo.VERSION_SLASHY\n + \"] [\"\n + Util.DEVICE_DEBUG_INFO\n + \"]\");\n applicationContext = builder.context.getApplicationContext();\n analyticsCollector = builder.analyticsCollectorSupplier.get();\n priorityTaskManager = builder.priorityTaskManager;\n audioAttributes = builder.audioAttributes;\n videoScalingMode = builder.videoScalingMode;\n videoChangeFrameRateStrategy = builder.videoChangeFrameRateStrategy;\n skipSilenceEnabled = builder.skipSilenceEnabled;\n detachSurfaceTimeoutMs = builder.detachSurfaceTimeoutMs;\n componentListener = new ComponentListener();\n frameMetadataListener = new FrameMetadataListener();\n Handler eventHandler = new Handler(builder.looper);\n renderers =\n builder\n .renderersFactorySupplier\n .get()\n .createRenderers(\n eventHandler,\n componentListener,\n componentListener,\n componentListener,\n componentListener);\n checkState(renderers.length > 0);\n this.trackSelector = builder.trackSelectorSupplier.get();\n this.mediaSourceFactory = builder.mediaSourceFactorySupplier.get();\n this.bandwidthMeter = builder.bandwidthMeterSupplier.get();\n this.useLazyPreparation = builder.useLazyPreparation;\n this.seekParameters = builder.seekParameters;\n this.seekBackIncrementMs = builder.seekBackIncrementMs;\n this.seekForwardIncrementMs = builder.seekForwardIncrementMs;\n this.pauseAtEndOfMediaItems = builder.pauseAtEndOfMediaItems;\n this.applicationLooper = builder.looper;\n this.clock = builder.clock;\n this.wrappingPlayer = wrappingPlayer;\n listeners =\n new ListenerSet<>(\n applicationLooper,\n clock,\n (listener, flags) -> listener.onEvents(wrappingPlayer, new Events(flags)));\n listenerArraySet = new CopyOnWriteArraySet<>();\n audioOffloadListeners = new CopyOnWriteArraySet<>();\n mediaSourceHolderSnapshots = new ArrayList<>();\n shuffleOrder = new ShuffleOrder.DefaultShuffleOrder(/* length= */ 0);\n emptyTrackSelectorResult =\n new TrackSelectorResult(\n new RendererConfiguration[renderers.length],\n new ExoTrackSelection[renderers.length],\n TracksInfo.EMPTY,\n /* info= */ null);\n period = new Timeline.Period();\n window = new Timeline.Window();\n permanentAvailableCommands =\n new Commands.Builder()\n .addAll(\n COMMAND_PLAY_PAUSE,\n COMMAND_PREPARE,\n COMMAND_STOP,\n COMMAND_SET_SPEED_AND_PITCH,\n COMMAND_SET_SHUFFLE_MODE,\n COMMAND_SET_REPEAT_MODE,\n COMMAND_GET_CURRENT_MEDIA_ITEM,\n COMMAND_GET_TIMELINE,\n COMMAND_GET_MEDIA_ITEMS_METADATA,\n COMMAND_SET_MEDIA_ITEMS_METADATA,\n COMMAND_CHANGE_MEDIA_ITEMS,\n COMMAND_GET_TRACK_INFOS,\n COMMAND_GET_AUDIO_ATTRIBUTES,\n COMMAND_GET_VOLUME,\n COMMAND_GET_DEVICE_VOLUME,\n COMMAND_SET_VOLUME,\n COMMAND_SET_DEVICE_VOLUME,\n COMMAND_ADJUST_DEVICE_VOLUME,\n COMMAND_SET_VIDEO_SURFACE,\n COMMAND_GET_TEXT)\n .addIf(\n COMMAND_SET_TRACK_SELECTION_PARAMETERS, trackSelector.isSetParametersSupported())\n .build();\n availableCommands =\n new Commands.Builder()\n .addAll(permanentAvailableCommands)\n .add(COMMAND_SEEK_TO_DEFAULT_POSITION)\n .add(COMMAND_SEEK_TO_MEDIA_ITEM)\n .build();\n playbackInfoUpdateHandler = clock.createHandler(applicationLooper, /* callback= */ null);\n playbackInfoUpdateListener =\n playbackInfoUpdate ->\n playbackInfoUpdateHandler.post(() -> handlePlaybackInfo(playbackInfoUpdate));\n playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult);\n analyticsCollector.setPlayer(wrappingPlayer, applicationLooper);\n PlayerId playerId = Util.SDK_INT < 31 ? new PlayerId() : Api31.createPlayerId();\n internalPlayer =\n new ExoPlayerImplInternal(\n renderers,\n trackSelector,\n emptyTrackSelectorResult,\n builder.loadControlSupplier.get(),\n bandwidthMeter,\n repeatMode,\n shuffleModeEnabled,\n analyticsCollector,\n seekParameters,\n builder.livePlaybackSpeedControl,\n builder.releaseTimeoutMs,\n pauseAtEndOfMediaItems,\n applicationLooper,\n clock,\n playbackInfoUpdateListener,\n playerId);\n\n volume = 1;\n repeatMode = Player.REPEAT_MODE_OFF;\n mediaMetadata = MediaMetadata.EMPTY;\n playlistMetadata = MediaMetadata.EMPTY;\n staticAndDynamicMediaMetadata = MediaMetadata.EMPTY;\n maskingWindowIndex = C.INDEX_UNSET;\n if (Util.SDK_INT < 21) {\n audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET);\n } else {\n audioSessionId = Util.generateAudioSessionIdV21(applicationContext);\n }\n currentCues = ImmutableList.of();\n throwsWhenUsingWrongThread = true;\n\n listeners.add(analyticsCollector);\n bandwidthMeter.addEventListener(new Handler(applicationLooper), analyticsCollector);\n listeners.add(componentListener);\n addAudioOffloadListener(componentListener);\n if (builder.foregroundModeTimeoutMs > 0) {\n experimentalSetForegroundModeTimeoutMs(builder.foregroundModeTimeoutMs);\n }\n\n audioBecomingNoisyManager =\n new AudioBecomingNoisyManager(builder.context, eventHandler, componentListener);\n audioBecomingNoisyManager.setEnabled(builder.handleAudioBecomingNoisy);\n audioFocusManager = new AudioFocusManager(builder.context, eventHandler, componentListener);\n audioFocusManager.setAudioAttributes(builder.handleAudioFocus ? audioAttributes : null);\n streamVolumeManager =\n new StreamVolumeManager(builder.context, eventHandler, componentListener);\n streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage));\n wakeLockManager = new WakeLockManager(builder.context);\n wakeLockManager.setEnabled(builder.wakeMode != C.WAKE_MODE_NONE);\n wifiLockManager = new WifiLockManager(builder.context);\n wifiLockManager.setEnabled(builder.wakeMode == C.WAKE_MODE_NETWORK);\n deviceInfo = createDeviceInfo(streamVolumeManager);\n videoSize = VideoSize.UNKNOWN;\n\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes);\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode);\n sendRendererMessage(\n TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy);\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled);\n sendRendererMessage(\n TRACK_TYPE_VIDEO, MSG_SET_VIDEO_FRAME_METADATA_LISTENER, frameMetadataListener);\n sendRendererMessage(\n TRACK_TYPE_CAMERA_MOTION, MSG_SET_CAMERA_MOTION_LISTENER, frameMetadataListener);\n } finally {\n constructorFinished.open();\n }\n }\n\n /**\n * Sets a limit on the time a call to {@link #setForegroundMode} can spend. If a call to {@link\n * #setForegroundMode} takes more than {@code timeoutMs} milliseconds to complete, the player will\n * raise an error via {@link Player.Listener#onPlayerError}.\n *\n *

This method is experimental, and will be renamed or removed in a future release. It should\n * only be called before the player is used.\n *\n * @param timeoutMs The time limit in milliseconds.\n */\n public void experimentalSetForegroundModeTimeoutMs(long timeoutMs) {\n internalPlayer.experimentalSetForegroundModeTimeoutMs(timeoutMs);\n }\n\n public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) {\n verifyApplicationThread();\n internalPlayer.experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled);\n }\n\n public boolean experimentalIsSleepingForOffload() {\n verifyApplicationThread();\n return playbackInfo.sleepingForOffload;\n }\n\n public Looper getPlaybackLooper() {\n // Don't verify application thread. We allow calls to this method from any thread.\n return internalPlayer.getPlaybackLooper();\n }\n\n public Looper getApplicationLooper() {\n // Don't verify application thread. We allow calls to this method from any thread.\n return applicationLooper;\n }\n\n public Clock getClock() {\n // Don't verify application thread. We allow calls to this method from any thread.\n return clock;\n }\n\n public void addAudioOffloadListener(AudioOffloadListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n audioOffloadListeners.add(listener);\n }\n\n public void removeAudioOffloadListener(AudioOffloadListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n audioOffloadListeners.remove(listener);\n }\n\n public Commands getAvailableCommands() {\n verifyApplicationThread();\n return availableCommands;\n }\n\n public @State int getPlaybackState() {\n verifyApplicationThread();\n return playbackInfo.playbackState;\n }\n\n public @PlaybackSuppressionReason int getPlaybackSuppressionReason() {\n verifyApplicationThread();\n return playbackInfo.playbackSuppressionReason;\n }\n\n @Nullable\n public ExoPlaybackException getPlayerError() {\n verifyApplicationThread();\n return playbackInfo.playbackError;\n }\n\n /** @deprecated Use {@link #prepare()} instead. */\n @Deprecated\n public void retry() {\n prepare();\n }\n\n public void prepare() {\n verifyApplicationThread();\n boolean playWhenReady = getPlayWhenReady();\n @AudioFocusManager.PlayerCommand\n int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, Player.STATE_BUFFERING);\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n if (playbackInfo.playbackState != Player.STATE_IDLE) {\n return;\n }\n PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlaybackError(null);\n playbackInfo =\n playbackInfo.copyWithPlaybackState(\n playbackInfo.timeline.isEmpty() ? STATE_ENDED : STATE_BUFFERING);\n // Trigger internal prepare first before updating the playback info and notifying external\n // listeners to ensure that new operations issued in the listener notifications reach the\n // player after this prepare. The internal player can't change the playback info immediately\n // because it uses a callback.\n pendingOperationAcks++;\n internalPlayer.prepare();\n updatePlaybackInfo(\n playbackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_SOURCE_UPDATE,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n /**\n * @deprecated Use {@link #setMediaSource(MediaSource)} and {@link ExoPlayer#prepare()} instead.\n */\n @Deprecated\n public void prepare(MediaSource mediaSource) {\n verifyApplicationThread();\n setMediaSource(mediaSource);\n prepare();\n }\n\n /**\n * @deprecated Use {@link #setMediaSource(MediaSource, boolean)} and {@link ExoPlayer#prepare()}\n * instead.\n */\n @Deprecated\n public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) {\n verifyApplicationThread();\n setMediaSource(mediaSource, resetPosition);\n prepare();\n }\n\n public void setMediaItems(List mediaItems, boolean resetPosition) {\n verifyApplicationThread();\n setMediaSources(createMediaSources(mediaItems), resetPosition);\n }\n\n public void setMediaItems(List mediaItems, int startIndex, long startPositionMs) {\n verifyApplicationThread();\n setMediaSources(createMediaSources(mediaItems), startIndex, startPositionMs);\n }\n\n public void setMediaSource(MediaSource mediaSource) {\n verifyApplicationThread();\n setMediaSources(Collections.singletonList(mediaSource));\n }\n\n public void setMediaSource(MediaSource mediaSource, long startPositionMs) {\n verifyApplicationThread();\n setMediaSources(\n Collections.singletonList(mediaSource), /* startWindowIndex= */ 0, startPositionMs);\n }\n\n public void setMediaSource(MediaSource mediaSource, boolean resetPosition) {\n verifyApplicationThread();\n setMediaSources(Collections.singletonList(mediaSource), resetPosition);\n }\n\n public void setMediaSources(List mediaSources) {\n verifyApplicationThread();\n setMediaSources(mediaSources, /* resetPosition= */ true);\n }\n\n public void setMediaSources(List mediaSources, boolean resetPosition) {\n verifyApplicationThread();\n setMediaSourcesInternal(\n mediaSources,\n /* startWindowIndex= */ C.INDEX_UNSET,\n /* startPositionMs= */ C.TIME_UNSET,\n /* resetToDefaultPosition= */ resetPosition);\n }\n\n public void setMediaSources(\n List mediaSources, int startWindowIndex, long startPositionMs) {\n verifyApplicationThread();\n setMediaSourcesInternal(\n mediaSources, startWindowIndex, startPositionMs, /* resetToDefaultPosition= */ false);\n }\n\n public void addMediaItems(int index, List mediaItems) {\n verifyApplicationThread();\n index = min(index, mediaSourceHolderSnapshots.size());\n addMediaSources(index, createMediaSources(mediaItems));\n }\n\n public void addMediaSource(MediaSource mediaSource) {\n verifyApplicationThread();\n addMediaSources(Collections.singletonList(mediaSource));\n }\n\n public void addMediaSource(int index, MediaSource mediaSource) {\n verifyApplicationThread();\n addMediaSources(index, Collections.singletonList(mediaSource));\n }\n\n public void addMediaSources(List mediaSources) {\n verifyApplicationThread();\n addMediaSources(/* index= */ mediaSourceHolderSnapshots.size(), mediaSources);\n }\n\n public void addMediaSources(int index, List mediaSources) {\n verifyApplicationThread();\n Assertions.checkArgument(index >= 0);\n Timeline oldTimeline = getCurrentTimeline();\n pendingOperationAcks++;\n List holders = addMediaSourceHolders(index, mediaSources);\n Timeline newTimeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n newTimeline,\n getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));\n internalPlayer.addMediaSources(index, holders, shuffleOrder);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void removeMediaItems(int fromIndex, int toIndex) {\n verifyApplicationThread();\n toIndex = min(toIndex, mediaSourceHolderSnapshots.size());\n PlaybackInfo newPlaybackInfo = removeMediaItemsInternal(fromIndex, toIndex);\n boolean positionDiscontinuity =\n !newPlaybackInfo.periodId.periodUid.equals(playbackInfo.periodId.periodUid);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n positionDiscontinuity,\n DISCONTINUITY_REASON_REMOVE,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void moveMediaItems(int fromIndex, int toIndex, int newFromIndex) {\n verifyApplicationThread();\n Assertions.checkArgument(\n fromIndex >= 0\n && fromIndex <= toIndex\n && toIndex <= mediaSourceHolderSnapshots.size()\n && newFromIndex >= 0);\n Timeline oldTimeline = getCurrentTimeline();\n pendingOperationAcks++;\n newFromIndex = min(newFromIndex, mediaSourceHolderSnapshots.size() - (toIndex - fromIndex));\n Util.moveItems(mediaSourceHolderSnapshots, fromIndex, toIndex, newFromIndex);\n Timeline newTimeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n newTimeline,\n getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));\n internalPlayer.moveMediaSources(fromIndex, toIndex, newFromIndex, shuffleOrder);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void setShuffleOrder(ShuffleOrder shuffleOrder) {\n verifyApplicationThread();\n Timeline timeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n timeline,\n maskWindowPositionMsOrGetPeriodPositionUs(\n timeline, getCurrentMediaItemIndex(), getCurrentPosition()));\n pendingOperationAcks++;\n this.shuffleOrder = shuffleOrder;\n internalPlayer.setShuffleOrder(shuffleOrder);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void setPauseAtEndOfMediaItems(boolean pauseAtEndOfMediaItems) {\n verifyApplicationThread();\n if (this.pauseAtEndOfMediaItems == pauseAtEndOfMediaItems) {\n return;\n }\n this.pauseAtEndOfMediaItems = pauseAtEndOfMediaItems;\n internalPlayer.setPauseAtEndOfWindow(pauseAtEndOfMediaItems);\n }\n\n public boolean getPauseAtEndOfMediaItems() {\n verifyApplicationThread();\n return pauseAtEndOfMediaItems;\n }\n\n public void setPlayWhenReady(boolean playWhenReady) {\n verifyApplicationThread();\n @AudioFocusManager.PlayerCommand\n int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState());\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n }\n\n public void setPlayWhenReady(\n boolean playWhenReady,\n @PlaybackSuppressionReason int playbackSuppressionReason,\n @PlayWhenReadyChangeReason int playWhenReadyChangeReason) {\n if (playbackInfo.playWhenReady == playWhenReady\n && playbackInfo.playbackSuppressionReason == playbackSuppressionReason) {\n return;\n }\n pendingOperationAcks++;\n PlaybackInfo playbackInfo =\n this.playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason);\n internalPlayer.setPlayWhenReady(playWhenReady, playbackSuppressionReason);\n updatePlaybackInfo(\n playbackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n playWhenReadyChangeReason,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public boolean getPlayWhenReady() {\n verifyApplicationThread();\n return playbackInfo.playWhenReady;\n }\n\n public void setRepeatMode(@RepeatMode int repeatMode) {\n verifyApplicationThread();\n if (this.repeatMode != repeatMode) {\n this.repeatMode = repeatMode;\n internalPlayer.setRepeatMode(repeatMode);\n listeners.queueEvent(\n Player.EVENT_REPEAT_MODE_CHANGED, listener -> listener.onRepeatModeChanged(repeatMode));\n updateAvailableCommands();\n listeners.flushEvents();\n }\n }\n\n public @RepeatMode int getRepeatMode() {\n verifyApplicationThread();\n return repeatMode;\n }\n\n public void setShuffleModeEnabled(boolean shuffleModeEnabled) {\n verifyApplicationThread();\n if (this.shuffleModeEnabled != shuffleModeEnabled) {\n this.shuffleModeEnabled = shuffleModeEnabled;\n internalPlayer.setShuffleModeEnabled(shuffleModeEnabled);\n listeners.queueEvent(\n Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED,\n listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled));\n updateAvailableCommands();\n listeners.flushEvents();\n }\n }\n\n public boolean getShuffleModeEnabled() {\n verifyApplicationThread();\n return shuffleModeEnabled;\n }\n\n public boolean isLoading() {\n verifyApplicationThread();\n return playbackInfo.isLoading;\n }\n\n public void seekTo(int mediaItemIndex, long positionMs) {\n verifyApplicationThread();\n analyticsCollector.notifySeekStarted();\n Timeline timeline = playbackInfo.timeline;\n if (mediaItemIndex < 0\n || (!timeline.isEmpty() && mediaItemIndex >= timeline.getWindowCount())) {\n throw new IllegalSeekPositionException(timeline, mediaItemIndex, positionMs);\n }\n pendingOperationAcks++;\n if (isPlayingAd()) {\n // TODO: Investigate adding support for seeking during ads. This is complicated to do in\n // general because the midroll ad preceding the seek destination must be played before the\n // content position can be played, if a different ad is playing at the moment.\n Log.w(TAG, \"seekTo ignored because an ad is playing\");\n ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate =\n new ExoPlayerImplInternal.PlaybackInfoUpdate(this.playbackInfo);\n playbackInfoUpdate.incrementPendingOperationAcks(1);\n playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate);\n return;\n }\n @Player.State\n int newPlaybackState =\n getPlaybackState() == Player.STATE_IDLE ? Player.STATE_IDLE : STATE_BUFFERING;\n int oldMaskingMediaItemIndex = getCurrentMediaItemIndex();\n PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackState(newPlaybackState);\n newPlaybackInfo =\n maskTimelineAndPosition(\n newPlaybackInfo,\n timeline,\n maskWindowPositionMsOrGetPeriodPositionUs(timeline, mediaItemIndex, positionMs));\n internalPlayer.seekTo(timeline, mediaItemIndex, Util.msToUs(positionMs));\n updatePlaybackInfo(\n newPlaybackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ true,\n /* positionDiscontinuity= */ true,\n /* positionDiscontinuityReason= */ DISCONTINUITY_REASON_SEEK,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),\n oldMaskingMediaItemIndex);\n }\n\n public long getSeekBackIncrement() {\n verifyApplicationThread();\n return seekBackIncrementMs;\n }\n\n public long getSeekForwardIncrement() {\n verifyApplicationThread();\n return seekForwardIncrementMs;\n }\n\n public long getMaxSeekToPreviousPosition() {\n verifyApplicationThread();\n return C.DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS;\n }\n\n public void setPlaybackParameters(PlaybackParameters playbackParameters) {\n verifyApplicationThread();\n if (playbackParameters == null) {\n playbackParameters = PlaybackParameters.DEFAULT;\n }\n if (playbackInfo.playbackParameters.equals(playbackParameters)) {\n return;\n }\n PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters);\n pendingOperationAcks++;\n internalPlayer.setPlaybackParameters(playbackParameters);\n updatePlaybackInfo(\n newPlaybackInfo,\n /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ false,\n /* ignored */ DISCONTINUITY_REASON_INTERNAL,\n /* ignored */ C.TIME_UNSET,\n /* ignored */ C.INDEX_UNSET);\n }\n\n public PlaybackParameters getPlaybackParameters() {\n verifyApplicationThread();\n return playbackInfo.playbackParameters;\n }\n\n public void setSeekParameters(@Nullable SeekParameters seekParameters) {\n verifyApplicationThread();\n if (seekParameters == null) {\n seekParameters = SeekParameters.DEFAULT;\n }\n if (!this.seekParameters.equals(seekParameters)) {\n this.seekParameters = seekParameters;\n internalPlayer.setSeekParameters(seekParameters);\n }\n }\n\n public SeekParameters getSeekParameters() {\n verifyApplicationThread();\n return seekParameters;\n }\n\n public void setForegroundMode(boolean foregroundMode) {\n verifyApplicationThread();\n if (this.foregroundMode != foregroundMode) {\n this.foregroundMode = foregroundMode;\n if (!internalPlayer.setForegroundMode(foregroundMode)) {\n // One of the renderers timed out releasing its resources.\n stop(\n /* reset= */ false,\n ExoPlaybackException.createForUnexpected(\n new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_SET_FOREGROUND_MODE),\n PlaybackException.ERROR_CODE_TIMEOUT));\n }\n }\n }\n\n public void stop() {\n stop(/* reset= */ false);\n }\n\n public void stop(boolean reset) {\n verifyApplicationThread();\n audioFocusManager.updateAudioFocus(getPlayWhenReady(), Player.STATE_IDLE);\n stop(reset, /* error= */ null);\n currentCues = ImmutableList.of();\n }\n\n /**\n * Stops the player.\n *\n * @param reset Whether the playlist should be cleared and whether the playback position and\n * playback error should be reset.\n * @param error An optional {@link ExoPlaybackException} to set.\n */\n public void stop(boolean reset, @Nullable ExoPlaybackException error) {\n PlaybackInfo playbackInfo;\n if (reset) {\n playbackInfo =\n removeMediaItemsInternal(\n /* fromIndex= */ 0, /* toIndex= */ mediaSourceHolderSnapshots.size());\n playbackInfo = playbackInfo.copyWithPlaybackError(null);\n } else {\n playbackInfo = this.playbackInfo.copyWithLoadingMediaPeriodId(this.playbackInfo.periodId);\n playbackInfo.bufferedPositionUs = playbackInfo.positionUs;\n playbackInfo.totalBufferedDurationUs = 0;\n }\n playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE);\n if (error != null) {\n playbackInfo = playbackInfo.copyWithPlaybackError(error);\n }\n pendingOperationAcks++;\n internalPlayer.stop();\n boolean positionDiscontinuity =\n playbackInfo.timeline.isEmpty() && !this.playbackInfo.timeline.isEmpty();\n updatePlaybackInfo(\n playbackInfo,\n TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n positionDiscontinuity,\n DISCONTINUITY_REASON_REMOVE,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(playbackInfo),\n /* ignored */ C.INDEX_UNSET);\n }\n\n public void release() {\n Log.i(\n TAG,\n \"Release \"\n + Integer.toHexString(System.identityHashCode(this))\n + \" [\"\n + MediaLibraryInfo.VERSION_SLASHY\n + \"] [\"\n + Util.DEVICE_DEBUG_INFO\n + \"] [\"\n + MediaLibraryInfo.registeredModules()\n + \"]\");\n verifyApplicationThread();\n if (Util.SDK_INT < 21 && keepSessionIdAudioTrack != null) {\n keepSessionIdAudioTrack.release();\n keepSessionIdAudioTrack = null;\n }\n audioBecomingNoisyManager.setEnabled(false);\n streamVolumeManager.release();\n wakeLockManager.setStayAwake(false);\n wifiLockManager.setStayAwake(false);\n audioFocusManager.release();\n if (!internalPlayer.release()) {\n // One of the renderers timed out releasing its resources.\n listeners.sendEvent(\n Player.EVENT_PLAYER_ERROR,\n listener ->\n listener.onPlayerError(\n ExoPlaybackException.createForUnexpected(\n new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_RELEASE),\n PlaybackException.ERROR_CODE_TIMEOUT)));\n }\n listeners.release();\n playbackInfoUpdateHandler.removeCallbacksAndMessages(null);\n bandwidthMeter.removeEventListener(analyticsCollector);\n playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE);\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(playbackInfo.periodId);\n playbackInfo.bufferedPositionUs = playbackInfo.positionUs;\n playbackInfo.totalBufferedDurationUs = 0;\n analyticsCollector.release();\n removeSurfaceCallbacks();\n if (ownedSurface != null) {\n ownedSurface.release();\n ownedSurface = null;\n }\n if (isPriorityTaskManagerRegistered) {\n checkNotNull(priorityTaskManager).remove(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = false;\n }\n currentCues = ImmutableList.of();\n playerReleased = true;\n }\n\n public PlayerMessage createMessage(Target target) {\n verifyApplicationThread();\n return createMessageInternal(target);\n }\n\n public int getCurrentPeriodIndex() {\n verifyApplicationThread();\n if (playbackInfo.timeline.isEmpty()) {\n return maskingPeriodIndex;\n } else {\n return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid);\n }\n }\n\n public int getCurrentMediaItemIndex() {\n verifyApplicationThread();\n int currentWindowIndex = getCurrentWindowIndexInternal();\n return currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex;\n }\n\n public long getDuration() {\n verifyApplicationThread();\n if (isPlayingAd()) {\n MediaPeriodId periodId = playbackInfo.periodId;\n playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);\n long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup);\n return Util.usToMs(adDurationUs);\n }\n return getContentDuration();\n }\n\n private long getContentDuration() {\n Timeline timeline = getCurrentTimeline();\n return timeline.isEmpty()\n ? C.TIME_UNSET\n : timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs();\n }\n\n public long getCurrentPosition() {\n verifyApplicationThread();\n return Util.usToMs(getCurrentPositionUsInternal(playbackInfo));\n }\n\n public long getBufferedPosition() {\n verifyApplicationThread();\n if (isPlayingAd()) {\n return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)\n ? Util.usToMs(playbackInfo.bufferedPositionUs)\n : getDuration();\n }\n return getContentBufferedPosition();\n }\n\n public long getTotalBufferedDuration() {\n verifyApplicationThread();\n return Util.usToMs(playbackInfo.totalBufferedDurationUs);\n }\n\n public boolean isPlayingAd() {\n verifyApplicationThread();\n return playbackInfo.periodId.isAd();\n }\n\n public int getCurrentAdGroupIndex() {\n verifyApplicationThread();\n return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET;\n }\n\n public int getCurrentAdIndexInAdGroup() {\n verifyApplicationThread();\n return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET;\n }\n\n public long getContentPosition() {\n verifyApplicationThread();\n if (isPlayingAd()) {\n playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);\n return playbackInfo.requestedContentPositionUs == C.TIME_UNSET\n ? playbackInfo\n .timeline\n .getWindow(getCurrentMediaItemIndex(), window)\n .getDefaultPositionMs()\n : period.getPositionInWindowMs() + Util.usToMs(playbackInfo.requestedContentPositionUs);\n } else {\n return getCurrentPosition();\n }\n }\n\n public long getContentBufferedPosition() {\n verifyApplicationThread();\n if (playbackInfo.timeline.isEmpty()) {\n return maskingWindowPositionMs;\n }\n if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber\n != playbackInfo.periodId.windowSequenceNumber) {\n return playbackInfo.timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs();\n }\n long contentBufferedPositionUs = playbackInfo.bufferedPositionUs;\n if (playbackInfo.loadingMediaPeriodId.isAd()) {\n Timeline.Period loadingPeriod =\n playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period);\n contentBufferedPositionUs =\n loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex);\n if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) {\n contentBufferedPositionUs = loadingPeriod.durationUs;\n }\n }\n return Util.usToMs(\n periodPositionUsToWindowPositionUs(\n playbackInfo.timeline, playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs));\n }\n\n public int getRendererCount() {\n verifyApplicationThread();\n return renderers.length;\n }\n\n public @C.TrackType int getRendererType(int index) {\n verifyApplicationThread();\n return renderers[index].getTrackType();\n }\n\n public Renderer getRenderer(int index) {\n verifyApplicationThread();\n return renderers[index];\n }\n\n public TrackSelector getTrackSelector() {\n verifyApplicationThread();\n return trackSelector;\n }\n\n public TrackGroupArray getCurrentTrackGroups() {\n verifyApplicationThread();\n return playbackInfo.trackGroups;\n }\n\n public TrackSelectionArray getCurrentTrackSelections() {\n verifyApplicationThread();\n return new TrackSelectionArray(playbackInfo.trackSelectorResult.selections);\n }\n\n public TracksInfo getCurrentTracksInfo() {\n verifyApplicationThread();\n return playbackInfo.trackSelectorResult.tracksInfo;\n }\n\n public TrackSelectionParameters getTrackSelectionParameters() {\n verifyApplicationThread();\n return trackSelector.getParameters();\n }\n\n public void setTrackSelectionParameters(TrackSelectionParameters parameters) {\n verifyApplicationThread();\n if (!trackSelector.isSetParametersSupported()\n || parameters.equals(trackSelector.getParameters())) {\n return;\n }\n trackSelector.setParameters(parameters);\n listeners.queueEvent(\n EVENT_TRACK_SELECTION_PARAMETERS_CHANGED,\n listener -> listener.onTrackSelectionParametersChanged(parameters));\n }\n\n public MediaMetadata getMediaMetadata() {\n verifyApplicationThread();\n return mediaMetadata;\n }\n\n private void onMetadata(Metadata metadata) {\n staticAndDynamicMediaMetadata =\n staticAndDynamicMediaMetadata.buildUpon().populateFromMetadata(metadata).build();\n\n MediaMetadata newMediaMetadata = buildUpdatedMediaMetadata();\n\n if (newMediaMetadata.equals(mediaMetadata)) {\n return;\n }\n mediaMetadata = newMediaMetadata;\n listeners.sendEvent(\n EVENT_MEDIA_METADATA_CHANGED, listener -> listener.onMediaMetadataChanged(mediaMetadata));\n }\n\n public MediaMetadata getPlaylistMetadata() {\n verifyApplicationThread();\n return playlistMetadata;\n }\n\n public void setPlaylistMetadata(MediaMetadata playlistMetadata) {\n verifyApplicationThread();\n checkNotNull(playlistMetadata);\n if (playlistMetadata.equals(this.playlistMetadata)) {\n return;\n }\n this.playlistMetadata = playlistMetadata;\n listeners.sendEvent(\n EVENT_PLAYLIST_METADATA_CHANGED,\n listener -> listener.onPlaylistMetadataChanged(this.playlistMetadata));\n }\n\n public Timeline getCurrentTimeline() {\n verifyApplicationThread();\n return playbackInfo.timeline;\n }\n\n public void setVideoScalingMode(@C.VideoScalingMode int videoScalingMode) {\n verifyApplicationThread();\n this.videoScalingMode = videoScalingMode;\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode);\n }\n\n public @C.VideoScalingMode int getVideoScalingMode() {\n return videoScalingMode;\n }\n\n public void setVideoChangeFrameRateStrategy(\n @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy) {\n verifyApplicationThread();\n if (this.videoChangeFrameRateStrategy == videoChangeFrameRateStrategy) {\n return;\n }\n this.videoChangeFrameRateStrategy = videoChangeFrameRateStrategy;\n sendRendererMessage(\n TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy);\n }\n\n public @C.VideoChangeFrameRateStrategy int getVideoChangeFrameRateStrategy() {\n return videoChangeFrameRateStrategy;\n }\n\n public VideoSize getVideoSize() {\n return videoSize;\n }\n\n public void clearVideoSurface() {\n verifyApplicationThread();\n removeSurfaceCallbacks();\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n\n public void clearVideoSurface(@Nullable Surface surface) {\n verifyApplicationThread();\n if (surface != null && surface == videoOutput) {\n clearVideoSurface();\n }\n }\n\n public void setVideoSurface(@Nullable Surface surface) {\n verifyApplicationThread();\n removeSurfaceCallbacks();\n setVideoOutputInternal(surface);\n int newSurfaceSize = surface == null ? 0 : C.LENGTH_UNSET;\n maybeNotifySurfaceSizeChanged(/* width= */ newSurfaceSize, /* height= */ newSurfaceSize);\n }\n\n public void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) {\n verifyApplicationThread();\n if (surfaceHolder == null) {\n clearVideoSurface();\n } else {\n removeSurfaceCallbacks();\n this.surfaceHolderSurfaceIsVideoOutput = true;\n this.surfaceHolder = surfaceHolder;\n surfaceHolder.addCallback(componentListener);\n Surface surface = surfaceHolder.getSurface();\n if (surface != null && surface.isValid()) {\n setVideoOutputInternal(surface);\n Rect surfaceSize = surfaceHolder.getSurfaceFrame();\n maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height());\n } else {\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n }\n }\n\n public void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) {\n verifyApplicationThread();\n if (surfaceHolder != null && surfaceHolder == this.surfaceHolder) {\n clearVideoSurface();\n }\n }\n\n public void setVideoSurfaceView(@Nullable SurfaceView surfaceView) {\n verifyApplicationThread();\n if (surfaceView instanceof VideoDecoderOutputBufferRenderer) {\n removeSurfaceCallbacks();\n setVideoOutputInternal(surfaceView);\n setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder());\n } else if (surfaceView instanceof SphericalGLSurfaceView) {\n removeSurfaceCallbacks();\n sphericalGLSurfaceView = (SphericalGLSurfaceView) surfaceView;\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW)\n .setPayload(sphericalGLSurfaceView)\n .send();\n sphericalGLSurfaceView.addVideoSurfaceListener(componentListener);\n setVideoOutputInternal(sphericalGLSurfaceView.getVideoSurface());\n setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder());\n } else {\n setVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());\n }\n }\n\n public void clearVideoSurfaceView(@Nullable SurfaceView surfaceView) {\n verifyApplicationThread();\n clearVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());\n }\n\n public void setVideoTextureView(@Nullable TextureView textureView) {\n verifyApplicationThread();\n if (textureView == null) {\n clearVideoSurface();\n } else {\n removeSurfaceCallbacks();\n this.textureView = textureView;\n if (textureView.getSurfaceTextureListener() != null) {\n Log.w(TAG, \"Replacing existing SurfaceTextureListener.\");\n }\n textureView.setSurfaceTextureListener(componentListener);\n @Nullable\n SurfaceTexture surfaceTexture =\n textureView.isAvailable() ? textureView.getSurfaceTexture() : null;\n if (surfaceTexture == null) {\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n } else {\n setSurfaceTextureInternal(surfaceTexture);\n maybeNotifySurfaceSizeChanged(textureView.getWidth(), textureView.getHeight());\n }\n }\n }\n\n public void clearVideoTextureView(@Nullable TextureView textureView) {\n verifyApplicationThread();\n if (textureView != null && textureView == this.textureView) {\n clearVideoSurface();\n }\n }\n\n public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) {\n verifyApplicationThread();\n if (playerReleased) {\n return;\n }\n if (!Util.areEqual(this.audioAttributes, audioAttributes)) {\n this.audioAttributes = audioAttributes;\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes);\n streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage));\n analyticsCollector.onAudioAttributesChanged(audioAttributes);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onAudioAttributesChanged(audioAttributes);\n }\n }\n\n audioFocusManager.setAudioAttributes(handleAudioFocus ? audioAttributes : null);\n boolean playWhenReady = getPlayWhenReady();\n @AudioFocusManager.PlayerCommand\n int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState());\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n }\n\n public AudioAttributes getAudioAttributes() {\n return audioAttributes;\n }\n\n public void setAudioSessionId(int audioSessionId) {\n verifyApplicationThread();\n if (this.audioSessionId == audioSessionId) {\n return;\n }\n if (audioSessionId == C.AUDIO_SESSION_ID_UNSET) {\n if (Util.SDK_INT < 21) {\n audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET);\n } else {\n audioSessionId = Util.generateAudioSessionIdV21(applicationContext);\n }\n } else if (Util.SDK_INT < 21) {\n // We need to re-initialize keepSessionIdAudioTrack to make sure the session is kept alive for\n // as long as the player is using it.\n initializeKeepSessionIdAudioTrack(audioSessionId);\n }\n this.audioSessionId = audioSessionId;\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId);\n analyticsCollector.onAudioSessionIdChanged(audioSessionId);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onAudioSessionIdChanged(audioSessionId);\n }\n }\n\n public int getAudioSessionId() {\n return audioSessionId;\n }\n\n public void setAuxEffectInfo(AuxEffectInfo auxEffectInfo) {\n verifyApplicationThread();\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUX_EFFECT_INFO, auxEffectInfo);\n }\n\n public void clearAuxEffectInfo() {\n setAuxEffectInfo(new AuxEffectInfo(AuxEffectInfo.NO_AUX_EFFECT_ID, /* sendLevel= */ 0f));\n }\n\n public void setVolume(float volume) {\n verifyApplicationThread();\n volume = Util.constrainValue(volume, /* min= */ 0, /* max= */ 1);\n if (this.volume == volume) {\n return;\n }\n this.volume = volume;\n sendVolumeToRenderers();\n analyticsCollector.onVolumeChanged(volume);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onVolumeChanged(volume);\n }\n }\n\n public float getVolume() {\n return volume;\n }\n\n public boolean getSkipSilenceEnabled() {\n return skipSilenceEnabled;\n }\n\n public void setSkipSilenceEnabled(boolean skipSilenceEnabled) {\n verifyApplicationThread();\n if (this.skipSilenceEnabled == skipSilenceEnabled) {\n return;\n }\n this.skipSilenceEnabled = skipSilenceEnabled;\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled);\n notifySkipSilenceEnabledChanged();\n }\n\n public AnalyticsCollector getAnalyticsCollector() {\n return analyticsCollector;\n }\n\n public void addAnalyticsListener(AnalyticsListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n checkNotNull(listener);\n analyticsCollector.addListener(listener);\n }\n\n public void removeAnalyticsListener(AnalyticsListener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n analyticsCollector.removeListener(listener);\n }\n\n public void setHandleAudioBecomingNoisy(boolean handleAudioBecomingNoisy) {\n verifyApplicationThread();\n if (playerReleased) {\n return;\n }\n audioBecomingNoisyManager.setEnabled(handleAudioBecomingNoisy);\n }\n\n public void setPriorityTaskManager(@Nullable PriorityTaskManager priorityTaskManager) {\n verifyApplicationThread();\n if (Util.areEqual(this.priorityTaskManager, priorityTaskManager)) {\n return;\n }\n if (isPriorityTaskManagerRegistered) {\n checkNotNull(this.priorityTaskManager).remove(C.PRIORITY_PLAYBACK);\n }\n if (priorityTaskManager != null && isLoading()) {\n priorityTaskManager.add(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = true;\n } else {\n isPriorityTaskManagerRegistered = false;\n }\n this.priorityTaskManager = priorityTaskManager;\n }\n\n @Nullable\n public Format getVideoFormat() {\n return videoFormat;\n }\n\n @Nullable\n public Format getAudioFormat() {\n return audioFormat;\n }\n\n @Nullable\n public DecoderCounters getVideoDecoderCounters() {\n return videoDecoderCounters;\n }\n\n @Nullable\n public DecoderCounters getAudioDecoderCounters() {\n return audioDecoderCounters;\n }\n\n public void setVideoFrameMetadataListener(VideoFrameMetadataListener listener) {\n verifyApplicationThread();\n videoFrameMetadataListener = listener;\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER)\n .setPayload(listener)\n .send();\n }\n\n public void clearVideoFrameMetadataListener(VideoFrameMetadataListener listener) {\n verifyApplicationThread();\n if (videoFrameMetadataListener != listener) {\n return;\n }\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER)\n .setPayload(null)\n .send();\n }\n\n public void setCameraMotionListener(CameraMotionListener listener) {\n verifyApplicationThread();\n cameraMotionListener = listener;\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER)\n .setPayload(listener)\n .send();\n }\n\n public void clearCameraMotionListener(CameraMotionListener listener) {\n verifyApplicationThread();\n if (cameraMotionListener != listener) {\n return;\n }\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER)\n .setPayload(null)\n .send();\n }\n\n public List getCurrentCues() {\n verifyApplicationThread();\n return currentCues;\n }\n\n public void addListener(Listener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n checkNotNull(listener);\n listeners.add(listener);\n listenerArraySet.add(listener);\n }\n\n public void removeListener(Listener listener) {\n // Don't verify application thread. We allow calls to this method from any thread.\n checkNotNull(listener);\n listeners.remove(listener);\n listenerArraySet.remove(listener);\n }\n\n public void setHandleWakeLock(boolean handleWakeLock) {\n setWakeMode(handleWakeLock ? C.WAKE_MODE_LOCAL : C.WAKE_MODE_NONE);\n }\n\n public void setWakeMode(@C.WakeMode int wakeMode) {\n verifyApplicationThread();\n switch (wakeMode) {\n case C.WAKE_MODE_NONE:\n wakeLockManager.setEnabled(false);\n wifiLockManager.setEnabled(false);\n break;\n case C.WAKE_MODE_LOCAL:\n wakeLockManager.setEnabled(true);\n wifiLockManager.setEnabled(false);\n break;\n case C.WAKE_MODE_NETWORK:\n wakeLockManager.setEnabled(true);\n wifiLockManager.setEnabled(true);\n break;\n default:\n break;\n }\n }\n\n public DeviceInfo getDeviceInfo() {\n verifyApplicationThread();\n return deviceInfo;\n }\n\n public int getDeviceVolume() {\n verifyApplicationThread();\n return streamVolumeManager.getVolume();\n }\n\n public boolean isDeviceMuted() {\n verifyApplicationThread();\n return streamVolumeManager.isMuted();\n }\n\n public void setDeviceVolume(int volume) {\n verifyApplicationThread();\n streamVolumeManager.setVolume(volume);\n }\n\n public void increaseDeviceVolume() {\n verifyApplicationThread();\n streamVolumeManager.increaseVolume();\n }\n\n public void decreaseDeviceVolume() {\n verifyApplicationThread();\n streamVolumeManager.decreaseVolume();\n }\n\n public void setDeviceMuted(boolean muted) {\n verifyApplicationThread();\n streamVolumeManager.setMuted(muted);\n }\n\n /* package */ void setThrowsWhenUsingWrongThread(boolean throwsWhenUsingWrongThread) {\n this.throwsWhenUsingWrongThread = throwsWhenUsingWrongThread;\n }\n\n private int getCurrentWindowIndexInternal() {\n if (playbackInfo.timeline.isEmpty()) {\n return maskingWindowIndex;\n } else {\n return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period)\n .windowIndex;\n }\n }\n\n private long getCurrentPositionUsInternal(PlaybackInfo playbackInfo) {\n if (playbackInfo.timeline.isEmpty()) {\n return Util.msToUs(maskingWindowPositionMs);\n } else if (playbackInfo.periodId.isAd()) {\n return playbackInfo.positionUs;\n } else {\n return periodPositionUsToWindowPositionUs(\n playbackInfo.timeline, playbackInfo.periodId, playbackInfo.positionUs);\n }\n }\n\n private List createMediaSources(List mediaItems) {\n List mediaSources = new ArrayList<>();\n for (int i = 0; i < mediaItems.size(); i++) {\n mediaSources.add(mediaSourceFactory.createMediaSource(mediaItems.get(i)));\n }\n return mediaSources;\n }\n\n private void handlePlaybackInfo(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate) {\n pendingOperationAcks -= playbackInfoUpdate.operationAcks;\n if (playbackInfoUpdate.positionDiscontinuity) {\n pendingDiscontinuityReason = playbackInfoUpdate.discontinuityReason;\n pendingDiscontinuity = true;\n }\n if (playbackInfoUpdate.hasPlayWhenReadyChangeReason) {\n pendingPlayWhenReadyChangeReason = playbackInfoUpdate.playWhenReadyChangeReason;\n }\n if (pendingOperationAcks == 0) {\n Timeline newTimeline = playbackInfoUpdate.playbackInfo.timeline;\n if (!this.playbackInfo.timeline.isEmpty() && newTimeline.isEmpty()) {\n // Update the masking variables, which are used when the timeline becomes empty because a\n // ConcatenatingMediaSource has been cleared.\n maskingWindowIndex = C.INDEX_UNSET;\n maskingWindowPositionMs = 0;\n maskingPeriodIndex = 0;\n }\n if (!newTimeline.isEmpty()) {\n List timelines = ((PlaylistTimeline) newTimeline).getChildTimelines();\n checkState(timelines.size() == mediaSourceHolderSnapshots.size());\n for (int i = 0; i < timelines.size(); i++) {\n mediaSourceHolderSnapshots.get(i).timeline = timelines.get(i);\n }\n }\n boolean positionDiscontinuity = false;\n long discontinuityWindowStartPositionUs = C.TIME_UNSET;\n if (pendingDiscontinuity) {\n positionDiscontinuity =\n !playbackInfoUpdate.playbackInfo.periodId.equals(playbackInfo.periodId)\n || playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs\n != playbackInfo.positionUs;\n if (positionDiscontinuity) {\n discontinuityWindowStartPositionUs =\n newTimeline.isEmpty() || playbackInfoUpdate.playbackInfo.periodId.isAd()\n ? playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs\n : periodPositionUsToWindowPositionUs(\n newTimeline,\n playbackInfoUpdate.playbackInfo.periodId,\n playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs);\n }\n }\n pendingDiscontinuity = false;\n updatePlaybackInfo(\n playbackInfoUpdate.playbackInfo,\n TIMELINE_CHANGE_REASON_SOURCE_UPDATE,\n pendingPlayWhenReadyChangeReason,\n /* seekProcessed= */ false,\n positionDiscontinuity,\n pendingDiscontinuityReason,\n discontinuityWindowStartPositionUs,\n /* ignored */ C.INDEX_UNSET);\n }\n }\n\n // Calling deprecated listeners.\n @SuppressWarnings(\"deprecation\")\n private void updatePlaybackInfo(\n PlaybackInfo playbackInfo,\n @TimelineChangeReason int timelineChangeReason,\n @PlayWhenReadyChangeReason int playWhenReadyChangeReason,\n boolean seekProcessed,\n boolean positionDiscontinuity,\n @DiscontinuityReason int positionDiscontinuityReason,\n long discontinuityWindowStartPositionUs,\n int oldMaskingMediaItemIndex) {\n\n // Assign playback info immediately such that all getters return the right values, but keep\n // snapshot of previous and new state so that listener invocations are triggered correctly.\n PlaybackInfo previousPlaybackInfo = this.playbackInfo;\n PlaybackInfo newPlaybackInfo = playbackInfo;\n this.playbackInfo = playbackInfo;\n\n Pair mediaItemTransitionInfo =\n evaluateMediaItemTransitionReason(\n newPlaybackInfo,\n previousPlaybackInfo,\n positionDiscontinuity,\n positionDiscontinuityReason,\n !previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline));\n boolean mediaItemTransitioned = mediaItemTransitionInfo.first;\n int mediaItemTransitionReason = mediaItemTransitionInfo.second;\n MediaMetadata newMediaMetadata = mediaMetadata;\n @Nullable MediaItem mediaItem = null;\n if (mediaItemTransitioned) {\n if (!newPlaybackInfo.timeline.isEmpty()) {\n int windowIndex =\n newPlaybackInfo.timeline.getPeriodByUid(newPlaybackInfo.periodId.periodUid, period)\n .windowIndex;\n mediaItem = newPlaybackInfo.timeline.getWindow(windowIndex, window).mediaItem;\n }\n staticAndDynamicMediaMetadata = MediaMetadata.EMPTY;\n }\n if (mediaItemTransitioned\n || !previousPlaybackInfo.staticMetadata.equals(newPlaybackInfo.staticMetadata)) {\n staticAndDynamicMediaMetadata =\n staticAndDynamicMediaMetadata\n .buildUpon()\n .populateFromMetadata(newPlaybackInfo.staticMetadata)\n .build();\n\n newMediaMetadata = buildUpdatedMediaMetadata();\n }\n boolean metadataChanged = !newMediaMetadata.equals(mediaMetadata);\n mediaMetadata = newMediaMetadata;\n\n if (!previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline)) {\n listeners.queueEvent(\n Player.EVENT_TIMELINE_CHANGED,\n listener -> listener.onTimelineChanged(newPlaybackInfo.timeline, timelineChangeReason));\n }\n if (positionDiscontinuity) {\n PositionInfo previousPositionInfo =\n getPreviousPositionInfo(\n positionDiscontinuityReason, previousPlaybackInfo, oldMaskingMediaItemIndex);\n PositionInfo positionInfo = getPositionInfo(discontinuityWindowStartPositionUs);\n listeners.queueEvent(\n Player.EVENT_POSITION_DISCONTINUITY,\n listener -> {\n listener.onPositionDiscontinuity(positionDiscontinuityReason);\n listener.onPositionDiscontinuity(\n previousPositionInfo, positionInfo, positionDiscontinuityReason);\n });\n }\n if (mediaItemTransitioned) {\n @Nullable final MediaItem finalMediaItem = mediaItem;\n listeners.queueEvent(\n Player.EVENT_MEDIA_ITEM_TRANSITION,\n listener -> listener.onMediaItemTransition(finalMediaItem, mediaItemTransitionReason));\n }\n if (previousPlaybackInfo.playbackError != newPlaybackInfo.playbackError) {\n listeners.queueEvent(\n Player.EVENT_PLAYER_ERROR,\n listener -> listener.onPlayerErrorChanged(newPlaybackInfo.playbackError));\n if (newPlaybackInfo.playbackError != null) {\n listeners.queueEvent(\n Player.EVENT_PLAYER_ERROR,\n listener -> listener.onPlayerError(newPlaybackInfo.playbackError));\n }\n }\n if (previousPlaybackInfo.trackSelectorResult != newPlaybackInfo.trackSelectorResult) {\n trackSelector.onSelectionActivated(newPlaybackInfo.trackSelectorResult.info);\n TrackSelectionArray newSelection =\n new TrackSelectionArray(newPlaybackInfo.trackSelectorResult.selections);\n listeners.queueEvent(\n Player.EVENT_TRACKS_CHANGED,\n listener -> listener.onTracksChanged(newPlaybackInfo.trackGroups, newSelection));\n listeners.queueEvent(\n Player.EVENT_TRACKS_CHANGED,\n listener -> listener.onTracksInfoChanged(newPlaybackInfo.trackSelectorResult.tracksInfo));\n }\n if (metadataChanged) {\n final MediaMetadata finalMediaMetadata = mediaMetadata;\n listeners.queueEvent(\n EVENT_MEDIA_METADATA_CHANGED,\n listener -> listener.onMediaMetadataChanged(finalMediaMetadata));\n }\n if (previousPlaybackInfo.isLoading != newPlaybackInfo.isLoading) {\n listeners.queueEvent(\n Player.EVENT_IS_LOADING_CHANGED,\n listener -> {\n listener.onLoadingChanged(newPlaybackInfo.isLoading);\n listener.onIsLoadingChanged(newPlaybackInfo.isLoading);\n });\n }\n if (previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState\n || previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady) {\n listeners.queueEvent(\n /* eventFlag= */ C.INDEX_UNSET,\n listener ->\n listener.onPlayerStateChanged(\n newPlaybackInfo.playWhenReady, newPlaybackInfo.playbackState));\n }\n if (previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState) {\n listeners.queueEvent(\n Player.EVENT_PLAYBACK_STATE_CHANGED,\n listener -> listener.onPlaybackStateChanged(newPlaybackInfo.playbackState));\n }\n if (previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady) {\n listeners.queueEvent(\n Player.EVENT_PLAY_WHEN_READY_CHANGED,\n listener ->\n listener.onPlayWhenReadyChanged(\n newPlaybackInfo.playWhenReady, playWhenReadyChangeReason));\n }\n if (previousPlaybackInfo.playbackSuppressionReason\n != newPlaybackInfo.playbackSuppressionReason) {\n listeners.queueEvent(\n Player.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED,\n listener ->\n listener.onPlaybackSuppressionReasonChanged(\n newPlaybackInfo.playbackSuppressionReason));\n }\n if (isPlaying(previousPlaybackInfo) != isPlaying(newPlaybackInfo)) {\n listeners.queueEvent(\n Player.EVENT_IS_PLAYING_CHANGED,\n listener -> listener.onIsPlayingChanged(isPlaying(newPlaybackInfo)));\n }\n if (!previousPlaybackInfo.playbackParameters.equals(newPlaybackInfo.playbackParameters)) {\n listeners.queueEvent(\n Player.EVENT_PLAYBACK_PARAMETERS_CHANGED,\n listener -> listener.onPlaybackParametersChanged(newPlaybackInfo.playbackParameters));\n }\n if (seekProcessed) {\n listeners.queueEvent(/* eventFlag= */ C.INDEX_UNSET, Listener::onSeekProcessed);\n }\n updateAvailableCommands();\n listeners.flushEvents();\n\n if (previousPlaybackInfo.offloadSchedulingEnabled != newPlaybackInfo.offloadSchedulingEnabled) {\n for (AudioOffloadListener listener : audioOffloadListeners) {\n listener.onExperimentalOffloadSchedulingEnabledChanged(\n newPlaybackInfo.offloadSchedulingEnabled);\n }\n }\n if (previousPlaybackInfo.sleepingForOffload != newPlaybackInfo.sleepingForOffload) {\n for (AudioOffloadListener listener : audioOffloadListeners) {\n listener.onExperimentalSleepingForOffloadChanged(newPlaybackInfo.sleepingForOffload);\n }\n }\n }\n\n private PositionInfo getPreviousPositionInfo(\n @DiscontinuityReason int positionDiscontinuityReason,\n PlaybackInfo oldPlaybackInfo,\n int oldMaskingMediaItemIndex) {\n @Nullable Object oldWindowUid = null;\n @Nullable Object oldPeriodUid = null;\n int oldMediaItemIndex = oldMaskingMediaItemIndex;\n int oldPeriodIndex = C.INDEX_UNSET;\n @Nullable MediaItem oldMediaItem = null;\n Timeline.Period oldPeriod = new Timeline.Period();\n if (!oldPlaybackInfo.timeline.isEmpty()) {\n oldPeriodUid = oldPlaybackInfo.periodId.periodUid;\n oldPlaybackInfo.timeline.getPeriodByUid(oldPeriodUid, oldPeriod);\n oldMediaItemIndex = oldPeriod.windowIndex;\n oldPeriodIndex = oldPlaybackInfo.timeline.getIndexOfPeriod(oldPeriodUid);\n oldWindowUid = oldPlaybackInfo.timeline.getWindow(oldMediaItemIndex, window).uid;\n oldMediaItem = window.mediaItem;\n }\n long oldPositionUs;\n long oldContentPositionUs;\n if (positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) {\n if (oldPlaybackInfo.periodId.isAd()) {\n // The old position is the end of the previous ad.\n oldPositionUs =\n oldPeriod.getAdDurationUs(\n oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup);\n // The ad cue point is stored in the old requested content position.\n oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo);\n } else if (oldPlaybackInfo.periodId.nextAdGroupIndex != C.INDEX_UNSET) {\n // The old position is the end of a clipped content before an ad group. Use the exact ad\n // cue point as the transition position.\n oldPositionUs = getRequestedContentPositionUs(playbackInfo);\n oldContentPositionUs = oldPositionUs;\n } else {\n // The old position is the end of a Timeline period. Use the exact duration.\n oldPositionUs = oldPeriod.positionInWindowUs + oldPeriod.durationUs;\n oldContentPositionUs = oldPositionUs;\n }\n } else if (oldPlaybackInfo.periodId.isAd()) {\n oldPositionUs = oldPlaybackInfo.positionUs;\n oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo);\n } else {\n oldPositionUs = oldPeriod.positionInWindowUs + oldPlaybackInfo.positionUs;\n oldContentPositionUs = oldPositionUs;\n }\n return new PositionInfo(\n oldWindowUid,\n oldMediaItemIndex,\n oldMediaItem,\n oldPeriodUid,\n oldPeriodIndex,\n Util.usToMs(oldPositionUs),\n Util.usToMs(oldContentPositionUs),\n oldPlaybackInfo.periodId.adGroupIndex,\n oldPlaybackInfo.periodId.adIndexInAdGroup);\n }\n\n private PositionInfo getPositionInfo(long discontinuityWindowStartPositionUs) {\n @Nullable Object newWindowUid = null;\n @Nullable Object newPeriodUid = null;\n int newMediaItemIndex = getCurrentMediaItemIndex();\n int newPeriodIndex = C.INDEX_UNSET;\n @Nullable MediaItem newMediaItem = null;\n if (!playbackInfo.timeline.isEmpty()) {\n newPeriodUid = playbackInfo.periodId.periodUid;\n playbackInfo.timeline.getPeriodByUid(newPeriodUid, period);\n newPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(newPeriodUid);\n newWindowUid = playbackInfo.timeline.getWindow(newMediaItemIndex, window).uid;\n newMediaItem = window.mediaItem;\n }\n long positionMs = Util.usToMs(discontinuityWindowStartPositionUs);\n return new PositionInfo(\n newWindowUid,\n newMediaItemIndex,\n newMediaItem,\n newPeriodUid,\n newPeriodIndex,\n positionMs,\n /* contentPositionMs= */ playbackInfo.periodId.isAd()\n ? Util.usToMs(getRequestedContentPositionUs(playbackInfo))\n : positionMs,\n playbackInfo.periodId.adGroupIndex,\n playbackInfo.periodId.adIndexInAdGroup);\n }\n\n private static long getRequestedContentPositionUs(PlaybackInfo playbackInfo) {\n Timeline.Window window = new Timeline.Window();\n Timeline.Period period = new Timeline.Period();\n playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);\n return playbackInfo.requestedContentPositionUs == C.TIME_UNSET\n ? playbackInfo.timeline.getWindow(period.windowIndex, window).getDefaultPositionUs()\n : period.getPositionInWindowUs() + playbackInfo.requestedContentPositionUs;\n }\n\n private Pair evaluateMediaItemTransitionReason(\n PlaybackInfo playbackInfo,\n PlaybackInfo oldPlaybackInfo,\n boolean positionDiscontinuity,\n @DiscontinuityReason int positionDiscontinuityReason,\n boolean timelineChanged) {\n\n Timeline oldTimeline = oldPlaybackInfo.timeline;\n Timeline newTimeline = playbackInfo.timeline;\n if (newTimeline.isEmpty() && oldTimeline.isEmpty()) {\n return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET);\n } else if (newTimeline.isEmpty() != oldTimeline.isEmpty()) {\n return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED);\n }\n\n int oldWindowIndex =\n oldTimeline.getPeriodByUid(oldPlaybackInfo.periodId.periodUid, period).windowIndex;\n Object oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid;\n int newWindowIndex =\n newTimeline.getPeriodByUid(playbackInfo.periodId.periodUid, period).windowIndex;\n Object newWindowUid = newTimeline.getWindow(newWindowIndex, window).uid;\n if (!oldWindowUid.equals(newWindowUid)) {\n @Player.MediaItemTransitionReason int transitionReason;\n if (positionDiscontinuity\n && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) {\n transitionReason = MEDIA_ITEM_TRANSITION_REASON_AUTO;\n } else if (positionDiscontinuity\n && positionDiscontinuityReason == DISCONTINUITY_REASON_SEEK) {\n transitionReason = MEDIA_ITEM_TRANSITION_REASON_SEEK;\n } else if (timelineChanged) {\n transitionReason = MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED;\n } else {\n // A change in window uid must be justified by one of the reasons above.\n throw new IllegalStateException();\n }\n return new Pair<>(/* isTransitioning */ true, transitionReason);\n } else if (positionDiscontinuity\n && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION\n && oldPlaybackInfo.periodId.windowSequenceNumber\n < playbackInfo.periodId.windowSequenceNumber) {\n return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_REPEAT);\n }\n return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET);\n }\n\n private void updateAvailableCommands() {\n Commands previousAvailableCommands = availableCommands;\n availableCommands = Util.getAvailableCommands(wrappingPlayer, permanentAvailableCommands);\n if (!availableCommands.equals(previousAvailableCommands)) {\n listeners.queueEvent(\n Player.EVENT_AVAILABLE_COMMANDS_CHANGED,\n listener -> listener.onAvailableCommandsChanged(availableCommands));\n }\n }\n\n private void setMediaSourcesInternal(\n List mediaSources,\n int startWindowIndex,\n long startPositionMs,\n boolean resetToDefaultPosition) {\n int currentWindowIndex = getCurrentWindowIndexInternal();\n long currentPositionMs = getCurrentPosition();\n pendingOperationAcks++;\n if (!mediaSourceHolderSnapshots.isEmpty()) {\n removeMediaSourceHolders(\n /* fromIndex= */ 0, /* toIndexExclusive= */ mediaSourceHolderSnapshots.size());\n }\n List holders =\n addMediaSourceHolders(/* index= */ 0, mediaSources);\n Timeline timeline = createMaskingTimeline();\n if (!timeline.isEmpty() && startWindowIndex >= timeline.getWindowCount()) {\n throw new IllegalSeekPositionException(timeline, startWindowIndex, startPositionMs);\n }\n // Evaluate the actual start position.\n if (resetToDefaultPosition) {\n startWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled);\n startPositionMs = C.TIME_UNSET;\n } else if (startWindowIndex == C.INDEX_UNSET) {\n startWindowIndex = currentWindowIndex;\n startPositionMs = currentPositionMs;\n }\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n timeline,\n maskWindowPositionMsOrGetPeriodPositionUs(timeline, startWindowIndex, startPositionMs));\n // Mask the playback state.\n int maskingPlaybackState = newPlaybackInfo.playbackState;\n if (startWindowIndex != C.INDEX_UNSET && newPlaybackInfo.playbackState != STATE_IDLE) {\n // Position reset to startWindowIndex (results in pending initial seek).\n if (timeline.isEmpty() || startWindowIndex >= timeline.getWindowCount()) {\n // Setting an empty timeline or invalid seek transitions to ended.\n maskingPlaybackState = STATE_ENDED;\n } else {\n maskingPlaybackState = STATE_BUFFERING;\n }\n }\n newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(maskingPlaybackState);\n internalPlayer.setMediaSources(\n holders, startWindowIndex, Util.msToUs(startPositionMs), shuffleOrder);\n boolean positionDiscontinuity =\n !playbackInfo.periodId.periodUid.equals(newPlaybackInfo.periodId.periodUid)\n && !playbackInfo.timeline.isEmpty();\n updatePlaybackInfo(\n newPlaybackInfo,\n /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED,\n /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,\n /* seekProcessed= */ false,\n /* positionDiscontinuity= */ positionDiscontinuity,\n DISCONTINUITY_REASON_REMOVE,\n /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo),\n /* ignored */ C.INDEX_UNSET);\n }\n\n private List addMediaSourceHolders(\n int index, List mediaSources) {\n List holders = new ArrayList<>();\n for (int i = 0; i < mediaSources.size(); i++) {\n MediaSourceList.MediaSourceHolder holder =\n new MediaSourceList.MediaSourceHolder(mediaSources.get(i), useLazyPreparation);\n holders.add(holder);\n mediaSourceHolderSnapshots.add(\n i + index, new MediaSourceHolderSnapshot(holder.uid, holder.mediaSource.getTimeline()));\n }\n shuffleOrder =\n shuffleOrder.cloneAndInsert(\n /* insertionIndex= */ index, /* insertionCount= */ holders.size());\n return holders;\n }\n\n private PlaybackInfo removeMediaItemsInternal(int fromIndex, int toIndex) {\n Assertions.checkArgument(\n fromIndex >= 0 && toIndex >= fromIndex && toIndex <= mediaSourceHolderSnapshots.size());\n int currentIndex = getCurrentMediaItemIndex();\n Timeline oldTimeline = getCurrentTimeline();\n int currentMediaSourceCount = mediaSourceHolderSnapshots.size();\n pendingOperationAcks++;\n removeMediaSourceHolders(fromIndex, /* toIndexExclusive= */ toIndex);\n Timeline newTimeline = createMaskingTimeline();\n PlaybackInfo newPlaybackInfo =\n maskTimelineAndPosition(\n playbackInfo,\n newTimeline,\n getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline));\n // Player transitions to STATE_ENDED if the current index is part of the removed tail.\n final boolean transitionsToEnded =\n newPlaybackInfo.playbackState != STATE_IDLE\n && newPlaybackInfo.playbackState != STATE_ENDED\n && fromIndex < toIndex\n && toIndex == currentMediaSourceCount\n && currentIndex >= newPlaybackInfo.timeline.getWindowCount();\n if (transitionsToEnded) {\n newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(STATE_ENDED);\n }\n internalPlayer.removeMediaSources(fromIndex, toIndex, shuffleOrder);\n return newPlaybackInfo;\n }\n\n private void removeMediaSourceHolders(int fromIndex, int toIndexExclusive) {\n for (int i = toIndexExclusive - 1; i >= fromIndex; i--) {\n mediaSourceHolderSnapshots.remove(i);\n }\n shuffleOrder = shuffleOrder.cloneAndRemove(fromIndex, toIndexExclusive);\n }\n\n private Timeline createMaskingTimeline() {\n return new PlaylistTimeline(mediaSourceHolderSnapshots, shuffleOrder);\n }\n\n private PlaybackInfo maskTimelineAndPosition(\n PlaybackInfo playbackInfo, Timeline timeline, @Nullable Pair periodPositionUs) {\n Assertions.checkArgument(timeline.isEmpty() || periodPositionUs != null);\n Timeline oldTimeline = playbackInfo.timeline;\n // Mask the timeline.\n playbackInfo = playbackInfo.copyWithTimeline(timeline);\n\n if (timeline.isEmpty()) {\n // Reset periodId and loadingPeriodId.\n MediaPeriodId dummyMediaPeriodId = PlaybackInfo.getDummyPeriodForEmptyTimeline();\n long positionUs = Util.msToUs(maskingWindowPositionMs);\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n dummyMediaPeriodId,\n positionUs,\n /* requestedContentPositionUs= */ positionUs,\n /* discontinuityStartPositionUs= */ positionUs,\n /* totalBufferedDurationUs= */ 0,\n TrackGroupArray.EMPTY,\n emptyTrackSelectorResult,\n /* staticMetadata= */ ImmutableList.of());\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(dummyMediaPeriodId);\n playbackInfo.bufferedPositionUs = playbackInfo.positionUs;\n return playbackInfo;\n }\n\n Object oldPeriodUid = playbackInfo.periodId.periodUid;\n boolean playingPeriodChanged = !oldPeriodUid.equals(castNonNull(periodPositionUs).first);\n MediaPeriodId newPeriodId =\n playingPeriodChanged ? new MediaPeriodId(periodPositionUs.first) : playbackInfo.periodId;\n long newContentPositionUs = periodPositionUs.second;\n long oldContentPositionUs = Util.msToUs(getContentPosition());\n if (!oldTimeline.isEmpty()) {\n oldContentPositionUs -=\n oldTimeline.getPeriodByUid(oldPeriodUid, period).getPositionInWindowUs();\n }\n\n if (playingPeriodChanged || newContentPositionUs < oldContentPositionUs) {\n checkState(!newPeriodId.isAd());\n // The playing period changes or a backwards seek within the playing period occurs.\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n newPeriodId,\n /* positionUs= */ newContentPositionUs,\n /* requestedContentPositionUs= */ newContentPositionUs,\n /* discontinuityStartPositionUs= */ newContentPositionUs,\n /* totalBufferedDurationUs= */ 0,\n playingPeriodChanged ? TrackGroupArray.EMPTY : playbackInfo.trackGroups,\n playingPeriodChanged ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult,\n playingPeriodChanged ? ImmutableList.of() : playbackInfo.staticMetadata);\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId);\n playbackInfo.bufferedPositionUs = newContentPositionUs;\n } else if (newContentPositionUs == oldContentPositionUs) {\n // Period position remains unchanged.\n int loadingPeriodIndex =\n timeline.getIndexOfPeriod(playbackInfo.loadingMediaPeriodId.periodUid);\n if (loadingPeriodIndex == C.INDEX_UNSET\n || timeline.getPeriod(loadingPeriodIndex, period).windowIndex\n != timeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex) {\n // Discard periods after the playing period, if the loading period is discarded or the\n // playing and loading period are not in the same window.\n timeline.getPeriodByUid(newPeriodId.periodUid, period);\n long maskedBufferedPositionUs =\n newPeriodId.isAd()\n ? period.getAdDurationUs(newPeriodId.adGroupIndex, newPeriodId.adIndexInAdGroup)\n : period.durationUs;\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n newPeriodId,\n /* positionUs= */ playbackInfo.positionUs,\n /* requestedContentPositionUs= */ playbackInfo.positionUs,\n playbackInfo.discontinuityStartPositionUs,\n /* totalBufferedDurationUs= */ maskedBufferedPositionUs - playbackInfo.positionUs,\n playbackInfo.trackGroups,\n playbackInfo.trackSelectorResult,\n playbackInfo.staticMetadata);\n playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId);\n playbackInfo.bufferedPositionUs = maskedBufferedPositionUs;\n }\n } else {\n checkState(!newPeriodId.isAd());\n // A forward seek within the playing period (timeline did not change).\n long maskedTotalBufferedDurationUs =\n max(\n 0,\n playbackInfo.totalBufferedDurationUs - (newContentPositionUs - oldContentPositionUs));\n long maskedBufferedPositionUs = playbackInfo.bufferedPositionUs;\n if (playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)) {\n maskedBufferedPositionUs = newContentPositionUs + maskedTotalBufferedDurationUs;\n }\n playbackInfo =\n playbackInfo.copyWithNewPosition(\n newPeriodId,\n /* positionUs= */ newContentPositionUs,\n /* requestedContentPositionUs= */ newContentPositionUs,\n /* discontinuityStartPositionUs= */ newContentPositionUs,\n maskedTotalBufferedDurationUs,\n playbackInfo.trackGroups,\n playbackInfo.trackSelectorResult,\n playbackInfo.staticMetadata);\n playbackInfo.bufferedPositionUs = maskedBufferedPositionUs;\n }\n return playbackInfo;\n }\n\n @Nullable\n private Pair getPeriodPositionUsAfterTimelineChanged(\n Timeline oldTimeline, Timeline newTimeline) {\n long currentPositionMs = getContentPosition();\n if (oldTimeline.isEmpty() || newTimeline.isEmpty()) {\n boolean isCleared = !oldTimeline.isEmpty() && newTimeline.isEmpty();\n return maskWindowPositionMsOrGetPeriodPositionUs(\n newTimeline,\n isCleared ? C.INDEX_UNSET : getCurrentWindowIndexInternal(),\n isCleared ? C.TIME_UNSET : currentPositionMs);\n }\n int currentMediaItemIndex = getCurrentMediaItemIndex();\n @Nullable\n Pair oldPeriodPositionUs =\n oldTimeline.getPeriodPositionUs(\n window, period, currentMediaItemIndex, Util.msToUs(currentPositionMs));\n Object periodUid = castNonNull(oldPeriodPositionUs).first;\n if (newTimeline.getIndexOfPeriod(periodUid) != C.INDEX_UNSET) {\n // The old period position is still available in the new timeline.\n return oldPeriodPositionUs;\n }\n // Period uid not found in new timeline. Try to get subsequent period.\n @Nullable\n Object nextPeriodUid =\n ExoPlayerImplInternal.resolveSubsequentPeriod(\n window, period, repeatMode, shuffleModeEnabled, periodUid, oldTimeline, newTimeline);\n if (nextPeriodUid != null) {\n // Reset position to the default position of the window of the subsequent period.\n newTimeline.getPeriodByUid(nextPeriodUid, period);\n return maskWindowPositionMsOrGetPeriodPositionUs(\n newTimeline,\n period.windowIndex,\n newTimeline.getWindow(period.windowIndex, window).getDefaultPositionMs());\n } else {\n // No subsequent period found and the new timeline is not empty. Use the default position.\n return maskWindowPositionMsOrGetPeriodPositionUs(\n newTimeline, /* windowIndex= */ C.INDEX_UNSET, /* windowPositionMs= */ C.TIME_UNSET);\n }\n }\n\n @Nullable\n private Pair maskWindowPositionMsOrGetPeriodPositionUs(\n Timeline timeline, int windowIndex, long windowPositionMs) {\n if (timeline.isEmpty()) {\n // If empty we store the initial seek in the masking variables.\n maskingWindowIndex = windowIndex;\n maskingWindowPositionMs = windowPositionMs == C.TIME_UNSET ? 0 : windowPositionMs;\n maskingPeriodIndex = 0;\n return null;\n }\n if (windowIndex == C.INDEX_UNSET || windowIndex >= timeline.getWindowCount()) {\n // Use default position of timeline if window index still unset or if a previous initial seek\n // now turns out to be invalid.\n windowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled);\n windowPositionMs = timeline.getWindow(windowIndex, window).getDefaultPositionMs();\n }\n return timeline.getPeriodPositionUs(window, period, windowIndex, Util.msToUs(windowPositionMs));\n }\n\n private long periodPositionUsToWindowPositionUs(\n Timeline timeline, MediaPeriodId periodId, long positionUs) {\n timeline.getPeriodByUid(periodId.periodUid, period);\n positionUs += period.getPositionInWindowUs();\n return positionUs;\n }\n\n private PlayerMessage createMessageInternal(Target target) {\n int currentWindowIndex = getCurrentWindowIndexInternal();\n return new PlayerMessage(\n internalPlayer,\n target,\n playbackInfo.timeline,\n currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex,\n clock,\n internalPlayer.getPlaybackLooper());\n }\n\n /**\n * Builds a {@link MediaMetadata} from the main sources.\n *\n *

{@link MediaItem} {@link MediaMetadata} is prioritized, with any gaps/missing fields\n * populated by metadata from static ({@link TrackGroup} {@link Format}) and dynamic ({@link\n * #onMetadata(Metadata)}) sources.\n */\n private MediaMetadata buildUpdatedMediaMetadata() {\n Timeline timeline = getCurrentTimeline();\n if (timeline.isEmpty()) {\n return staticAndDynamicMediaMetadata;\n }\n MediaItem mediaItem = timeline.getWindow(getCurrentMediaItemIndex(), window).mediaItem;\n // MediaItem metadata is prioritized over metadata within the media.\n return staticAndDynamicMediaMetadata.buildUpon().populate(mediaItem.mediaMetadata).build();\n }\n\n private void removeSurfaceCallbacks() {\n if (sphericalGLSurfaceView != null) {\n createMessageInternal(frameMetadataListener)\n .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW)\n .setPayload(null)\n .send();\n sphericalGLSurfaceView.removeVideoSurfaceListener(componentListener);\n sphericalGLSurfaceView = null;\n }\n if (textureView != null) {\n if (textureView.getSurfaceTextureListener() != componentListener) {\n Log.w(TAG, \"SurfaceTextureListener already unset or replaced.\");\n } else {\n textureView.setSurfaceTextureListener(null);\n }\n textureView = null;\n }\n if (surfaceHolder != null) {\n surfaceHolder.removeCallback(componentListener);\n surfaceHolder = null;\n }\n }\n\n private void setSurfaceTextureInternal(SurfaceTexture surfaceTexture) {\n Surface surface = new Surface(surfaceTexture);\n setVideoOutputInternal(surface);\n ownedSurface = surface;\n }\n\n private void setVideoOutputInternal(@Nullable Object videoOutput) {\n // Note: We don't turn this method into a no-op if the output is being replaced with itself so\n // as to ensure onRenderedFirstFrame callbacks are still called in this case.\n List messages = new ArrayList<>();\n for (Renderer renderer : renderers) {\n if (renderer.getTrackType() == TRACK_TYPE_VIDEO) {\n messages.add(\n createMessageInternal(renderer)\n .setType(MSG_SET_VIDEO_OUTPUT)\n .setPayload(videoOutput)\n .send());\n }\n }\n boolean messageDeliveryTimedOut = false;\n if (this.videoOutput != null && this.videoOutput != videoOutput) {\n // We're replacing an output. Block to ensure that this output will not be accessed by the\n // renderers after this method returns.\n try {\n for (PlayerMessage message : messages) {\n message.blockUntilDelivered(detachSurfaceTimeoutMs);\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n } catch (TimeoutException e) {\n messageDeliveryTimedOut = true;\n }\n if (this.videoOutput == ownedSurface) {\n // We're replacing a surface that we are responsible for releasing.\n ownedSurface.release();\n ownedSurface = null;\n }\n }\n this.videoOutput = videoOutput;\n if (messageDeliveryTimedOut) {\n stop(\n /* reset= */ false,\n ExoPlaybackException.createForUnexpected(\n new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_DETACH_SURFACE),\n PlaybackException.ERROR_CODE_TIMEOUT));\n }\n }\n\n /**\n * Sets the holder of the surface that will be displayed to the user, but which should\n * not be the output for video renderers. This case occurs when video frames need to be\n * rendered to an intermediate surface (which is not the one held by the provided holder).\n *\n * @param nonVideoOutputSurfaceHolder The holder of the surface that will eventually be displayed\n * to the user.\n */\n private void setNonVideoOutputSurfaceHolderInternal(SurfaceHolder nonVideoOutputSurfaceHolder) {\n // Although we won't use the view's surface directly as the video output, still use the holder\n // to query the surface size, to be informed in changes to the size via componentListener, and\n // for equality checking in clearVideoSurfaceHolder.\n surfaceHolderSurfaceIsVideoOutput = false;\n surfaceHolder = nonVideoOutputSurfaceHolder;\n surfaceHolder.addCallback(componentListener);\n Surface surface = surfaceHolder.getSurface();\n if (surface != null && surface.isValid()) {\n Rect surfaceSize = surfaceHolder.getSurfaceFrame();\n maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height());\n } else {\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n }\n\n private void maybeNotifySurfaceSizeChanged(int width, int height) {\n if (width != surfaceWidth || height != surfaceHeight) {\n surfaceWidth = width;\n surfaceHeight = height;\n analyticsCollector.onSurfaceSizeChanged(width, height);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onSurfaceSizeChanged(width, height);\n }\n }\n }\n\n private void sendVolumeToRenderers() {\n float scaledVolume = volume * audioFocusManager.getVolumeMultiplier();\n sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_VOLUME, scaledVolume);\n }\n\n private void notifySkipSilenceEnabledChanged() {\n analyticsCollector.onSkipSilenceEnabledChanged(skipSilenceEnabled);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onSkipSilenceEnabledChanged(skipSilenceEnabled);\n }\n }\n\n private void updatePlayWhenReady(\n boolean playWhenReady,\n @AudioFocusManager.PlayerCommand int playerCommand,\n @Player.PlayWhenReadyChangeReason int playWhenReadyChangeReason) {\n playWhenReady = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY;\n @PlaybackSuppressionReason\n int playbackSuppressionReason =\n playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY\n ? Player.PLAYBACK_SUPPRESSION_REASON_TRANSIENT_AUDIO_FOCUS_LOSS\n : Player.PLAYBACK_SUPPRESSION_REASON_NONE;\n setPlayWhenReady(playWhenReady, playbackSuppressionReason, playWhenReadyChangeReason);\n }\n\n private void updateWakeAndWifiLock() {\n @State int playbackState = getPlaybackState();\n switch (playbackState) {\n case Player.STATE_READY:\n case Player.STATE_BUFFERING:\n boolean isSleeping = experimentalIsSleepingForOffload();\n wakeLockManager.setStayAwake(getPlayWhenReady() && !isSleeping);\n // The wifi lock is not released while sleeping to avoid interrupting downloads.\n wifiLockManager.setStayAwake(getPlayWhenReady());\n break;\n case Player.STATE_ENDED:\n case Player.STATE_IDLE:\n wakeLockManager.setStayAwake(false);\n wifiLockManager.setStayAwake(false);\n break;\n default:\n throw new IllegalStateException();\n }\n }\n\n private void verifyApplicationThread() {\n // The constructor may be executed on a background thread. Wait with accessing the player from\n // the app thread until the constructor finished executing.\n constructorFinished.blockUninterruptible();\n if (Thread.currentThread() != getApplicationLooper().getThread()) {\n String message =\n Util.formatInvariant(\n \"Player is accessed on the wrong thread.\\n\"\n + \"Current thread: '%s'\\n\"\n + \"Expected thread: '%s'\\n\"\n + \"See https://exoplayer.dev/issues/player-accessed-on-wrong-thread\",\n Thread.currentThread().getName(), getApplicationLooper().getThread().getName());\n if (throwsWhenUsingWrongThread) {\n throw new IllegalStateException(message);\n }\n Log.w(TAG, message, hasNotifiedFullWrongThreadWarning ? null : new IllegalStateException());\n hasNotifiedFullWrongThreadWarning = true;\n }\n }\n\n private void sendRendererMessage(\n @C.TrackType int trackType, int messageType, @Nullable Object payload) {\n for (Renderer renderer : renderers) {\n if (renderer.getTrackType() == trackType) {\n createMessageInternal(renderer).setType(messageType).setPayload(payload).send();\n }\n }\n }\n\n /**\n * Initializes {@link #keepSessionIdAudioTrack} to keep an audio session ID alive. If the audio\n * session ID is {@link C#AUDIO_SESSION_ID_UNSET} then a new audio session ID is generated.\n *\n *

Use of this method is only required on API level 21 and earlier.\n *\n * @param audioSessionId The audio session ID, or {@link C#AUDIO_SESSION_ID_UNSET} to generate a\n * new one.\n * @return The audio session ID.\n */\n private int initializeKeepSessionIdAudioTrack(int audioSessionId) {\n if (keepSessionIdAudioTrack != null\n && keepSessionIdAudioTrack.getAudioSessionId() != audioSessionId) {\n keepSessionIdAudioTrack.release();\n keepSessionIdAudioTrack = null;\n }\n if (keepSessionIdAudioTrack == null) {\n int sampleRate = 4000; // Minimum sample rate supported by the platform.\n int channelConfig = AudioFormat.CHANNEL_OUT_MONO;\n @C.PcmEncoding int encoding = C.ENCODING_PCM_16BIT;\n int bufferSize = 2; // Use a two byte buffer, as it is not actually used for playback.\n keepSessionIdAudioTrack =\n new AudioTrack(\n C.STREAM_TYPE_DEFAULT,\n sampleRate,\n channelConfig,\n encoding,\n bufferSize,\n AudioTrack.MODE_STATIC,\n audioSessionId);\n }\n return keepSessionIdAudioTrack.getAudioSessionId();\n }\n\n private static DeviceInfo createDeviceInfo(StreamVolumeManager streamVolumeManager) {\n return new DeviceInfo(\n DeviceInfo.PLAYBACK_TYPE_LOCAL,\n streamVolumeManager.getMinVolume(),\n streamVolumeManager.getMaxVolume());\n }\n\n private static int getPlayWhenReadyChangeReason(boolean playWhenReady, int playerCommand) {\n return playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY\n ? PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS\n : PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;\n }\n\n private static boolean isPlaying(PlaybackInfo playbackInfo) {\n return playbackInfo.playbackState == Player.STATE_READY\n && playbackInfo.playWhenReady\n && playbackInfo.playbackSuppressionReason == PLAYBACK_SUPPRESSION_REASON_NONE;\n }\n\n private static final class MediaSourceHolderSnapshot implements MediaSourceInfoHolder {\n\n private final Object uid;\n\n private Timeline timeline;\n\n public MediaSourceHolderSnapshot(Object uid, Timeline timeline) {\n this.uid = uid;\n this.timeline = timeline;\n }\n\n @Override\n public Object getUid() {\n return uid;\n }\n\n @Override\n public Timeline getTimeline() {\n return timeline;\n }\n }\n\n private final class ComponentListener\n implements Player.Listener,\n VideoRendererEventListener,\n AudioRendererEventListener,\n TextOutput,\n MetadataOutput,\n SurfaceHolder.Callback,\n TextureView.SurfaceTextureListener,\n SphericalGLSurfaceView.VideoSurfaceListener,\n AudioFocusManager.PlayerControl,\n AudioBecomingNoisyManager.EventListener,\n StreamVolumeManager.Listener,\n AudioOffloadListener {\n\n // VideoRendererEventListener implementation\n\n @Override\n public void onVideoEnabled(DecoderCounters counters) {\n videoDecoderCounters = counters;\n analyticsCollector.onVideoEnabled(counters);\n }\n\n @Override\n public void onVideoDecoderInitialized(\n String decoderName, long initializedTimestampMs, long initializationDurationMs) {\n analyticsCollector.onVideoDecoderInitialized(\n decoderName, initializedTimestampMs, initializationDurationMs);\n }\n\n @Override\n public void onVideoInputFormatChanged(\n Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) {\n videoFormat = format;\n analyticsCollector.onVideoInputFormatChanged(format, decoderReuseEvaluation);\n }\n\n @Override\n public void onDroppedFrames(int count, long elapsed) {\n analyticsCollector.onDroppedFrames(count, elapsed);\n }\n\n @Override\n public void onVideoSizeChanged(VideoSize videoSize) {\n ExoPlayerImpl.this.videoSize = videoSize;\n analyticsCollector.onVideoSizeChanged(videoSize);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onVideoSizeChanged(videoSize);\n }\n }\n\n @Override\n public void onRenderedFirstFrame(Object output, long renderTimeMs) {\n analyticsCollector.onRenderedFirstFrame(output, renderTimeMs);\n if (videoOutput == output) {\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onRenderedFirstFrame();\n }\n }\n }\n\n @Override\n public void onVideoDecoderReleased(String decoderName) {\n analyticsCollector.onVideoDecoderReleased(decoderName);\n }\n\n @Override\n public void onVideoDisabled(DecoderCounters counters) {\n analyticsCollector.onVideoDisabled(counters);\n videoFormat = null;\n videoDecoderCounters = null;\n }\n\n @Override\n public void onVideoFrameProcessingOffset(long totalProcessingOffsetUs, int frameCount) {\n analyticsCollector.onVideoFrameProcessingOffset(totalProcessingOffsetUs, frameCount);\n }\n\n @Override\n public void onVideoCodecError(Exception videoCodecError) {\n analyticsCollector.onVideoCodecError(videoCodecError);\n }\n\n // AudioRendererEventListener implementation\n\n @Override\n public void onAudioEnabled(DecoderCounters counters) {\n audioDecoderCounters = counters;\n analyticsCollector.onAudioEnabled(counters);\n }\n\n @Override\n public void onAudioDecoderInitialized(\n String decoderName, long initializedTimestampMs, long initializationDurationMs) {\n analyticsCollector.onAudioDecoderInitialized(\n decoderName, initializedTimestampMs, initializationDurationMs);\n }\n\n @Override\n public void onAudioInputFormatChanged(\n Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) {\n audioFormat = format;\n analyticsCollector.onAudioInputFormatChanged(format, decoderReuseEvaluation);\n }\n\n @Override\n public void onAudioPositionAdvancing(long playoutStartSystemTimeMs) {\n analyticsCollector.onAudioPositionAdvancing(playoutStartSystemTimeMs);\n }\n\n @Override\n public void onAudioUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) {\n analyticsCollector.onAudioUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs);\n }\n\n @Override\n public void onAudioDecoderReleased(String decoderName) {\n analyticsCollector.onAudioDecoderReleased(decoderName);\n }\n\n @Override\n public void onAudioDisabled(DecoderCounters counters) {\n analyticsCollector.onAudioDisabled(counters);\n audioFormat = null;\n audioDecoderCounters = null;\n }\n\n @Override\n public void onSkipSilenceEnabledChanged(boolean skipSilenceEnabled) {\n if (ExoPlayerImpl.this.skipSilenceEnabled == skipSilenceEnabled) {\n return;\n }\n ExoPlayerImpl.this.skipSilenceEnabled = skipSilenceEnabled;\n notifySkipSilenceEnabledChanged();\n }\n\n @Override\n public void onAudioSinkError(Exception audioSinkError) {\n analyticsCollector.onAudioSinkError(audioSinkError);\n }\n\n @Override\n public void onAudioCodecError(Exception audioCodecError) {\n analyticsCollector.onAudioCodecError(audioCodecError);\n }\n\n // TextOutput implementation\n\n @Override\n public void onCues(List cues) {\n currentCues = cues;\n analyticsCollector.onCues(cues);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listeners : listenerArraySet) {\n listeners.onCues(cues);\n }\n }\n\n // MetadataOutput implementation\n\n @Override\n public void onMetadata(Metadata metadata) {\n analyticsCollector.onMetadata(metadata);\n ExoPlayerImpl.this.onMetadata(metadata);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onMetadata(metadata);\n }\n }\n\n // SurfaceHolder.Callback implementation\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n if (surfaceHolderSurfaceIsVideoOutput) {\n setVideoOutputInternal(holder.getSurface());\n }\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n maybeNotifySurfaceSizeChanged(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n if (surfaceHolderSurfaceIsVideoOutput) {\n setVideoOutputInternal(/* videoOutput= */ null);\n }\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n }\n\n // TextureView.SurfaceTextureListener implementation\n\n @Override\n public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {\n setSurfaceTextureInternal(surfaceTexture);\n maybeNotifySurfaceSizeChanged(width, height);\n }\n\n @Override\n public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {\n maybeNotifySurfaceSizeChanged(width, height);\n }\n\n @Override\n public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {\n setVideoOutputInternal(/* videoOutput= */ null);\n maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0);\n return true;\n }\n\n @Override\n public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {\n // Do nothing.\n }\n\n // SphericalGLSurfaceView.VideoSurfaceListener\n\n @Override\n public void onVideoSurfaceCreated(Surface surface) {\n setVideoOutputInternal(surface);\n }\n\n @Override\n public void onVideoSurfaceDestroyed(Surface surface) {\n setVideoOutputInternal(/* videoOutput= */ null);\n }\n\n // AudioFocusManager.PlayerControl implementation\n\n @Override\n public void setVolumeMultiplier(float volumeMultiplier) {\n sendVolumeToRenderers();\n }\n\n @Override\n public void executePlayerCommand(@AudioFocusManager.PlayerCommand int playerCommand) {\n boolean playWhenReady = getPlayWhenReady();\n updatePlayWhenReady(\n playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand));\n }\n\n // AudioBecomingNoisyManager.EventListener implementation.\n\n @Override\n public void onAudioBecomingNoisy() {\n updatePlayWhenReady(\n /* playWhenReady= */ false,\n AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY,\n Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY);\n }\n\n // StreamVolumeManager.Listener implementation.\n\n @Override\n public void onStreamTypeChanged(@C.StreamType int streamType) {\n DeviceInfo deviceInfo = createDeviceInfo(streamVolumeManager);\n if (!deviceInfo.equals(ExoPlayerImpl.this.deviceInfo)) {\n ExoPlayerImpl.this.deviceInfo = deviceInfo;\n analyticsCollector.onDeviceInfoChanged(deviceInfo);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onDeviceInfoChanged(deviceInfo);\n }\n }\n }\n\n @Override\n public void onStreamVolumeChanged(int streamVolume, boolean streamMuted) {\n analyticsCollector.onDeviceVolumeChanged(streamVolume, streamMuted);\n // TODO(internal b/187152483): Events should be dispatched via ListenerSet\n for (Listener listener : listenerArraySet) {\n listener.onDeviceVolumeChanged(streamVolume, streamMuted);\n }\n }\n\n // Player.Listener implementation.\n\n @Override\n public void onIsLoadingChanged(boolean isLoading) {\n if (priorityTaskManager != null) {\n if (isLoading && !isPriorityTaskManagerRegistered) {\n priorityTaskManager.add(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = true;\n } else if (!isLoading && isPriorityTaskManagerRegistered) {\n priorityTaskManager.remove(C.PRIORITY_PLAYBACK);\n isPriorityTaskManagerRegistered = false;\n }\n }\n }\n\n @Override\n public void onPlaybackStateChanged(@State int playbackState) {\n updateWakeAndWifiLock();\n }\n\n @Override\n public void onPlayWhenReadyChanged(\n boolean playWhenReady, @PlayWhenReadyChangeReason int reason) {\n updateWakeAndWifiLock();\n }\n\n // Player.AudioOffloadListener implementation.\n\n @Override\n public void onExperimentalSleepingForOffloadChanged(boolean sleepingForOffload) {\n updateWakeAndWifiLock();\n }\n }\n\n /** Listeners that are called on the playback thread. */\n private static final class FrameMetadataListener\n implements VideoFrameMetadataListener, CameraMotionListener, PlayerMessage.Target {\n\n public static final @MessageType int MSG_SET_VIDEO_FRAME_METADATA_LISTENER =\n Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER;\n\n public static final @MessageType int MSG_SET_CAMERA_MOTION_LISTENER =\n Renderer.MSG_SET_CAMERA_MOTION_LISTENER;\n\n public static final @MessageType int MSG_SET_SPHERICAL_SURFACE_VIEW = Renderer.MSG_CUSTOM_BASE;\n\n @Nullable private VideoFrameMetadataListener videoFrameMetadataListener;\n @Nullable private CameraMotionListener cameraMotionListener;\n @Nullable private VideoFrameMetadataListener internalVideoFrameMetadataListener;\n @Nullable private CameraMotionListener internalCameraMotionListener;\n\n @Override\n public void handleMessage(@MessageType int messageType, @Nullable Object message) {\n switch (messageType) {\n case MSG_SET_VIDEO_FRAME_METADATA_LISTENER:\n videoFrameMetadataListener = (VideoFrameMetadataListener) message;\n break;\n case MSG_SET_CAMERA_MOTION_LISTENER:\n cameraMotionListener = (CameraMotionListener) message;\n break;\n case MSG_SET_SPHERICAL_SURFACE_VIEW:\n @Nullable SphericalGLSurfaceView surfaceView = (SphericalGLSurfaceView) message;\n if (surfaceView == null) {\n internalVideoFrameMetadataListener = null;\n internalCameraMotionListener = null;\n } else {\n internalVideoFrameMetadataListener = surfaceView.getVideoFrameMetadataListener();\n internalCameraMotionListener = surfaceView.getCameraMotionListener();\n }\n break;\n case Renderer.MSG_SET_AUDIO_ATTRIBUTES:\n case Renderer.MSG_SET_AUDIO_SESSION_ID:\n case Renderer.MSG_SET_AUX_EFFECT_INFO:\n case Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY:\n case Renderer.MSG_SET_SCALING_MODE:\n case Renderer.MSG_SET_SKIP_SILENCE_ENABLED:\n case Renderer.MSG_SET_VIDEO_OUTPUT:\n case Renderer.MSG_SET_VOLUME:\n case Renderer.MSG_SET_WAKEUP_LISTENER:\n default:\n break;\n }\n }\n\n // VideoFrameMetadataListener\n\n @Override\n public void onVideoFrameAboutToBeRendered(\n long presentationTimeUs,\n long releaseTimeNs,\n Format format,\n @Nullable MediaFormat mediaFormat) {\n if (internalVideoFrameMetadataListener != null) {\n internalVideoFrameMetadataListener.onVideoFrameAboutToBeRendered(\n presentationTimeUs, releaseTimeNs, format, mediaFormat);\n }\n if (videoFrameMetadataListener != null) {\n videoFrameMetadataListener.onVideoFrameAboutToBeRendered(\n presentationTimeUs, releaseTimeNs, format, mediaFormat);\n }\n }\n\n // CameraMotionListener\n\n @Override\n public void onCameraMotion(long timeUs, float[] rotation) {\n if (internalCameraMotionListener != null) {\n internalCameraMotionListener.onCameraMotion(timeUs, rotation);\n }\n if (cameraMotionListener != null) {\n cameraMotionListener.onCameraMotion(timeUs, rotation);\n }\n }\n\n @Override\n public void onCameraMotionReset() {\n if (internalCameraMotionListener != null) {\n internalCameraMotionListener.onCameraMotionReset();\n }\n if (cameraMotionListener != null) {\n cameraMotionListener.onCameraMotionReset();\n }\n }\n }\n\n @RequiresApi(31)\n private static final class Api31 {\n private Api31() {}\n\n @DoNotInline\n public static PlayerId createPlayerId() {\n // TODO: Create a MediaMetricsListener and obtain LogSessionId from it.\n return new PlayerId(LogSessionId.LOG_SESSION_ID_NONE);\n }\n }\n}\n"},"message":{"kind":"string","value":"Remove self-listening from ExoPlayerImpl\n\nSimpleExoPlayer used to register a listener on ExoPlayerImpl for\nthe old EventListener callbacks. Now both classes are merged, this is\nno longer needed and should be removed in favor of calling methods\ndirectly.\n\n#minor-release\n\nPiperOrigin-RevId: 427187875\n"},"old_file":{"kind":"string","value":"libraries/exoplayer/src/main/java/androidx/media3/exoplayer/ExoPlayerImpl.java"},"subject":{"kind":"string","value":"Remove self-listening from ExoPlayerImpl"}}},{"rowIdx":1287,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"918c251891109e8877f569f1ef23d437d6bb30d0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"scholzj/barnabas,scholzj/barnabas,ppatierno/kaas,ppatierno/kaas"},"new_contents":{"kind":"string","value":"/*\n * Copyright Strimzi authors.\n * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).\n */\npackage io.strimzi.operator.common;\n\nimport io.fabric8.kubernetes.api.model.LabelSelector;\nimport io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding;\nimport io.fabric8.kubernetes.client.CustomResource;\nimport io.fabric8.kubernetes.client.Watch;\nimport io.fabric8.kubernetes.client.WatcherException;\nimport io.micrometer.core.instrument.Counter;\nimport io.micrometer.core.instrument.Tag;\nimport io.micrometer.core.instrument.Tags;\nimport io.micrometer.core.instrument.Timer;\nimport io.micrometer.core.instrument.Meter;\nimport io.strimzi.api.kafka.model.Spec;\nimport io.strimzi.api.kafka.model.status.Condition;\nimport io.strimzi.api.kafka.model.status.ConditionBuilder;\nimport io.strimzi.api.kafka.model.status.Status;\nimport io.strimzi.operator.cluster.model.InvalidResourceException;\nimport io.strimzi.operator.cluster.model.StatusDiff;\nimport io.strimzi.operator.common.model.Labels;\nimport io.strimzi.operator.common.model.NamespaceAndName;\nimport io.strimzi.operator.common.model.ResourceVisitor;\nimport io.strimzi.operator.common.model.ValidationVisitor;\nimport io.strimzi.operator.common.operator.resource.AbstractWatchableStatusedResourceOperator;\nimport io.strimzi.operator.common.operator.resource.ReconcileResult;\nimport io.strimzi.operator.common.operator.resource.StatusUtils;\nimport io.strimzi.operator.common.operator.resource.TimeoutException;\nimport io.vertx.core.AsyncResult;\nimport io.vertx.core.Future;\nimport io.vertx.core.Promise;\nimport io.vertx.core.Vertx;\nimport io.vertx.core.shareddata.Lock;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.Collections;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n\nimport static io.strimzi.operator.common.Util.async;\n\n/**\n * A base implementation of {@link Operator}.\n *\n *

    \n *
  • uses the Fabric8 kubernetes API and implements\n * {@link #reconcile(Reconciliation)} by delegating to abstract {@link #createOrUpdate(Reconciliation, CustomResource)}\n * and {@link #delete(Reconciliation)} methods for subclasses to implement.\n * \n *
  • add support for operator-side {@linkplain #validate(CustomResource) validation}.\n * This can be used to automatically log warnings about source resources which used deprecated part of the CR API.\n *ą\n *
\n * @param The Java representation of the Kubernetes resource, e.g. {@code Kafka} or {@code KafkaConnect}\n * @param The \"Resource Operator\" for the source resource type. Typically this will be some instantiation of\n * {@link io.strimzi.operator.common.operator.resource.CrdOperator}.\n */\npublic abstract class AbstractOperator<\n T extends CustomResource,\n P extends Spec,\n S extends Status,\n O extends AbstractWatchableStatusedResourceOperator>\n implements Operator {\n\n private static final Logger log = LogManager.getLogger(AbstractOperator.class);\n\n private static final long PROGRESS_WARNING = 60_000L;\n protected static final int LOCK_TIMEOUT_MS = 10000;\n public static final String METRICS_PREFIX = \"strimzi.\";\n\n protected final Vertx vertx;\n protected final O resourceOperator;\n private final String kind;\n\n private final Optional selector;\n\n protected final MetricsProvider metrics;\n private final Counter periodicReconciliationsCounter;\n private final Counter reconciliationsCounter;\n private final Counter failedReconciliationsCounter;\n private final Counter successfulReconciliationsCounter;\n private final Counter lockedReconciliationsCounter;\n private final AtomicInteger pausedResourceCounter;\n private final AtomicInteger resourceCounter;\n private final Timer reconciliationsTimer;\n private final Map resourcesStateCounter;\n\n public AbstractOperator(Vertx vertx, String kind, O resourceOperator, MetricsProvider metrics, Labels selectorLabels) {\n this.vertx = vertx;\n this.kind = kind;\n this.resourceOperator = resourceOperator;\n this.selector = (selectorLabels == null || selectorLabels.toMap().isEmpty()) ? Optional.empty() : Optional.of(new LabelSelector(null, selectorLabels.toMap()));\n this.metrics = metrics;\n\n // Setup metrics\n Tags metricTags = Tags.of(Tag.of(\"kind\", kind()));\n\n periodicReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.periodical\",\n \"Number of periodical reconciliations done by the operator\",\n metricTags);\n\n reconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations\",\n \"Number of reconciliations done by the operator for individual resources\",\n metricTags);\n\n pausedResourceCounter = metrics.gauge(METRICS_PREFIX + \"resources.paused\",\n \"Number of custom resources the operator sees but does not reconcile due to paused reconciliations\",\n metricTags);\n\n failedReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.failed\",\n \"Number of reconciliations done by the operator for individual resources which failed\",\n metricTags);\n\n successfulReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.successful\",\n \"Number of reconciliations done by the operator for individual resources which were successful\",\n metricTags);\n\n lockedReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.locked\",\n \"Number of reconciliations skipped because another reconciliation for the same resource was still running\",\n metricTags);\n\n resourceCounter = metrics.gauge(METRICS_PREFIX + \"resources\",\n \"Number of custom resources the operator sees\",\n metricTags);\n\n reconciliationsTimer = metrics.timer(METRICS_PREFIX + \"reconciliations.duration\",\n \"The time the reconciliation takes to complete\",\n metricTags);\n\n resourcesStateCounter = new ConcurrentHashMap<>();\n }\n\n @Override\n public String kind() {\n return kind;\n }\n\n /**\n * Gets the name of the lock to be used for operating on the given {@code namespace} and\n * cluster {@code name}\n *\n * @param namespace The namespace containing the cluster\n * @param name The name of the cluster\n */\n private String getLockName(String namespace, String name) {\n return \"lock::\" + namespace + \"::\" + kind() + \"::\" + name;\n }\n\n /**\n * Asynchronously creates or updates the given {@code resource}.\n * This method can be called when the given {@code resource} has been created,\n * or updated and also at some regular interval while the resource continues to exist in Kubernetes.\n * The calling of this method does not imply that anything has actually changed.\n * @param reconciliation Uniquely identifies the reconciliation itself.\n * @param resource The resource to be created, or updated.\n * @return A Future which is completed once the reconciliation of the given resource instance is complete.\n */\n protected abstract Future createOrUpdate(Reconciliation reconciliation, T resource);\n\n /**\n * Asynchronously deletes the resource identified by {@code reconciliation}.\n * Operators which only create other Kubernetes resources in order to honour their source resource can rely\n * on Kubernetes Garbage Collection to handle deletion.\n * Such operators should return a Future which completes with {@code false}.\n * Operators which handle deletion themselves should return a Future which completes with {@code true}.\n * @param reconciliation\n * @return\n */\n protected abstract Future delete(Reconciliation reconciliation);\n\n /**\n * Reconcile assembly resources in the given namespace having the given {@code name}.\n * Reconciliation works by getting the assembly resource (e.g. {@code KafkaUser})\n * in the given namespace with the given name and\n * comparing with the corresponding resource.\n * @param reconciliation The reconciliation.\n * @return A Future which is completed with the result of the reconciliation.\n */\n @Override\n @SuppressWarnings(\"unchecked\")\n public final Future reconcile(Reconciliation reconciliation) {\n String namespace = reconciliation.namespace();\n String name = reconciliation.name();\n\n reconciliationsCounter.increment();\n Timer.Sample reconciliationTimerSample = Timer.start(metrics.meterRegistry());\n\n Future handler = withLock(reconciliation, LOCK_TIMEOUT_MS, () -> {\n T cr = resourceOperator.get(namespace, name);\n\n if (cr != null) {\n if (!Util.matchesSelector(selector(), cr)) {\n // When the labels matching the selector are removed from the custom resource, a DELETE event is\n // triggered by the watch even through the custom resource might not match the watch labels anymore\n // and might not be really deleted. We have to filter these situations out and ignore the\n // reconciliation because such resource might be already operated by another instance (where the\n // same change triggered ADDED event).\n log.debug(\"{}: {} {} in namespace {} does not match label selector {} and will be ignored\", reconciliation, kind(), name, namespace, selector().get().getMatchLabels());\n return Future.succeededFuture();\n }\n\n Promise createOrUpdate = Promise.promise();\n if (Annotations.isReconciliationPausedWithAnnotation(cr)) {\n S status = createStatus();\n Set conditions = validate(cr);\n conditions.add(StatusUtils.getPausedCondition());\n status.setConditions(new ArrayList<>(conditions));\n status.setObservedGeneration(cr.getStatus() != null ? cr.getStatus().getObservedGeneration() : 0);\n\n updateStatus(reconciliation, status).onComplete(statusResult -> {\n if (statusResult.succeeded()) {\n createOrUpdate.complete();\n } else {\n createOrUpdate.fail(statusResult.cause());\n }\n });\n getPausedResourceCounter().getAndIncrement();\n log.debug(\"{}: Reconciliation of {} {} is paused\", reconciliation, kind, name);\n return createOrUpdate.future();\n } else if (cr.getSpec() == null) {\n InvalidResourceException exception = new InvalidResourceException(\"Spec cannot be null\");\n\n S status = createStatus();\n Condition errorCondition = new ConditionBuilder()\n .withLastTransitionTime(StatusUtils.iso8601Now())\n .withType(\"NotReady\")\n .withStatus(\"True\")\n .withReason(exception.getClass().getSimpleName())\n .withMessage(exception.getMessage())\n .build();\n status.setObservedGeneration(cr.getMetadata().getGeneration());\n status.addCondition(errorCondition);\n\n log.error(\"{}: {} spec cannot be null\", reconciliation, cr.getMetadata().getName());\n updateStatus(reconciliation, status).onComplete(notUsed -> {\n createOrUpdate.fail(exception);\n });\n\n return createOrUpdate.future();\n }\n\n Set unknownAndDeprecatedConditions = validate(cr);\n\n log.info(\"{}: {} {} will be checked for creation or modification\", reconciliation, kind, name);\n\n createOrUpdate(reconciliation, cr)\n .onComplete(res -> {\n if (res.succeeded()) {\n S status = res.result();\n\n addWarningsToStatus(status, unknownAndDeprecatedConditions);\n updateStatus(reconciliation, status).onComplete(statusResult -> {\n if (statusResult.succeeded()) {\n createOrUpdate.complete();\n } else {\n createOrUpdate.fail(statusResult.cause());\n }\n });\n } else {\n if (res.cause() instanceof ReconciliationException) {\n ReconciliationException e = (ReconciliationException) res.cause();\n Status status = e.getStatus();\n addWarningsToStatus(status, unknownAndDeprecatedConditions);\n\n log.error(\"{}: createOrUpdate failed\", reconciliation, e.getCause());\n\n updateStatus(reconciliation, (S) status).onComplete(statusResult -> {\n createOrUpdate.fail(e.getCause());\n });\n } else {\n log.error(\"{}: createOrUpdate failed\", reconciliation, res.cause());\n createOrUpdate.fail(res.cause());\n }\n }\n });\n\n return createOrUpdate.future();\n } else {\n log.info(\"{}: {} {} should be deleted\", reconciliation, kind, name);\n return delete(reconciliation).map(deleteResult -> {\n if (deleteResult) {\n log.info(\"{}: {} {} deleted\", reconciliation, kind, name);\n } else {\n log.info(\"{}: Assembly {} or some parts of it will be deleted by garbage collection\", reconciliation, name);\n }\n return (Void) null;\n }).recover(deleteResult -> {\n log.error(\"{}: Deletion of {} {} failed\", reconciliation, kind, name, deleteResult);\n return Future.failedFuture(deleteResult);\n });\n }\n });\n\n Promise result = Promise.promise();\n handler.onComplete(reconcileResult -> {\n handleResult(reconciliation, reconcileResult, reconciliationTimerSample);\n result.handle(reconcileResult);\n });\n\n return result.future();\n }\n\n protected void addWarningsToStatus(Status status, Set unknownAndDeprecatedConditions) {\n if (status != null) {\n status.addConditions(unknownAndDeprecatedConditions);\n }\n }\n\n /**\n * Updates the Status field of the Kafka CR. It diffs the desired status against the current status and calls\n * the update only when there is any difference in non-timestamp fields.\n *\n * @param reconciliation the reconciliation identified\n * @param desiredStatus The KafkaStatus which should be set\n *\n * @return\n */\n Future updateStatus(Reconciliation reconciliation, S desiredStatus) {\n if (desiredStatus == null) {\n log.debug(\"{}: Desired status is null - status will not be updated\", reconciliation);\n return Future.succeededFuture();\n }\n\n String namespace = reconciliation.namespace();\n String name = reconciliation.name();\n\n return resourceOperator.getAsync(namespace, name)\n .compose(res -> {\n if (res != null) {\n S currentStatus = res.getStatus();\n StatusDiff sDiff = new StatusDiff(currentStatus, desiredStatus);\n\n if (!sDiff.isEmpty()) {\n res.setStatus(desiredStatus);\n\n return resourceOperator.updateStatusAsync(res)\n .compose(notUsed -> {\n log.debug(\"{}: Completed status update\", reconciliation);\n return Future.succeededFuture();\n }, error -> {\n log.error(\"{}: Failed to update status\", reconciliation, error);\n return Future.failedFuture(error);\n });\n } else {\n log.debug(\"{}: Status did not change\", reconciliation);\n return Future.succeededFuture();\n }\n } else {\n log.error(\"{}: Current {} resource not found\", reconciliation, reconciliation.kind());\n return Future.failedFuture(\"Current \" + reconciliation.kind() + \" resource with name \" + name + \" not found\");\n }\n }, error -> {\n log.error(\"{}: Failed to get the current {} resource and its status\", reconciliation, reconciliation.kind(), error);\n return Future.failedFuture(error);\n });\n }\n\n protected abstract S createStatus();\n\n /**\n * The exception by which Futures returned by {@link #withLock(Reconciliation, long, Callable)} are failed when\n * the lock cannot be acquired within the timeout.\n */\n static class UnableToAcquireLockException extends TimeoutException { }\n\n /**\n * Acquire the lock for the resource implied by the {@code reconciliation}\n * and call the given {@code callable} with the lock held.\n * Once the callable returns (or if it throws) release the lock and complete the returned Future.\n * If the lock cannot be acquired the given {@code callable} is not called and the returned Future is completed with {@link UnableToAcquireLockException}.\n * @param reconciliation\n * @param callable\n * @param \n * @return\n */\n protected final Future withLock(Reconciliation reconciliation, long lockTimeoutMs, Callable> callable) {\n Promise handler = Promise.promise();\n String namespace = reconciliation.namespace();\n String name = reconciliation.name();\n final String lockName = getLockName(namespace, name);\n log.debug(\"{}: Try to acquire lock {}\", reconciliation, lockName);\n vertx.sharedData().getLockWithTimeout(lockName, lockTimeoutMs, res -> {\n if (res.succeeded()) {\n log.debug(\"{}: Lock {} acquired\", reconciliation, lockName);\n\n Lock lock = res.result();\n long timerId = vertx.setPeriodic(PROGRESS_WARNING, timer -> {\n log.info(\"{}: Reconciliation is in progress\", reconciliation);\n });\n\n try {\n callable.call().onComplete(callableRes -> {\n if (callableRes.succeeded()) {\n handler.complete(callableRes.result());\n } else {\n handler.fail(callableRes.cause());\n }\n\n vertx.cancelTimer(timerId);\n lock.release();\n log.debug(\"{}: Lock {} released\", reconciliation, lockName);\n });\n } catch (Throwable ex) {\n vertx.cancelTimer(timerId);\n lock.release();\n log.debug(\"{}: Lock {} released\", reconciliation, lockName);\n log.error(\"{}: Reconciliation failed\", reconciliation, ex);\n handler.fail(ex);\n }\n } else {\n log.debug(\"{}: Failed to acquire lock {} within {}ms.\", reconciliation, lockName, lockTimeoutMs);\n handler.fail(new UnableToAcquireLockException());\n }\n });\n return handler.future();\n }\n\n /**\n * Validate the Custom Resource.\n * This should log at the WARN level (rather than throwing)\n * if the resource can safely be reconciled (e.g. it merely using deprecated API).\n * @param resource The custom resource\n * @throws InvalidResourceException if the resource cannot be safely reconciled.\n * @return set of conditions\n */\n /*test*/ public Set validate(T resource) {\n if (resource != null) {\n Set warningConditions = new LinkedHashSet<>(0);\n\n ResourceVisitor.visit(resource, new ValidationVisitor(resource, log, warningConditions));\n\n return warningConditions;\n }\n\n return Collections.emptySet();\n }\n\n public Future> allResourceNames(String namespace) {\n return resourceOperator.listAsync(namespace, selector())\n .map(resourceList ->\n resourceList.stream()\n .map(resource -> new NamespaceAndName(resource.getMetadata().getNamespace(), resource.getMetadata().getName()))\n .collect(Collectors.toSet()));\n }\n\n /**\n * A selector to narrow the scope of the {@linkplain #createWatch(String, Consumer) watch}\n * and {@linkplain #allResourceNames(String) query}.\n * @return A selector.\n */\n public Optional selector() {\n return selector;\n }\n\n /**\n * Create Kubernetes watch.\n *\n * @param namespace Namespace where to watch for users.\n * @param onClose Callback called when the watch is closed.\n *\n * @return A future which completes when the watcher has been created.\n */\n public Future createWatch(String namespace, Consumer onClose) {\n return async(vertx, () -> resourceOperator.watch(namespace, selector(), new OperatorWatcher<>(this, namespace, onClose)));\n }\n\n public Consumer recreateWatch(String namespace) {\n Consumer kubernetesClientExceptionConsumer = new Consumer() {\n @Override\n public void accept(WatcherException e) {\n if (e != null) {\n log.error(\"Watcher closed with exception in namespace {}\", namespace, e);\n createWatch(namespace, this);\n } else {\n log.info(\"Watcher closed in namespace {}\", namespace);\n }\n }\n };\n return kubernetesClientExceptionConsumer;\n }\n\n /**\n * Log the reconciliation outcome.\n */\n private void handleResult(Reconciliation reconciliation, AsyncResult result, Timer.Sample reconciliationTimerSample) {\n if (result.succeeded()) {\n updateResourceState(reconciliation, true);\n successfulReconciliationsCounter.increment();\n reconciliationTimerSample.stop(reconciliationsTimer);\n log.info(\"{}: reconciled\", reconciliation);\n } else {\n Throwable cause = result.cause();\n\n if (cause instanceof InvalidConfigParameterException) {\n updateResourceState(reconciliation, false);\n failedReconciliationsCounter.increment();\n reconciliationTimerSample.stop(reconciliationsTimer);\n log.warn(\"{}: Failed to reconcile {}\", reconciliation, cause.getMessage());\n } else if (cause instanceof UnableToAcquireLockException) {\n lockedReconciliationsCounter.increment();\n } else {\n updateResourceState(reconciliation, false);\n failedReconciliationsCounter.increment();\n reconciliationTimerSample.stop(reconciliationsTimer);\n log.warn(\"{}: Failed to reconcile\", reconciliation, cause);\n }\n }\n }\n\n public Counter getPeriodicReconciliationsCounter() {\n return periodicReconciliationsCounter;\n }\n\n public AtomicInteger getResourceCounter() {\n return resourceCounter;\n }\n\n public AtomicInteger getPausedResourceCounter() {\n return pausedResourceCounter;\n }\n\n /**\n * Updates the resource state metric for the provided reconciliation which brings kind, name and namespace\n * of the custom resource.\n *\n * @param reconciliation reconciliation to use to update the resource state metric\n * @param ready if reconcile was successful and the resource is ready\n */\n private void updateResourceState(Reconciliation reconciliation, boolean ready) {\n Tags metricTags = Tags.of(\n Tag.of(\"kind\", reconciliation.kind()),\n Tag.of(\"name\", reconciliation.name()),\n Tag.of(\"resource-namespace\", reconciliation.namespace()));\n\n T cr = resourceOperator.get(reconciliation.namespace(), reconciliation.name());\n if (cr != null) {\n resourcesStateCounter.computeIfAbsent(metricTags, tags ->\n metrics.gauge(METRICS_PREFIX + \"resource.state\", \"Current state of the resource: 1 ready, 0 fail\", tags)\n );\n resourcesStateCounter.get(metricTags).set(ready ? 1 : 0);\n log.debug(\"{}: Updated metric \" + METRICS_PREFIX + \"resource.state{} = {}\", reconciliation, metricTags, ready ? 1 : 0);\n } else {\n Optional gauge = metrics.meterRegistry().getMeters()\n .stream()\n .filter(meter -> meter.getId().getName().equals(METRICS_PREFIX + \"resource.state\") &&\n meter.getId().getTags().equals(metricTags.stream().collect(Collectors.toList()))\n ).findFirst();\n\n if (gauge.isPresent()) {\n metrics.meterRegistry().remove(gauge.get().getId());\n resourcesStateCounter.remove(metricTags);\n log.debug(\"{}: Removed metric \" + METRICS_PREFIX + \"resource.state{}\", reconciliation, metricTags);\n }\n }\n }\n\n /**\n * In some cases, when the ClusterRoleBinding reconciliation fails with RBAC error and the desired object is null,\n * we want to ignore the error and return success. This is used to let Strimzi work without some Cluster-wide RBAC\n * rights when the features they are needed for are not used by the user.\n *\n * @param reconcileFuture The original reconciliation future\n * @param desired The desired state of the resource.\n * @return A future which completes when the resource was reconciled.\n */\n public Future> withIgnoreRbacError(Future> reconcileFuture, ClusterRoleBinding desired) {\n return reconcileFuture.compose(\n rr -> Future.succeededFuture(),\n e -> {\n if (desired == null\n && e.getMessage() != null\n && e.getMessage().contains(\"Message: Forbidden!\")) {\n log.debug(\"Ignoring forbidden access to ClusterRoleBindings resource which does not seem to be required.\");\n return Future.succeededFuture();\n }\n return Future.failedFuture(e.getMessage());\n }\n );\n }\n\n}\n"},"new_file":{"kind":"string","value":"operator-common/src/main/java/io/strimzi/operator/common/AbstractOperator.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright Strimzi authors.\n * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).\n */\npackage io.strimzi.operator.common;\n\nimport io.fabric8.kubernetes.api.model.LabelSelector;\nimport io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding;\nimport io.fabric8.kubernetes.client.CustomResource;\nimport io.fabric8.kubernetes.client.Watch;\nimport io.fabric8.kubernetes.client.WatcherException;\nimport io.micrometer.core.instrument.Counter;\nimport io.micrometer.core.instrument.Tag;\nimport io.micrometer.core.instrument.Tags;\nimport io.micrometer.core.instrument.Timer;\nimport io.micrometer.core.instrument.Meter;\nimport io.strimzi.api.kafka.model.Spec;\nimport io.strimzi.api.kafka.model.status.Condition;\nimport io.strimzi.api.kafka.model.status.ConditionBuilder;\nimport io.strimzi.api.kafka.model.status.Status;\nimport io.strimzi.operator.cluster.model.InvalidResourceException;\nimport io.strimzi.operator.cluster.model.StatusDiff;\nimport io.strimzi.operator.common.model.Labels;\nimport io.strimzi.operator.common.model.NamespaceAndName;\nimport io.strimzi.operator.common.model.ResourceVisitor;\nimport io.strimzi.operator.common.model.ValidationVisitor;\nimport io.strimzi.operator.common.operator.resource.AbstractWatchableStatusedResourceOperator;\nimport io.strimzi.operator.common.operator.resource.ReconcileResult;\nimport io.strimzi.operator.common.operator.resource.StatusUtils;\nimport io.strimzi.operator.common.operator.resource.TimeoutException;\nimport io.vertx.core.AsyncResult;\nimport io.vertx.core.Future;\nimport io.vertx.core.Promise;\nimport io.vertx.core.Vertx;\nimport io.vertx.core.shareddata.Lock;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.Collections;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n\nimport static io.strimzi.operator.common.Util.async;\n\n/**\n * A base implementation of {@link Operator}.\n *\n *
    \n *
  • uses the Fabric8 kubernetes API and implements\n * {@link #reconcile(Reconciliation)} by delegating to abstract {@link #createOrUpdate(Reconciliation, CustomResource)}\n * and {@link #delete(Reconciliation)} methods for subclasses to implement.\n * \n *
  • add support for operator-side {@linkplain #validate(CustomResource) validation}.\n * This can be used to automatically log warnings about source resources which used deprecated part of the CR API.\n *ą\n *
\n * @param The Java representation of the Kubernetes resource, e.g. {@code Kafka} or {@code KafkaConnect}\n * @param The \"Resource Operator\" for the source resource type. Typically this will be some instantiation of\n * {@link io.strimzi.operator.common.operator.resource.CrdOperator}.\n */\npublic abstract class AbstractOperator<\n T extends CustomResource,\n P extends Spec,\n S extends Status,\n O extends AbstractWatchableStatusedResourceOperator>\n implements Operator {\n\n private static final Logger log = LogManager.getLogger(AbstractOperator.class);\n\n protected static final int LOCK_TIMEOUT_MS = 10000;\n public static final String METRICS_PREFIX = \"strimzi.\";\n\n protected final Vertx vertx;\n protected final O resourceOperator;\n private final String kind;\n\n private final Optional selector;\n\n protected final MetricsProvider metrics;\n private final Counter periodicReconciliationsCounter;\n private final Counter reconciliationsCounter;\n private final Counter failedReconciliationsCounter;\n private final Counter successfulReconciliationsCounter;\n private final Counter lockedReconciliationsCounter;\n private final AtomicInteger pausedResourceCounter;\n private final AtomicInteger resourceCounter;\n private final Timer reconciliationsTimer;\n private final Map resourcesStateCounter;\n\n public AbstractOperator(Vertx vertx, String kind, O resourceOperator, MetricsProvider metrics, Labels selectorLabels) {\n this.vertx = vertx;\n this.kind = kind;\n this.resourceOperator = resourceOperator;\n this.selector = (selectorLabels == null || selectorLabels.toMap().isEmpty()) ? Optional.empty() : Optional.of(new LabelSelector(null, selectorLabels.toMap()));\n this.metrics = metrics;\n\n // Setup metrics\n Tags metricTags = Tags.of(Tag.of(\"kind\", kind()));\n\n periodicReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.periodical\",\n \"Number of periodical reconciliations done by the operator\",\n metricTags);\n\n reconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations\",\n \"Number of reconciliations done by the operator for individual resources\",\n metricTags);\n\n pausedResourceCounter = metrics.gauge(METRICS_PREFIX + \"resources.paused\",\n \"Number of custom resources the operator sees but does not reconcile due to paused reconciliations\",\n metricTags);\n\n failedReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.failed\",\n \"Number of reconciliations done by the operator for individual resources which failed\",\n metricTags);\n\n successfulReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.successful\",\n \"Number of reconciliations done by the operator for individual resources which were successful\",\n metricTags);\n\n lockedReconciliationsCounter = metrics.counter(METRICS_PREFIX + \"reconciliations.locked\",\n \"Number of reconciliations skipped because another reconciliation for the same resource was still running\",\n metricTags);\n\n resourceCounter = metrics.gauge(METRICS_PREFIX + \"resources\",\n \"Number of custom resources the operator sees\",\n metricTags);\n\n reconciliationsTimer = metrics.timer(METRICS_PREFIX + \"reconciliations.duration\",\n \"The time the reconciliation takes to complete\",\n metricTags);\n\n resourcesStateCounter = new ConcurrentHashMap<>();\n }\n\n @Override\n public String kind() {\n return kind;\n }\n\n /**\n * Gets the name of the lock to be used for operating on the given {@code namespace} and\n * cluster {@code name}\n *\n * @param namespace The namespace containing the cluster\n * @param name The name of the cluster\n */\n private String getLockName(String namespace, String name) {\n return \"lock::\" + namespace + \"::\" + kind() + \"::\" + name;\n }\n\n /**\n * Asynchronously creates or updates the given {@code resource}.\n * This method can be called when the given {@code resource} has been created,\n * or updated and also at some regular interval while the resource continues to exist in Kubernetes.\n * The calling of this method does not imply that anything has actually changed.\n * @param reconciliation Uniquely identifies the reconciliation itself.\n * @param resource The resource to be created, or updated.\n * @return A Future which is completed once the reconciliation of the given resource instance is complete.\n */\n protected abstract Future createOrUpdate(Reconciliation reconciliation, T resource);\n\n /**\n * Asynchronously deletes the resource identified by {@code reconciliation}.\n * Operators which only create other Kubernetes resources in order to honour their source resource can rely\n * on Kubernetes Garbage Collection to handle deletion.\n * Such operators should return a Future which completes with {@code false}.\n * Operators which handle deletion themselves should return a Future which completes with {@code true}.\n * @param reconciliation\n * @return\n */\n protected abstract Future delete(Reconciliation reconciliation);\n\n /**\n * Reconcile assembly resources in the given namespace having the given {@code name}.\n * Reconciliation works by getting the assembly resource (e.g. {@code KafkaUser})\n * in the given namespace with the given name and\n * comparing with the corresponding resource.\n * @param reconciliation The reconciliation.\n * @return A Future which is completed with the result of the reconciliation.\n */\n @Override\n @SuppressWarnings(\"unchecked\")\n public final Future reconcile(Reconciliation reconciliation) {\n String namespace = reconciliation.namespace();\n String name = reconciliation.name();\n\n reconciliationsCounter.increment();\n Timer.Sample reconciliationTimerSample = Timer.start(metrics.meterRegistry());\n\n Future handler = withLock(reconciliation, LOCK_TIMEOUT_MS, () -> {\n T cr = resourceOperator.get(namespace, name);\n\n if (cr != null) {\n if (!Util.matchesSelector(selector(), cr)) {\n // When the labels matching the selector are removed from the custom resource, a DELETE event is\n // triggered by the watch even through the custom resource might not match the watch labels anymore\n // and might not be really deleted. We have to filter these situations out and ignore the\n // reconciliation because such resource might be already operated by another instance (where the\n // same change triggered ADDED event).\n log.debug(\"{}: {} {} in namespace {} does not match label selector {} and will be ignored\", reconciliation, kind(), name, namespace, selector().get().getMatchLabels());\n return Future.succeededFuture();\n }\n\n Promise createOrUpdate = Promise.promise();\n if (Annotations.isReconciliationPausedWithAnnotation(cr)) {\n S status = createStatus();\n Set conditions = validate(cr);\n conditions.add(StatusUtils.getPausedCondition());\n status.setConditions(new ArrayList<>(conditions));\n status.setObservedGeneration(cr.getStatus() != null ? cr.getStatus().getObservedGeneration() : 0);\n\n updateStatus(reconciliation, status).onComplete(statusResult -> {\n if (statusResult.succeeded()) {\n createOrUpdate.complete();\n } else {\n createOrUpdate.fail(statusResult.cause());\n }\n });\n getPausedResourceCounter().getAndIncrement();\n log.debug(\"{}: Reconciliation of {} {} is paused\", reconciliation, kind, name);\n return createOrUpdate.future();\n } else if (cr.getSpec() == null) {\n InvalidResourceException exception = new InvalidResourceException(\"Spec cannot be null\");\n\n S status = createStatus();\n Condition errorCondition = new ConditionBuilder()\n .withLastTransitionTime(StatusUtils.iso8601Now())\n .withType(\"NotReady\")\n .withStatus(\"True\")\n .withReason(exception.getClass().getSimpleName())\n .withMessage(exception.getMessage())\n .build();\n status.setObservedGeneration(cr.getMetadata().getGeneration());\n status.addCondition(errorCondition);\n\n log.error(\"{}: {} spec cannot be null\", reconciliation, cr.getMetadata().getName());\n updateStatus(reconciliation, status).onComplete(notUsed -> {\n createOrUpdate.fail(exception);\n });\n\n return createOrUpdate.future();\n }\n\n Set unknownAndDeprecatedConditions = validate(cr);\n\n log.info(\"{}: {} {} will be checked for creation or modification\", reconciliation, kind, name);\n\n createOrUpdate(reconciliation, cr)\n .onComplete(res -> {\n if (res.succeeded()) {\n S status = res.result();\n\n addWarningsToStatus(status, unknownAndDeprecatedConditions);\n updateStatus(reconciliation, status).onComplete(statusResult -> {\n if (statusResult.succeeded()) {\n createOrUpdate.complete();\n } else {\n createOrUpdate.fail(statusResult.cause());\n }\n });\n } else {\n if (res.cause() instanceof ReconciliationException) {\n ReconciliationException e = (ReconciliationException) res.cause();\n Status status = e.getStatus();\n addWarningsToStatus(status, unknownAndDeprecatedConditions);\n\n log.error(\"{}: createOrUpdate failed\", reconciliation, e.getCause());\n\n updateStatus(reconciliation, (S) status).onComplete(statusResult -> {\n createOrUpdate.fail(e.getCause());\n });\n } else {\n log.error(\"{}: createOrUpdate failed\", reconciliation, res.cause());\n createOrUpdate.fail(res.cause());\n }\n }\n });\n\n return createOrUpdate.future();\n } else {\n log.info(\"{}: {} {} should be deleted\", reconciliation, kind, name);\n return delete(reconciliation).map(deleteResult -> {\n if (deleteResult) {\n log.info(\"{}: {} {} deleted\", reconciliation, kind, name);\n } else {\n log.info(\"{}: Assembly {} or some parts of it will be deleted by garbage collection\", reconciliation, name);\n }\n return (Void) null;\n }).recover(deleteResult -> {\n log.error(\"{}: Deletion of {} {} failed\", reconciliation, kind, name, deleteResult);\n return Future.failedFuture(deleteResult);\n });\n }\n });\n\n Promise result = Promise.promise();\n handler.onComplete(reconcileResult -> {\n handleResult(reconciliation, reconcileResult, reconciliationTimerSample);\n result.handle(reconcileResult);\n });\n\n return result.future();\n }\n\n protected void addWarningsToStatus(Status status, Set unknownAndDeprecatedConditions) {\n if (status != null) {\n status.addConditions(unknownAndDeprecatedConditions);\n }\n }\n\n /**\n * Updates the Status field of the Kafka CR. It diffs the desired status against the current status and calls\n * the update only when there is any difference in non-timestamp fields.\n *\n * @param reconciliation the reconciliation identified\n * @param desiredStatus The KafkaStatus which should be set\n *\n * @return\n */\n Future updateStatus(Reconciliation reconciliation, S desiredStatus) {\n if (desiredStatus == null) {\n log.debug(\"{}: Desired status is null - status will not be updated\", reconciliation);\n return Future.succeededFuture();\n }\n\n String namespace = reconciliation.namespace();\n String name = reconciliation.name();\n\n return resourceOperator.getAsync(namespace, name)\n .compose(res -> {\n if (res != null) {\n S currentStatus = res.getStatus();\n StatusDiff sDiff = new StatusDiff(currentStatus, desiredStatus);\n\n if (!sDiff.isEmpty()) {\n res.setStatus(desiredStatus);\n\n return resourceOperator.updateStatusAsync(res)\n .compose(notUsed -> {\n log.debug(\"{}: Completed status update\", reconciliation);\n return Future.succeededFuture();\n }, error -> {\n log.error(\"{}: Failed to update status\", reconciliation, error);\n return Future.failedFuture(error);\n });\n } else {\n log.debug(\"{}: Status did not change\", reconciliation);\n return Future.succeededFuture();\n }\n } else {\n log.error(\"{}: Current {} resource not found\", reconciliation, reconciliation.kind());\n return Future.failedFuture(\"Current \" + reconciliation.kind() + \" resource with name \" + name + \" not found\");\n }\n }, error -> {\n log.error(\"{}: Failed to get the current {} resource and its status\", reconciliation, reconciliation.kind(), error);\n return Future.failedFuture(error);\n });\n }\n\n protected abstract S createStatus();\n\n /**\n * The exception by which Futures returned by {@link #withLock(Reconciliation, long, Callable)} are failed when\n * the lock cannot be acquired within the timeout.\n */\n static class UnableToAcquireLockException extends TimeoutException { }\n\n /**\n * Acquire the lock for the resource implied by the {@code reconciliation}\n * and call the given {@code callable} with the lock held.\n * Once the callable returns (or if it throws) release the lock and complete the returned Future.\n * If the lock cannot be acquired the given {@code callable} is not called and the returned Future is completed with {@link UnableToAcquireLockException}.\n * @param reconciliation\n * @param callable\n * @param \n * @return\n */\n protected final Future withLock(Reconciliation reconciliation, long lockTimeoutMs, Callable> callable) {\n Promise handler = Promise.promise();\n String namespace = reconciliation.namespace();\n String name = reconciliation.name();\n final String lockName = getLockName(namespace, name);\n log.debug(\"{}: Try to acquire lock {}\", reconciliation, lockName);\n vertx.sharedData().getLockWithTimeout(lockName, lockTimeoutMs, res -> {\n if (res.succeeded()) {\n log.debug(\"{}: Lock {} acquired\", reconciliation, lockName);\n Lock lock = res.result();\n try {\n callable.call().onComplete(callableRes -> {\n if (callableRes.succeeded()) {\n handler.complete(callableRes.result());\n } else {\n handler.fail(callableRes.cause());\n }\n\n lock.release();\n log.debug(\"{}: Lock {} released\", reconciliation, lockName);\n });\n } catch (Throwable ex) {\n lock.release();\n log.debug(\"{}: Lock {} released\", reconciliation, lockName);\n log.error(\"{}: Reconciliation failed\", reconciliation, ex);\n handler.fail(ex);\n }\n } else {\n log.warn(\"{}: Failed to acquire lock {} within {}ms.\", reconciliation, lockName, lockTimeoutMs);\n handler.fail(new UnableToAcquireLockException());\n }\n });\n return handler.future();\n }\n\n /**\n * Validate the Custom Resource.\n * This should log at the WARN level (rather than throwing)\n * if the resource can safely be reconciled (e.g. it merely using deprecated API).\n * @param resource The custom resource\n * @throws InvalidResourceException if the resource cannot be safely reconciled.\n * @return set of conditions\n */\n /*test*/ public Set validate(T resource) {\n if (resource != null) {\n Set warningConditions = new LinkedHashSet<>(0);\n\n ResourceVisitor.visit(resource, new ValidationVisitor(resource, log, warningConditions));\n\n return warningConditions;\n }\n\n return Collections.emptySet();\n }\n\n public Future> allResourceNames(String namespace) {\n return resourceOperator.listAsync(namespace, selector())\n .map(resourceList ->\n resourceList.stream()\n .map(resource -> new NamespaceAndName(resource.getMetadata().getNamespace(), resource.getMetadata().getName()))\n .collect(Collectors.toSet()));\n }\n\n /**\n * A selector to narrow the scope of the {@linkplain #createWatch(String, Consumer) watch}\n * and {@linkplain #allResourceNames(String) query}.\n * @return A selector.\n */\n public Optional selector() {\n return selector;\n }\n\n /**\n * Create Kubernetes watch.\n *\n * @param namespace Namespace where to watch for users.\n * @param onClose Callback called when the watch is closed.\n *\n * @return A future which completes when the watcher has been created.\n */\n public Future createWatch(String namespace, Consumer onClose) {\n return async(vertx, () -> resourceOperator.watch(namespace, selector(), new OperatorWatcher<>(this, namespace, onClose)));\n }\n\n public Consumer recreateWatch(String namespace) {\n Consumer kubernetesClientExceptionConsumer = new Consumer() {\n @Override\n public void accept(WatcherException e) {\n if (e != null) {\n log.error(\"Watcher closed with exception in namespace {}\", namespace, e);\n createWatch(namespace, this);\n } else {\n log.info(\"Watcher closed in namespace {}\", namespace);\n }\n }\n };\n return kubernetesClientExceptionConsumer;\n }\n\n /**\n * Log the reconciliation outcome.\n */\n private void handleResult(Reconciliation reconciliation, AsyncResult result, Timer.Sample reconciliationTimerSample) {\n if (result.succeeded()) {\n updateResourceState(reconciliation, true);\n successfulReconciliationsCounter.increment();\n reconciliationTimerSample.stop(reconciliationsTimer);\n log.info(\"{}: reconciled\", reconciliation);\n } else {\n Throwable cause = result.cause();\n\n if (cause instanceof InvalidConfigParameterException) {\n updateResourceState(reconciliation, false);\n failedReconciliationsCounter.increment();\n reconciliationTimerSample.stop(reconciliationsTimer);\n log.warn(\"{}: Failed to reconcile {}\", reconciliation, cause.getMessage());\n } else if (cause instanceof UnableToAcquireLockException) {\n lockedReconciliationsCounter.increment();\n } else {\n updateResourceState(reconciliation, false);\n failedReconciliationsCounter.increment();\n reconciliationTimerSample.stop(reconciliationsTimer);\n log.warn(\"{}: Failed to reconcile\", reconciliation, cause);\n }\n }\n }\n\n public Counter getPeriodicReconciliationsCounter() {\n return periodicReconciliationsCounter;\n }\n\n public AtomicInteger getResourceCounter() {\n return resourceCounter;\n }\n\n public AtomicInteger getPausedResourceCounter() {\n return pausedResourceCounter;\n }\n\n /**\n * Updates the resource state metric for the provided reconciliation which brings kind, name and namespace\n * of the custom resource.\n *\n * @param reconciliation reconciliation to use to update the resource state metric\n * @param ready if reconcile was successful and the resource is ready\n */\n private void updateResourceState(Reconciliation reconciliation, boolean ready) {\n Tags metricTags = Tags.of(\n Tag.of(\"kind\", reconciliation.kind()),\n Tag.of(\"name\", reconciliation.name()),\n Tag.of(\"resource-namespace\", reconciliation.namespace()));\n\n T cr = resourceOperator.get(reconciliation.namespace(), reconciliation.name());\n if (cr != null) {\n resourcesStateCounter.computeIfAbsent(metricTags, tags ->\n metrics.gauge(METRICS_PREFIX + \"resource.state\", \"Current state of the resource: 1 ready, 0 fail\", tags)\n );\n resourcesStateCounter.get(metricTags).set(ready ? 1 : 0);\n log.debug(\"{}: Updated metric \" + METRICS_PREFIX + \"resource.state{} = {}\", reconciliation, metricTags, ready ? 1 : 0);\n } else {\n Optional gauge = metrics.meterRegistry().getMeters()\n .stream()\n .filter(meter -> meter.getId().getName().equals(METRICS_PREFIX + \"resource.state\") &&\n meter.getId().getTags().equals(metricTags.stream().collect(Collectors.toList()))\n ).findFirst();\n\n if (gauge.isPresent()) {\n metrics.meterRegistry().remove(gauge.get().getId());\n resourcesStateCounter.remove(metricTags);\n log.debug(\"{}: Removed metric \" + METRICS_PREFIX + \"resource.state{}\", reconciliation, metricTags);\n }\n }\n }\n\n /**\n * In some cases, when the ClusterRoleBinding reconciliation fails with RBAC error and the desired object is null,\n * we want to ignore the error and return success. This is used to let Strimzi work without some Cluster-wide RBAC\n * rights when the features they are needed for are not used by the user.\n *\n * @param reconcileFuture The original reconciliation future\n * @param desired The desired state of the resource.\n * @return A future which completes when the resource was reconciled.\n */\n public Future> withIgnoreRbacError(Future> reconcileFuture, ClusterRoleBinding desired) {\n return reconcileFuture.compose(\n rr -> Future.succeededFuture(),\n e -> {\n if (desired == null\n && e.getMessage() != null\n && e.getMessage().contains(\"Message: Forbidden!\")) {\n log.debug(\"Ignoring forbidden access to ClusterRoleBindings resource which does not seem to be required.\");\n return Future.succeededFuture();\n }\n return Future.failedFuture(e.getMessage());\n }\n );\n }\n\n}\n"},"message":{"kind":"string","value":"Remove confusing failed to acquire lock warning (#4521)\n\nSigned-off-by: Jakub Scholz "},"old_file":{"kind":"string","value":"operator-common/src/main/java/io/strimzi/operator/common/AbstractOperator.java"},"subject":{"kind":"string","value":"Remove confusing failed to acquire lock warning (#4521)"}}},{"rowIdx":1288,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"5d845092c787bb9c2ecfaa227893a15e1800df46"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"AArhin/head,AArhin/head,vorburger/mifos-head,AArhin/head,maduhu/head,jpodeszwik/mifos,maduhu/mifos-head,vorburger/mifos-head,maduhu/mifos-head,maduhu/head,maduhu/mifos-head,maduhu/head,maduhu/mifos-head,jpodeszwik/mifos,maduhu/head,vorburger/mifos-head,jpodeszwik/mifos,jpodeszwik/mifos,maduhu/head,AArhin/head,AArhin/head,vorburger/mifos-head,maduhu/mifos-head"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) 2005-2010 Grameen Foundation USA\n * 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 * 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\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\n * See also http://www.apache.org/licenses/LICENSE-2.0.html for an\n * explanation of the license and how it is applied.\n */\n\npackage org.mifos.ui.core.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.mvc.AbstractController;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n\n@SuppressWarnings( { \"PMD.SystemPrintln\", \"PMD.SingularField\" })\n@Controller\npublic class GenericController extends AbstractController {\n\n @Override\n @RequestMapping(value={\"/accessDenied.ftl\",\"/pageNotFound.ftl\",\"/ping.ftl\",\"/cheetah.css.ftl\",\"/gazelle.css.ftl\",\"/adminHome.ftl\",\"/maincss.css\",\"/screen.css\",\"/maincss.css.ftl\",\"/screen.css.ftl\",\"/admin.ftl\",\"/viewProductCategories.ftl\",\"/viewLoanProducts.ftl\",\"/viewFunds.ftl\",\"/defineLabels.ftl\",\"/defineLookupOptions.ftl\",\"/viewChecklists.ftl\",\"/viewEditCheckLists.ftl\",\"/viewEditSavingsProduct.ftl\",\"/viewEditLoanProduct.ftl\",\"/viewOffices.ftl\",\"/viewHolidays.ftl\",\"/viewSystemUsers.ftl\",\"/viewAdditionalFields.ftl\",\"/viewReportsTemplates.ftl\",\"/viewReportsCategory.ftl\",\"/manageRolesAndPermissions.ftl\",\"/defineAdditionalFields.ftl\",\"/defineNewCategory.ftl\",\"/defineNewChecklist.ftl\",\"/defineNewHolidays.ftl\",\"/defineNewOffice.ftl\",\"/defineNewSystemUser.ftl\",\"/defineSavingsProduct.ftl\",\"/redoLoansDisbursal.ftl\"})\n protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {\n Map model = new HashMap();\n model.put(\"request\", request);\n Map status = new HashMap();\n List errorMessages = new ArrayList();\n status.put(\"errorMessages\", errorMessages);\n ModelAndView modelAndView = new ModelAndView(getPageToDisplay(request), \"model\", model);\n modelAndView.addObject(\"status\", status);\n return modelAndView;\n }\n\n public String getPageToDisplay(HttpServletRequest request) {\n return request.getRequestURI().replaceFirst(\"/mifos.*/\",\"\").replace(\".ftl\", \"\");\n }\n}\n"},"new_file":{"kind":"string","value":"userInterface/src/main/java/org/mifos/ui/core/controller/GenericController.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2005-2010 Grameen Foundation USA\n * 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 * 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\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\n * See also http://www.apache.org/licenses/LICENSE-2.0.html for an\n * explanation of the license and how it is applied.\n */\n\npackage org.mifos.ui.core.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.mvc.AbstractController;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n\n@SuppressWarnings( { \"PMD.SystemPrintln\", \"PMD.SingularField\" })\n@Controller\npublic class GenericController extends AbstractController {\n\n @Override\n @RequestMapping(value={\"/accessDenied.ftl\",\"/pageNotFound.ftl\",\"/ping.ftl\",\"/cheetah.css.ftl\",\"/gazelle.css.ftl\",\"/adminHome.ftl\",\"/maincss.css\",\"/screen.css\",\"/maincss.css.ftl\",\"/screen.css.ftl\",\"/admin.ftl\",\"/viewProductMix.ftl\",\"/viewProductCategories.ftl\",\"/viewLoanProducts.ftl\",\"/viewFunds.ftl\",\"/defineLabels.ftl\",\"/defineLookupOptions.ftl\",\"/viewChecklists.ftl\",\"/viewEditCheckLists.ftl\",\"/viewEditSavingsProduct.ftl\",\"/viewEditLoanProduct.ftl\",\"/viewOffices.ftl\",\"/viewHolidays.ftl\",\"/viewSystemUsers.ftl\",\"/viewAdditionalFields.ftl\",\"/viewReportsTemplates.ftl\",\"/viewReportsCategory.ftl\",\"/manageRolesAndPermissions.ftl\",\"/defineAdditionalFields.ftl\",\"/defineNewCategory.ftl\",\"/defineNewChecklist.ftl\",\"/defineNewHolidays.ftl\",\"/defineNewOffice.ftl\",\"/defineNewSystemUser.ftl\",\"/defineSavingsProduct.ftl\",\"/redoLoansDisbursal.ftl\"})\n protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {\n Map model = new HashMap();\n model.put(\"request\", request);\n Map status = new HashMap();\n List errorMessages = new ArrayList();\n status.put(\"errorMessages\", errorMessages);\n ModelAndView modelAndView = new ModelAndView(getPageToDisplay(request), \"model\", model);\n modelAndView.addObject(\"status\", status);\n return modelAndView;\n }\n\n public String getPageToDisplay(HttpServletRequest request) {\n return request.getRequestURI().replaceFirst(\"/mifos.*/\",\"\").replace(\".ftl\", \"\");\n }\n}\n"},"message":{"kind":"string","value":"removing viewProductMix.ftl mapping in GenericController\n"},"old_file":{"kind":"string","value":"userInterface/src/main/java/org/mifos/ui/core/controller/GenericController.java"},"subject":{"kind":"string","value":"removing viewProductMix.ftl mapping in GenericController"}}},{"rowIdx":1289,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"518dbc14e17feb3a338b530a9217548760fd7dd9"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE"},"new_contents":{"kind":"string","value":"package uk.ac.ebi.quickgo.index.geneproduct;\n\nimport uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository;\nimport uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument;\nimport uk.ac.ebi.quickgo.index.common.SolrCrudRepoWriter;\nimport uk.ac.ebi.quickgo.index.common.listener.LogJobListener;\nimport uk.ac.ebi.quickgo.index.common.listener.LogStepListener;\nimport uk.ac.ebi.quickgo.geneproduct.common.RepoConfig;\nimport uk.ac.ebi.quickgo.index.common.listener.SkipLoggerListener;\n\nimport java.util.Arrays;\nimport org.springframework.batch.core.Job;\nimport org.springframework.batch.core.JobExecutionListener;\nimport org.springframework.batch.core.Step;\nimport org.springframework.batch.core.StepListener;\nimport org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;\nimport org.springframework.batch.core.configuration.annotation.JobBuilderFactory;\nimport org.springframework.batch.core.configuration.annotation.StepBuilderFactory;\nimport org.springframework.batch.item.ItemProcessor;\nimport org.springframework.batch.item.ItemWriter;\nimport org.springframework.batch.item.file.FlatFileItemReader;\nimport org.springframework.batch.item.file.FlatFileParseException;\nimport org.springframework.batch.item.file.LineMapper;\nimport org.springframework.batch.item.file.MultiResourceItemReader;\nimport org.springframework.batch.item.file.mapping.DefaultLineMapper;\nimport org.springframework.batch.item.file.mapping.FieldSetMapper;\nimport org.springframework.batch.item.file.transform.DelimitedLineTokenizer;\nimport org.springframework.batch.item.file.transform.LineTokenizer;\nimport org.springframework.batch.item.support.CompositeItemProcessor;\nimport org.springframework.batch.item.validator.ValidatingItemProcessor;\nimport org.springframework.batch.item.validator.ValidationException;\nimport org.springframework.batch.item.validator.Validator;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Import;\nimport org.springframework.core.io.Resource;\n\n/**\n * Sets up batch jobs for gene product indexing.\n */\n@Configuration\n@EnableBatchProcessing\n@Import({RepoConfig.class})\npublic class GeneProductConfig {\n static final String GENE_PRODUCT_INDEXING_STEP_NAME = \"geneProductIndex\";\n\n private static final String COLUMN_DELIMITER = \"\\t\";\n private static final String INTER_VALUE_DELIMITER = \"\\\\|\";\n private static final String INTRA_VALUE_DELIMITER = \"=\";\n\n @Autowired\n private JobBuilderFactory jobBuilders;\n\n @Autowired\n private StepBuilderFactory stepBuilders;\n\n @Value(\"${indexing.geneproduct.source}\")\n private Resource[] resources;\n\n @Value(\"${indexing.geneproduct.chunk.size:500}\")\n private int chunkSize;\n\n @Value(\"${indexing.geneproduct.header.lines:17}\")\n private int headerLines;\n\n @Value(\"${indexing.geneproduct.skip.limit:100}\")\n private int skipLimit;\n\n @Autowired\n private GeneProductRepository repository;\n\n @Bean\n public Job geneProductJob() {\n return jobBuilders.get(\"geneProductJob\")\n .start(readGeneProductData())\n .listener(logJobListener())\n .build();\n }\n\n private Step readGeneProductData() {\n return stepBuilders.get(GENE_PRODUCT_INDEXING_STEP_NAME)\n .chunk(chunkSize)\n .faultTolerant()\n .skipLimit(skipLimit)\n .skip(FlatFileParseException.class)\n .skip(ValidationException.class)\n .reader(multiFileReader())\n .processor(compositeProcessor(gpValidator(), docConverter()))\n .writer(geneProductRepositoryWriter())\n .listener(logStepListener())\n .listener(skipLogListener())\n .build();\n }\n\n private MultiResourceItemReader multiFileReader() {\n MultiResourceItemReader reader = new MultiResourceItemReader<>();\n reader.setResources(resources);\n reader.setDelegate(singleFileReader());\n return reader;\n }\n\n private FlatFileItemReader singleFileReader() {\n FlatFileItemReader reader = new FlatFileItemReader<>();\n reader.setLineMapper(lineMapper());\n reader.setLinesToSkip(headerLines);\n return reader;\n }\n\n private LineMapper lineMapper() {\n DefaultLineMapper lineMapper = new DefaultLineMapper<>();\n lineMapper.setLineTokenizer(lineTokenizer());\n lineMapper.setFieldSetMapper(fieldSetMapper());\n\n return lineMapper;\n }\n\n private LineTokenizer lineTokenizer() {\n return new DelimitedLineTokenizer(COLUMN_DELIMITER);\n }\n\n private FieldSetMapper fieldSetMapper() {\n return new StringToGeneProductMapper();\n }\n\n private ItemProcessor docConverter() {\n return new GeneProductDocumentConverter(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER);\n }\n\n private ItemProcessor gpValidator() {\n Validator geneProductValidator =\n new GeneProductValidator(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER);\n return new ValidatingItemProcessor<>(geneProductValidator);\n }\n\n private ItemProcessor compositeProcessor(ItemProcessor... processors) {\n CompositeItemProcessor compositeProcessor = new CompositeItemProcessor<>();\n compositeProcessor.setDelegates(Arrays.asList(processors));\n\n return compositeProcessor;\n }\n\n private ItemWriter geneProductRepositoryWriter() {\n return new SolrCrudRepoWriter<>(repository);\n }\n\n private JobExecutionListener logJobListener() {\n return new LogJobListener();\n }\n\n private StepListener logStepListener() {\n return new LogStepListener();\n }\n\n private StepListener skipLogListener() {\n return new SkipLoggerListener();\n }\n}"},"new_file":{"kind":"string","value":"indexing/src/main/java/uk/ac/ebi/quickgo/index/geneproduct/GeneProductConfig.java"},"old_contents":{"kind":"string","value":"package uk.ac.ebi.quickgo.index.geneproduct;\n\nimport uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository;\nimport uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument;\nimport uk.ac.ebi.quickgo.index.common.DocumentReaderException;\nimport uk.ac.ebi.quickgo.index.common.SolrCrudRepoWriter;\nimport uk.ac.ebi.quickgo.index.common.listener.LogJobListener;\nimport uk.ac.ebi.quickgo.index.common.listener.LogStepListener;\nimport uk.ac.ebi.quickgo.geneproduct.common.RepoConfig;\n\nimport java.util.Arrays;\nimport org.springframework.batch.core.Job;\nimport org.springframework.batch.core.Step;\nimport org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;\nimport org.springframework.batch.core.configuration.annotation.JobBuilderFactory;\nimport org.springframework.batch.core.configuration.annotation.StepBuilderFactory;\nimport org.springframework.batch.item.ItemProcessor;\nimport org.springframework.batch.item.ItemWriter;\nimport org.springframework.batch.item.file.FlatFileItemReader;\nimport org.springframework.batch.item.file.FlatFileParseException;\nimport org.springframework.batch.item.file.LineMapper;\nimport org.springframework.batch.item.file.MultiResourceItemReader;\nimport org.springframework.batch.item.file.mapping.DefaultLineMapper;\nimport org.springframework.batch.item.file.mapping.FieldSetMapper;\nimport org.springframework.batch.item.file.transform.DelimitedLineTokenizer;\nimport org.springframework.batch.item.file.transform.LineTokenizer;\nimport org.springframework.batch.item.support.CompositeItemProcessor;\nimport org.springframework.batch.item.validator.ValidatingItemProcessor;\nimport org.springframework.batch.item.validator.ValidationException;\nimport org.springframework.batch.item.validator.Validator;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Import;\nimport org.springframework.core.io.Resource;\n\n/**\n * Sets up batch jobs for gene product indexing.\n */\n@Configuration\n@EnableBatchProcessing\n@Import({RepoConfig.class})\npublic class GeneProductConfig {\n static final String GENE_PRODUCT_INDEXING_STEP_NAME = \"geneProductIndex\";\n\n private static final String COLUMN_DELIMITER = \"\\t\";\n private static final String INTER_VALUE_DELIMITER = \"\\\\|\";\n private static final String INTRA_VALUE_DELIMITER = \"=\";\n\n @Autowired\n private JobBuilderFactory jobBuilders;\n\n @Autowired\n private StepBuilderFactory stepBuilders;\n\n @Value(\"${indexing.geneproduct.source}\")\n private Resource[] resources;\n\n @Value(\"${indexing.geneproduct.chunk.size:500}\")\n private int chunkSize;\n\n @Value(\"${indexing.geneproduct.header.lines:17}\")\n private int headerLines;\n\n @Value(\"${indexing.geneproduct.skip.limit:100}\")\n private int skipLimit;\n\n @Autowired\n private GeneProductRepository repository;\n\n @Bean\n public Job geneProductJob() {\n return jobBuilders.get(\"geneProductJob\")\n .listener(logJobListener())\n .flow(readGeneProductData())\n .end()\n .build();\n }\n\n private Step readGeneProductData() {\n return stepBuilders.get(GENE_PRODUCT_INDEXING_STEP_NAME)\n .chunk(chunkSize)\n .faultTolerant()\n .skipLimit(skipLimit)\n .skip(FlatFileParseException.class)\n .skip(ValidationException.class)\n .reader(multiFileReader())\n .processor(compositeProcessor(gpValidator(), docConverter()))\n .writer(geneProductRepositoryWriter())\n .listener(logStepListener())\n .build();\n }\n\n private MultiResourceItemReader multiFileReader() {\n MultiResourceItemReader reader = new MultiResourceItemReader<>();\n reader.setResources(resources);\n reader.setDelegate(singleFileReader());\n return reader;\n }\n\n private FlatFileItemReader singleFileReader() {\n FlatFileItemReader reader = new FlatFileItemReader<>();\n reader.setLineMapper(lineMapper());\n reader.setLinesToSkip(headerLines);\n return reader;\n }\n\n private LineMapper lineMapper() {\n DefaultLineMapper lineMapper = new DefaultLineMapper<>();\n lineMapper.setLineTokenizer(lineTokenizer());\n lineMapper.setFieldSetMapper(fieldSetMapper());\n\n return lineMapper;\n }\n\n private LineTokenizer lineTokenizer() {\n return new DelimitedLineTokenizer(COLUMN_DELIMITER);\n }\n\n private FieldSetMapper fieldSetMapper() {\n return new StringToGeneProductMapper();\n }\n\n private ItemProcessor docConverter() {\n return new GeneProductDocumentConverter(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER);\n }\n\n private ItemProcessor gpValidator() {\n Validator geneProductValidator =\n new GeneProductValidator(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER);\n return new ValidatingItemProcessor<>(geneProductValidator);\n }\n\n private ItemProcessor compositeProcessor(ItemProcessor... processors) {\n CompositeItemProcessor compositeProcessor = new CompositeItemProcessor<>();\n compositeProcessor.setDelegates(Arrays.asList(processors));\n\n return compositeProcessor;\n }\n\n private ItemWriter geneProductRepositoryWriter() {\n return new SolrCrudRepoWriter<>(repository);\n }\n\n private LogJobListener logJobListener() {\n return new LogJobListener();\n }\n\n private LogStepListener logStepListener() {\n return new LogStepListener();\n }\n}"},"message":{"kind":"string","value":"Add step listener to the step.\n"},"old_file":{"kind":"string","value":"indexing/src/main/java/uk/ac/ebi/quickgo/index/geneproduct/GeneProductConfig.java"},"subject":{"kind":"string","value":"Add step listener to the step."}}},{"rowIdx":1290,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e6a80aed3776535e684081ec7d50c728a78d0674"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j"},"new_contents":{"kind":"string","value":"/**\r\n * Licensed to Neo Technology under one or more contributor\r\n * license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright\r\n * ownership. Neo Technology licenses this file to you under\r\n * the Apache License, Version 2.0 (the \"License\"); you may\r\n * not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing,\r\n * software distributed under the License is distributed on an\r\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n * KIND, either express or implied. See the License for the\r\n * specific language governing permissions and limitations\r\n * under the License.\r\n */\r\npackage org.neo4j.windows.test;\r\n\r\nimport com.sun.jersey.api.client.ClientHandlerException;\r\nimport org.junit.Test;\r\nimport org.neo4j.server.rest.JaxRsResponse;\r\nimport org.neo4j.server.rest.RestRequest;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.io.InputStreamReader;\r\n\r\nimport static org.hamcrest.Matchers.equalTo;\r\nimport static org.junit.Assert.*;\r\n\r\npublic class TheTest {\r\n @Test\r\n public void Test() throws Throwable {\r\n Result install = run(\"msiexec /i target\\\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet INSTALL_DIR=\\\"C:\\\\det är dåligt. mycket mycket dåligt. gör inte såhär.\\\"\");\r\n install.checkResults();\r\n\t\tcheckDataRest();\r\n\t\t\r\n Result uninstall = run(\"msiexec /x target\\\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet\");\r\n uninstall.checkResults();\r\n\t\ttry {\r\n\t\t\tcheckDataRest();\r\n\t\t\tfail(\"Server is still listening to port 7474 even after uninstall\");\r\n\t\t} catch (ClientHandlerException e) {\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void checkDataRest() throws Exception {\r\n\t\tJaxRsResponse r = RestRequest.req().get(\"http://localhost:7474/db/data/\");\r\n\t\tassertThat(r.getStatus(), equalTo(200));\r\n } \r\n\r\n private Result run(String cmd) throws IOException, InterruptedException {\r\n System.out.println(cmd);\r\n StringBuilder builder = new StringBuilder();\r\n Process installer = Runtime.getRuntime().exec(cmd);\r\n BufferedReader bri = new BufferedReader(new InputStreamReader(installer.getInputStream()));\r\n BufferedReader bre = new BufferedReader(new InputStreamReader(installer.getErrorStream()));\r\n String line;\r\n while ((line = bri.readLine()) != null) {\r\n builder.append(line);\r\n builder.append(\"\\r\\n\");\r\n }\r\n bri.close();\r\n while ((line = bre.readLine()) != null) {\r\n builder.append(line);\r\n builder.append(\"\\r\\n\");\r\n }\r\n bre.close();\r\n installer.waitFor();\r\n\r\n return new Result(installer.exitValue(), builder.toString(), cmd);\r\n }\r\n\r\n private class Result {\r\n private final int result;\r\n private final String message;\r\n\r\n private Result(int result, String message, String cmd) {\r\n this.result = result;\r\n String userDir = System.getProperty(\"user.dir\");\r\n\r\n this.message = \"Path: \" + userDir + \"\\r\\n\" +\r\n \"Cmd: \" + cmd + \"\\r\\n\" +\r\n message;\r\n }\r\n\r\n public int getResult() {\r\n return result;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n\r\n public void checkResults() {\r\n assertEquals(message, getResult(), 0);\r\n }\r\n }\r\n}"},"new_file":{"kind":"string","value":"packaging/win-test/src/test/java/org/neo4j/windows/test/TheTest.java"},"old_contents":{"kind":"string","value":"/**\r\n * Licensed to Neo Technology under one or more contributor\r\n * license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright\r\n * ownership. Neo Technology licenses this file to you under\r\n * the Apache License, Version 2.0 (the \"License\"); you may\r\n * not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing,\r\n * software distributed under the License is distributed on an\r\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n * KIND, either express or implied. See the License for the\r\n * specific language governing permissions and limitations\r\n * under the License.\r\n */\r\n\r\n package org.neo4j.windows.test;\r\n \r\nimport org.junit.Test;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.io.InputStreamReader;\r\nimport org.neo4j.server.rest.RestRequest;\r\nimport org.neo4j.server.rest.JaxRsResponse;\r\nimport com.sun.jersey.api.client.ClientHandlerException;\r\n\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.*;\r\nimport static org.hamcrest.Matchers.equalTo;\r\n\r\npublic class TheTest {\r\n @Test\r\n public void Test() throws Throwable {\r\n Result install = run(\"msiexec /i target\\\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet\");\r\n install.checkResults();\r\n\t\tJaxRsResponse r = RestRequest.req().get(\"http://localhost:7474/db/data/\");\r\n\t\tassertThat(r.getStatus(), equalTo(200));\r\n\t\t\r\n Result uninstall = run(\"msiexec /x target\\\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet\");\r\n uninstall.checkResults();\r\n\t\ttry {\r\n\t\t\tr = RestRequest.req().get(\"http://localhost:7474/db/data/\");\r\n\t\t\tint status = r.getStatus();\r\n\t\t\tfail(\"Server is still listening to port 7474 even after uninstall\");\r\n\t\t} catch (ClientHandlerException e) {\r\n\t\t}\r\n\t}\r\n\r\n private Result run(String cmd) throws IOException, InterruptedException {\r\n System.out.println(cmd);\r\n StringBuilder builder = new StringBuilder();\r\n Process installer = Runtime.getRuntime().exec(cmd);\r\n BufferedReader bri = new BufferedReader(new InputStreamReader(installer.getInputStream()));\r\n BufferedReader bre = new BufferedReader(new InputStreamReader(installer.getErrorStream()));\r\n String line;\r\n while ((line = bri.readLine()) != null) {\r\n builder.append(line);\r\n builder.append(\"\\r\\n\");\r\n }\r\n bri.close();\r\n while ((line = bre.readLine()) != null) {\r\n builder.append(line);\r\n builder.append(\"\\r\\n\");\r\n }\r\n bre.close();\r\n installer.waitFor();\r\n\r\n return new Result(installer.exitValue(), builder.toString(), cmd);\r\n }\r\n\r\n private class Result {\r\n private final int result;\r\n private final String message;\r\n\r\n private Result(int result, String message, String cmd) {\r\n this.result = result;\r\n String userDir = System.getProperty(\"user.dir\");\r\n\r\n this.message = \"Path: \" + userDir + \"\\r\\n\" +\r\n \"Cmd: \" + cmd + \"\\r\\n\" +\r\n message;\r\n }\r\n\r\n public int getResult() {\r\n return result;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n\r\n public void checkResults() {\r\n assertEquals(message, getResult(), 0);\r\n }\r\n }\r\n}"},"message":{"kind":"string","value":"Added tests to install the server on a path with strange characters and space in it\n"},"old_file":{"kind":"string","value":"packaging/win-test/src/test/java/org/neo4j/windows/test/TheTest.java"},"subject":{"kind":"string","value":"Added tests to install the server on a path with strange characters and space in it"}}},{"rowIdx":1291,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"89f4bf9d11d94943d357ee72613a7b098166b5de"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"cnldw/APITools"},"new_contents":{"kind":"string","value":"package com.itlaborer.utils;\n\nimport java.awt.Toolkit;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.StringWriter;\nimport java.io.UnsupportedEncodingException;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.Charset;\nimport java.security.MessageDigest;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.log4j.Logger;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.dnd.Clipboard;\nimport org.eclipse.swt.dnd.DND;\nimport org.eclipse.swt.dnd.DropTarget;\nimport org.eclipse.swt.dnd.DropTargetEvent;\nimport org.eclipse.swt.dnd.DropTargetListener;\nimport org.eclipse.swt.dnd.FileTransfer;\nimport org.eclipse.swt.dnd.TextTransfer;\nimport org.eclipse.swt.dnd.Transfer;\nimport org.eclipse.swt.events.KeyEvent;\nimport org.eclipse.swt.events.KeyListener;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.widgets.Menu;\nimport org.eclipse.swt.widgets.MenuItem;\nimport org.eclipse.swt.widgets.Shell;\n\nimport net.dongliu.requests.RawResponse;\nimport net.dongliu.requests.Requests;\n\n/**\n * \n * 工具类\n * \n * @author liu\n *\n */\npublic class ApiUtils {\n\n\tprivate static Logger logger = Logger.getLogger(ApiUtils.class.getName());\n\n\tpublic ApiUtils() {\n\t}\n\n\t// MD5字符串算法\n\tpublic final static String MD5(String s) {\n\n\t\tchar hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n\t\ttry {\n\t\t\tbyte[] btInput = s.getBytes();\n\t\t\tMessageDigest mdInst = MessageDigest.getInstance(\"MD5\");\n\t\t\tmdInst.update(btInput);\n\t\t\tbyte[] md = mdInst.digest();\n\t\t\tint j = md.length;\n\t\t\tchar str[] = new char[j * 2];\n\t\t\tint k = 0;\n\t\t\tfor (int i = 0; i < j; i++) {\n\t\t\t\tbyte byte0 = md[i];\n\t\t\t\tstr[k++] = hexDigits[byte0 >>> 4 & 0xf];\n\t\t\t\tstr[k++] = hexDigits[byte0 & 0xf];\n\t\t\t}\n\t\t\treturn new String(str);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"异常\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t// HTTP GET 忽略证书安全\n\tpublic static RawResponse HttpGet(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.get(url).verify(false).headers(header).cookies(cookies).params(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP POST 忽略证书安全\n\tpublic static RawResponse HttpPost(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.post(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP HEAD 忽略证书安全\n\tpublic static RawResponse HttpHead(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.head(url).verify(false).headers(header).cookies(cookies).params(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP PUT 忽略证书安全\n\tpublic static RawResponse HttpPut(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.put(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP PATCH 忽略证书安全\n\tpublic static RawResponse HttpPatch(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.patch(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP DELETE 忽略证书安全\n\tpublic static RawResponse HttpDelete(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.delete(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// 设置程序窗口居中\n\tpublic static void SetCenter(Shell shell) {\n\t\tint screenH = Toolkit.getDefaultToolkit().getScreenSize().height;\n\t\tint screenW = Toolkit.getDefaultToolkit().getScreenSize().width;\n\t\tint shellH = shell.getBounds().height;\n\t\tint shellW = shell.getBounds().width;\n\t\tif (shellH > screenH) {\n\t\t\tshellH = screenH;\n\t\t}\n\t\tif (shellW > screenW) {\n\t\t\tshellW = screenW;\n\t\t}\n\t\tshell.setLocation(((screenW - shellW) / 2), ((screenH - shellH) / 2));\n\t}\n\n\t// 设置程序窗口居中于父窗口\n\tpublic static void SetCenterinParent(Shell parentshell, Shell shell) {\n\t\tint screenH = Toolkit.getDefaultToolkit().getScreenSize().height;\n\t\tint screenW = Toolkit.getDefaultToolkit().getScreenSize().width;\n\t\tint shellH = shell.getBounds().height;\n\t\tint shellW = shell.getBounds().width;\n\t\t// 如果窗口大小超过屏幕大小,调整为屏幕大小\n\t\tif (shellH > screenH) {\n\t\t\tshellH = screenH;\n\t\t}\n\t\tif (shellW > screenW) {\n\t\t\tshellW = screenW;\n\t\t}\n\t\tint targetx = parentshell.getLocation().x + parentshell.getBounds().width / 2 - shell.getBounds().width / 2;\n\t\tint targety = parentshell.getLocation().y + parentshell.getBounds().height / 2 - shell.getBounds().height / 2;\n\t\tif (targetx + shellW > screenW) {\n\t\t\ttargetx = screenW - shellW;\n\t\t}\n\t\tif (targety + shellH > screenH) {\n\t\t\ttargety = screenH - shellH;\n\t\t}\n\t\tshell.setLocation(targetx, targety);\n\t}\n\n\t// 读取文件到String字符串\n\tpublic static String ReadFromFile(File file, String encoding) {\n\t\tInputStreamReader reader = null;\n\t\tStringWriter writer = new StringWriter();\n\t\ttry {\n\t\t\tif (encoding == null || \"\".equals(encoding.trim())) {\n\t\t\t\treader = new InputStreamReader(new FileInputStream(file), encoding);\n\t\t\t} else {\n\t\t\t\treader = new InputStreamReader(new FileInputStream(file));\n\t\t\t}\n\t\t\tchar[] buffer = new char[4096];\n\t\t\tint n = 0;\n\t\t\twhile (-1 != (n = reader.read(buffer))) {\n\t\t\t\twriter.write(buffer, 0, n);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"异常\", e);\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tif (reader != null)\n\t\t\t\ttry {\n\t\t\t\t\treader.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogger.error(\"异常\", e);\n\t\t\t\t}\n\t\t}\n\t\treturn writer.toString();\n\t}\n\n\t// String保存到文件方法\n\tpublic static boolean SaveToFile(File file, String content) {\n\t\tFileWriter fwriter = null;\n\t\ttry {\n\t\t\tfwriter = new FileWriter(file);\n\t\t\tfwriter.write(content);\n\t\t\tfwriter.flush();\n\t\t\tfwriter.close();\n\t\t\treturn true;\n\t\t} catch (Exception ex) {\n\t\t\tlogger.error(\"捕获异常\", ex);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// 文件复制方法\n\tpublic static long CopyFile(File f1, File f2) throws Exception {\n\t\tlong time = new Date().getTime();\n\t\tint length = 2097152;\n\t\tFileInputStream in = new FileInputStream(f1);\n\t\tFileOutputStream out = new FileOutputStream(f2);\n\t\tbyte[] buffer = new byte[length];\n\t\twhile (true) {\n\t\t\tint ins = in.read(buffer);\n\t\t\tif (ins == -1) {\n\t\t\t\tin.close();\n\t\t\t\tout.flush();\n\t\t\t\tout.close();\n\t\t\t\treturn new Date().getTime() - time;\n\t\t\t} else\n\t\t\t\tout.write(buffer, 0, ins);\n\t\t}\n\t}\n\n\t// String编码转换方法\n\tpublic static String GetUTF8StringFromGBKString(String gbkStr) {\n\t\ttry {\n\t\t\treturn new String(GetUTF8BytesFromGBKString(gbkStr), \"UTF-8\");\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new InternalError();\n\t\t}\n\t}\n\n\t// GBK字符串转换到UTF-8\n\tpublic static byte[] GetUTF8BytesFromGBKString(String gbkStr) {\n\t\tint n = gbkStr.length();\n\t\tbyte[] utfBytes = new byte[3 * n];\n\t\tint k = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint m = gbkStr.charAt(i);\n\t\t\tif (m < 128 && m >= 0) {\n\t\t\t\tutfBytes[k++] = (byte) m;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tutfBytes[k++] = (byte) (0xe0 | (m >> 12));\n\t\t\tutfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));\n\t\t\tutfBytes[k++] = (byte) (0x80 | (m & 0x3f));\n\t\t}\n\t\tif (k < utfBytes.length) {\n\t\t\tbyte[] tmp = new byte[k];\n\t\t\tSystem.arraycopy(utfBytes, 0, tmp, 0, k);\n\t\t\treturn tmp;\n\t\t}\n\t\treturn utfBytes;\n\t}\n\n\t// 删除文件夹的方法\n\tpublic static boolean DeleteDir(File dir) {\n\t\tif (dir.isDirectory()) {\n\t\t\tString[] children = dir.list();\n\t\t\tfor (int i = 0; i < children.length; i++) {\n\t\t\t\tboolean success = DeleteDir(new File(dir, children[i]));\n\t\t\t\tif (!success) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dir.delete();\n\t}\n\n\t// 字符串转unicode\n\tpublic static String string2Unicode(String string) {\n\n\t\tStringBuffer unicode = new StringBuffer();\n\t\tfor (int i = 0; i < string.length(); i++) {\n\t\t\t// 取出每一个字符\n\t\t\tchar c = string.charAt(i);\n\t\t\tString unicodestring = Integer.toHexString(c);\n\t\t\t// 英文的话,要补全四位\n\t\t\tif (unicodestring.length() == 2) {\n\t\t\t\tunicodestring = \"00\" + unicodestring;\n\t\t\t}\n\t\t\t// 转换为unicode\n\t\t\tunicode.append(\"\\\\u\" + unicodestring);\n\t\t}\n\t\treturn unicode.toString();\n\t}\n\n\t// 字符串转unicode-只转换中日韩\n\tpublic static String stringzh2Unicode(String string) {\n\n\t\tStringBuffer unicode = new StringBuffer();\n\t\tfor (int i = 0; i < string.length(); i++) {\n\t\t\t// 取出每一个字符\n\t\t\tchar c = string.charAt(i);\n\t\t\t// 转换为unicode\n\t\t\tif (isChinese(c)) {\n\t\t\t\tunicode.append(\"\\\\u\" + Integer.toHexString(c));\n\t\t\t} else {\n\t\t\t\tunicode.append(c);\n\t\t\t}\n\t\t}\n\t\treturn unicode.toString();\n\t}\n\n\t// unicode串解码\n\tpublic static String unicode2String(String str) {\n\n\t\tCharset set = Charset.forName(\"UTF-16\");\n\t\tPattern p = Pattern.compile(\"\\\\\\\\u([0-9a-fA-F]{4})\");\n\t\tMatcher m = p.matcher(str);\n\t\tint start = 0;\n\t\tint start2 = 0;\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile (m.find(start)) {\n\t\t\tstart2 = m.start();\n\t\t\tif (start2 > start) {\n\t\t\t\tString seg = str.substring(start, start2);\n\t\t\t\tsb.append(seg);\n\t\t\t}\n\t\t\tString code = m.group(1);\n\t\t\tint i = Integer.valueOf(code, 16);\n\t\t\tbyte[] bb = new byte[4];\n\t\t\tbb[0] = (byte) ((i >> 8) & 0xFF);\n\t\t\tbb[1] = (byte) (i & 0xFF);\n\t\t\tByteBuffer b = ByteBuffer.wrap(bb);\n\t\t\tsb.append(String.valueOf(set.decode(b)).trim());\n\t\t\tstart = m.end();\n\t\t}\n\t\tstart2 = str.length();\n\t\tif (start2 > start) {\n\t\t\tString seg = str.substring(start, start2);\n\t\t\tsb.append(seg);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t// 判断字符是否是中日韩字符\n\tprivate static final boolean isChinese(char c) {\n\t\tCharacter.UnicodeBlock ub = Character.UnicodeBlock.of(c);\n\t\tif (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS\n\t\t\t\t|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS\n\t\t\t\t|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A\n\t\t\t\t|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION\n\t\t\t\t|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION\n\t\t\t\t|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t// 给不支持右键菜单的StyledText添加右键菜单\n\tpublic static void StyledTextAddContextMenu(StyledText styledText) {\n\t\tMenu popupMenu = new Menu(styledText);\n\t\tMenuItem cut = new MenuItem(popupMenu, SWT.NONE);\n\t\tcut.setText(\"剪切\");\n\t\tMenuItem copy = new MenuItem(popupMenu, SWT.NONE);\n\t\tcopy.setText(\"复制\");\n\t\tMenuItem paste = new MenuItem(popupMenu, SWT.NONE);\n\t\tpaste.setText(\"粘贴\");\n\t\tMenuItem allSelect = new MenuItem(popupMenu, SWT.NONE);\n\t\tallSelect.setText(\"全选\");\n\t\tMenuItem clear = new MenuItem(popupMenu, SWT.NONE);\n\t\tclear.setText(\"清空\");\n\t\tMenuItem warp = new MenuItem(popupMenu, SWT.NONE);\n\t\twarp.setText(\"自动换行\");\n\t\tstyledText.setMenu(popupMenu);\n\n\t\t// 判断初始自动换行状态\n\t\tif (styledText.getWordWrap()) {\n\t\t\twarp.setText(\"关闭自动换行\");\n\t\t} else {\n\t\t\twarp.setText(\"打开自动换行\");\n\t\t}\n\t\tstyledText.addKeyListener(new KeyListener() {\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e) {\n\t\t\t\tif (e.stateMask == SWT.CTRL && e.keyCode == 'a') {\n\t\t\t\t\tstyledText.selectAll();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t}\n\t\t});\n\t\t// 剪切菜单的点击事件\n\t\tcut.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tif (styledText.getSelectionCount() == 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tClipboard clipboard = new Clipboard(styledText.getDisplay());\n\t\t\t\tString plainText = styledText.getSelectionText();\n\t\t\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\t\t\tclipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer });\n\t\t\t\tclipboard.dispose();\n\t\t\t\t// 将已经剪切走的部分删除,并将插入符移动到剪切位置\n\t\t\t\tint caretOffset = styledText.getSelection().x;\n\t\t\t\tstyledText.setText(new StringBuffer(styledText.getText())\n\t\t\t\t\t\t.replace(styledText.getSelection().x, styledText.getSelection().y, \"\").toString());\n\t\t\t\tstyledText.setCaretOffset(caretOffset);\n\t\t\t}\n\t\t});\n\n\t\t// 粘贴菜单的点击事件\n\t\tpaste.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tClipboard clipboard = new Clipboard(styledText.getDisplay());\n\t\t\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\t\t\t// 获取剪切板上的文本\n\t\t\t\tString cliptext = (clipboard.getContents(textTransfer) != null\n\t\t\t\t\t\t? clipboard.getContents(textTransfer).toString() : \"\");\n\t\t\t\tclipboard.dispose();\n\t\t\t\tint caretOffset = styledText.getSelection().x;\n\t\t\t\tstyledText.setText(new StringBuffer(styledText.getText())\n\t\t\t\t\t\t.replace(styledText.getSelection().x, styledText.getSelection().y, cliptext).toString());\n\t\t\t\tstyledText.setCaretOffset(caretOffset + cliptext.length());\n\t\t\t}\n\t\t});\n\n\t\t// 复制上下文菜单的点击事件\n\t\tcopy.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tif (styledText.getSelectionCount() == 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tClipboard clipboard = new Clipboard(styledText.getDisplay());\n\t\t\t\tString plainText = styledText.getSelectionText();\n\t\t\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\t\t\tclipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer });\n\t\t\t\tclipboard.dispose();\n\t\t\t}\n\t\t});\n\n\t\t// 全选上下文菜单的点击事件\n\t\tallSelect.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tstyledText.selectAll();\n\t\t\t}\n\t\t});\n\n\t\t// 清空上下文菜单的点击事件\n\t\tclear.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tstyledText.setText(\"\");\n\t\t\t}\n\t\t});\n\n\t\t// 更改是否自动换行\n\t\twarp.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tif (styledText.getWordWrap()) {\n\t\t\t\t\tstyledText.setWordWrap(false);\n\t\t\t\t\twarp.setText(\"打开自动换行\");\n\t\t\t\t} else {\n\t\t\t\t\tstyledText.setWordWrap(true);\n\t\t\t\t\twarp.setText(\"关闭自动换行\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static void DropTargetSupport(Shell shell) {\n\n\t\tDropTarget dropTarget = new DropTarget(shell, DND.DROP_NONE);\n\t\tTransfer[] transfer = new Transfer[] { FileTransfer.getInstance() };\n\t\tdropTarget.setTransfer(transfer);\n\t\t// 拖拽监听\n\t\tdropTarget.addDropListener(new DropTargetListener() {\n\t\t\t@Override\n\t\t\tpublic void dragEnter(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dragLeave(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dragOperationChanged(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dragOver(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t// 获取拖放进来的文件,暂无用途\n\t\t\t@Override\n\t\t\tpublic void drop(DropTargetEvent event) {\n\t\t\t\tString[] files = (String[]) event.data;\n\t\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\t\t@SuppressWarnings(\"unused\")\n\t\t\t\t\tFile file = new File(files[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void dropAccept(DropTargetEvent event) {\n\t\t\t}\n\t\t});\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/com/itlaborer/utils/ApiUtils.java"},"old_contents":{"kind":"string","value":"package com.itlaborer.utils;\n\nimport java.awt.Toolkit;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.StringWriter;\nimport java.io.UnsupportedEncodingException;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.Charset;\nimport java.security.MessageDigest;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.log4j.Logger;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.dnd.Clipboard;\nimport org.eclipse.swt.dnd.DND;\nimport org.eclipse.swt.dnd.DropTarget;\nimport org.eclipse.swt.dnd.DropTargetEvent;\nimport org.eclipse.swt.dnd.DropTargetListener;\nimport org.eclipse.swt.dnd.FileTransfer;\nimport org.eclipse.swt.dnd.TextTransfer;\nimport org.eclipse.swt.dnd.Transfer;\nimport org.eclipse.swt.events.KeyEvent;\nimport org.eclipse.swt.events.KeyListener;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.widgets.Menu;\nimport org.eclipse.swt.widgets.MenuItem;\nimport org.eclipse.swt.widgets.Shell;\n\nimport net.dongliu.requests.RawResponse;\nimport net.dongliu.requests.Requests;\n\n/**\n * \n * 工具类\n * \n * @author liu\n *\n */\npublic class ApiUtils {\n\n\tprivate static Logger logger = Logger.getLogger(ApiUtils.class.getName());\n\n\tpublic ApiUtils() {\n\t}\n\n\t// MD5字符串算法\n\tpublic final static String MD5(String s) {\n\n\t\tchar hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n\t\ttry {\n\t\t\tbyte[] btInput = s.getBytes();\n\t\t\tMessageDigest mdInst = MessageDigest.getInstance(\"MD5\");\n\t\t\tmdInst.update(btInput);\n\t\t\tbyte[] md = mdInst.digest();\n\t\t\tint j = md.length;\n\t\t\tchar str[] = new char[j * 2];\n\t\t\tint k = 0;\n\t\t\tfor (int i = 0; i < j; i++) {\n\t\t\t\tbyte byte0 = md[i];\n\t\t\t\tstr[k++] = hexDigits[byte0 >>> 4 & 0xf];\n\t\t\t\tstr[k++] = hexDigits[byte0 & 0xf];\n\t\t\t}\n\t\t\treturn new String(str);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"异常\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t// HTTP GET 忽略证书安全\n\tpublic static RawResponse HttpGet(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.get(url).verify(false).headers(header).cookies(cookies).params(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP POST 忽略证书安全\n\tpublic static RawResponse HttpPost(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.post(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP HEAD 忽略证书安全\n\tpublic static RawResponse HttpHead(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.head(url).verify(false).headers(header).cookies(cookies).params(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP PUT 忽略证书安全\n\tpublic static RawResponse HttpPut(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.put(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP PATCH 忽略证书安全\n\tpublic static RawResponse HttpPatch(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.patch(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// HTTP DELETE 忽略证书安全\n\tpublic static RawResponse HttpDelete(String url, HashMap parameter,\n\t\t\tLinkedHashMap header, LinkedHashMap cookies, Charset requestCharset)\n\t\t\tthrows Exception {\n\t\tRawResponse resp = Requests.delete(url).verify(false).headers(header).cookies(cookies).forms(parameter)\n\t\t\t\t.requestCharset(requestCharset).send();\n\t\treturn resp;\n\t}\n\n\t// 设置程序窗口居中\n\tpublic static void SetCenter(Shell shell) {\n\t\tint screenH = Toolkit.getDefaultToolkit().getScreenSize().height;\n\t\tint screenW = Toolkit.getDefaultToolkit().getScreenSize().width;\n\t\tint shellH = shell.getBounds().height;\n\t\tint shellW = shell.getBounds().width;\n\t\tif (shellH > screenH) {\n\t\t\tshellH = screenH;\n\t\t}\n\t\tif (shellW > screenW) {\n\t\t\tshellW = screenW;\n\t\t}\n\t\tshell.setLocation(((screenW - shellW) / 2), ((screenH - shellH) / 2));\n\t}\n\n\t// 设置程序窗口居中于父窗口\n\tpublic static void SetCenterinParent(Shell parentshell, Shell shell) {\n\t\tint screenH = Toolkit.getDefaultToolkit().getScreenSize().height;\n\t\tint screenW = Toolkit.getDefaultToolkit().getScreenSize().width;\n\t\tint shellH = shell.getBounds().height;\n\t\tint shellW = shell.getBounds().width;\n\t\t// 如果窗口大小超过屏幕大小,调整为屏幕大小\n\t\tif (shellH > screenH) {\n\t\t\tshellH = screenH;\n\t\t}\n\t\tif (shellW > screenW) {\n\t\t\tshellW = screenW;\n\t\t}\n\t\tint targetx = parentshell.getLocation().x + parentshell.getBounds().width / 2 - shell.getBounds().width / 2;\n\t\tint targety = parentshell.getLocation().y + parentshell.getBounds().height / 2 - shell.getBounds().height / 2;\n\t\tif (targetx + shellW > screenW) {\n\t\t\ttargetx = screenW - shellW;\n\t\t}\n\t\tif (targety + shellH > screenH) {\n\t\t\ttargety = screenH - shellH;\n\t\t}\n\t\tshell.setLocation(targetx, targety);\n\t}\n\n\t// 读取文件到String字符串\n\tpublic static String ReadFromFile(File file, String encoding) {\n\t\tInputStreamReader reader = null;\n\t\tStringWriter writer = new StringWriter();\n\t\ttry {\n\t\t\tif (encoding == null || \"\".equals(encoding.trim())) {\n\t\t\t\treader = new InputStreamReader(new FileInputStream(file), encoding);\n\t\t\t} else {\n\t\t\t\treader = new InputStreamReader(new FileInputStream(file));\n\t\t\t}\n\t\t\tchar[] buffer = new char[4096];\n\t\t\tint n = 0;\n\t\t\twhile (-1 != (n = reader.read(buffer))) {\n\t\t\t\twriter.write(buffer, 0, n);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"异常\", e);\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tif (reader != null)\n\t\t\t\ttry {\n\t\t\t\t\treader.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogger.error(\"异常\", e);\n\t\t\t\t}\n\t\t}\n\t\treturn writer.toString();\n\t}\n\n\t// String保存到文件方法\n\tpublic static boolean SaveToFile(File file, String content) {\n\t\tFileWriter fwriter = null;\n\t\ttry {\n\t\t\tfwriter = new FileWriter(file);\n\t\t\tfwriter.write(content);\n\t\t\tfwriter.flush();\n\t\t\tfwriter.close();\n\t\t\treturn true;\n\t\t} catch (Exception ex) {\n\t\t\tlogger.error(\"捕获异常\", ex);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// 文件复制方法\n\tpublic static long CopyFile(File f1, File f2) throws Exception {\n\t\tlong time = new Date().getTime();\n\t\tint length = 2097152;\n\t\tFileInputStream in = new FileInputStream(f1);\n\t\tFileOutputStream out = new FileOutputStream(f2);\n\t\tbyte[] buffer = new byte[length];\n\t\twhile (true) {\n\t\t\tint ins = in.read(buffer);\n\t\t\tif (ins == -1) {\n\t\t\t\tin.close();\n\t\t\t\tout.flush();\n\t\t\t\tout.close();\n\t\t\t\treturn new Date().getTime() - time;\n\t\t\t} else\n\t\t\t\tout.write(buffer, 0, ins);\n\t\t}\n\t}\n\n\t// String编码转换方法\n\tpublic static String GetUTF8StringFromGBKString(String gbkStr) {\n\t\ttry {\n\t\t\treturn new String(GetUTF8BytesFromGBKString(gbkStr), \"UTF-8\");\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new InternalError();\n\t\t}\n\t}\n\n\t// GBK字符串转换到UTF-8\n\tpublic static byte[] GetUTF8BytesFromGBKString(String gbkStr) {\n\t\tint n = gbkStr.length();\n\t\tbyte[] utfBytes = new byte[3 * n];\n\t\tint k = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint m = gbkStr.charAt(i);\n\t\t\tif (m < 128 && m >= 0) {\n\t\t\t\tutfBytes[k++] = (byte) m;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tutfBytes[k++] = (byte) (0xe0 | (m >> 12));\n\t\t\tutfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));\n\t\t\tutfBytes[k++] = (byte) (0x80 | (m & 0x3f));\n\t\t}\n\t\tif (k < utfBytes.length) {\n\t\t\tbyte[] tmp = new byte[k];\n\t\t\tSystem.arraycopy(utfBytes, 0, tmp, 0, k);\n\t\t\treturn tmp;\n\t\t}\n\t\treturn utfBytes;\n\t}\n\n\t// 删除文件夹的方法\n\tpublic static boolean DeleteDir(File dir) {\n\t\tif (dir.isDirectory()) {\n\t\t\tString[] children = dir.list();\n\t\t\tfor (int i = 0; i < children.length; i++) {\n\t\t\t\tboolean success = DeleteDir(new File(dir, children[i]));\n\t\t\t\tif (!success) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dir.delete();\n\t}\n\n\t// 字符串转unicode\n\tpublic static String string2Unicode(String string) {\n\n\t\tStringBuffer unicode = new StringBuffer();\n\t\tfor (int i = 0; i < string.length(); i++) {\n\t\t\t// 取出每一个字符\n\t\t\tchar c = string.charAt(i);\n\t\t\tString unicodestring = Integer.toHexString(c);\n\t\t\t// 英文的话,要补全四位\n\t\t\tif (unicodestring.length() == 2) {\n\t\t\t\tunicodestring = \"00\" + unicodestring;\n\t\t\t}\n\t\t\t// 转换为unicode\n\t\t\tunicode.append(\"\\\\u\" + unicodestring);\n\t\t}\n\t\treturn unicode.toString();\n\t}\n\n\t// 字符串转unicode-只转换中日韩\n\tpublic static String stringzh2Unicode(String string) {\n\n\t\tStringBuffer unicode = new StringBuffer();\n\t\tfor (int i = 0; i < string.length(); i++) {\n\t\t\t// 取出每一个字符\n\t\t\tchar c = string.charAt(i);\n\t\t\t// 转换为unicode\n\t\t\tif (isChinese(c)) {\n\t\t\t\tunicode.append(\"\\\\u\" + Integer.toHexString(c));\n\t\t\t} else {\n\t\t\t\tunicode.append(c);\n\t\t\t}\n\t\t}\n\t\treturn unicode.toString();\n\t}\n\n\t// unicode串解码\n\tpublic static String unicode2String(String str) {\n\n\t\tCharset set = Charset.forName(\"UTF-16\");\n\t\tPattern p = Pattern.compile(\"\\\\\\\\u([0-9a-fA-F]{4})\");\n\t\tMatcher m = p.matcher(str);\n\t\tint start = 0;\n\t\tint start2 = 0;\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile (m.find(start)) {\n\t\t\tstart2 = m.start();\n\t\t\tif (start2 > start) {\n\t\t\t\tString seg = str.substring(start, start2);\n\t\t\t\tsb.append(seg);\n\t\t\t}\n\t\t\tString code = m.group(1);\n\t\t\tint i = Integer.valueOf(code, 16);\n\t\t\tbyte[] bb = new byte[4];\n\t\t\tbb[0] = (byte) ((i >> 8) & 0xFF);\n\t\t\tbb[1] = (byte) (i & 0xFF);\n\t\t\tByteBuffer b = ByteBuffer.wrap(bb);\n\t\t\tsb.append(String.valueOf(set.decode(b)).trim());\n\t\t\tstart = m.end();\n\t\t}\n\t\tstart2 = str.length();\n\t\tif (start2 > start) {\n\t\t\tString seg = str.substring(start, start2);\n\t\t\tsb.append(seg);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t// 判断字符是否是中日韩字符\n\tprivate static final boolean isChinese(char c) {\n\t\tCharacter.UnicodeBlock ub = Character.UnicodeBlock.of(c);\n\t\tif (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS\n\t\t\t\t|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS\n\t\t\t\t|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A\n\t\t\t\t|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION\n\t\t\t\t|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION\n\t\t\t\t|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t// 给不支持右键菜单的StyledText添加右键菜单\n\tpublic static void StyledTextAddContextMenu(StyledText styledText) {\n\t\tMenu popupMenu = new Menu(styledText);\n\t\tMenuItem cut = new MenuItem(popupMenu, SWT.NONE);\n\t\tcut.setText(\"剪切\");\n\t\tMenuItem copy = new MenuItem(popupMenu, SWT.NONE);\n\t\tcopy.setText(\"复制\");\n\t\tMenuItem paste = new MenuItem(popupMenu, SWT.NONE);\n\t\tpaste.setText(\"粘贴\");\n\t\tMenuItem allSelect = new MenuItem(popupMenu, SWT.NONE);\n\t\tallSelect.setText(\"全选\");\n\t\tMenuItem clear = new MenuItem(popupMenu, SWT.NONE);\n\t\tclear.setText(\"清空\");\n\t\tMenuItem warp = new MenuItem(popupMenu, SWT.NONE);\n\t\twarp.setText(\"自动换行\");\n\t\tstyledText.setMenu(popupMenu);\n\n\t\t// 判断初始自动换行状态\n\t\tif (styledText.getWordWrap()) {\n\t\t\twarp.setText(\"关闭自动换行\");\n\t\t} else {\n\t\t\twarp.setText(\"打开自动换行\");\n\t\t}\n\t\tstyledText.addKeyListener(new KeyListener() {\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent e) {\n\t\t\t\tif (e.stateMask == SWT.CTRL && e.keyCode == 'a') {\n\t\t\t\t\tstyledText.selectAll();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent e) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t}\n\t\t});\n\t\t// 剪切菜单的点击事件\n\t\tcut.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tif (styledText.getSelectionCount() == 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tClipboard clipboard = new Clipboard(styledText.getDisplay());\n\t\t\t\tString plainText = styledText.getSelectionText();\n\t\t\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\t\t\tclipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer });\n\t\t\t\tclipboard.dispose();\n\t\t\t\t// 将已经剪切走的部分删除,并将插入符移动到剪切位置\n\t\t\t\tint caretOffset = styledText.getSelection().x;\n\t\t\t\tstyledText.setText(new StringBuffer(styledText.getText())\n\t\t\t\t\t\t.replace(styledText.getSelection().x, styledText.getSelection().y, \"\").toString());\n\t\t\t\tstyledText.setCaretOffset(caretOffset);\n\t\t\t}\n\t\t});\n\n\t\t// 粘贴菜单的点击事件\n\t\tpaste.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tClipboard clipboard = new Clipboard(styledText.getDisplay());\n\t\t\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\t\t\t// 获取剪切板上的文本\n\t\t\t\tString cliptext = (clipboard.getContents(textTransfer) != null\n\t\t\t\t\t\t? clipboard.getContents(textTransfer).toString() : \"\");\n\t\t\t\tclipboard.dispose();\n\t\t\t\tint caretOffset = styledText.getSelection().x;\n\t\t\t\tstyledText.setText(new StringBuffer(styledText.getText())\n\t\t\t\t\t\t.replace(styledText.getSelection().x, styledText.getSelection().y, cliptext).toString());\n\t\t\t\tstyledText.setCaretOffset(caretOffset + cliptext.length());\n\t\t\t}\n\t\t});\n\n\t\t// 复制上下文菜单的点击事件\n\t\tcopy.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tif (styledText.getSelectionCount() == 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tClipboard clipboard = new Clipboard(styledText.getDisplay());\n\t\t\t\tString plainText = styledText.getSelectionText();\n\t\t\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\t\t\tclipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer });\n\t\t\t\tclipboard.dispose();\n\t\t\t}\n\t\t});\n\n\t\t// 全选上下文菜单的点击事件\n\t\tallSelect.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tstyledText.selectAll();\n\t\t\t}\n\t\t});\n\n\t\t// 清空上下文菜单的点击事件\n\t\tclear.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tstyledText.setText(\"\");\n\t\t\t}\n\t\t});\n\n\t\t// 更改是否自动换行\n\t\twarp.addSelectionListener(new SelectionAdapter() {\n\t\t\t@Override\n\t\t\tpublic void widgetSelected(SelectionEvent e) {\n\t\t\t\tif (styledText.getWordWrap()) {\n\t\t\t\t\tstyledText.setWordWrap(false);\n\t\t\t\t\twarp.setText(\"打开自动换行\");\n\t\t\t\t} else {\n\t\t\t\t\tstyledText.setWordWrap(true);\n\t\t\t\t\twarp.setText(\"关闭自动换行\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static void DropTargetSupport(Shell shell) {\n\n\t\tDropTarget dropTarget = new DropTarget(shell, DND.DROP_NONE);\n\t\tTransfer[] transfer = new Transfer[] { FileTransfer.getInstance() };\n\t\tdropTarget.setTransfer(transfer);\n\t\t// 拖拽监听\n\t\tdropTarget.addDropListener(new DropTargetListener() {\n\t\t\t@Override\n\t\t\tpublic void dragEnter(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dragLeave(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dragOperationChanged(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dragOver(DropTargetEvent event) {\n\t\t\t}\n\n\t\t\t// 获取拖放进来的文件,暂无用途\n\t\t\t@Override\n\t\t\tpublic void drop(DropTargetEvent event) {\n\t\t\t\tString[] files = (String[]) event.data;\n\t\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\t\t@SuppressWarnings(\"unused\")\n\t\t\t\t\tFile file = new File(files[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void dropAccept(DropTargetEvent event) {\n\t\t\t}\n\t\t});\n\t}\n}\n"},"message":{"kind":"string","value":"no commit message"},"old_file":{"kind":"string","value":"src/com/itlaborer/utils/ApiUtils.java"},"subject":{"kind":"string","value":"no commit message"}}},{"rowIdx":1292,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"3e2245a4266ac4e0a01fda752a58a67043ea91e6"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"rhdunn/marklogic-intellij-plugin"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2017 Reece H. Dunn\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 */\npackage uk.co.reecedunn.intellij.plugin.marklogic.tests.query;\n\nimport uk.co.reecedunn.intellij.plugin.marklogic.configuration.MarkLogicRunConfiguration;\nimport uk.co.reecedunn.intellij.plugin.marklogic.query.Function;\nimport uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilder;\nimport uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilderFactory;\nimport uk.co.reecedunn.intellij.plugin.marklogic.tests.configuration.ConfigurationTestCase;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n\n@SuppressWarnings(\"ConstantConditions\")\npublic class FunctionTest extends ConfigurationTestCase {\n public void testEval() {\n final String query = \"(1, 2, 3)\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"(1, 2, 3)\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := /\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testQueryWithDoubleQuotes() {\n final String query = \"1 || \\\"st\\\"\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"1 || \\\"\\\"st\\\"\\\"\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := /\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testQueryWithXmlEntities() {\n final String query = \"&amp;\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"&amp;amp;\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := /\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testQueryWithOptions() {\n final String query = \"(1, 2)\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n configuration.setContentDatabase(\"lorem\");\n configuration.setModuleDatabase(\"ipsum\");\n configuration.setModuleRoot(\"dolor\");\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"(1, 2)\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := \" +\n \"\" +\n \"{xdmp:database(\\\"lorem\\\")}\" +\n \"{xdmp:database(\\\"ipsum\\\")}\" +\n \"dolor\" +\n \"\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testNoVarsAndOptionsBuilder() {\n final String query = \"select * from authors\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.sql\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 8.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"select * from authors\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := ()\\n\" +\n \"return try { xdmp:sql($query) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n}\n"},"new_file":{"kind":"string","value":"src/test/java/uk/co/reecedunn/intellij/plugin/marklogic/tests/query/FunctionTest.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2017 Reece H. Dunn\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 */\npackage uk.co.reecedunn.intellij.plugin.marklogic.tests.query;\n\nimport uk.co.reecedunn.intellij.plugin.marklogic.configuration.MarkLogicRunConfiguration;\nimport uk.co.reecedunn.intellij.plugin.marklogic.query.Function;\nimport uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilder;\nimport uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilderFactory;\nimport uk.co.reecedunn.intellij.plugin.marklogic.tests.configuration.ConfigurationTestCase;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n\n@SuppressWarnings(\"ConstantConditions\")\npublic class FunctionTest extends ConfigurationTestCase {\n public void testEval() {\n final String query = \"(1, 2, 3)\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"(1, 2, 3)\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := /\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testQueryWithDoubleQuotes() {\n final String query = \"1 || \\\"st\\\"\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"1 || \\\"\\\"st\\\"\\\"\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := /\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testQueryWithXmlEntities() {\n final String query = \"&amp;\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"&amp;amp;\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := /\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testQueryWithOptions() {\n final String query = \"(1, 2)\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.xqy\", query));\n configuration.setContentDatabase(\"lorem\");\n configuration.setModuleDatabase(\"ipsum\");\n configuration.setModuleRoot(\"dolor\");\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"(1, 2)\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := \" +\n \"\" +\n \"{xdmp:database(\\\"lorem\\\")}\" +\n \"{xdmp:database(\\\"ipsum\\\")}\" +\n \"dolor\" +\n \"\\n\" +\n \"return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n\n public void testSQL() {\n final String query = \"select * from authors\";\n final MarkLogicRunConfiguration configuration = createConfiguration();\n configuration.setMainModuleFile(createVirtualFile(\"test.sql\", query));\n\n QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath());\n Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 8.0);\n\n StringBuilder builder = new StringBuilder();\n function.buildQuery(builder, configuration);\n\n final String expected =\n \"let $query := \\\"select * from authors\\\"\\n\" +\n \"let $vars := ()\\n\" +\n \"let $options := ()\\n\" +\n \"return try { xdmp:sql($query) } catch ($e) { $e }\\n\";\n assertThat(builder.toString(), is(expected));\n }\n}\n"},"message":{"kind":"string","value":"Rename the FunctionTest.testSQL to reflect what it is actually testing.\n"},"old_file":{"kind":"string","value":"src/test/java/uk/co/reecedunn/intellij/plugin/marklogic/tests/query/FunctionTest.java"},"subject":{"kind":"string","value":"Rename the FunctionTest.testSQL to reflect what it is actually testing."}}},{"rowIdx":1293,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"57d531265530f1d2b1ed192c8706877e54142ead"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra"},"new_contents":{"kind":"string","value":"/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.elasticsearch.common.xcontent;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport org.elasticsearch.common.CheckedSupplier;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.common.bytes.BytesReference;\nimport org.elasticsearch.common.xcontent.json.JsonXContent;\nimport org.elasticsearch.test.ESTestCase;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static java.util.Collections.emptyMap;\nimport static java.util.Collections.singletonMap;\nimport static org.hamcrest.Matchers.contains;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.instanceOf;\nimport static org.hamcrest.Matchers.isIn;\nimport static org.hamcrest.Matchers.nullValue;\n\npublic class XContentParserTests extends ESTestCase {\n\n public void testFloat() throws IOException {\n final XContentType xContentType = randomFrom(XContentType.values());\n\n final String field = randomAlphaOfLengthBetween(1, 5);\n final Float value = randomFloat();\n\n try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) {\n builder.startObject();\n if (randomBoolean()) {\n builder.field(field, value);\n } else {\n builder.field(field).value(value);\n }\n builder.endObject();\n\n final Number number;\n try (XContentParser parser = createParser(xContentType.xContent(), BytesReference.bytes(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(field, parser.currentName());\n assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());\n\n number = parser.numberValue();\n\n assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());\n assertNull(parser.nextToken());\n }\n\n assertEquals(value, number.floatValue(), 0.0f);\n\n if (xContentType == XContentType.CBOR) {\n // CBOR parses back a float\n assertTrue(number instanceof Float);\n } else {\n // JSON, YAML and SMILE parses back the float value as a double\n // This will change for SMILE in Jackson 2.9 where all binary based\n // formats will return a float\n assertTrue(number instanceof Double);\n }\n }\n }\n\n public void testReadList() throws IOException {\n assertThat(readList(\"{\\\"foo\\\": [\\\"bar\\\"]}\"), contains(\"bar\"));\n assertThat(readList(\"{\\\"foo\\\": [\\\"bar\\\",\\\"baz\\\"]}\"), contains(\"bar\", \"baz\"));\n assertThat(readList(\"{\\\"foo\\\": [1, 2, 3], \\\"bar\\\": 4}\"), contains(1, 2, 3));\n assertThat(readList(\"{\\\"foo\\\": [{\\\"bar\\\":1},{\\\"baz\\\":2},{\\\"qux\\\":3}]}\"), hasSize(3));\n assertThat(readList(\"{\\\"foo\\\": [null]}\"), contains(nullValue()));\n assertThat(readList(\"{\\\"foo\\\": []}\"), hasSize(0));\n assertThat(readList(\"{\\\"foo\\\": [1]}\"), contains(1));\n assertThat(readList(\"{\\\"foo\\\": [1,2]}\"), contains(1, 2));\n assertThat(readList(\"{\\\"foo\\\": [{},{},{},{}]}\"), hasSize(4));\n }\n\n public void testReadListThrowsException() throws IOException {\n // Calling XContentParser.list() or listOrderedMap() to read a simple\n // value or object should throw an exception\n assertReadListThrowsException(\"{\\\"foo\\\": \\\"bar\\\"}\");\n assertReadListThrowsException(\"{\\\"foo\\\": 1, \\\"bar\\\": 2}\");\n assertReadListThrowsException(\"{\\\"foo\\\": {\\\"bar\\\":\\\"baz\\\"}}\");\n }\n\n @SuppressWarnings(\"unchecked\")\n private List readList(String source) throws IOException {\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n return (List) (randomBoolean() ? parser.listOrderedMap() : parser.list());\n }\n }\n\n private void assertReadListThrowsException(String source) {\n try {\n readList(source);\n fail(\"should have thrown a parse exception\");\n } catch (Exception e) {\n assertThat(e, instanceOf(XContentParseException.class));\n assertThat(e.getMessage(), containsString(\"Failed to parse list\"));\n }\n }\n\n public void testReadMapStrings() throws IOException {\n Map map = readMapStrings(\"{\\\"foo\\\": {\\\"kbar\\\":\\\"vbar\\\"}}\");\n assertThat(map.get(\"kbar\"), equalTo(\"vbar\"));\n assertThat(map.size(), equalTo(1));\n map = readMapStrings(\"{\\\"foo\\\": {\\\"kbar\\\":\\\"vbar\\\", \\\"kbaz\\\":\\\"vbaz\\\"}}\");\n assertThat(map.get(\"kbar\"), equalTo(\"vbar\"));\n assertThat(map.get(\"kbaz\"), equalTo(\"vbaz\"));\n assertThat(map.size(), equalTo(2));\n map = readMapStrings(\"{\\\"foo\\\": {}}\");\n assertThat(map.size(), equalTo(0));\n }\n\n public void testMap() throws IOException {\n String source = \"{\\\"i\\\": {\\\"_doc\\\": {\\\"f1\\\": {\\\"type\\\": \\\"text\\\", \\\"analyzer\\\": \\\"english\\\"}, \" +\n \"\\\"f2\\\": {\\\"type\\\": \\\"object\\\", \\\"properties\\\": {\\\"sub1\\\": {\\\"type\\\": \\\"keyword\\\", \\\"foo\\\": 17}}}}}}\";\n Map f1 = new HashMap<>();\n f1.put(\"type\", \"text\");\n f1.put(\"analyzer\", \"english\");\n\n Map sub1 = new HashMap<>();\n sub1.put(\"type\", \"keyword\");\n sub1.put(\"foo\", 17);\n\n Map properties = new HashMap<>();\n properties.put(\"sub1\", sub1);\n\n Map f2 = new HashMap<>();\n f2.put(\"type\", \"object\");\n f2.put(\"properties\", properties);\n\n Map doc = new HashMap<>();\n doc.put(\"f1\", f1);\n doc.put(\"f2\", f2);\n\n Map expected = new HashMap<>();\n expected.put(\"_doc\", doc);\n\n Map i = new HashMap<>();\n i.put(\"i\", expected);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n Map map = parser.map();\n assertThat(map, equalTo(i));\n }\n }\n\n private Map readMapStrings(String source) throws IOException {\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n return randomBoolean() ? parser.mapStringsOrdered() : parser.mapStrings();\n }\n }\n\n @SuppressWarnings(\"deprecation\") // #isBooleanValueLenient() and #booleanValueLenient() are the test subjects\n public void testReadLenientBooleans() throws IOException {\n // allow String, boolean and int representations of lenient booleans\n String falsy = randomFrom(\"\\\"off\\\"\", \"\\\"no\\\"\", \"\\\"0\\\"\", \"0\", \"\\\"false\\\"\", \"false\");\n String truthy = randomFrom(\"\\\"on\\\"\", \"\\\"yes\\\"\", \"\\\"1\\\"\", \"1\", \"\\\"true\\\"\", \"true\");\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, \"{\\\"foo\\\": \" + falsy + \", \\\"bar\\\": \" + truthy + \"}\")) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, isIn(\n Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValueLenient());\n assertFalse(parser.booleanValueLenient());\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"bar\"));\n token = parser.nextToken();\n assertThat(token, isIn(\n Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValueLenient());\n assertTrue(parser.booleanValueLenient());\n }\n }\n\n public void testReadBooleansFailsForLenientBooleans() throws IOException {\n String falsy = randomFrom(\"\\\"off\\\"\", \"\\\"no\\\"\", \"\\\"0\\\"\", \"0\");\n String truthy = randomFrom(\"\\\"on\\\"\", \"\\\"yes\\\"\", \"\\\"1\\\"\", \"1\");\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, \"{\\\"foo\\\": \" + falsy + \", \\\"bar\\\": \" + truthy + \"}\")) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER)));\n assertFalse(parser.isBooleanValue());\n if (token.equals(XContentParser.Token.VALUE_STRING)) {\n expectThrows(IllegalArgumentException.class, parser::booleanValue);\n } else {\n expectThrows(JsonParseException.class, parser::booleanValue);\n }\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"bar\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER)));\n assertFalse(parser.isBooleanValue());\n if (token.equals(XContentParser.Token.VALUE_STRING)) {\n expectThrows(IllegalArgumentException.class, parser::booleanValue);\n } else {\n expectThrows(JsonParseException.class, parser::booleanValue);\n }\n }\n }\n\n public void testReadBooleans() throws IOException {\n String falsy = randomFrom(\"\\\"false\\\"\", \"false\");\n String truthy = randomFrom(\"\\\"true\\\"\", \"true\");\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, \"{\\\"foo\\\": \" + falsy + \", \\\"bar\\\": \" + truthy + \"}\")) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValue());\n assertFalse(parser.booleanValue());\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"bar\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValue());\n assertTrue(parser.booleanValue());\n }\n }\n\n public void testEmptyList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(Collections.emptyList(), parser.list());\n }\n }\n\n public void testSimpleList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .value(1)\n .value(3)\n .value(0)\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(Arrays.asList(1, 3, 0), parser.list());\n }\n }\n\n public void testNestedList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .startArray().endArray()\n .startArray().value(1).value(3).endArray()\n .startArray().value(2).endArray()\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(\n Arrays.asList(Collections.emptyList(), Arrays.asList(1, 3), Arrays.asList(2)),\n parser.list());\n }\n }\n\n public void testNestedMapInList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .startObject().field(\"foo\", \"bar\").endObject()\n .startObject().endObject()\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(\n Arrays.asList(singletonMap(\"foo\", \"bar\"), emptyMap()),\n parser.list());\n }\n }\n\n public void testSubParserObject() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n int numberOfTokens;\n numberOfTokens = generateRandomObjectForMarking(builder);\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field\n assertEquals(\"first_field\", parser.currentName());\n assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); // foo\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // marked field\n assertEquals(\"marked_field\", parser.currentName());\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); // {\n XContentParser subParser = new XContentSubParser(parser);\n try {\n int tokensToSkip = randomInt(numberOfTokens - 1);\n for (int i = 0; i < tokensToSkip; i++) {\n // Simulate incomplete parsing\n assertNotNull(subParser.nextToken());\n }\n if (randomBoolean()) {\n // And sometimes skipping children\n subParser.skipChildren();\n }\n\n } finally {\n assertFalse(subParser.isClosed());\n subParser.close();\n assertTrue(subParser.isClosed());\n }\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // last field\n assertEquals(\"last_field\", parser.currentName());\n assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken());\n assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());\n assertNull(parser.nextToken());\n }\n }\n\n public void testSubParserArray() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n int numberOfArrayElements = randomInt(10);\n builder.startObject();\n builder.field(\"array\");\n builder.startArray();\n int numberOfTokens = 0;\n for (int i = 0; i < numberOfArrayElements; ++i) {\n numberOfTokens += generateRandomObject(builder, 0);\n }\n builder.endArray();\n builder.endObject();\n\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // array field\n assertEquals(\"array\", parser.currentName());\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); // [\n XContentParser subParser = new XContentSubParser(parser);\n try {\n int tokensToSkip = randomInt(numberOfTokens);\n for (int i = 0; i < tokensToSkip; i++) {\n // Simulate incomplete parsing\n assertNotNull(subParser.nextToken());\n }\n if (randomBoolean()) {\n // And sometimes skipping children\n subParser.skipChildren();\n }\n\n } finally {\n assertFalse(subParser.isClosed());\n subParser.close();\n assertTrue(subParser.isClosed());\n }\n assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken());\n assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());\n assertNull(parser.nextToken());\n }\n }\n\n public void testCreateSubParserAtAWrongPlace() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n generateRandomObjectForMarking(builder);\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field\n assertEquals(\"first_field\", parser.currentName());\n IllegalStateException exception = expectThrows(IllegalStateException.class, () -> new XContentSubParser(parser));\n assertEquals(\"The sub parser has to be created on the start of an object or array\", exception.getMessage());\n }\n }\n\n\n public void testCreateRootSubParser() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n int numberOfTokens = generateRandomObjectForMarking(builder);\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n try (XContentParser subParser = new XContentSubParser(parser)) {\n int tokensToSkip = randomInt(numberOfTokens + 3);\n for (int i = 0; i < tokensToSkip; i++) {\n // Simulate incomplete parsing\n assertNotNull(subParser.nextToken());\n }\n }\n assertNull(parser.nextToken());\n }\n\n }\n\n /**\n * Generates a random object {\"first_field\": \"foo\", \"marked_field\": {...random...}, \"last_field\": \"bar}\n *\n * Returns the number of tokens in the marked field\n */\n private int generateRandomObjectForMarking(XContentBuilder builder) throws IOException {\n builder.startObject()\n .field(\"first_field\", \"foo\")\n .field(\"marked_field\");\n int numberOfTokens = generateRandomObject(builder, 0);\n builder.field(\"last_field\", \"bar\").endObject();\n return numberOfTokens;\n }\n\n private int generateRandomObject(XContentBuilder builder, int level) throws IOException {\n int tokens = 2;\n builder.startObject();\n int numberOfElements = randomInt(5);\n for (int i = 0; i < numberOfElements; i++) {\n builder.field(randomAlphaOfLength(10) + \"_\" + i);\n tokens += generateRandomValue(builder, level + 1);\n }\n builder.endObject();\n return tokens;\n }\n\n private int generateRandomValue(XContentBuilder builder, int level) throws IOException {\n @SuppressWarnings(\"unchecked\") CheckedSupplier fieldGenerator = randomFrom(\n () -> {\n builder.value(randomInt());\n return 1;\n },\n () -> {\n builder.value(randomAlphaOfLength(10));\n return 1;\n },\n () -> {\n builder.value(randomDouble());\n return 1;\n },\n () -> {\n if (level < 3) {\n // don't need to go too deep\n return generateRandomObject(builder, level + 1);\n } else {\n builder.value(0);\n return 1;\n }\n },\n () -> {\n if (level < 5) { // don't need to go too deep\n return generateRandomArray(builder, level);\n } else {\n builder.value(0);\n return 1;\n }\n }\n );\n return fieldGenerator.get();\n }\n\n private int generateRandomArray(XContentBuilder builder, int level) throws IOException {\n int tokens = 2;\n int arraySize = randomInt(3);\n builder.startArray();\n for (int i = 0; i < arraySize; i++) {\n tokens += generateRandomValue(builder, level + 1);\n }\n builder.endArray();\n return tokens;\n }\n\n}\n"},"new_file":{"kind":"string","value":"libs/x-content/src/test/java/org/elasticsearch/common/xcontent/XContentParserTests.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\npackage org.elasticsearch.common.xcontent;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport org.elasticsearch.common.CheckedSupplier;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.common.bytes.BytesReference;\nimport org.elasticsearch.common.xcontent.json.JsonXContent;\nimport org.elasticsearch.test.ESTestCase;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static java.util.Collections.emptyMap;\nimport static java.util.Collections.singletonMap;\nimport static org.hamcrest.Matchers.contains;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.hasSize;\nimport static org.hamcrest.Matchers.instanceOf;\nimport static org.hamcrest.Matchers.isIn;\nimport static org.hamcrest.Matchers.nullValue;\n\npublic class XContentParserTests extends ESTestCase {\n\n public void testFloat() throws IOException {\n final XContentType xContentType = randomFrom(XContentType.values());\n\n final String field = randomAlphaOfLengthBetween(1, 5);\n final Float value = randomFloat();\n\n try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) {\n builder.startObject();\n if (randomBoolean()) {\n builder.field(field, value);\n } else {\n builder.field(field).value(value);\n }\n builder.endObject();\n\n final Number number;\n try (XContentParser parser = createParser(xContentType.xContent(), BytesReference.bytes(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(field, parser.currentName());\n assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());\n\n number = parser.numberValue();\n\n assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());\n assertNull(parser.nextToken());\n }\n\n assertEquals(value, number.floatValue(), 0.0f);\n\n if (xContentType == XContentType.CBOR) {\n // CBOR parses back a float\n assertTrue(number instanceof Float);\n } else {\n // JSON, YAML and SMILE parses back the float value as a double\n // This will change for SMILE in Jackson 2.9 where all binary based\n // formats will return a float\n assertTrue(number instanceof Double);\n }\n }\n }\n\n public void testReadList() throws IOException {\n assertThat(readList(\"{\\\"foo\\\": [\\\"bar\\\"]}\"), contains(\"bar\"));\n assertThat(readList(\"{\\\"foo\\\": [\\\"bar\\\",\\\"baz\\\"]}\"), contains(\"bar\", \"baz\"));\n assertThat(readList(\"{\\\"foo\\\": [1, 2, 3], \\\"bar\\\": 4}\"), contains(1, 2, 3));\n assertThat(readList(\"{\\\"foo\\\": [{\\\"bar\\\":1},{\\\"baz\\\":2},{\\\"qux\\\":3}]}\"), hasSize(3));\n assertThat(readList(\"{\\\"foo\\\": [null]}\"), contains(nullValue()));\n assertThat(readList(\"{\\\"foo\\\": []}\"), hasSize(0));\n assertThat(readList(\"{\\\"foo\\\": [1]}\"), contains(1));\n assertThat(readList(\"{\\\"foo\\\": [1,2]}\"), contains(1, 2));\n assertThat(readList(\"{\\\"foo\\\": [{},{},{},{}]}\"), hasSize(4));\n }\n\n public void testReadListThrowsException() throws IOException {\n // Calling XContentParser.list() or listOrderedMap() to read a simple\n // value or object should throw an exception\n assertReadListThrowsException(\"{\\\"foo\\\": \\\"bar\\\"}\");\n assertReadListThrowsException(\"{\\\"foo\\\": 1, \\\"bar\\\": 2}\");\n assertReadListThrowsException(\"{\\\"foo\\\": {\\\"bar\\\":\\\"baz\\\"}}\");\n }\n\n @SuppressWarnings(\"unchecked\")\n private List readList(String source) throws IOException {\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n return (List) (randomBoolean() ? parser.listOrderedMap() : parser.list());\n }\n }\n\n private void assertReadListThrowsException(String source) {\n try {\n readList(source);\n fail(\"should have thrown a parse exception\");\n } catch (Exception e) {\n assertThat(e, instanceOf(XContentParseException.class));\n assertThat(e.getMessage(), containsString(\"Failed to parse list\"));\n }\n }\n\n public void testReadMapStrings() throws IOException {\n Map map = readMapStrings(\"{\\\"foo\\\": {\\\"kbar\\\":\\\"vbar\\\"}}\");\n assertThat(map.get(\"kbar\"), equalTo(\"vbar\"));\n assertThat(map.size(), equalTo(1));\n map = readMapStrings(\"{\\\"foo\\\": {\\\"kbar\\\":\\\"vbar\\\", \\\"kbaz\\\":\\\"vbaz\\\"}}\");\n assertThat(map.get(\"kbar\"), equalTo(\"vbar\"));\n assertThat(map.get(\"kbaz\"), equalTo(\"vbaz\"));\n assertThat(map.size(), equalTo(2));\n map = readMapStrings(\"{\\\"foo\\\": {}}\");\n assertThat(map.size(), equalTo(0));\n }\n\n public void testMap() throws IOException {\n String source = \"{\\\"i\\\": {\\\"_doc\\\": {\\\"f1\\\": {\\\"type\\\": \\\"text\\\", \\\"analyzer\\\": \\\"english\\\"}, \" +\n \"\\\"f2\\\": {\\\"type\\\": \\\"object\\\", \\\"properties\\\": {\\\"sub1\\\": {\\\"type\\\": \\\"keyword\\\", \\\"foo\\\": 17}}}}}}\";\n Map f1 = new HashMap<>();\n f1.put(\"type\", \"text\");\n f1.put(\"analyzer\", \"english\");\n\n Map sub1 = new HashMap<>();\n sub1.put(\"type\", \"keyword\");\n sub1.put(\"foo\", 17);\n\n Map properties = new HashMap<>();\n properties.put(\"sub1\", sub1);\n\n Map f2 = new HashMap<>();\n f2.put(\"type\", \"object\");\n f2.put(\"properties\", properties);\n\n Map doc = new HashMap<>();\n doc.put(\"f1\", f1);\n doc.put(\"f2\", f2);\n\n Map expected = new HashMap<>();\n expected.put(\"_doc\", doc);\n\n Map i = new HashMap<>();\n i.put(\"i\", expected);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n Map map = parser.map();\n assertThat(map, equalTo(i));\n }\n }\n\n private Map readMapStrings(String source) throws IOException {\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n return randomBoolean() ? parser.mapStringsOrdered() : parser.mapStrings();\n }\n }\n\n @SuppressWarnings(\"deprecation\") // #isBooleanValueLenient() and #booleanValueLenient() are the test subjects\n public void testReadLenientBooleans() throws IOException {\n // allow String, boolean and int representations of lenient booleans\n String falsy = randomFrom(\"\\\"off\\\"\", \"\\\"no\\\"\", \"\\\"0\\\"\", \"0\", \"\\\"false\\\"\", \"false\");\n String truthy = randomFrom(\"\\\"on\\\"\", \"\\\"yes\\\"\", \"\\\"1\\\"\", \"1\", \"\\\"true\\\"\", \"true\");\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, \"{\\\"foo\\\": \" + falsy + \", \\\"bar\\\": \" + truthy + \"}\")) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, isIn(\n Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValueLenient());\n assertFalse(parser.booleanValueLenient());\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"bar\"));\n token = parser.nextToken();\n assertThat(token, isIn(\n Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValueLenient());\n assertTrue(parser.booleanValueLenient());\n }\n }\n\n public void testReadBooleansFailsForLenientBooleans() throws IOException {\n String falsy = randomFrom(\"\\\"off\\\"\", \"\\\"no\\\"\", \"\\\"0\\\"\", \"0\");\n String truthy = randomFrom(\"\\\"on\\\"\", \"\\\"yes\\\"\", \"\\\"1\\\"\", \"1\");\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, \"{\\\"foo\\\": \" + falsy + \", \\\"bar\\\": \" + truthy + \"}\")) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER)));\n assertFalse(parser.isBooleanValue());\n if (token.equals(XContentParser.Token.VALUE_STRING)) {\n expectThrows(IllegalArgumentException.class, parser::booleanValue);\n } else {\n expectThrows(JsonParseException.class, parser::booleanValue);\n }\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"bar\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER)));\n assertFalse(parser.isBooleanValue());\n if (token.equals(XContentParser.Token.VALUE_STRING)) {\n expectThrows(IllegalArgumentException.class, parser::booleanValue);\n } else {\n expectThrows(JsonParseException.class, parser::booleanValue);\n }\n }\n }\n\n public void testReadBooleans() throws IOException {\n String falsy = randomFrom(\"\\\"false\\\"\", \"false\");\n String truthy = randomFrom(\"\\\"true\\\"\", \"true\");\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, \"{\\\"foo\\\": \" + falsy + \", \\\"bar\\\": \" + truthy + \"}\")) {\n XContentParser.Token token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.START_OBJECT));\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"foo\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValue());\n assertFalse(parser.booleanValue());\n\n token = parser.nextToken();\n assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));\n assertThat(parser.currentName(), equalTo(\"bar\"));\n token = parser.nextToken();\n assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN)));\n assertTrue(parser.isBooleanValue());\n assertTrue(parser.booleanValue());\n }\n }\n\n public void testEmptyList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(Collections.emptyList(), parser.list());\n }\n }\n\n public void testSimpleList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .value(1)\n .value(3)\n .value(0)\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(Arrays.asList(1, 3, 0), parser.list());\n }\n }\n\n public void testNestedList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .startArray().endArray()\n .startArray().value(1).value(3).endArray()\n .startArray().value(2).endArray()\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(\n Arrays.asList(Collections.emptyList(), Arrays.asList(1, 3), Arrays.asList(2)),\n parser.list());\n }\n }\n\n public void testNestedMapInList() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder().startObject()\n .startArray(\"some_array\")\n .startObject().field(\"foo\", \"bar\").endObject()\n .startObject().endObject()\n .endArray().endObject();\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());\n assertEquals(\"some_array\", parser.currentName());\n if (random().nextBoolean()) {\n // sometimes read the start array token, sometimes not\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());\n }\n assertEquals(\n Arrays.asList(singletonMap(\"foo\", \"bar\"), emptyMap()),\n parser.list());\n }\n }\n\n public void testSubParserObject() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n int numberOfTokens;\n numberOfTokens = generateRandomObjectForMarking(builder);\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field\n assertEquals(\"first_field\", parser.currentName());\n assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); // foo\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // marked field\n assertEquals(\"marked_field\", parser.currentName());\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); // {\n XContentParser subParser = new XContentSubParser(parser);\n try {\n int tokensToSkip = randomInt(numberOfTokens - 1);\n for (int i = 0; i < tokensToSkip; i++) {\n // Simulate incomplete parsing\n assertNotNull(subParser.nextToken());\n }\n if (randomBoolean()) {\n // And sometimes skipping children\n subParser.skipChildren();\n }\n\n } finally {\n assertFalse(subParser.isClosed());\n subParser.close();\n assertTrue(subParser.isClosed());\n }\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // last field\n assertEquals(\"last_field\", parser.currentName());\n assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken());\n assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());\n assertNull(parser.nextToken());\n }\n }\n\n public void testSubParserArray() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n int numberOfArrayElements = randomInt(10);\n builder.startObject();\n builder.field(\"array\");\n builder.startArray();\n int numberOfTokens = 0;\n for (int i = 0; i < numberOfArrayElements; ++i) {\n numberOfTokens += generateRandomObjectForMarking(builder);\n }\n builder.endArray();\n builder.endObject();\n\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // array field\n assertEquals(\"array\", parser.currentName());\n assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); // [\n XContentParser subParser = new XContentSubParser(parser);\n try {\n int tokensToSkip = randomInt(numberOfTokens - 1);\n for (int i = 0; i < tokensToSkip; i++) {\n // Simulate incomplete parsing\n assertNotNull(subParser.nextToken());\n }\n if (randomBoolean()) {\n // And sometimes skipping children\n subParser.skipChildren();\n }\n\n } finally {\n assertFalse(subParser.isClosed());\n subParser.close();\n assertTrue(subParser.isClosed());\n }\n assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken());\n assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());\n assertNull(parser.nextToken());\n }\n }\n\n public void testCreateSubParserAtAWrongPlace() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n generateRandomObjectForMarking(builder);\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field\n assertEquals(\"first_field\", parser.currentName());\n IllegalStateException exception = expectThrows(IllegalStateException.class, () -> new XContentSubParser(parser));\n assertEquals(\"The sub parser has to be created on the start of an object or array\", exception.getMessage());\n }\n }\n\n\n public void testCreateRootSubParser() throws IOException {\n XContentBuilder builder = XContentFactory.jsonBuilder();\n int numberOfTokens = generateRandomObjectForMarking(builder);\n String content = Strings.toString(builder);\n\n try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) {\n assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());\n try (XContentParser subParser = new XContentSubParser(parser)) {\n int tokensToSkip = randomInt(numberOfTokens + 3);\n for (int i = 0; i < tokensToSkip; i++) {\n // Simulate incomplete parsing\n assertNotNull(subParser.nextToken());\n }\n }\n assertNull(parser.nextToken());\n }\n\n }\n\n /**\n * Generates a random object {\"first_field\": \"foo\", \"marked_field\": {...random...}, \"last_field\": \"bar}\n *\n * Returns the number of tokens in the marked field\n */\n private int generateRandomObjectForMarking(XContentBuilder builder) throws IOException {\n builder.startObject()\n .field(\"first_field\", \"foo\")\n .field(\"marked_field\");\n int numberOfTokens = generateRandomObject(builder, 0);\n builder.field(\"last_field\", \"bar\").endObject();\n return numberOfTokens;\n }\n\n private int generateRandomObject(XContentBuilder builder, int level) throws IOException {\n int tokens = 2;\n builder.startObject();\n int numberOfElements = randomInt(5);\n for (int i = 0; i < numberOfElements; i++) {\n builder.field(randomAlphaOfLength(10) + \"_\" + i);\n tokens += generateRandomValue(builder, level + 1);\n }\n builder.endObject();\n return tokens;\n }\n\n private int generateRandomValue(XContentBuilder builder, int level) throws IOException {\n @SuppressWarnings(\"unchecked\") CheckedSupplier fieldGenerator = randomFrom(\n () -> {\n builder.value(randomInt());\n return 1;\n },\n () -> {\n builder.value(randomAlphaOfLength(10));\n return 1;\n },\n () -> {\n builder.value(randomDouble());\n return 1;\n },\n () -> {\n if (level < 3) {\n // don't need to go too deep\n return generateRandomObject(builder, level + 1);\n } else {\n builder.value(0);\n return 1;\n }\n },\n () -> {\n if (level < 5) { // don't need to go too deep\n return generateRandomArray(builder, level);\n } else {\n builder.value(0);\n return 1;\n }\n }\n );\n return fieldGenerator.get();\n }\n\n private int generateRandomArray(XContentBuilder builder, int level) throws IOException {\n int tokens = 2;\n int arraySize = randomInt(3);\n builder.startArray();\n for (int i = 0; i < arraySize; i++) {\n tokens += generateRandomValue(builder, level + 1);\n }\n builder.endArray();\n return tokens;\n }\n\n}\n"},"message":{"kind":"string","value":"Unmute and fix testSubParserArray (#40626)\n\ntestSubParserArray failed, fixed and improved to not always have an\r\nobject as outer-level inside array.\r\n\r\nCloses #40617"},"old_file":{"kind":"string","value":"libs/x-content/src/test/java/org/elasticsearch/common/xcontent/XContentParserTests.java"},"subject":{"kind":"string","value":"Unmute and fix testSubParserArray (#40626)"}}},{"rowIdx":1294,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24f70e9111d185318bff6f043f181c0637a40db9"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j"},"new_contents":{"kind":"string","value":"/**\n * Copyright (c) 2002-2011 \"Neo Technology,\"\n * Network Engine for Objects in Lund AB [http://neotechnology.com]\n *\n * This file is part of Neo4j.\n *\n * Neo4j is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\npackage org.neo4j.shell;\n\nimport static java.util.regex.Pattern.compile;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.neo4j.graphdb.DynamicRelationshipType.withName;\nimport static org.neo4j.helpers.collection.IteratorUtil.asCollection;\nimport static org.neo4j.kernel.impl.util.FileUtils.deleteRecursively;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.rmi.RemoteException;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.regex.Pattern;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Ignore;\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.NotFoundException;\nimport org.neo4j.graphdb.Relationship;\nimport org.neo4j.graphdb.RelationshipType;\nimport org.neo4j.graphdb.Transaction;\nimport org.neo4j.kernel.EmbeddedGraphDatabase;\nimport org.neo4j.shell.impl.RemoteOutput;\nimport org.neo4j.shell.impl.SameJvmClient;\nimport org.neo4j.shell.kernel.GraphDatabaseShellServer;\n\n@Ignore\npublic abstract class AbstractShellTest\n{\n private static final String DB_PATH = \"target/var/shelldb\";\n protected static GraphDatabaseService db;\n private static ShellServer shellServer;\n private ShellClient shellClient;\n protected static final RelationshipType RELATIONSHIP_TYPE = withName( \"TYPE\" );\n \n @BeforeClass\n public static void startUp() throws Exception\n {\n deleteRecursively( new File( DB_PATH ) );\n db = new EmbeddedGraphDatabase( DB_PATH );\n shellServer = new GraphDatabaseShellServer( db );\n }\n \n @Before\n public void doBefore()\n {\n shellClient = new SameJvmClient( shellServer );\n }\n \n @After\n public void doAfter()\n {\n shellClient.shutdown();\n }\n \n @AfterClass\n public static void shutDown() throws Exception\n {\n shellServer.shutdown();\n db.shutdown();\n }\n \n protected static String pwdOutputFor( Object... entities )\n {\n StringBuilder builder = new StringBuilder();\n for ( Object entity : entities )\n {\n builder.append( (builder.length() == 0 ? \"\" : \"-->\") );\n if ( entity instanceof Node )\n {\n builder.append( \"(\" + ((Node)entity).getId() + \")\" );\n }\n else\n {\n builder.append( \"<\" + ((Relationship)entity).getId() + \">\" );\n }\n }\n return Pattern.quote( builder.toString() );\n }\n \n public void executeCommand( String command, String... theseLinesMustExistRegEx ) throws Exception\n {\n OutputCollector output = new OutputCollector();\n shellServer.interpretLine( command, shellClient.session(), output );\n \n for ( String lineThatMustExist : theseLinesMustExistRegEx )\n {\n boolean negative = lineThatMustExist.startsWith( \"!\" );\n lineThatMustExist = negative ? lineThatMustExist.substring( 1 ) : lineThatMustExist;\n Pattern pattern = compile( lineThatMustExist );\n boolean found = false;\n for ( String line : output )\n {\n if ( pattern.matcher( line ).find() )\n {\n found = true;\n break;\n }\n }\n assertTrue( \"Was expecting a line matching '\" + lineThatMustExist + \"', but didn't find any from out of \" +\n asCollection( output ), found != negative );\n }\n }\n\n public void executeCommandExpectingException( String command, String errorMessageShouldContain ) throws Exception\n {\n OutputCollector output = new OutputCollector();\n try\n {\n shellServer.interpretLine( command, shellClient.session(), output );\n fail( \"Was expecting an exception\" );\n }\n catch ( ShellException e )\n {\n String errorMessage = e.getMessage();\n if ( !errorMessage.toLowerCase().contains( errorMessageShouldContain.toLowerCase() ) )\n {\n fail( \"Error message '\" + errorMessage + \"' should have contained '\" + errorMessageShouldContain + \"'\" );\n }\n }\n }\n \n protected void assertRelationshipExists( Relationship relationship )\n {\n assertRelationshipExists( relationship.getId() );\n }\n \n protected void assertRelationshipExists( long id )\n {\n db.getRelationshipById( id );\n }\n \n protected void assertRelationshipDoesnExist( Relationship relationship )\n {\n assertRelationshipDoesnExist( relationship.getId() );\n }\n \n protected void assertRelationshipDoesnExist( long id )\n {\n try\n {\n db.getRelationshipById( id );\n fail( \"Relationship \" + id + \" shouldn't exist\" );\n }\n catch ( NotFoundException e )\n { // Good\n }\n }\n \n protected Relationship[] createRelationshipChain( int length )\n {\n return createRelationshipChain( db.getReferenceNode(), length );\n }\n \n protected Relationship[] createRelationshipChain( Node startingFromNode, int length )\n {\n Relationship[] rels = new Relationship[length];\n Transaction tx = db.beginTx();\n Node firstNode = db.getReferenceNode();\n for ( int i = 0; i < rels.length; i++ )\n {\n Node secondNode = db.createNode();\n rels[i] = firstNode.createRelationshipTo( secondNode, RELATIONSHIP_TYPE );\n firstNode = secondNode;\n }\n tx.success();\n tx.finish();\n return rels;\n }\n \n protected void setProperty( Node node, String key, Object value )\n {\n Transaction tx = db.beginTx();\n node.setProperty( key, value );\n tx.success();\n tx.finish();\n }\n\n public class OutputCollector implements Output, Serializable, Iterable\n {\n private static final long serialVersionUID = 1L;\n private final List lines = new ArrayList();\n private String ongoingLine = \"\";\n\n @Override\n public Appendable append( CharSequence csq, int start, int end )\n throws IOException\n {\n this.print( RemoteOutput.asString( csq ).substring( start, end ) );\n return this;\n }\n\n @Override\n public Appendable append( char c ) throws IOException\n {\n this.print( c );\n return this;\n }\n\n @Override\n public Appendable append( CharSequence csq ) throws IOException\n {\n this.print( RemoteOutput.asString( csq ) );\n return this;\n }\n\n @Override\n public void println( Serializable object ) throws RemoteException\n {\n print( object );\n println();\n }\n\n @Override\n public void println() throws RemoteException\n {\n lines.add( ongoingLine );\n ongoingLine = \"\";\n }\n\n @Override\n public void print( Serializable object ) throws RemoteException\n {\n ongoingLine += object.toString();\n }\n\n @Override\n public Iterator iterator()\n {\n return lines.iterator();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"community/shell/src/test/java/org/neo4j/shell/AbstractShellTest.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (c) 2002-2011 \"Neo Technology,\"\n * Network Engine for Objects in Lund AB [http://neotechnology.com]\n *\n * This file is part of Neo4j.\n *\n * Neo4j is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\npackage org.neo4j.shell;\n\nimport static java.util.regex.Pattern.compile;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.neo4j.graphdb.DynamicRelationshipType.withName;\nimport static org.neo4j.helpers.collection.IteratorUtil.asCollection;\nimport static org.neo4j.kernel.impl.util.FileUtils.deleteRecursively;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.rmi.RemoteException;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.regex.Pattern;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.NotFoundException;\nimport org.neo4j.graphdb.Relationship;\nimport org.neo4j.graphdb.RelationshipType;\nimport org.neo4j.graphdb.Transaction;\nimport org.neo4j.kernel.EmbeddedGraphDatabase;\nimport org.neo4j.shell.impl.RemoteOutput;\nimport org.neo4j.shell.impl.SameJvmClient;\nimport org.neo4j.shell.kernel.GraphDatabaseShellServer;\n\npublic class AbstractShellTest\n{\n private static final String DB_PATH = \"target/var/shelldb\";\n protected static GraphDatabaseService db;\n private static ShellServer shellServer;\n private ShellClient shellClient;\n protected static final RelationshipType RELATIONSHIP_TYPE = withName( \"TYPE\" );\n \n @BeforeClass\n public static void startUp() throws Exception\n {\n deleteRecursively( new File( DB_PATH ) );\n db = new EmbeddedGraphDatabase( DB_PATH );\n shellServer = new GraphDatabaseShellServer( db );\n }\n \n @Before\n public void doBefore()\n {\n shellClient = new SameJvmClient( shellServer );\n }\n \n @After\n public void doAfter()\n {\n shellClient.shutdown();\n }\n \n @AfterClass\n public static void shutDown() throws Exception\n {\n shellServer.shutdown();\n db.shutdown();\n }\n \n protected static String pwdOutputFor( Object... entities )\n {\n StringBuilder builder = new StringBuilder();\n for ( Object entity : entities )\n {\n builder.append( (builder.length() == 0 ? \"\" : \"-->\") );\n if ( entity instanceof Node )\n {\n builder.append( \"(\" + ((Node)entity).getId() + \")\" );\n }\n else\n {\n builder.append( \"<\" + ((Relationship)entity).getId() + \">\" );\n }\n }\n return Pattern.quote( builder.toString() );\n }\n \n public void executeCommand( String command, String... theseLinesMustExistRegEx ) throws Exception\n {\n OutputCollector output = new OutputCollector();\n shellServer.interpretLine( command, shellClient.session(), output );\n \n for ( String lineThatMustExist : theseLinesMustExistRegEx )\n {\n boolean negative = lineThatMustExist.startsWith( \"!\" );\n lineThatMustExist = negative ? lineThatMustExist.substring( 1 ) : lineThatMustExist;\n Pattern pattern = compile( lineThatMustExist );\n boolean found = false;\n for ( String line : output )\n {\n if ( pattern.matcher( line ).find() )\n {\n found = true;\n break;\n }\n }\n assertTrue( \"Was expecting a line matching '\" + lineThatMustExist + \"', but didn't find any from out of \" +\n asCollection( output ), found != negative );\n }\n }\n\n public void executeCommandExpectingException( String command, String errorMessageShouldContain ) throws Exception\n {\n OutputCollector output = new OutputCollector();\n try\n {\n shellServer.interpretLine( command, shellClient.session(), output );\n fail( \"Was expecting an exception\" );\n }\n catch ( ShellException e )\n {\n String errorMessage = e.getMessage();\n if ( !errorMessage.toLowerCase().contains( errorMessageShouldContain.toLowerCase() ) )\n {\n fail( \"Error message '\" + errorMessage + \"' should have contained '\" + errorMessageShouldContain + \"'\" );\n }\n }\n }\n \n protected void assertRelationshipExists( Relationship relationship )\n {\n assertRelationshipExists( relationship.getId() );\n }\n \n protected void assertRelationshipExists( long id )\n {\n db.getRelationshipById( id );\n }\n \n protected void assertRelationshipDoesnExist( Relationship relationship )\n {\n assertRelationshipDoesnExist( relationship.getId() );\n }\n \n protected void assertRelationshipDoesnExist( long id )\n {\n try\n {\n db.getRelationshipById( id );\n fail( \"Relationship \" + id + \" shouldn't exist\" );\n }\n catch ( NotFoundException e )\n { // Good\n }\n }\n \n protected Relationship[] createRelationshipChain( int length )\n {\n return createRelationshipChain( db.getReferenceNode(), length );\n }\n \n protected Relationship[] createRelationshipChain( Node startingFromNode, int length )\n {\n Relationship[] rels = new Relationship[length];\n Transaction tx = db.beginTx();\n Node firstNode = db.getReferenceNode();\n for ( int i = 0; i < rels.length; i++ )\n {\n Node secondNode = db.createNode();\n rels[i] = firstNode.createRelationshipTo( secondNode, RELATIONSHIP_TYPE );\n firstNode = secondNode;\n }\n tx.success();\n tx.finish();\n return rels;\n }\n \n protected void setProperty( Node node, String key, Object value )\n {\n Transaction tx = db.beginTx();\n node.setProperty( key, value );\n tx.success();\n tx.finish();\n }\n\n public class OutputCollector implements Output, Serializable, Iterable\n {\n private static final long serialVersionUID = 1L;\n private final List lines = new ArrayList();\n private String ongoingLine = \"\";\n\n @Override\n public Appendable append( CharSequence csq, int start, int end )\n throws IOException\n {\n this.print( RemoteOutput.asString( csq ).substring( start, end ) );\n return this;\n }\n\n @Override\n public Appendable append( char c ) throws IOException\n {\n this.print( c );\n return this;\n }\n\n @Override\n public Appendable append( CharSequence csq ) throws IOException\n {\n this.print( RemoteOutput.asString( csq ) );\n return this;\n }\n\n @Override\n public void println( Serializable object ) throws RemoteException\n {\n print( object );\n println();\n }\n\n @Override\n public void println() throws RemoteException\n {\n lines.add( ongoingLine );\n ongoingLine = \"\";\n }\n\n @Override\n public void print( Serializable object ) throws RemoteException\n {\n ongoingLine += object.toString();\n }\n\n @Override\n public Iterator iterator()\n {\n return lines.iterator();\n }\n }\n}\n"},"message":{"kind":"string","value":"Test class error\n"},"old_file":{"kind":"string","value":"community/shell/src/test/java/org/neo4j/shell/AbstractShellTest.java"},"subject":{"kind":"string","value":"Test class error"}}},{"rowIdx":1295,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"a61512451a6d3ce9f96fa1b902c41cbcde7558a8"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ksokol/carldav"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2005-2007 Open Source Applications Foundation\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 */\npackage org.unitedinternet.cosmo.dao.query.hibernate;\n\nimport carldav.entity.Item;\nimport org.unitedinternet.cosmo.calendar.query.CalendarFilter;\nimport org.unitedinternet.cosmo.dao.query.ItemFilterProcessor;\nimport org.unitedinternet.cosmo.model.filter.*;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\nimport javax.persistence.Query;\nimport java.util.*;\nimport java.util.Map.Entry;\n\nimport static java.util.Locale.ENGLISH;\n\n/**\n * Standard Implementation of ItemFilterProcessor.\n * Translates filter into HQL Query, executes\n * query and processes the results.\n */\npublic class StandardItemFilterProcessor implements ItemFilterProcessor {\n\n private static final CalendarFilterConverter filterConverter = new CalendarFilterConverter();\n\n @PersistenceContext\n private EntityManager entityManager;\n\n public void setEntityManager(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n\n public List processFilter(CalendarFilter filter) {\n final ItemFilter itemFilter = filterConverter.translateToItemFilter(filter);\n Query hibQuery = buildQuery(entityManager, itemFilter);\n return hibQuery.getResultList();\n }\n\n /**\n * Build Hibernate Query from ItemFilter using HQL.\n * The query returned is essentially the first pass at\n * retrieving the matched items. A second pass is required in\n * order determine if any recurring events match a timeRange\n * in the filter. This is due to the fact that recurring events\n * may have complicated recurrence rules that are extremely\n * hard to match using HQL.\n *\n * @param session session\n * @param filter item filter\n * @return hibernate query built using HQL\n */\n public Query buildQuery(EntityManager session, ItemFilter filter) {\n StringBuffer selectBuf = new StringBuffer();\n StringBuffer whereBuf = new StringBuffer();\n StringBuffer orderBuf = new StringBuffer();\n\n Map params = new TreeMap<>();\n\n selectBuf.append(\"select i from Item i\");\n\n if (filter instanceof NoteItemFilter) {\n handleNoteItemFilter(selectBuf, whereBuf, params, (NoteItemFilter) filter);\n } else {\n handleItemFilter(selectBuf, whereBuf, params, filter);\n }\n\n selectBuf.append(whereBuf);\n selectBuf.append(orderBuf);\n\n Query hqlQuery = session.createQuery(selectBuf.toString());\n\n for (Entry param : params.entrySet()) {\n hqlQuery.setParameter(param.getKey(), param.getValue());\n }\n\n if (filter.getMaxResults() != null) {\n hqlQuery.setMaxResults(filter.getMaxResults());\n }\n\n return hqlQuery;\n }\n\n private void handleItemFilter(StringBuffer selectBuf,\n StringBuffer whereBuf, Map params,\n ItemFilter filter) {\n\n // filter on uid\n if (filter.getUid() != null) {\n formatExpression(whereBuf, params, \"i.uid\", filter.getUid());\n }\n\n\n // filter on parent\n if (filter.getParent() != null) {\n selectBuf.append(\" join i.collection pd\");\n appendWhere(whereBuf, \"pd.id=:parent\");\n params.put(\"parent\", filter.getParent());\n }\n\n if (filter.getDisplayName() != null) {\n formatExpression(whereBuf, params, \"i.displayName\", filter.getDisplayName());\n }\n\n handleStampFilters(whereBuf, filter, params);\n\n }\n\n private void handleStampFilters(StringBuffer whereBuf,\n ItemFilter filter,\n Map params) {\n for (StampFilter stampFilter : filter.getStampFilters()) {\n handleStampFilter(whereBuf, stampFilter, params);\n }\n }\n\n private void handleStampFilter(StringBuffer whereBuf,\n StampFilter filter,\n Map params) {\n\n if(filter.getType() != null) {\n appendWhere(whereBuf, \"i.type=:type\");\n params.put(\"type\", filter.getType());\n }\n\n // handle recurring event filter\n if (filter.getIsRecurring() != null) {\n appendWhere(whereBuf, \"(i.recurring=:recurring)\");\n params.put(\"recurring\", filter.getIsRecurring());\n }\n\n if (filter.getPeriod() != null) {\n whereBuf.append(\" and ( \");\n whereBuf.append(\"(i.startDate < :endDate)\");\n whereBuf.append(\" and i.endDate > :startDate)\");\n\n // edge case where start==end\n whereBuf.append(\" or (i.startDate=i.endDate and (i.startDate=:startDate or i.startDate=:endDate))\");\n\n whereBuf.append(\")\");\n\n params.put(\"startDate\", filter.getStart());\n params.put(\"endDate\", filter.getEnd());\n }\n }\n\n private void handleNoteItemFilter(StringBuffer selectBuf,\n StringBuffer whereBuf, Map params,\n NoteItemFilter filter) {\n handleItemFilter(selectBuf, whereBuf, params, filter);\n handleContentItemFilter(selectBuf, whereBuf, params, filter);\n\n // filter by icaluid\n if (filter.getIcalUid() != null) {\n formatExpression(whereBuf, params, \"i.uid\", filter.getIcalUid());\n }\n\n // filter by reminderTime\n if (filter.getReminderTime() != null) {\n formatExpression(whereBuf, params, \"i.remindertime\", filter.getReminderTime());\n }\n\n if(filter.getModifiedSince() != null){\n formatExpression(whereBuf, params, \"i.modifiedDate\", filter.getModifiedSince());\n }\n }\n\n private void handleContentItemFilter(StringBuffer selectBuf,\n StringBuffer whereBuf, Map params,\n ItemFilter filter) {\n\n if (\"\".equals(selectBuf.toString())) {\n handleItemFilter(selectBuf, whereBuf, params, filter);\n }\n }\n\n\n private void appendWhere(StringBuffer whereBuf, String toAppend) {\n if (\"\".equals(whereBuf.toString())) {\n whereBuf.append(\" where \" + toAppend);\n } else {\n whereBuf.append(\" and \" + toAppend);\n }\n }\n\n private String formatForLike(String toFormat) {\n return \"%\" + toFormat + \"%\";\n }\n\n private void formatExpression(StringBuffer whereBuf,\n Map params, String propName,\n FilterCriteria fc) {\n\n StringBuffer expBuf = new StringBuffer();\n\n FilterExpression exp = (FilterExpression) fc;\n\n if (exp instanceof NullExpression) {\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\" is not null\");\n } else {\n expBuf.append(\" is null\");\n }\n } else if (exp instanceof BetweenExpression) {\n BetweenExpression be = (BetweenExpression) exp;\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\" not\");\n }\n\n String param = \"param\" + params.size();\n expBuf.append(\" between :\" + param);\n params.put(param, be.getValue1());\n param = \"param\" + params.size();\n expBuf.append(\" and :\" + param);\n params.put(param, be.getValue2());\n } else {\n String param = \"param\" + params.size();\n if (exp instanceof EqualsExpression) {\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\"!=\");\n } else {\n expBuf.append(\"=\");\n }\n\n params.put(param, exp.getValue());\n\n } else if (exp instanceof LikeExpression) {\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\" not like \");\n } else {\n expBuf.append(\" like \");\n }\n\n params.put(param, formatForLike(exp.getValue().toString()));\n } else if (exp instanceof ILikeExpression) {\n expBuf.append(\"lower(\" + propName + \")\");\n if (exp.isNegated()) {\n expBuf.append(\" not like \");\n } else {\n expBuf.append(\" like \");\n }\n\n params.put(param, formatForLike(exp.getValue().toString().toLowerCase(ENGLISH)));\n }\n\n expBuf.append(\":\" + param);\n }\n\n appendWhere(whereBuf, expBuf.toString());\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/unitedinternet/cosmo/dao/query/hibernate/StandardItemFilterProcessor.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2005-2007 Open Source Applications Foundation\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 */\npackage org.unitedinternet.cosmo.dao.query.hibernate;\n\nimport carldav.entity.Item;\nimport org.unitedinternet.cosmo.calendar.query.CalendarFilter;\nimport org.unitedinternet.cosmo.dao.query.ItemFilterProcessor;\nimport org.unitedinternet.cosmo.model.filter.*;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\nimport javax.persistence.Query;\nimport java.util.*;\nimport java.util.Map.Entry;\n\nimport static java.util.Locale.ENGLISH;\n\n/**\n * Standard Implementation of ItemFilterProcessor.\n * Translates filter into HQL Query, executes\n * query and processes the results.\n */\npublic class StandardItemFilterProcessor implements ItemFilterProcessor {\n\n private static final CalendarFilterConverter filterConverter = new CalendarFilterConverter();\n\n @PersistenceContext\n private EntityManager entityManager;\n\n public void setEntityManager(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n\n public List processFilter(CalendarFilter filter) {\n final ItemFilter itemFilter = filterConverter.translateToItemFilter(filter);\n Query hibQuery = buildQuery(entityManager, itemFilter);\n return hibQuery.getResultList();\n }\n\n /**\n * Build Hibernate Query from ItemFilter using HQL.\n * The query returned is essentially the first pass at\n * retrieving the matched items. A second pass is required in\n * order determine if any recurring events match a timeRange\n * in the filter. This is due to the fact that recurring events\n * may have complicated recurrence rules that are extremely\n * hard to match using HQL.\n *\n * @param session session\n * @param filter item filter\n * @return hibernate query built using HQL\n */\n public Query buildQuery(EntityManager session, ItemFilter filter) {\n StringBuffer selectBuf = new StringBuffer();\n StringBuffer whereBuf = new StringBuffer();\n StringBuffer orderBuf = new StringBuffer();\n\n Map params = new TreeMap<>();\n\n if (filter instanceof NoteItemFilter) {\n handleNoteItemFilter(selectBuf, whereBuf, params, (NoteItemFilter) filter);\n } else {\n handleItemFilter(selectBuf, whereBuf, params, filter);\n }\n\n selectBuf.append(whereBuf);\n selectBuf.append(orderBuf);\n\n Query hqlQuery = session.createQuery(selectBuf.toString());\n\n for (Entry param : params.entrySet()) {\n hqlQuery.setParameter(param.getKey(), param.getValue());\n }\n\n if (filter.getMaxResults() != null) {\n hqlQuery.setMaxResults(filter.getMaxResults());\n }\n\n return hqlQuery;\n }\n\n private void handleItemFilter(StringBuffer selectBuf,\n StringBuffer whereBuf, Map params,\n ItemFilter filter) {\n\n if (\"\".equals(selectBuf.toString())) {\n selectBuf.append(\"select i from Item i\");\n }\n\n // filter on uid\n if (filter.getUid() != null) {\n formatExpression(whereBuf, params, \"i.uid\", filter.getUid());\n }\n\n\n // filter on parent\n if (filter.getParent() != null) {\n selectBuf.append(\" join i.collection pd\");\n appendWhere(whereBuf, \"pd.id=:parent\");\n params.put(\"parent\", filter.getParent());\n }\n\n if (filter.getDisplayName() != null) {\n formatExpression(whereBuf, params, \"i.displayName\", filter.getDisplayName());\n }\n\n handleStampFilters(whereBuf, filter, params);\n\n }\n\n private void handleStampFilters(StringBuffer whereBuf,\n ItemFilter filter,\n Map params) {\n for (StampFilter stampFilter : filter.getStampFilters()) {\n handleStampFilter(whereBuf, stampFilter, params);\n }\n }\n\n private void handleStampFilter(StringBuffer whereBuf,\n StampFilter filter,\n Map params) {\n\n if(filter.getType() != null) {\n appendWhere(whereBuf, \"i.type=:type\");\n params.put(\"type\", filter.getType());\n }\n\n // handle recurring event filter\n if (filter.getIsRecurring() != null) {\n appendWhere(whereBuf, \"(i.recurring=:recurring)\");\n params.put(\"recurring\", filter.getIsRecurring());\n }\n\n if (filter.getPeriod() != null) {\n whereBuf.append(\" and ( \");\n whereBuf.append(\"(i.startDate < :endDate)\");\n whereBuf.append(\" and i.endDate > :startDate)\");\n\n // edge case where start==end\n whereBuf.append(\" or (i.startDate=i.endDate and (i.startDate=:startDate or i.startDate=:endDate))\");\n\n whereBuf.append(\")\");\n\n params.put(\"startDate\", filter.getStart());\n params.put(\"endDate\", filter.getEnd());\n }\n }\n\n private void handleNoteItemFilter(StringBuffer selectBuf,\n StringBuffer whereBuf, Map params,\n NoteItemFilter filter) {\n selectBuf.append(\"select i from Item i\");\n handleItemFilter(selectBuf, whereBuf, params, filter);\n handleContentItemFilter(selectBuf, whereBuf, params, filter);\n\n // filter by icaluid\n if (filter.getIcalUid() != null) {\n formatExpression(whereBuf, params, \"i.uid\", filter.getIcalUid());\n }\n\n // filter by reminderTime\n if (filter.getReminderTime() != null) {\n formatExpression(whereBuf, params, \"i.remindertime\", filter.getReminderTime());\n }\n\n if(filter.getModifiedSince() != null){\n formatExpression(whereBuf, params, \"i.modifiedDate\", filter.getModifiedSince());\n }\n }\n\n private void handleContentItemFilter(StringBuffer selectBuf,\n StringBuffer whereBuf, Map params,\n ItemFilter filter) {\n\n if (\"\".equals(selectBuf.toString())) {\n handleItemFilter(selectBuf, whereBuf, params, filter);\n }\n }\n\n\n private void appendWhere(StringBuffer whereBuf, String toAppend) {\n if (\"\".equals(whereBuf.toString())) {\n whereBuf.append(\" where \" + toAppend);\n } else {\n whereBuf.append(\" and \" + toAppend);\n }\n }\n\n private String formatForLike(String toFormat) {\n return \"%\" + toFormat + \"%\";\n }\n\n private void formatExpression(StringBuffer whereBuf,\n Map params, String propName,\n FilterCriteria fc) {\n\n StringBuffer expBuf = new StringBuffer();\n\n FilterExpression exp = (FilterExpression) fc;\n\n if (exp instanceof NullExpression) {\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\" is not null\");\n } else {\n expBuf.append(\" is null\");\n }\n } else if (exp instanceof BetweenExpression) {\n BetweenExpression be = (BetweenExpression) exp;\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\" not\");\n }\n\n String param = \"param\" + params.size();\n expBuf.append(\" between :\" + param);\n params.put(param, be.getValue1());\n param = \"param\" + params.size();\n expBuf.append(\" and :\" + param);\n params.put(param, be.getValue2());\n } else {\n String param = \"param\" + params.size();\n if (exp instanceof EqualsExpression) {\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\"!=\");\n } else {\n expBuf.append(\"=\");\n }\n\n params.put(param, exp.getValue());\n\n } else if (exp instanceof LikeExpression) {\n expBuf.append(propName);\n if (exp.isNegated()) {\n expBuf.append(\" not like \");\n } else {\n expBuf.append(\" like \");\n }\n\n params.put(param, formatForLike(exp.getValue().toString()));\n } else if (exp instanceof ILikeExpression) {\n expBuf.append(\"lower(\" + propName + \")\");\n if (exp.isNegated()) {\n expBuf.append(\" not like \");\n } else {\n expBuf.append(\" like \");\n }\n\n params.put(param, formatForLike(exp.getValue().toString().toLowerCase(ENGLISH)));\n }\n\n expBuf.append(\":\" + param);\n }\n\n appendWhere(whereBuf, expBuf.toString());\n }\n\n}\n"},"message":{"kind":"string","value":"simplified StandardItemFilterProcessor\n"},"old_file":{"kind":"string","value":"src/main/java/org/unitedinternet/cosmo/dao/query/hibernate/StandardItemFilterProcessor.java"},"subject":{"kind":"string","value":"simplified StandardItemFilterProcessor"}}},{"rowIdx":1296,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"668728f906e434b7c2641b95efd7e18780ddd04f"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ChetnaChaudhari/tez,apache/tez,navis/tez,dongjiaqiang/tez,Parth-Brahmbhatt/tez,bernhardschaefer/tez,guiling/tez,dongjiaqiang/tez,guiling/tez,sidseth/tez,guiling/tez,dongjiaqiang/tez,bernhardschaefer/tez,amirsojoodi/tez,sidseth/tez,apache/incubator-tez,navis/tez,amirsojoodi/tez,Altiscale/tez,Parth-Brahmbhatt/tez,apache/tez,zjffdu/tez,Altiscale/tez,ueshin/apache-tez,apache/tez,jth/tez,ueshin/apache-tez,jth/tez,ueshin/apache-tez,guiling/tez,navis/tez,jth/tez,ChetnaChaudhari/tez,zjffdu/tez,Parth-Brahmbhatt/tez,jth/tez,dongjiaqiang/tez,bernhardschaefer/tez,amirsojoodi/tez,dongjiaqiang/tez,sequenceiq/tez,Parth-Brahmbhatt/tez,sidseth/tez,zjffdu/tez,ueshin/apache-tez,navis/tez,Altiscale/tez,zjffdu/tez,bernhardschaefer/tez,amirsojoodi/tez,amirsojoodi/tez,sidseth/tez,apache/tez,apache/incubator-tez,zjffdu/tez,sequenceiq/tez,navis/tez,ueshin/apache-tez,guiling/tez,ChetnaChaudhari/tez,sidseth/tez,Parth-Brahmbhatt/tez,sequenceiq/tez,jth/tez,ChetnaChaudhari/tez,Altiscale/tez,bernhardschaefer/tez,apache/tez,ChetnaChaudhari/tez"},"new_contents":{"kind":"string","value":"/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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\npackage org.apache.tez.engine.newruntime;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.classification.InterfaceAudience.Private;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.security.token.Token;\nimport org.apache.tez.dag.api.ProcessorDescriptor;\nimport org.apache.tez.dag.api.TezUncheckedException;\nimport org.apache.tez.dag.records.TezTaskAttemptID;\nimport org.apache.tez.engine.common.security.JobTokenIdentifier;\nimport org.apache.tez.engine.newapi.Event;\nimport org.apache.tez.engine.newapi.Input;\nimport org.apache.tez.engine.newapi.LogicalIOProcessor;\nimport org.apache.tez.engine.newapi.LogicalInput;\nimport org.apache.tez.engine.newapi.LogicalOutput;\nimport org.apache.tez.engine.newapi.Output;\nimport org.apache.tez.engine.newapi.Processor;\nimport org.apache.tez.engine.newapi.TezInputContext;\nimport org.apache.tez.engine.newapi.TezOutputContext;\nimport org.apache.tez.engine.newapi.TezProcessorContext;\nimport org.apache.tez.engine.newapi.impl.EventMetaData;\nimport org.apache.tez.engine.newapi.impl.EventMetaData.EventProducerConsumerType;\nimport org.apache.tez.engine.newapi.impl.InputSpec;\nimport org.apache.tez.engine.newapi.impl.OutputSpec;\nimport org.apache.tez.engine.newapi.impl.TaskSpec;\nimport org.apache.tez.engine.newapi.impl.TezEvent;\nimport org.apache.tez.engine.newapi.impl.TezInputContextImpl;\nimport org.apache.tez.engine.newapi.impl.TezOutputContextImpl;\nimport org.apache.tez.engine.newapi.impl.TezProcessorContextImpl;\nimport org.apache.tez.engine.newapi.impl.TezUmbilical;\nimport org.apache.tez.engine.shuffle.common.ShuffleUtils;\n\nimport com.google.common.base.Preconditions;\n\n@Private\npublic class LogicalIOProcessorRuntimeTask extends RuntimeTask {\n\n private static final Log LOG = LogFactory\n .getLog(LogicalIOProcessorRuntimeTask.class);\n\n private final TaskSpec taskSpec;\n private final Configuration tezConf;\n private final TezUmbilical tezUmbilical;\n\n private final List inputSpecs;\n private final List inputs;\n\n private final List outputSpecs;\n private final List outputs;\n\n private final ProcessorDescriptor processorDescriptor;\n private final LogicalIOProcessor processor;\n\n private final Map serviceConsumerMetadata;\n\n private Map inputMap;\n private Map outputMap;\n\n public LogicalIOProcessorRuntimeTask(TaskSpec taskSpec,\n Configuration tezConf, TezUmbilical tezUmbilical,\n Token jobToken) throws IOException {\n // TODO Remove jobToken from here post TEZ-421\n LOG.info(\"Initializing LogicalIOProcessorRuntimeTask with TaskSpec: \"\n + taskSpec);\n this.taskSpec = taskSpec;\n this.tezConf = tezConf;\n this.tezUmbilical = tezUmbilical;\n this.inputSpecs = taskSpec.getInputs();\n this.inputs = createInputs(inputSpecs);\n this.outputSpecs = taskSpec.getOutputs();\n this.outputs = createOutputs(outputSpecs);\n this.processorDescriptor = taskSpec.getProcessorDescriptor();\n this.processor = createProcessor(processorDescriptor);\n this.serviceConsumerMetadata = new HashMap();\n this.serviceConsumerMetadata.put(ShuffleUtils.SHUFFLE_HANDLER_SERVICE_ID,\n ShuffleUtils.convertJobTokenToBytes(jobToken));\n this.state = State.NEW;\n }\n\n public void initialize() throws Exception {\n Preconditions.checkState(this.state == State.NEW, \"Already initialized\");\n this.state = State.INITED;\n inputMap = new LinkedHashMap(inputs.size());\n outputMap = new LinkedHashMap(outputs.size());\n\n // TODO Maybe close initialized inputs / outputs in case of failure to\n // initialize.\n // Initialize all inputs. TODO: Multi-threaded at some point.\n for (int i = 0; i < inputs.size(); i++) {\n String srcVertexName = inputSpecs.get(i).getSourceVertexName();\n initializeInput(inputs.get(i),\n inputSpecs.get(i));\n inputMap.put(srcVertexName, inputs.get(i));\n }\n\n // Initialize all outputs. TODO: Multi-threaded at some point.\n for (int i = 0; i < outputs.size(); i++) {\n String destVertexName = outputSpecs.get(i).getDestinationVertexName();\n initializeOutput(outputs.get(i), outputSpecs.get(i));\n outputMap.put(destVertexName, outputs.get(i));\n }\n\n // Initialize processor.\n initializeLogicalIOProcessor();\n }\n\n public void run() throws Exception {\n synchronized (this.state) {\n Preconditions.checkState(this.state == State.INITED,\n \"Can only run while in INITED state. Current: \" + this.state);\n this.state = State.RUNNING;\n }\n LogicalIOProcessor lioProcessor = (LogicalIOProcessor) processor;\n lioProcessor.run(inputMap, outputMap);\n }\n\n public void close() throws Exception {\n Preconditions.checkState(this.state == State.RUNNING,\n \"Can only run while in RUNNING state. Current: \" + this.state);\n this.state = State.CLOSED;\n\n // Close the Inputs.\n for (int i = 0; i < inputs.size(); i++) {\n String srcVertexName = inputSpecs.get(i).getSourceVertexName();\n List closeInputEvents = inputs.get(i).close();\n sendTaskGeneratedEvents(closeInputEvents,\n EventProducerConsumerType.INPUT, taskSpec.getVertexName(),\n srcVertexName, taskSpec.getTaskAttemptID());\n }\n\n // Close the Processor.\n processor.close();\n\n // Close the Outputs.\n for (int i = 0; i < outputs.size(); i++) {\n String destVertexName = outputSpecs.get(i).getDestinationVertexName();\n List closeOutputEvents = outputs.get(i).close();\n sendTaskGeneratedEvents(closeOutputEvents,\n EventProducerConsumerType.OUTPUT, taskSpec.getVertexName(),\n destVertexName, taskSpec.getTaskAttemptID());\n }\n }\n\n private void initializeInput(Input input, InputSpec inputSpec)\n throws Exception {\n TezInputContext tezInputContext = createInputContext(inputSpec);\n if (input instanceof LogicalInput) {\n ((LogicalInput) input).setNumPhysicalInputs(inputSpec\n .getPhysicalEdgeCount());\n }\n List events = input.initialize(tezInputContext);\n sendTaskGeneratedEvents(events, EventProducerConsumerType.INPUT,\n tezInputContext.getTaskVertexName(),\n tezInputContext.getSourceVertexName(), taskSpec.getTaskAttemptID());\n }\n\n private void initializeOutput(Output output, OutputSpec outputSpec)\n throws Exception {\n TezOutputContext tezOutputContext = createOutputContext(outputSpec);\n if (output instanceof LogicalOutput) {\n ((LogicalOutput) output).setNumPhysicalOutputs(outputSpec\n .getPhysicalEdgeCount());\n }\n List events = output.initialize(tezOutputContext);\n sendTaskGeneratedEvents(events, EventProducerConsumerType.OUTPUT,\n tezOutputContext.getTaskVertexName(),\n tezOutputContext.getDestinationVertexName(),\n taskSpec.getTaskAttemptID());\n }\n\n private void initializeLogicalIOProcessor() throws Exception {\n TezProcessorContext processorContext = createProcessorContext();\n processor.initialize(processorContext);\n }\n\n private TezInputContext createInputContext(InputSpec inputSpec) {\n TezInputContext inputContext = new TezInputContextImpl(tezConf,\n tezUmbilical, taskSpec.getVertexName(), inputSpec.getSourceVertexName(),\n taskSpec.getTaskAttemptID(), tezCounters,\n inputSpec.getInputDescriptor().getUserPayload(), this,\n serviceConsumerMetadata);\n return inputContext;\n }\n\n private TezOutputContext createOutputContext(OutputSpec outputSpec) {\n TezOutputContext outputContext = new TezOutputContextImpl(tezConf,\n tezUmbilical, taskSpec.getVertexName(),\n outputSpec.getDestinationVertexName(),\n taskSpec.getTaskAttemptID(), tezCounters,\n outputSpec.getOutputDescriptor().getUserPayload(), this,\n serviceConsumerMetadata);\n return outputContext;\n }\n\n private TezProcessorContext createProcessorContext() {\n TezProcessorContext processorContext = new TezProcessorContextImpl(tezConf,\n tezUmbilical, taskSpec.getVertexName(), taskSpec.getTaskAttemptID(),\n tezCounters, processorDescriptor.getUserPayload(), this,\n serviceConsumerMetadata);\n return processorContext;\n }\n\n private List createInputs(List inputSpecs) {\n List inputs = new ArrayList(inputSpecs.size());\n for (InputSpec inputSpec : inputSpecs) {\n Input input = RuntimeUtils.createClazzInstance(inputSpec\n .getInputDescriptor().getClassName());\n\n if (input instanceof LogicalInput) {\n inputs.add((LogicalInput) input);\n } else {\n throw new TezUncheckedException(input.getClass().getName()\n + \" is not a sub-type of LogicalInput.\"\n + \" Only LogicalInput sub-types supported by LogicalIOProcessor.\");\n }\n\n }\n return inputs;\n }\n\n private List createOutputs(List outputSpecs) {\n List outputs = new ArrayList(\n outputSpecs.size());\n for (OutputSpec outputSpec : outputSpecs) {\n Output output = RuntimeUtils.createClazzInstance(outputSpec\n .getOutputDescriptor().getClassName());\n if (output instanceof LogicalOutput) {\n outputs.add((LogicalOutput) output);\n } else {\n throw new TezUncheckedException(output.getClass().getName()\n + \" is not a sub-type of LogicalOutput.\"\n + \" Only LogicalOutput sub-types supported by LogicalIOProcessor.\");\n }\n }\n return outputs;\n }\n\n private LogicalIOProcessor createProcessor(\n ProcessorDescriptor processorDescriptor) {\n Processor processor = RuntimeUtils.createClazzInstance(processorDescriptor\n .getClassName());\n if (!(processor instanceof LogicalIOProcessor)) {\n throw new TezUncheckedException(processor.getClass().getName()\n + \" is not a sub-type of LogicalIOProcessor.\"\n + \" Only LogicalOutput sub-types supported by LogicalIOProcessor.\");\n }\n return (LogicalIOProcessor) processor;\n }\n\n private void sendTaskGeneratedEvents(List events,\n EventProducerConsumerType generator, String taskVertexName,\n String edgeVertexName, TezTaskAttemptID taskAttemptID) {\n if (events != null && events.size() > 0) {\n EventMetaData eventMetaData = new EventMetaData(generator,\n taskVertexName, edgeVertexName, taskAttemptID);\n List tezEvents = new ArrayList(events.size());\n for (Event e : events) {\n TezEvent te = new TezEvent(e, eventMetaData);\n tezEvents.add(te);\n }\n tezUmbilical.addEvents(tezEvents);\n }\n }\n\n public void handleEvent(TezEvent e) {\n switch (e.getDestinationInfo().getEventGenerator()) {\n case INPUT:\n LogicalInput input = inputMap.get(\n e.getDestinationInfo().getEdgeVertexName());\n if (input != null) {\n input.handleEvents(Collections.singletonList(e.getEvent()));\n } else {\n throw new TezUncheckedException(\"Unhandled event for invalid target: \"\n + e);\n }\n break;\n case OUTPUT:\n LogicalOutput output = outputMap.get(\n e.getDestinationInfo().getEdgeVertexName());\n if (output != null) {\n output.handleEvents(Collections.singletonList(e.getEvent()));\n } else {\n throw new TezUncheckedException(\"Unhandled event for invalid target: \"\n + e);\n }\n break;\n case PROCESSOR:\n processor.handleEvents(Collections.singletonList(e.getEvent()));\n break;\n case SYSTEM:\n LOG.warn(\"Trying to send a System event in a Task: \" + e);\n break;\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"tez-engine/src/main/java/org/apache/tez/engine/newruntime/LogicalIOProcessorRuntimeTask.java"},"old_contents":{"kind":"string","value":"/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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\npackage org.apache.tez.engine.newruntime;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.classification.InterfaceAudience.Private;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.security.token.Token;\nimport org.apache.tez.dag.api.ProcessorDescriptor;\nimport org.apache.tez.dag.api.TezUncheckedException;\nimport org.apache.tez.engine.common.security.JobTokenIdentifier;\nimport org.apache.tez.engine.newapi.Event;\nimport org.apache.tez.engine.newapi.Input;\nimport org.apache.tez.engine.newapi.LogicalIOProcessor;\nimport org.apache.tez.engine.newapi.LogicalInput;\nimport org.apache.tez.engine.newapi.LogicalOutput;\nimport org.apache.tez.engine.newapi.Output;\nimport org.apache.tez.engine.newapi.Processor;\nimport org.apache.tez.engine.newapi.TezInputContext;\nimport org.apache.tez.engine.newapi.TezOutputContext;\nimport org.apache.tez.engine.newapi.TezProcessorContext;\nimport org.apache.tez.engine.newapi.impl.InputSpec;\nimport org.apache.tez.engine.newapi.impl.OutputSpec;\nimport org.apache.tez.engine.newapi.impl.TaskSpec;\nimport org.apache.tez.engine.newapi.impl.TezEvent;\nimport org.apache.tez.engine.newapi.impl.TezInputContextImpl;\nimport org.apache.tez.engine.newapi.impl.TezOutputContextImpl;\nimport org.apache.tez.engine.newapi.impl.TezProcessorContextImpl;\nimport org.apache.tez.engine.newapi.impl.TezUmbilical;\nimport org.apache.tez.engine.shuffle.common.ShuffleUtils;\n\nimport com.google.common.base.Preconditions;\n\n@Private\npublic class LogicalIOProcessorRuntimeTask extends RuntimeTask {\n\n private static final Log LOG = LogFactory\n .getLog(LogicalIOProcessorRuntimeTask.class);\n\n private final TaskSpec taskSpec;\n private final Configuration tezConf;\n private final TezUmbilical tezUmbilical;\n\n private final List inputSpecs;\n private final List inputs;\n\n private final List outputSpecs;\n private final List outputs;\n\n private final ProcessorDescriptor processorDescriptor;\n private final LogicalIOProcessor processor;\n\n private final Map serviceConsumerMetadata;\n\n private Map inputMap;\n private Map outputMap;\n\n private Map> initInputEventMap;\n private Map> initOutputEventMap;\n\n private Map> closeInputEventMap;\n private Map> closeOutputEventMap;\n\n\n\n public LogicalIOProcessorRuntimeTask(TaskSpec taskSpec,\n Configuration tezConf, TezUmbilical tezUmbilical,\n Token jobToken) throws IOException {\n // TODO Remove jobToken from here post TEZ-421\n LOG.info(\"Initializing LogicalIOProcessorRuntimeTask with TaskSpec: \"\n + taskSpec);\n this.taskSpec = taskSpec;\n this.tezConf = tezConf;\n this.tezUmbilical = tezUmbilical;\n this.inputSpecs = taskSpec.getInputs();\n this.inputs = createInputs(inputSpecs);\n this.outputSpecs = taskSpec.getOutputs();\n this.outputs = createOutputs(outputSpecs);\n this.processorDescriptor = taskSpec.getProcessorDescriptor();\n this.processor = createProcessor(processorDescriptor);\n this.serviceConsumerMetadata = new HashMap();\n this.serviceConsumerMetadata.put(ShuffleUtils.SHUFFLE_HANDLER_SERVICE_ID,\n ShuffleUtils.convertJobTokenToBytes(jobToken));\n this.state = State.NEW;\n }\n\n public void initialize() throws Exception {\n Preconditions.checkState(this.state == State.NEW, \"Already initialized\");\n this.state = State.INITED;\n inputMap = new LinkedHashMap(inputs.size());\n outputMap = new LinkedHashMap(outputs.size());\n\n initInputEventMap = new LinkedHashMap>(inputs.size());\n initOutputEventMap = new LinkedHashMap>(outputs.size());\n\n // TODO Maybe close initialized inputs / outputs in case of failure to\n // initialize.\n // Initialize all inputs. TODO: Multi-threaded at some point.\n for (int i = 0; i < inputs.size(); i++) {\n String srcVertexName = inputSpecs.get(i).getSourceVertexName();\n List initInputEvents = initializeInput(inputs.get(i),\n inputSpecs.get(i));\n // TODO Add null/event list checking here or in the actual executor.\n initInputEventMap.put(srcVertexName, initInputEvents);\n inputMap.put(srcVertexName, inputs.get(i));\n }\n\n // Initialize all outputs. TODO: Multi-threaded at some point.\n for (int i = 0; i < outputs.size(); i++) {\n String destVertexName = outputSpecs.get(i).getDestinationVertexName();\n List initOutputEvents = initializeOutput(outputs.get(i),\n outputSpecs.get(i));\n // TODO Add null/event list checking here or in the actual executor.\n initOutputEventMap.put(destVertexName, initOutputEvents);\n outputMap.put(destVertexName, outputs.get(i));\n }\n\n // Initialize processor.\n initializeLogicalIOProcessor();\n }\n\n public Map> getInputInitEvents() {\n Preconditions.checkState(this.state != State.NEW, \"Not initialized yet\");\n return initInputEventMap;\n }\n\n public Map> getOutputInitEvents() {\n Preconditions.checkState(this.state != State.NEW, \"Not initialized yet\");\n return initOutputEventMap;\n }\n\n public void run() throws Exception {\n synchronized (this.state) {\n Preconditions.checkState(this.state == State.INITED,\n \"Can only run while in INITED state. Current: \" + this.state);\n this.state = State.RUNNING;\n }\n LogicalIOProcessor lioProcessor = (LogicalIOProcessor) processor;\n lioProcessor.run(inputMap, outputMap);\n }\n\n public void close() throws Exception {\n Preconditions.checkState(this.state == State.RUNNING,\n \"Can only run while in RUNNING state. Current: \" + this.state);\n this.state=State.CLOSED;\n closeInputEventMap = new LinkedHashMap>(inputs.size());\n closeOutputEventMap = new LinkedHashMap>(outputs.size());\n\n // Close the Inputs.\n for (int i = 0; i < inputs.size(); i++) {\n String srcVertexName = inputSpecs.get(i).getSourceVertexName();\n List closeInputEvents = inputs.get(i).close();\n closeInputEventMap.put(srcVertexName, closeInputEvents);\n }\n\n // Close the Processor.\n processor.close();\n\n // Close the Outputs.\n for (int i = 0; i < outputs.size(); i++) {\n String destVertexName = outputSpecs.get(i).getDestinationVertexName();\n List closeOutputEvents = outputs.get(i).close();\n closeOutputEventMap.put(destVertexName, closeOutputEvents);\n }\n }\n\n public Map> getInputCloseEvents() {\n Preconditions.checkState(this.state == State.CLOSED, \"Not closed yet\");\n return closeInputEventMap;\n }\n\n public Map> getOutputCloseEvents() {\n Preconditions.checkState(this.state == State.CLOSED, \"Not closed yet\");\n return closeOutputEventMap;\n }\n\n private List initializeInput(Input input, InputSpec inputSpec)\n throws Exception {\n TezInputContext tezInputContext = createInputContext(inputSpec);\n if (input instanceof LogicalInput) {\n ((LogicalInput) input).setNumPhysicalInputs(inputSpec\n .getPhysicalEdgeCount());\n }\n return input.initialize(tezInputContext);\n }\n\n private List initializeOutput(Output output, OutputSpec outputSpec)\n throws Exception {\n TezOutputContext tezOutputContext = createOutputContext(outputSpec);\n if (output instanceof LogicalOutput) {\n ((LogicalOutput) output).setNumPhysicalOutputs(outputSpec\n .getPhysicalEdgeCount());\n }\n return output.initialize(tezOutputContext);\n }\n\n private void initializeLogicalIOProcessor() throws Exception {\n TezProcessorContext processorContext = createProcessorContext();\n processor.initialize(processorContext);\n }\n\n private TezInputContext createInputContext(InputSpec inputSpec) {\n TezInputContext inputContext = new TezInputContextImpl(tezConf,\n tezUmbilical, taskSpec.getVertexName(), inputSpec.getSourceVertexName(),\n taskSpec.getTaskAttemptID(), tezCounters,\n inputSpec.getInputDescriptor().getUserPayload(), this,\n serviceConsumerMetadata);\n return inputContext;\n }\n\n private TezOutputContext createOutputContext(OutputSpec outputSpec) {\n TezOutputContext outputContext = new TezOutputContextImpl(tezConf,\n tezUmbilical, taskSpec.getVertexName(),\n outputSpec.getDestinationVertexName(),\n taskSpec.getTaskAttemptID(), tezCounters,\n outputSpec.getOutputDescriptor().getUserPayload(), this,\n serviceConsumerMetadata);\n return outputContext;\n }\n\n private TezProcessorContext createProcessorContext() {\n TezProcessorContext processorContext = new TezProcessorContextImpl(tezConf,\n tezUmbilical, taskSpec.getVertexName(), taskSpec.getTaskAttemptID(),\n tezCounters, processorDescriptor.getUserPayload(), this,\n serviceConsumerMetadata);\n return processorContext;\n }\n\n private List createInputs(List inputSpecs) {\n List inputs = new ArrayList(inputSpecs.size());\n for (InputSpec inputSpec : inputSpecs) {\n Input input = RuntimeUtils.createClazzInstance(inputSpec\n .getInputDescriptor().getClassName());\n\n if (input instanceof LogicalInput) {\n inputs.add((LogicalInput) input);\n } else {\n throw new TezUncheckedException(input.getClass().getName()\n + \" is not a sub-type of LogicalInput.\"\n + \" Only LogicalInput sub-types supported by LogicalIOProcessor.\");\n }\n\n }\n return inputs;\n }\n\n private List createOutputs(List outputSpecs) {\n List outputs = new ArrayList(\n outputSpecs.size());\n for (OutputSpec outputSpec : outputSpecs) {\n Output output = RuntimeUtils.createClazzInstance(outputSpec\n .getOutputDescriptor().getClassName());\n if (output instanceof LogicalOutput) {\n outputs.add((LogicalOutput) output);\n } else {\n throw new TezUncheckedException(output.getClass().getName()\n + \" is not a sub-type of LogicalOutput.\"\n + \" Only LogicalOutput sub-types supported by LogicalIOProcessor.\");\n }\n }\n return outputs;\n }\n\n private LogicalIOProcessor createProcessor(\n ProcessorDescriptor processorDescriptor) {\n Processor processor = RuntimeUtils.createClazzInstance(processorDescriptor\n .getClassName());\n if (!(processor instanceof LogicalIOProcessor)) {\n throw new TezUncheckedException(processor.getClass().getName()\n + \" is not a sub-type of LogicalIOProcessor.\"\n + \" Only LogicalOutput sub-types supported by LogicalIOProcessor.\");\n }\n return (LogicalIOProcessor) processor;\n }\n\n public void handleEvent(TezEvent e) {\n switch (e.getDestinationInfo().getEventGenerator()) {\n case INPUT:\n LogicalInput input = inputMap.get(\n e.getDestinationInfo().getEdgeVertexName());\n if (input != null) {\n input.handleEvents(Collections.singletonList(e.getEvent()));\n } else {\n throw new TezUncheckedException(\"Unhandled event for invalid target: \"\n + e);\n }\n break;\n case OUTPUT:\n LogicalOutput output = outputMap.get(\n e.getDestinationInfo().getEdgeVertexName());\n if (output != null) {\n output.handleEvents(Collections.singletonList(e.getEvent()));\n } else {\n throw new TezUncheckedException(\"Unhandled event for invalid target: \"\n + e);\n }\n break;\n case PROCESSOR:\n processor.handleEvents(Collections.singletonList(e.getEvent()));\n break;\n case SYSTEM:\n LOG.warn(\"Trying to send a System event in a Task: \" + e);\n break;\n }\n }\n\n}\n"},"message":{"kind":"string","value":"TEZ-442. Handle events generated by I/O initialize and close (part of\nTEZ-398). (sseth)\n"},"old_file":{"kind":"string","value":"tez-engine/src/main/java/org/apache/tez/engine/newruntime/LogicalIOProcessorRuntimeTask.java"},"subject":{"kind":"string","value":"TEZ-442. Handle events generated by I/O initialize and close (part of TEZ-398). (sseth)"}}},{"rowIdx":1297,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9886e3d402c0c2acef6341888999ca2e4679ebb9"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"NerdCats/RoboCat"},"new_contents":{"kind":"string","value":"package co.gobd.gofetch.activity;\n\nimport android.content.res.Configuration;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\n\nimport co.gobd.gofetch.R;\nimport co.gobd.gofetch.adapter.SupportedOrderAdapter;\n\n\npublic class SupportedOrderActivity extends AppCompatActivity {\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_supported_order);\n\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n\n RecyclerView rvSupportedOrder = (RecyclerView) findViewById(R.id.recycler_view_supported_order);\n rvSupportedOrder.setHasFixedSize(false);\n\n // Number of columns in the staggered grid view\n final int SPAN_COUNT = 2;\n\n GridLayoutManager layoutManager = new GridLayoutManager(this, SPAN_COUNT, GridLayoutManager.VERTICAL, false);\n layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n @Override\n public int getSpanSize(int position) {\n return (position % 3 == 0 ? 2 : 1);\n }\n });\n\n rvSupportedOrder.setLayoutManager(layoutManager);\n\n SupportedOrderAdapter supportedOrderAdapter = new SupportedOrderAdapter(SupportedOrderActivity.this);\n rvSupportedOrder.setAdapter(supportedOrderAdapter);\n\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n }\n\n\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/co/gobd/gofetch/activity/SupportedOrderActivity.java"},"old_contents":{"kind":"string","value":"package co.gobd.gofetch.activity;\n\nimport android.content.res.Configuration;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\n\nimport co.gobd.gofetch.R;\nimport co.gobd.gofetch.adapter.SupportedOrderAdapter;\nimport co.gobd.gofetch.mock.FakeServiceCall;\n\n\npublic class SupportedOrderActivity extends AppCompatActivity {\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_supported_order);\n\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n\n RecyclerView rvSupportedOrder = (RecyclerView) findViewById(R.id.recycler_view_supported_order);\n rvSupportedOrder.setHasFixedSize(false);\n\n // Number of columns in the staggered grid view\n final int SPAN_COUNT = 2;\n\n GridLayoutManager layoutManager = new GridLayoutManager(this, SPAN_COUNT, GridLayoutManager.VERTICAL, false);\n layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n @Override\n public int getSpanSize(int position) {\n return (position % 3 == 0 ? 2 : 1);\n }\n });\n\n rvSupportedOrder.setLayoutManager(layoutManager);\n\n SupportedOrderAdapter supportedOrderAdapter = new SupportedOrderAdapter(SupportedOrderActivity.this);\n rvSupportedOrder.setAdapter(supportedOrderAdapter);\n\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n }\n\n\n}\n"},"message":{"kind":"string","value":"GFETCH-72 Screen orientation change is handled in Activity#onConfigurationChanged() method. This solves the problem of recreating the activity and instances but causes some design issues. The app bar on protrait/landscaped mode is not properly showed, it keeps its previous state always. Need to fix this issue later but for now on, it's working.\n"},"old_file":{"kind":"string","value":"app/src/main/java/co/gobd/gofetch/activity/SupportedOrderActivity.java"},"subject":{"kind":"string","value":"GFETCH-72 Screen orientation change is handled in Activity#onConfigurationChanged() method. This solves the problem of recreating the activity and instances but causes some design issues. The app bar on protrait/landscaped mode is not properly showed, it keeps its previous state always. Need to fix this issue later but for now on, it's working."}}},{"rowIdx":1298,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"bd7b73664347e7b739149ce08caf6d71fffb91f1"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"chaoyi66/commons-lang,hollycroxton/commons-lang,byMan/naya279,PascalSchumacher/commons-lang,longestname1/commonslang,xuerenlv/commons-lang,jacktan1991/commons-lang,MuShiiii/commons-lang,MarkDacek/commons-lang,arbasha/commons-lang,vanta/commons-lang,chaoyi66/commons-lang,weston100721/commons-lang,xiwc/commons-lang,arbasha/commons-lang,xiwc/commons-lang,apache/commons-lang,MuShiiii/commons-lang,arbasha/commons-lang,mohanaraosv/commons-lang,apache/commons-lang,vanta/commons-lang,weston100721/commons-lang,jankill/commons-lang,PascalSchumacher/commons-lang,lovecindy/commons-lang,longestname1/commonslang,longestname1/commonslang,weston100721/commons-lang,Ajeet-Ganga/commons-lang,MuShiiii/commons-lang,Ajeet-Ganga/commons-lang,mohanaraosv/commons-lang,xuerenlv/commons-lang,MarkDacek/commons-lang,apache/commons-lang,suntengteng/commons-lang,byMan/naya279,chaoyi66/commons-lang,britter/commons-lang,jacktan1991/commons-lang,byMan/naya279,xiwc/commons-lang,jankill/commons-lang,lovecindy/commons-lang,hollycroxton/commons-lang,suntengteng/commons-lang,suntengteng/commons-lang,jacktan1991/commons-lang,britter/commons-lang,britter/commons-lang,MarkDacek/commons-lang,vanta/commons-lang,mohanaraosv/commons-lang,PascalSchumacher/commons-lang,Ajeet-Ganga/commons-lang,hollycroxton/commons-lang,xuerenlv/commons-lang,lovecindy/commons-lang,jankill/commons-lang"},"new_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF 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\n * the License. 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 */\npackage org.apache.commons.lang3.text.translate;\n\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.util.Arrays;\nimport java.util.EnumSet;\n\n/**\n * Translates escaped unicode values of the form \\\\u+\\d\\d\\d\\d back to \n * unicode.\n * \n * @author Apache Software Foundation\n * @since 3.0\n * @version $Id$\n */\npublic class UnicodeUnescaper extends CharSequenceTranslator {\n\n public static enum OPTION { escapePlus }\n\n // TODO?: Create an OptionsSet class to hide some of the conditional logic below\n private final EnumSet