{ // 获取包含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 CRLF +\n \"\" +\n CRLF, sResult);\n }\n}\n"},"new_file":{"kind":"string","value":"src/test/java/com/helger/commons/xml/serialize/write/XMLWriterTest.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (C) 2014-2015 Philip Helger (www.helger.com)\n * philip[at]helger[dot]com\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.helger.commons.xml.serialize.write;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.dom.DOMSource;\n\nimport org.junit.Test;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.SAXException;\n\nimport com.helger.commons.charset.CCharset;\nimport com.helger.commons.io.stream.NonBlockingByteArrayOutputStream;\nimport com.helger.commons.mock.AbstractCommonsTestCase;\nimport com.helger.commons.mock.CommonsTestHelper;\nimport com.helger.commons.system.ENewLineMode;\nimport com.helger.commons.xml.DefaultXMLIterationHandler;\nimport com.helger.commons.xml.EXMLVersion;\nimport com.helger.commons.xml.XMLFactory;\nimport com.helger.commons.xml.namespace.MapBasedNamespaceContext;\nimport com.helger.commons.xml.serialize.read.DOMReader;\nimport com.helger.commons.xml.transform.StringStreamResult;\nimport com.helger.commons.xml.transform.XMLTransformerFactory;\n\nimport edu.umd.cs.findbugs.annotations.SuppressFBWarnings;\n\n/**\n * Test class for {@link XMLWriter}\n *\n * @author Philip Helger\n */\npublic final class XMLWriterTest extends AbstractCommonsTestCase\n{\n private static final String DOCTYPE_XHTML10_QNAME = \"-//W3C//DTD XHTML 1.0 Strict//EN\";\n private static final String DOCTYPE_XHTML10_URI = \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\";\n private static final String CRLF = ENewLineMode.DEFAULT.getText ();\n\n /**\n * Test the method getXHTMLString\n */\n @SuppressFBWarnings (\"NP_NONNULL_PARAM_VIOLATION\")\n @Test\n public void testGetXHTMLString ()\n {\n final String sSPACER = \" \";\n final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING;\n final String sTAGNAME = \"notext\";\n\n // Java 1.6 JAXP handles things differently\n final String sSerTagName = \"<\" + sTAGNAME + \">\";\n\n final Document doc = XMLFactory.newDocument (\"html\", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI);\n final Element aHead = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI,\n \"head\"));\n aHead.appendChild (doc.createTextNode (\"Hallo\"));\n final Element aNoText = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI,\n sTAGNAME));\n aNoText.appendChild (doc.createTextNode (\"\"));\n\n // test including doc type\n {\n final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ());\n assertEquals (\"\" +\n CRLF +\n \"\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n sSerTagName +\n CRLF +\n \"\" +\n CRLF, sResult);\n assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()));\n }\n\n // test without doc type\n {\n final String sResult = XMLWriter.getNodeAsString (doc,\n XMLWriterSettings.createForXHTML ()\n .setSerializeDocType (EXMLSerializeDocType.IGNORE));\n assertEquals (\"\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n sSerTagName +\n CRLF +\n \"\" +\n CRLF, sResult);\n }\n\n {\n final String sResult = XMLWriter.getNodeAsString (doc,\n XMLWriterSettings.createForXHTML ()\n .setSerializeDocType (EXMLSerializeDocType.IGNORE)\n .setIndent (EXMLSerializeIndent.NONE));\n assertEquals (\"Hallo\" + sSerTagName + \"\", sResult);\n assertEquals (sResult,\n XMLWriter.getNodeAsString (doc,\n XMLWriterSettings.createForXHTML ()\n .setSerializeDocType (EXMLSerializeDocType.IGNORE)\n .setIndent (EXMLSerializeIndent.NONE)));\n }\n\n // add text element\n aNoText.appendChild (doc.createTextNode (\"Hallo \"));\n final Element b = (Element) aNoText.appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, \"strong\"));\n b.appendChild (doc.createTextNode (\"Welt\"));\n aNoText.appendChild (doc.createCDATASection (\"!!!\"));\n aNoText.appendChild (doc.createComment (\"No\"));\n\n // test without doc type\n {\n final String sResult = XMLWriter.getNodeAsString (doc,\n XMLWriterSettings.createForXHTML ()\n .setSerializeDocType (EXMLSerializeDocType.IGNORE)\n .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN));\n assertEquals (\"\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n \"Hallo Welt\" +\n CRLF +\n \"\" +\n CRLF, sResult);\n }\n\n // test as XML (with doc type and indent)\n {\n final String sResult = XMLWriter.getXMLString (doc);\n assertEquals (\"\" +\n CRLF +\n \"\" +\n CRLF +\n \"\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n \"Hallo Welt\" +\n CRLF +\n \"\" +\n CRLF, sResult);\n }\n\n // test as XML (without doc type and comments but indented)\n {\n final String sResult = XMLWriter.getNodeAsString (doc,\n new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE)\n .setSerializeComments (EXMLSerializeComments.IGNORE)\n .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN));\n assertEquals (\"\" +\n CRLF +\n \"\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n \"Hallo Welt\" +\n CRLF +\n \"\" +\n CRLF, sResult);\n }\n\n // test as XML (without doc type and comments but indented) with different\n // newline String\n {\n final String sResult = XMLWriter.getNodeAsString (doc,\n new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE)\n .setSerializeComments (EXMLSerializeComments.IGNORE)\n .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)\n .setNewLineMode (ENewLineMode.UNIX));\n assertEquals (\"\\n\" +\n \"\\n\" +\n sINDENT +\n \"Hallo\\n\" +\n sINDENT +\n \"Hallo Welt\\n\" +\n \"\\n\", sResult);\n }\n\n // test as XML (without doc type and comments but indented) with different\n // newline String and different indent\n {\n final String sResult = XMLWriter.getNodeAsString (doc,\n new XMLWriterSettings ().setSerializeDocType (EXMLSerializeDocType.IGNORE)\n .setSerializeComments (EXMLSerializeComments.IGNORE)\n .setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)\n .setNewLineMode (ENewLineMode.UNIX)\n .setIndentationString (\"\\t\"));\n assertEquals (\"\\n\" +\n \"\\n\" +\n \"\\tHallo\\n\" +\n \"\\tHallo Welt\\n\" +\n \"\\n\", sResult);\n }\n\n assertTrue (XMLWriter.writeToStream (doc, new NonBlockingByteArrayOutputStream ()).isSuccess ());\n new XMLSerializerCommons ().write (doc, new DefaultXMLIterationHandler ());\n }\n\n @Test\n public void testWriteXMLMultiThreaded ()\n {\n final String sSPACER = \" \";\n final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING;\n final String sTAGNAME = \"notext\";\n\n CommonsTestHelper.testInParallel (1000, new Runnable ()\n {\n public void run ()\n {\n // Java 1.6 JAXP handles things differently\n final String sSerTagName = \"<\" + sTAGNAME + \">\";\n\n final Document doc = XMLFactory.newDocument (\"html\", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI);\n final Element aHead = (Element) doc.getDocumentElement ()\n .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, \"head\"));\n aHead.appendChild (doc.createTextNode (\"Hallo\"));\n final Element aNoText = (Element) doc.getDocumentElement ()\n .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, sTAGNAME));\n aNoText.appendChild (doc.createTextNode (\"\"));\n\n // test including doc type\n final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ());\n assertEquals (\"\" +\n CRLF +\n \"\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n sSerTagName +\n CRLF +\n \"\" +\n CRLF, sResult);\n assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()));\n }\n });\n }\n\n @Test\n public void testNestedCDATAs ()\n {\n final Document doc = XMLFactory.newDocument ();\n\n // Containing the forbidden CDATA end marker\n Element e = doc.createElement (\"a\");\n e.appendChild (doc.createCDATASection (\"a]]>b\"));\n assertEquals (\"b]]>\" + CRLF, XMLWriter.getXMLString (e));\n\n // Containing more than one forbidden CDATA end marker\n e = doc.createElement (\"a\");\n e.appendChild (doc.createCDATASection (\"a]]>b]]>c\"));\n assertEquals (\"b]]]]>c]]>\" + CRLF, XMLWriter.getXMLString (e));\n\n // Containing a complete CDATA section\n e = doc.createElement (\"a\");\n e.appendChild (doc.createCDATASection (\"ab\"));\n assertEquals (\"b]]>\" + CRLF, XMLWriter.getXMLString (e));\n }\n\n @Test\n public void testWithNamespaceContext ()\n {\n final Document aDoc = XMLFactory.newDocument ();\n final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS (\"ns1url\", \"root\"));\n eRoot.appendChild (aDoc.createElementNS (\"ns2url\", \"child1\"));\n eRoot.appendChild (aDoc.createElementNS (\"ns2url\", \"child2\"));\n\n final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (CCharset.CHARSET_ISO_8859_1_OBJ)\n .setIndent (EXMLSerializeIndent.NONE);\n String s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext ();\n aCtx.addMapping (\"a\", \"ns1url\");\n aSettings.setNamespaceContext (aCtx);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n aCtx.addMapping (\"xy\", \"ns2url\");\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n aSettings.setUseDoubleQuotesForAttributes (false);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n aSettings.setSpaceOnSelfClosedElement (false);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n aSettings.setPutNamespaceContextPrefixesInRoot (true);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n eRoot.appendChild (aDoc.createElementNS (\"ns3url\", \"zz\"));\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n }\n\n @Test\n public void testWithoutEmitNamespaces ()\n {\n final Document aDoc = XMLFactory.newDocument ();\n final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS (\"ns1url\", \"root\"));\n eRoot.appendChild (aDoc.createElementNS (\"ns2url\", \"child1\"));\n eRoot.appendChild (aDoc.createElementNS (\"ns2url\", \"child2\"));\n\n final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (CCharset.CHARSET_ISO_8859_1_OBJ)\n .setIndent (EXMLSerializeIndent.NONE);\n String s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n aSettings.setEmitNamespaces (false);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n\n aSettings.setPutNamespaceContextPrefixesInRoot (true);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n }\n\n @Test\n public void testXMLVersionNumber ()\n {\n Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10);\n aDoc.appendChild (aDoc.createElement (\"any\"));\n String sXML = XMLWriter.getXMLString (aDoc);\n assertEquals (\"\" + CRLF + \"\" + CRLF, sXML);\n\n aDoc = XMLFactory.newDocument (EXMLVersion.XML_11);\n aDoc.appendChild (aDoc.createElement (\"any\"));\n sXML = XMLWriter.getXMLString (aDoc);\n assertEquals (\"\" + CRLF + \"\" + CRLF, sXML);\n }\n\n @Test\n public void testNumericReferencesXML10 () throws SAXException, TransformerException\n {\n for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i)\n if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_10, (char) i))\n {\n final String sText = \"abc\" + (char) i + \"def\";\n final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10);\n final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement (\"root\"));\n eRoot.appendChild (aDoc.createTextNode (sText));\n\n // Use regular transformer\n final Transformer aTransformer = XMLTransformerFactory.newTransformer ();\n aTransformer.setOutputProperty (OutputKeys.ENCODING, CCharset.CHARSET_UTF_8);\n aTransformer.setOutputProperty (OutputKeys.INDENT, \"yes\");\n aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_10.getVersion ());\n final StringStreamResult aRes = new StringStreamResult ();\n aTransformer.transform (new DOMSource (aDoc), aRes);\n\n final String sXML = aRes.getAsString ();\n final Document aDoc2 = DOMReader.readXMLDOM (sXML);\n assertNotNull (aDoc2);\n }\n }\n\n @Test\n public void testNumericReferencesXML11 () throws SAXException, TransformerException\n {\n for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i)\n if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_11, (char) i))\n {\n final String sText = \"abc\" + (char) i + \"def\";\n final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_11);\n final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement (\"root\"));\n eRoot.appendChild (aDoc.createTextNode (sText));\n\n final Transformer aTransformer = XMLTransformerFactory.newTransformer ();\n aTransformer.setOutputProperty (OutputKeys.ENCODING, CCharset.CHARSET_UTF_8);\n aTransformer.setOutputProperty (OutputKeys.INDENT, \"no\");\n aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_11.getVersion ());\n final StringStreamResult aRes = new StringStreamResult ();\n aTransformer.transform (new DOMSource (aDoc), aRes);\n\n final String sXML = aRes.getAsString ();\n final Document aDoc2 = DOMReader.readXMLDOM (sXML);\n assertNotNull (aDoc2);\n }\n }\n\n @Test\n public void testAttributesWithNamespaces () throws SAXException\n {\n final XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE)\n .setCharset (CCharset.CHARSET_ISO_8859_1_OBJ);\n final Document aDoc = XMLFactory.newDocument ();\n final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS (\"ns1url\", \"root\"));\n final Element e1 = (Element) eRoot.appendChild (aDoc.createElementNS (\"ns2url\", \"child1\"));\n e1.setAttributeNS (\"ns2url\", \"attr1\", \"value1\");\n final Element e2 = (Element) eRoot.appendChild (aDoc.createElementNS (\"ns2url\", \"child2\"));\n e2.setAttributeNS (\"ns3url\", \"attr2\", \"value2\");\n\n String s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n assertEquals (s, XMLWriter.getNodeAsString (DOMReader.readXMLDOM (s), aSettings));\n\n aSettings.setEmitNamespaces (false);\n s = XMLWriter.getNodeAsString (aDoc, aSettings);\n assertEquals (\"\"\n + \"\"\n + \"\"\n + \"\"\n + \"\", s);\n }\n}\n"},"message":{"kind":"string","value":"Added test for bracket mode handler"},"old_file":{"kind":"string","value":"src/test/java/com/helger/commons/xml/serialize/write/XMLWriterTest.java"},"subject":{"kind":"string","value":"Added test for bracket mode handler"},"git_diff":{"kind":"string","value":"rc/test/java/com/helger/commons/xml/serialize/write/XMLWriterTest.java\n import com.helger.commons.xml.transform.StringStreamResult;\n import com.helger.commons.xml.transform.XMLTransformerFactory;\n \nimport edu.umd.cs.findbugs.annotations.SuppressFBWarnings;\n\n /**\n * Test class for {@link XMLWriter}\n *\n private static final String DOCTYPE_XHTML10_URI = \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\";\n private static final String CRLF = ENewLineMode.DEFAULT.getText ();\n \n /**\n * Test the method getXHTMLString\n */\n @SuppressFBWarnings (\"NP_NONNULL_PARAM_VIOLATION\")\n @Test\n public void testGetXHTMLString ()\n {\n + \"\"\n + \"\", s);\n }\n\n @Test\n public void testHTML4BracketMode ()\n {\n final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING;\n\n final Document doc = XMLFactory.newDocument (\"html\", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI);\n final Element aHead = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI,\n \"head\"));\n aHead.appendChild (doc.createTextNode (\"Hallo\"));\n final Element aNoText = (Element) doc.getDocumentElement ().appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI,\n \"body\"));\n aNoText.appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, \"img\"));\n\n // test including doc type\n final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ());\n assertEquals (\" DOCTYPE_XHTML10_QNAME +\n \"\\\" \\\"\" +\n DOCTYPE_XHTML10_URI +\n \"\\\">\" +\n CRLF +\n \" DOCTYPE_XHTML10_URI +\n \"\\\">\" +\n CRLF +\n sINDENT +\n \"Hallo\" +\n CRLF +\n sINDENT +\n \"\" +\n CRLF +\n sINDENT +\n sINDENT +\n // Unclosed img :)\n \"\" +\n CRLF +\n sINDENT +\n \"\" +\n CRLF +\n \"\" +\n CRLF, sResult);\n }\n }"}}},{"rowIdx":198738,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"2fbc95fa8da1868a8b5c3fa548e0bb0855b51d66"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"UNFPAInnovation/GetIn_Mobile,UNFPAInnovation/GetIn_Mobile"},"new_contents":{"kind":"string","value":"package org.sana.android.procedure;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.graphics.drawable.Animatable;\nimport android.text.TextUtils;\nimport android.util.Log;\nimport android.view.Gravity;\nimport android.view.View;\nimport android.view.ViewGroup.LayoutParams;\nimport android.view.animation.Animation;\nimport android.widget.Button;\nimport android.widget.Gallery;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport org.sana.R;\nimport org.sana.android.media.AudioPlayer;\nimport org.sana.android.media.EducationResource;\nimport org.sana.android.util.SanaUtil;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.Text;\n\nimport java.net.URISyntaxException;\n\n/**\n * A ProcedureElement is an item that can be placed on a page in a Sana \n * procedure. Typically there will only be one ProcedureElement per page, but \n * this style suggestion is not enforced, and users can make XML procedure \n * definitions that contain several ProcedureElements per page. \n *

\n * A ProcedureElement, generally speaking, asks a question and may allow for an \n * answer. For example, a RadioElement poses a question and allows a user to \n * choose among response buttons.\n * \n * ProcedureElements are defined in XML and dynamically created from the XML in \n * Sana.\n *

\n *

    \n *
  • Clinical Use Defined by subclasses.
  • \n *
  • Collects Defined by subclasses.
  • \n *
\n * The Collects documentation should declare the format of any returned\n * answer strings\n * \n * @author Sana Development Team\n */\npublic abstract class ProcedureElement {\n public static String TAG = ProcedureElement.class.getSimpleName();\n \n /**\n * An enumeration of the valid ProcedureElement types.\n * \n * @author Sana Development Team\n */\n public static enum ElementType {\n \t/** Provides text display */\n \tTEXT(\"\"),\n \t\n \t/** Provides text capture. */\n ENTRY(\"\"), \n \n /** Provides exclusive option selector as a dropdown box. */\n SELECT(\"\"), \n \n /** An entry element for displaying/entering a patient identifier */\n PATIENT_ID(\"\"),\n \n /** A non-exclusive option selector as a list of checkboxes. */\n MULTI_SELECT(\"\"), \n \n /** An exclusive multi-option selector as a list of radio buttons */\n RADIO(\"\"), \n \n /** Provides capture of one or more images */\n PICTURE(\"image.jpg\"),\n \n /** Provides capture of a single audio resource. */\n SOUND(\"sound.3gp\"),\n \n /** Provides attachment of a binary file for upload */\n BINARYFILE(\"binary.bin\"),\n \n /** A marker for invalid elements */\n INVALID(\"\"), \n \n /** Provides capture of GPS coordinates */\n GPS(\"\"),\n \n /** Provides capture of a date */ \n DATE(\"\"),\n \n /** Provides a viewable resource for patient education. */\n EDUCATION_RESOURCE(\"\"),\n \n /** Provides access to 3rd party tools for data capture where the data\n * is returned directly. \n */\n PLUGIN(\"\"),\n \n /** Provides access to 3rd party tools for data capture where the data\n * is not returned directly and must be manually entered by the user. \n */\n ENTRY_PLUGIN(\"\"),\n HIDDEN(\"\"),\n AGE(\"\"),\n TRUTH;\n \t\n private String filename;\n\n private ElementType(){ this(\"\"); }\n\n private ElementType(String filename) {\n \tthis.filename = filename;\n }\n \n /**\n * Returns the default filename for a given ElementType\n * @return\n */\n public String getFilename() {\n \treturn filename;\n }\n }\n \n protected String id;\n protected String question;\n protected String answer;\n protected String concept;\n protected String action = null;\n\n // Resource of a corresponding figure for this element.\n protected String figure;\n // Resource of a corresponding audio prompt for this element.\n protected String audioPrompt;\n // Whether a null answer is allowed\n private boolean bRequired = false;\n\n // Optional attributes - specific element types must implement as necessary\n protected String defaultValue = null;\n protected String defaultPrompt = null;\n private Procedure procedure;\n private Context cachedContext;\n private View cachedView;\n private AudioPlayer mAudioPlayer;\n private String helpText;\n\n /**\n * Constructs the view of this ProcedureElement\n * \n * @param c the current Context\n */\n protected abstract View createView(Context c);\n \n void clearCachedView() {\n \tcachedView = null;\n }\n \n /**\n * Constructs a new Instance.\n * \n * @param id The unique identifier of this element within its procedure.\n * @param question The text that will be displayed to the user as a question\n * @param answer The result of data capture.\n * @param concept A required categorization of the type of data captured.\n * @param figure An optional figure to display to the user.\n * @param audioPrompt An optional audio prompt to play for the user. \n */\n protected ProcedureElement(String id, String question, String answer, \n \t\tString concept, String figure, String audioPrompt) \n {\n this.id = id;\n this.question = question;\n this.answer = answer;\n this.concept = concept;\n this.figure = figure;\n this.audioPrompt = audioPrompt;\n }\n \n /**\n * A reference to the enclosing Procedure\n * @return A Procedure instance.\n */\n protected Procedure getProcedure() { // set the ImageView bounds to match the Drawable's dimensions\n return procedure;\n }\n \n /**\n * Sets the enclosing procedure\n * @param procedure the new enclosing procedure.\n */\n public void setProcedure(Procedure procedure) {\n this.procedure = procedure;\n }\n \n /** \n * Whether this element is considered active.\n * @return\n */\n protected boolean isViewActive() {\n return !(cachedView == null);\n }\n \n /**\n * A cached Context.\n * @return The Context this element holds a reference to.\n */\n protected Context getContext() {\n return cachedContext;\n }\n \n /**\n * A visible representation of this object.\n * @param c The Context which will be used in the View constructors for this \n * \t\t\tobject's representation.\n * @return A new view of this object or cached view if it exists.\n */\n public View toView(Context c) {\n if(cachedView == null || cachedContext != c) {\n cachedView = createView(c);\n cachedContext = c;\n\n }\n return cachedView;\n }\n\n\t/**\n\t * Returns the ElementType of this element as defined in the \n\t * ProcedureElement ElementType enum.\n\t */\n public abstract ElementType getType(); \n \n /** \n * Gets the value of the answer attribute.\n * \n * @return A String representation of collected data.\n */\n public String getAnswer(){\n \t return answer;\n }\n \n /** \n * Set the value of the answer attribute as a String representation of \n * collected data.\n * \n * @param answer the new answer\n */\n public void setAnswer(String answer){\n \tthis.answer = answer;\n }\n \n /**\n * Whether this element is considered required\n * @return\n */\n public boolean isRequired() {\n \treturn bRequired;\n }\n \n /**\n * Sets the required state of this element.\n * @param required The new required state.\n */\n public void setRequired(boolean required) {\n \tthis.bRequired = required;\n }\n \n /**\n * Help text associated with this element\n * @return An informative string.\n */\n public String getHelpText() {\n \treturn helpText;\n }\n \n /**\n * Sets the help text for this instance.\n * @param helpText the new help string.\n */\n public void setHelpText(String helpText) {\n \tthis.helpText = helpText;\n }\n \n public String getAction(){\n \treturn action;\n }\n \n /**\n * Whether this element is valid.\n * @return true if not required or required and answer is not empty\n * @throws ValidationError\n */\n public boolean validate() throws ValidationError {\n \tif (bRequired && \"\".equals(getAnswer().trim())) {\n \t\tString msg = TextUtils.isEmpty(helpText)? \n \t\t\t\tgetString(R.string.general_input_required): helpText;\n \t\tthrow new ValidationError(msg);\n \t}\n \treturn true;\n }\n \n /**\n * Tell the element's widget to refresh itself. \n */\n public void refreshWidget() {\n \n }\n \n /**\n * Writes a string representation of this object to a StringBuilder. \n * Extending classes should override appendOptionalAttributes if they \n * require attributes beyond those defined in this class.\n * \n * @param sb the builder to write to.\n */\n public void buildXML(StringBuilder sb){\n sb.append(\"\\n\");\n }\n\n protected void appendOptionalAttributes(StringBuilder sb){\n \tif(!TextUtils.isEmpty(action))\n \t\tsb.append(\"action=\\\"\" + action+ \"\\\" \");\n if(hasDefault())\n sb.append(\"default=\\\"\" + getDefault()+ \"\\\" \");\n \treturn;\n }\n \n /**\n\t * Build the XML representation of this ProcedureElement. Should only use\n\t * this if you intend to use only the XML for this element. If you are\n\t * building the XML for this Procedure, then prefer buildXML with a\n\t * StringBuilder since String operations are slow.\n\t */\n public String toXML() {\n \tStringBuilder sb = new StringBuilder();\n \tbuildXML(sb);\n \treturn sb.toString();\n }\n \n /**\n * Create an element from an XML element node of a procedure definition.\n * @param node a Node object containing a ProcedureElement representation\n */\n public static ProcedureElement createElementfromXML(Node node) throws \n \tProcedureParseException \n {\n //Log.i(TAG, \"fromXML(\" + node.getNodeName() + \")\");\n \n if(!node.getNodeName().equals(\"Element\")) {\n throw new ProcedureParseException(\"Element got NodeName \" \n \t\t+ node.getNodeName());\n }\n\n String questionStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"question\", \"\");\n String answerStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"answer\", null);\n String typeStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"type\", \"INVALID\");\n String conceptStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"concept\", \"\");\n String idStr = SanaUtil.getNodeAttributeOrFail(node, \"id\", \n \t\tnew ProcedureParseException(\"Element doesn't have id number\"));\n String figureStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"figure\", \"\");\n String audioStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"audio\", \"\");\n \n ElementType etype = ElementType.valueOf(typeStr);\n \n ProcedureElement el = null;\n switch(etype) {\n case TEXT:\n el = TextElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case ENTRY:\n el = TextEntryElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case SELECT:\n el = SelectElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case MULTI_SELECT:\n el = MultiSelectElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case RADIO:\n el = RadioElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case PICTURE:\n el = PictureElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case SOUND:\n el = SoundElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case GPS:\n el = GpsElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case BINARYFILE:\n el = BinaryUploadElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case PATIENT_ID:\n el = PatientIdElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case DATE:\n el = DateElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case EDUCATION_RESOURCE:\n el = EducationResourceElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case PLUGIN:\n el = PluginElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case ENTRY_PLUGIN:\n el = PluginEntryElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n\n case HIDDEN:\n el = HiddenElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n\n case AGE:\n el = AgeElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case TRUTH:\n el = TruthElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case INVALID:\n default:\n throw new ProcedureParseException(\"Got invalid node type : \" \n \t\t+ etype);\n }\n \n if (el == null) {\n \tthrow new ProcedureParseException(\"Failed to parse node with id \" \n \t\t\t+ idStr);\n }\n\n String helpStr = SanaUtil.getNodeAttributeOrDefault(node, \"helpText\",\n \t\t\"\");\n el.setHelpText(helpStr);\n \n String requiredStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"required\", \"false\");\n if (\"true\".equals(requiredStr)) {\n \tel.setRequired(true);\n } else if (\"false\".equals(requiredStr)) {\n \tel.setRequired(false);\n } else {\n \tthrow new ProcedureParseException(\"Argument to \\'required\\' \"+\n \t\t\t\"attribute invalid for id \" + idStr \n \t\t\t+ \". Must be \\'true\\' or \\'false\\'\");\n }\n \n return el;\n }\n \n public static void parseOptionalAttributes(Node node, ProcedureElement el)\n throws ProcedureParseException {\n Log.i(TAG, \"parseOptionalAttributes(Node,ProcedureElement)\");\n String attr = null;\n\n // action\n attr = SanaUtil.getNodeAttributeOrDefault(node,\n \t\t\"action\", \"\");\n if(!TextUtils.isEmpty(attr))\n el.action = new String(attr);\n\n // default\n attr = SanaUtil.getNodeAttributeOrDefault(node,\n \"default\", \"\");\n el.setDefault(new String(attr));\n\n // helpText\n attr = SanaUtil.getNodeAttributeOrDefault(node, \"helpText\",\n \"\");\n el.setHelpText(new String(attr));\n\n // required\n attr = SanaUtil.getNodeAttributeOrDefault(node,\n \"required\", \"false\");\n if (\"true\".equals(attr)) {\n el.setRequired(true);\n } else if (\"false\".equals(attr)) {\n el.setRequired(false);\n } else {\n throw new ProcedureParseException(\"Argument to \\'required\\' \" +\n \"attribute invalid for id \" + el.getId()+\n \". Must be \\'true\\' or \\'false\\'\");\n }\n }\n \n \n /** @return The value of the id attribute */\n public String getId() {\n return id;\n }\n\n /** @return Gets the identifier for any associated education resources */\n public String mediaId(){\n \treturn EducationResource.toId(concept+question);\n }\n \n /**\n * @return the question string originally defined in the XML procedure \n * definition.\n */\n public String getQuestion() {\n return question;\n }\n \n /**\n * @return the medical concept associated with this ProcedureElement\n */\n public String getConcept() {\n \treturn concept;\n }\n \n /**\n * @return the figure URL associated with this ProcedureElement\n */\n public String getFigure() {\n \treturn figure;\n }\n /** @return true if this instance has an audio prompt */\n boolean hasAudioPrompt() {\n \treturn !\"\".equals(audioPrompt);\n }\n \n /** plays this instance's audio prompt */\n void playAudioPrompt() {\n \tif (mAudioPlayer != null)\n \t\tmAudioPlayer.play();\n }\n \n /** @return the audioPrompt string */\n public String getAudioPrompt() {\n \treturn audioPrompt;\n }\n \n /**\n * Returns a localized String from the application package's default string\n * table.\n * \n * @param resId Resource Id for the string\n * @return\n */\n public String getString(int resId){\n \treturn getContext().getString(resId);\n }\n \n /** \n * Appends another View object a view of this object to a new View .\n * @param c A valid Context.\n * @param v The view to append first.\n * @return A new View containing the parameter View and a View of this \n * \t\tobject.\n */\n public View encapsulateQuestion(Context c, View v) {\n \t\n \t// Add question view\n \tTextView textView = new TextView(c);\n \ttextView.setSingleLine(false);\n textView.setGravity(Gravity.LEFT);\n\t\tString q = question.replace(\"\\\\n\", \"\\n\");\n Log.d(TAG, \"...show question id = \" + getProcedure().idsShown());\n \tif(getProcedure().idsShown() && !getType().equals(ElementType.TEXT)){\n \t\ttextView.setText(String.format(\"%s: %s\", getId(), q));\n \t}else{\n \ttextView.setText(q);\n \t}\n \t//textView.setGravity(Gravity.CENTER_HORIZONTAL);\n \ttextView.setTextAppearance(c, android.R.style.TextAppearance_Large);\n \tView questionView = textView;\n \tquestionView.setPadding(10,5,10,5);\n \t// Add image if provided\n ImageView imageView = null;\n \n //Set accompanying figure\n if(!TextUtils.isEmpty(figure)) { \n\t try{\n\t \tString imagePath = c.getPackageName() + \":\" + figure;\n\t \tLog.d(TAG, \"Using figure: \" + figure);\n\t \tint resID = c.getResources().getIdentifier(figure, null, \n\t \t\t\tnull);\n\t \tLog.d(TAG, \"Using figure id: \" + resID);\n\t \timageView = new ImageView(c);\n\t \timageView.setImageResource(resID);\n\t \timageView.setAdjustViewBounds(true);\n\t \t // set the ImageView bounds to match the Drawable's dimensions\n\t \timageView.setLayoutParams(new Gallery.LayoutParams(\n\t \t\t\tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t \timageView.setPadding(10,10,10,10);\n\t }\n\t catch(Exception e){\n\t \tLog.e(TAG, \"Couldn't find resource figure \" + e.toString());\n\t }\n }\n \n // Add audio prompt if provided\n if (hasAudioPrompt()) {\n \ttry {\n \t\tString resourcePath = c.getPackageName() + \":\" + audioPrompt;\n \t\tint resID = c.getResources().getIdentifier(resourcePath, \n \t\t\t\tnull, null);\n \t\tLog.i(TAG, \"Looking up ID for resource: \" + resourcePath + \", \" \n \t\t\t\t+ \"got \" + resID);\n \t\t\n \t\tif (resID != 0) {\n\t \t\tmAudioPlayer = new AudioPlayer(resID);\n\t \t\tView playerView = mAudioPlayer.createView(c);\n\t \t\tplayerView.setLayoutParams(new LayoutParams(\n\t \t\t\tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t \t\tLinearLayout audioPromptView = new LinearLayout(c);\n\t audioPromptView.setOrientation(LinearLayout.HORIZONTAL);\n\t audioPromptView.setLayoutParams(new LayoutParams(\n\t \tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t audioPromptView.setGravity(Gravity.CENTER);\n\t \n\t // Insert the play button to the left of the current \n\t // question view.\n\t audioPromptView.addView(playerView);\n\t audioPromptView.addView(questionView);\n\t questionView = audioPromptView;\n \t\t}\n \t} catch (Exception e) {\n \t\tLog.e(TAG, \"Couldn't find resource for audio prompt: \" \n \t\t\t\t+ e.toString());\n \t}\n }\n\n \t\t\n //Log.d(TAG, \"Loaded: \" +this.toString());\n \tLinearLayout ll = new LinearLayout(c);\n \tll.setOrientation(LinearLayout.VERTICAL);\n\n \t//Add to layout\n \tll.addView(questionView);\n \tif (imageView != null)\n \t\tll.addView(imageView);\n\n \t// Add Buttons if provided\n \tif(!TextUtils.isEmpty(action)){\n \t\tView actionView = getActions(c);\n actionView.setPadding(5,5,5,5);\n \t\tll.addView(actionView);\n \t} else {\n //Log.w(TAG, \"Empty action string!\");\t\n \t}\n \t\n \tif(v != null){\n \t\tLinearLayout viewHolder = new LinearLayout(c);\n \t\t\n \t\tviewHolder.addView(v);\n \t\tviewHolder.setGravity(Gravity.CENTER_HORIZONTAL);\n \t\tll.addView(viewHolder, new LayoutParams(LayoutParams.MATCH_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \t}\n \t\t\n \tll.setGravity(Gravity.CENTER);\n \tll.setPadding(5, 0, 5, 0);\n \tll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n return ll;\n }\n \n @Override\n public String toString(){\n \t/*\n \tGson gson = new Gson();\n \treturn gson.toJson(this);\n \t*/\n \treturn String.format(\"ProcedureElement: type=%s, concept=%s, \"\n \t\t+\"required=%s, id=%s, question=%s, figure=%s, audio=%s, answer=%s,\"\n \t\t+\"action=%s\",\n \t getType(), concept, bRequired, id, question, figure, audioPrompt, \n \t answer,action);\n }\n \n /**\n * Returns a View containing a set of buttons, each of which can be\n * used as a launch point for another activity. \n * \n * @see {@link #getAction()} for more on action String format\n * @return a View containing a list of action buttons\n */\n public View getActions(Context c){\n\t\tLog.d(TAG, \"action=\" + action);\n \tLinearLayout ll = new LinearLayout(c);\n \tll.setOrientation(LinearLayout.VERTICAL);\n \tll.setGravity(Gravity.CENTER);\n ll.setBackgroundColor(Color.CYAN);\n \tll.setPadding(5, 0, 5, 0);\n \tll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \t\n \t// Get the intent \n \tfor(String intentStr: action.split(\",\")){\n \t\tLog.d(TAG, intentStr);\n \t\tButton button = new Button(c);\n \t\tbutton.setTextColor(Color.BLUE);\n button.setHint(\"TOUCH TO CALL\");\n button.setHintTextColor(Color.CYAN);\n button.setText(\"Call Anbulance\");\n \t\ttry {\n\t\t\t\tIntent buttonAction = Intent.parseUri(intentStr, Intent.URI_INTENT_SCHEME);\n\t \t\tbutton.setTag(buttonAction);\n\t \t\tbutton.setText(buttonAction.getStringExtra(Intent.EXTRA_TITLE));\n\t \t\tbutton.setOnClickListener(new View.OnClickListener(){\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\t\tIntent intent = (Intent) v.getTag();\n\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t}});\n\t\t\t} catch (URISyntaxException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t\tll.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \t}\n \t\n \t\n \treturn ll;\n }\n \n protected final Activity getActivity(){\n \treturn (Activity) getContext();\n }\n \n protected final void startActivity(Intent intent){\n \tActivity activity = getActivity();\n\t\tIntent launcher = new Intent(getContext(), activity.getClass());\n\t\tlauncher.putExtra(Intent.EXTRA_INTENT, intent);\n\t\tlauncher.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n\t\tgetContext().startActivity(launcher);\n }\n\n public String getDefault(){\n Log.i(TAG, \"getDefault()\");\n return defaultValue;\n }\n\n public void setDefault(String defaultValue){\n Log.i(TAG, \"setDefault(String)\");\n this.defaultValue = defaultValue;\n }\n\n public boolean hasDefault(){\n Log.i(TAG, \"hasDefault()\");\n return !TextUtils.isEmpty(defaultValue);\n }\n\n /** \n * Creates the element from an XML procedure definition.\n * \n * @param id The unique identifier of this element within its procedure.\n * @param question The text that will be displayed to the user as a question\n * @param answer The result of data capture.\n * @param concept A required categorization of the type of data captured.\n * @param figure An optional figure to display to the user.\n * @param audio An optional audio prompt to play for the user. \n * @param node The source xml node. \n * @return A new element.\n * @throws ProcedureParseException if an error occurred while parsing \n * \t\tadditional information from the Node\n */\n public static ProcedureElement fromXML(String id, String question, \n \tString answer, String concept, String figure, String audio, Node node) \n \tthrows ProcedureParseException \n {\n \tthrow new UnsupportedOperationException();\n }\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/org/sana/android/procedure/ProcedureElement.java"},"old_contents":{"kind":"string","value":"package org.sana.android.procedure;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.text.TextUtils;\nimport android.util.Log;\nimport android.view.Gravity;\nimport android.view.View;\nimport android.view.ViewGroup.LayoutParams;\nimport android.widget.Button;\nimport android.widget.Gallery;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport org.sana.R;\nimport org.sana.android.media.AudioPlayer;\nimport org.sana.android.media.EducationResource;\nimport org.sana.android.util.SanaUtil;\nimport org.w3c.dom.Node;\n\nimport java.net.URISyntaxException;\n\n/**\n * A ProcedureElement is an item that can be placed on a page in a Sana \n * procedure. Typically there will only be one ProcedureElement per page, but \n * this style suggestion is not enforced, and users can make XML procedure \n * definitions that contain several ProcedureElements per page. \n *

\n * A ProcedureElement, generally speaking, asks a question and may allow for an \n * answer. For example, a RadioElement poses a question and allows a user to \n * choose among response buttons.\n * \n * ProcedureElements are defined in XML and dynamically created from the XML in \n * Sana.\n *

\n *

    \n *
  • Clinical Use Defined by subclasses.
  • \n *
  • Collects Defined by subclasses.
  • \n *
\n * The Collects documentation should declare the format of any returned\n * answer strings\n * \n * @author Sana Development Team\n */\npublic abstract class ProcedureElement {\n public static String TAG = ProcedureElement.class.getSimpleName();\n \n /**\n * An enumeration of the valid ProcedureElement types.\n * \n * @author Sana Development Team\n */\n public static enum ElementType {\n \t/** Provides text display */\n \tTEXT(\"\"),\n \t\n \t/** Provides text capture. */\n ENTRY(\"\"), \n \n /** Provides exclusive option selector as a dropdown box. */\n SELECT(\"\"), \n \n /** An entry element for displaying/entering a patient identifier */\n PATIENT_ID(\"\"),\n \n /** A non-exclusive option selector as a list of checkboxes. */\n MULTI_SELECT(\"\"), \n \n /** An exclusive multi-option selector as a list of radio buttons */\n RADIO(\"\"), \n \n /** Provides capture of one or more images */\n PICTURE(\"image.jpg\"),\n \n /** Provides capture of a single audio resource. */\n SOUND(\"sound.3gp\"),\n \n /** Provides attachment of a binary file for upload */\n BINARYFILE(\"binary.bin\"),\n \n /** A marker for invalid elements */\n INVALID(\"\"), \n \n /** Provides capture of GPS coordinates */\n GPS(\"\"),\n \n /** Provides capture of a date */ \n DATE(\"\"),\n \n /** Provides a viewable resource for patient education. */\n EDUCATION_RESOURCE(\"\"),\n \n /** Provides access to 3rd party tools for data capture where the data\n * is returned directly. \n */\n PLUGIN(\"\"),\n \n /** Provides access to 3rd party tools for data capture where the data\n * is not returned directly and must be manually entered by the user. \n */\n ENTRY_PLUGIN(\"\"),\n HIDDEN(\"\"),\n AGE(\"\"),\n TRUTH;\n \t\n private String filename;\n\n private ElementType(){ this(\"\"); }\n\n private ElementType(String filename) {\n \tthis.filename = filename;\n }\n \n /**\n * Returns the default filename for a given ElementType\n * @return\n */\n public String getFilename() {\n \treturn filename;\n }\n }\n \n protected String id;\n protected String question;\n protected String answer;\n protected String concept;\n protected String action = null;\n\n // Resource of a corresponding figure for this element.\n protected String figure;\n // Resource of a corresponding audio prompt for this element.\n protected String audioPrompt;\n // Whether a null answer is allowed\n private boolean bRequired = false;\n\n // Optional attributes - specific element types must implement as necessary\n protected String defaultValue = null;\n protected String defaultPrompt = null;\n private Procedure procedure;\n private Context cachedContext;\n private View cachedView;\n private AudioPlayer mAudioPlayer;\n private String helpText;\n\n /**\n * Constructs the view of this ProcedureElement\n * \n * @param c the current Context\n */\n protected abstract View createView(Context c);\n \n void clearCachedView() {\n \tcachedView = null;\n }\n \n /**\n * Constructs a new Instance.\n * \n * @param id The unique identifier of this element within its procedure.\n * @param question The text that will be displayed to the user as a question\n * @param answer The result of data capture.\n * @param concept A required categorization of the type of data captured.\n * @param figure An optional figure to display to the user.\n * @param audioPrompt An optional audio prompt to play for the user. \n */\n protected ProcedureElement(String id, String question, String answer, \n \t\tString concept, String figure, String audioPrompt) \n {\n this.id = id;\n this.question = question;\n this.answer = answer;\n this.concept = concept;\n this.figure = figure;\n this.audioPrompt = audioPrompt;\n }\n \n /**\n * A reference to the enclosing Procedure\n * @return A Procedure instance.\n */\n protected Procedure getProcedure() { // set the ImageView bounds to match the Drawable's dimensions\n return procedure;\n }\n \n /**\n * Sets the enclosing procedure\n * @param procedure the new enclosing procedure.\n */\n public void setProcedure(Procedure procedure) {\n this.procedure = procedure;\n }\n \n /** \n * Whether this element is considered active.\n * @return\n */\n protected boolean isViewActive() {\n return !(cachedView == null);\n }\n \n /**\n * A cached Context.\n * @return The Context this element holds a reference to.\n */\n protected Context getContext() {\n return cachedContext;\n }\n \n /**\n * A visible representation of this object.\n * @param c The Context which will be used in the View constructors for this \n * \t\t\tobject's representation.\n * @return A new view of this object or cached view if it exists.\n */\n public View toView(Context c) {\n if(cachedView == null || cachedContext != c) {\n cachedView = createView(c);\n cachedContext = c;\n\n }\n return cachedView;\n }\n\n\t/**\n\t * Returns the ElementType of this element as defined in the \n\t * ProcedureElement ElementType enum.\n\t */\n public abstract ElementType getType(); \n \n /** \n * Gets the value of the answer attribute.\n * \n * @return A String representation of collected data.\n */\n public String getAnswer(){\n \t return answer;\n }\n \n /** \n * Set the value of the answer attribute as a String representation of \n * collected data.\n * \n * @param answer the new answer\n */\n public void setAnswer(String answer){\n \tthis.answer = answer;\n }\n \n /**\n * Whether this element is considered required\n * @return\n */\n public boolean isRequired() {\n \treturn bRequired;\n }\n \n /**\n * Sets the required state of this element.\n * @param required The new required state.\n */\n public void setRequired(boolean required) {\n \tthis.bRequired = required;\n }\n \n /**\n * Help text associated with this element\n * @return An informative string.\n */\n public String getHelpText() {\n \treturn helpText;\n }\n \n /**\n * Sets the help text for this instance.\n * @param helpText the new help string.\n */\n public void setHelpText(String helpText) {\n \tthis.helpText = helpText;\n }\n \n public String getAction(){\n \treturn action;\n }\n \n /**\n * Whether this element is valid.\n * @return true if not required or required and answer is not empty\n * @throws ValidationError\n */\n public boolean validate() throws ValidationError {\n \tif (bRequired && \"\".equals(getAnswer().trim())) {\n \t\tString msg = TextUtils.isEmpty(helpText)? \n \t\t\t\tgetString(R.string.general_input_required): helpText;\n \t\tthrow new ValidationError(msg);\n \t}\n \treturn true;\n }\n \n /**\n * Tell the element's widget to refresh itself. \n */\n public void refreshWidget() {\n \n }\n \n /**\n * Writes a string representation of this object to a StringBuilder. \n * Extending classes should override appendOptionalAttributes if they \n * require attributes beyond those defined in this class.\n * \n * @param sb the builder to write to.\n */\n public void buildXML(StringBuilder sb){\n sb.append(\"\\n\");\n }\n\n protected void appendOptionalAttributes(StringBuilder sb){\n \tif(!TextUtils.isEmpty(action))\n \t\tsb.append(\"action=\\\"\" + action+ \"\\\" \");\n if(hasDefault())\n sb.append(\"default=\\\"\" + getDefault()+ \"\\\" \");\n \treturn;\n }\n \n /**\n\t * Build the XML representation of this ProcedureElement. Should only use\n\t * this if you intend to use only the XML for this element. If you are\n\t * building the XML for this Procedure, then prefer buildXML with a\n\t * StringBuilder since String operations are slow.\n\t */\n public String toXML() {\n \tStringBuilder sb = new StringBuilder();\n \tbuildXML(sb);\n \treturn sb.toString();\n }\n \n /**\n * Create an element from an XML element node of a procedure definition.\n * @param node a Node object containing a ProcedureElement representation\n */\n public static ProcedureElement createElementfromXML(Node node) throws \n \tProcedureParseException \n {\n //Log.i(TAG, \"fromXML(\" + node.getNodeName() + \")\");\n \n if(!node.getNodeName().equals(\"Element\")) {\n throw new ProcedureParseException(\"Element got NodeName \" \n \t\t+ node.getNodeName());\n }\n\n String questionStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"question\", \"\");\n String answerStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"answer\", null);\n String typeStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"type\", \"INVALID\");\n String conceptStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"concept\", \"\");\n String idStr = SanaUtil.getNodeAttributeOrFail(node, \"id\", \n \t\tnew ProcedureParseException(\"Element doesn't have id number\"));\n String figureStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"figure\", \"\");\n String audioStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"audio\", \"\");\n \n ElementType etype = ElementType.valueOf(typeStr);\n \n ProcedureElement el = null;\n switch(etype) {\n case TEXT:\n el = TextElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case ENTRY:\n el = TextEntryElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case SELECT:\n el = SelectElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case MULTI_SELECT:\n el = MultiSelectElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case RADIO:\n el = RadioElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case PICTURE:\n el = PictureElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case SOUND:\n el = SoundElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case GPS:\n el = GpsElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case BINARYFILE:\n el = BinaryUploadElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case PATIENT_ID:\n el = PatientIdElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case DATE:\n el = DateElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case EDUCATION_RESOURCE:\n el = EducationResourceElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case PLUGIN:\n el = PluginElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n case ENTRY_PLUGIN:\n el = PluginEntryElement.fromXML(idStr, questionStr, answerStr,\n conceptStr, figureStr, audioStr, node);\n break;\n\n case HIDDEN:\n el = HiddenElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n\n case AGE:\n el = AgeElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case TRUTH:\n el = TruthElement.fromXML(idStr, questionStr, answerStr, conceptStr,\n figureStr, audioStr, node);\n break;\n case INVALID:\n default:\n throw new ProcedureParseException(\"Got invalid node type : \" \n \t\t+ etype);\n }\n \n if (el == null) {\n \tthrow new ProcedureParseException(\"Failed to parse node with id \" \n \t\t\t+ idStr);\n }\n\n String helpStr = SanaUtil.getNodeAttributeOrDefault(node, \"helpText\",\n \t\t\"\");\n el.setHelpText(helpStr);\n \n String requiredStr = SanaUtil.getNodeAttributeOrDefault(node, \n \t\t\"required\", \"false\");\n if (\"true\".equals(requiredStr)) {\n \tel.setRequired(true);\n } else if (\"false\".equals(requiredStr)) {\n \tel.setRequired(false);\n } else {\n \tthrow new ProcedureParseException(\"Argument to \\'required\\' \"+\n \t\t\t\"attribute invalid for id \" + idStr \n \t\t\t+ \". Must be \\'true\\' or \\'false\\'\");\n }\n \n return el;\n }\n \n public static void parseOptionalAttributes(Node node, ProcedureElement el)\n throws ProcedureParseException {\n Log.i(TAG, \"parseOptionalAttributes(Node,ProcedureElement)\");\n String attr = null;\n\n // action\n attr = SanaUtil.getNodeAttributeOrDefault(node,\n \t\t\"action\", \"\");\n if(!TextUtils.isEmpty(attr))\n el.action = new String(attr);\n\n // default\n attr = SanaUtil.getNodeAttributeOrDefault(node,\n \"default\", \"\");\n el.setDefault(new String(attr));\n\n // helpText\n attr = SanaUtil.getNodeAttributeOrDefault(node, \"helpText\",\n \"\");\n el.setHelpText(new String(attr));\n\n // required\n attr = SanaUtil.getNodeAttributeOrDefault(node,\n \"required\", \"false\");\n if (\"true\".equals(attr)) {\n el.setRequired(true);\n } else if (\"false\".equals(attr)) {\n el.setRequired(false);\n } else {\n throw new ProcedureParseException(\"Argument to \\'required\\' \" +\n \"attribute invalid for id \" + el.getId()+\n \". Must be \\'true\\' or \\'false\\'\");\n }\n }\n \n \n /** @return The value of the id attribute */\n public String getId() {\n return id;\n }\n\n /** @return Gets the identifier for any associated education resources */\n public String mediaId(){\n \treturn EducationResource.toId(concept+question);\n }\n \n /**\n * @return the question string originally defined in the XML procedure \n * definition.\n */\n public String getQuestion() {\n return question;\n }\n \n /**\n * @return the medical concept associated with this ProcedureElement\n */\n public String getConcept() {\n \treturn concept;\n }\n \n /**\n * @return the figure URL associated with this ProcedureElement\n */\n public String getFigure() {\n \treturn figure;\n }\n /** @return true if this instance has an audio prompt */\n boolean hasAudioPrompt() {\n \treturn !\"\".equals(audioPrompt);\n }\n \n /** plays this instance's audio prompt */\n void playAudioPrompt() {\n \tif (mAudioPlayer != null)\n \t\tmAudioPlayer.play();\n }\n \n /** @return the audioPrompt string */\n public String getAudioPrompt() {\n \treturn audioPrompt;\n }\n \n /**\n * Returns a localized String from the application package's default string\n * table.\n * \n * @param resId Resource Id for the string\n * @return\n */\n public String getString(int resId){\n \treturn getContext().getString(resId);\n }\n \n /** \n * Appends another View object a view of this object to a new View .\n * @param c A valid Context.\n * @param v The view to append first.\n * @return A new View containing the parameter View and a View of this \n * \t\tobject.\n */\n public View encapsulateQuestion(Context c, View v) {\n \t\n \t// Add question view\n \tTextView textView = new TextView(c);\n \ttextView.setSingleLine(false);\n textView.setGravity(Gravity.LEFT);\n\t\tString q = question.replace(\"\\\\n\", \"\\n\");\n Log.d(TAG, \"...show question id = \" + getProcedure().idsShown());\n \tif(getProcedure().idsShown() && !getType().equals(ElementType.TEXT)){\n \t\ttextView.setText(String.format(\"%s: %s\", getId(), q));\n \t}else{\n \ttextView.setText(q);\n \t}\n \t//textView.setGravity(Gravity.CENTER_HORIZONTAL);\n \ttextView.setTextAppearance(c, android.R.style.TextAppearance_Large);\n \tView questionView = textView;\n \tquestionView.setPadding(10,5,10,5);\n \t// Add image if provided\n ImageView imageView = null;\n \n //Set accompanying figure\n if(!TextUtils.isEmpty(figure)) { \n\t try{\n\t \tString imagePath = c.getPackageName() + \":\" + figure;\n\t \tLog.d(TAG, \"Using figure: \" + figure);\n\t \tint resID = c.getResources().getIdentifier(figure, null, \n\t \t\t\tnull);\n\t \tLog.d(TAG, \"Using figure id: \" + resID);\n\t \timageView = new ImageView(c);\n\t \timageView.setImageResource(resID);\n\t \timageView.setAdjustViewBounds(true);\n\t \t // set the ImageView bounds to match the Drawable's dimensions\n\t \timageView.setLayoutParams(new Gallery.LayoutParams(\n\t \t\t\tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t \timageView.setPadding(10,10,10,10);\n\t }\n\t catch(Exception e){\n\t \tLog.e(TAG, \"Couldn't find resource figure \" + e.toString());\n\t }\n }\n \n // Add audio prompt if provided\n if (hasAudioPrompt()) {\n \ttry {\n \t\tString resourcePath = c.getPackageName() + \":\" + audioPrompt;\n \t\tint resID = c.getResources().getIdentifier(resourcePath, \n \t\t\t\tnull, null);\n \t\tLog.i(TAG, \"Looking up ID for resource: \" + resourcePath + \", \" \n \t\t\t\t+ \"got \" + resID);\n \t\t\n \t\tif (resID != 0) {\n\t \t\tmAudioPlayer = new AudioPlayer(resID);\n\t \t\tView playerView = mAudioPlayer.createView(c);\n\t \t\tplayerView.setLayoutParams(new LayoutParams(\n\t \t\t\tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t \t\tLinearLayout audioPromptView = new LinearLayout(c);\n\t audioPromptView.setOrientation(LinearLayout.HORIZONTAL);\n\t audioPromptView.setLayoutParams(new LayoutParams(\n\t \tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t audioPromptView.setGravity(Gravity.CENTER);\n\t \n\t // Insert the play button to the left of the current \n\t // question view.\n\t audioPromptView.addView(playerView);\n\t audioPromptView.addView(questionView);\n\t questionView = audioPromptView;\n \t\t}\n \t} catch (Exception e) {\n \t\tLog.e(TAG, \"Couldn't find resource for audio prompt: \" \n \t\t\t\t+ e.toString());\n \t}\n }\n\n \t\t\n //Log.d(TAG, \"Loaded: \" +this.toString());\n \tLinearLayout ll = new LinearLayout(c);\n \tll.setOrientation(LinearLayout.VERTICAL);\n\n \t//Add to layout\n \tll.addView(questionView);\n \tif (imageView != null)\n \t\tll.addView(imageView);\n\n \t// Add Buttons if provided\n \tif(!TextUtils.isEmpty(action)){\n \t\tView actionView = getActions(c);\n actionView.setPadding(5,5,5,5);\n \t\tll.addView(actionView);\n \t} else {\n //Log.w(TAG, \"Empty action string!\");\t\n \t}\n \t\n \tif(v != null){\n \t\tLinearLayout viewHolder = new LinearLayout(c);\n \t\t\n \t\tviewHolder.addView(v);\n \t\tviewHolder.setGravity(Gravity.CENTER_HORIZONTAL);\n \t\tll.addView(viewHolder, new LayoutParams(LayoutParams.MATCH_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \t}\n \t\t\n \tll.setGravity(Gravity.CENTER);\n \tll.setPadding(5, 0, 5, 0);\n \tll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n return ll;\n }\n \n @Override\n public String toString(){\n \t/*\n \tGson gson = new Gson();\n \treturn gson.toJson(this);\n \t*/\n \treturn String.format(\"ProcedureElement: type=%s, concept=%s, \"\n \t\t+\"required=%s, id=%s, question=%s, figure=%s, audio=%s, answer=%s,\"\n \t\t+\"action=%s\",\n \t getType(), concept, bRequired, id, question, figure, audioPrompt, \n \t answer,action);\n }\n \n /**\n * Returns a View containing a set of buttons, each of which can be\n * used as a launch point for another activity. \n * \n * @see {@link #getAction()} for more on action String format\n * @return a View containing a list of action buttons\n */\n public View getActions(Context c){\n\t\tLog.d(TAG, \"action=\" + action);\n \tLinearLayout ll = new LinearLayout(c);\n \tll.setOrientation(LinearLayout.VERTICAL);\n \tll.setGravity(Gravity.CENTER);\n \tll.setPadding(5, 0, 5, 0);\n \tll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \t\n \t// Get the intent \n \tfor(String intentStr: action.split(\",\")){\n \t\tLog.d(TAG, intentStr);\n \t\tButton button = new Button(c);\n \t\tbutton.setText(\"????\");\n \t\ttry {\n\t\t\t\tIntent buttonAction = Intent.parseUri(intentStr, Intent.URI_INTENT_SCHEME);\n\t \t\tbutton.setTag(buttonAction);\n\t \t\tbutton.setText(buttonAction.getStringExtra(Intent.EXTRA_TITLE));\n\t \t\tbutton.setOnClickListener(new View.OnClickListener(){\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\t\tIntent intent = (Intent) v.getTag();\n\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t}});\n\t\t\t} catch (URISyntaxException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t\tll.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \t}\n \t\n \t\n \treturn ll;\n }\n \n protected final Activity getActivity(){\n \treturn (Activity) getContext();\n }\n \n protected final void startActivity(Intent intent){\n \tActivity activity = getActivity();\n\t\tIntent launcher = new Intent(getContext(), activity.getClass());\n\t\tlauncher.putExtra(Intent.EXTRA_INTENT, intent);\n\t\tlauncher.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n\t\tgetContext().startActivity(launcher);\n }\n\n public String getDefault(){\n Log.i(TAG, \"getDefault()\");\n return defaultValue;\n }\n\n public void setDefault(String defaultValue){\n Log.i(TAG, \"setDefault(String)\");\n this.defaultValue = defaultValue;\n }\n\n public boolean hasDefault(){\n Log.i(TAG, \"hasDefault()\");\n return !TextUtils.isEmpty(defaultValue);\n }\n\n /** \n * Creates the element from an XML procedure definition.\n * \n * @param id The unique identifier of this element within its procedure.\n * @param question The text that will be displayed to the user as a question\n * @param answer The result of data capture.\n * @param concept A required categorization of the type of data captured.\n * @param figure An optional figure to display to the user.\n * @param audio An optional audio prompt to play for the user. \n * @param node The source xml node. \n * @return A new element.\n * @throws ProcedureParseException if an error occurred while parsing \n * \t\tadditional information from the Node\n */\n public static ProcedureElement fromXML(String id, String question, \n \tString answer, String concept, String figure, String audio, Node node) \n \tthrows ProcedureParseException \n {\n \tthrow new UnsupportedOperationException();\n }\n}\n"},"message":{"kind":"string","value":"UI styling for Call button\n"},"old_file":{"kind":"string","value":"app/src/main/java/org/sana/android/procedure/ProcedureElement.java"},"subject":{"kind":"string","value":"UI styling for Call button"},"git_diff":{"kind":"string","value":"pp/src/main/java/org/sana/android/procedure/ProcedureElement.java\n import android.content.Context;\n import android.content.Intent;\n import android.graphics.Color;\nimport android.graphics.drawable.Animatable;\n import android.text.TextUtils;\n import android.util.Log;\n import android.view.Gravity;\n import android.view.View;\n import android.view.ViewGroup.LayoutParams;\nimport android.view.animation.Animation;\n import android.widget.Button;\n import android.widget.Gallery;\n import android.widget.ImageView;\n import org.sana.android.media.EducationResource;\n import org.sana.android.util.SanaUtil;\n import org.w3c.dom.Node;\nimport org.w3c.dom.Text;\n \n import java.net.URISyntaxException;\n \n \tLinearLayout ll = new LinearLayout(c);\n \tll.setOrientation(LinearLayout.VERTICAL);\n \tll.setGravity(Gravity.CENTER);\n ll.setBackgroundColor(Color.CYAN);\n \tll.setPadding(5, 0, 5, 0);\n \tll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,\n \t\t\tLayoutParams.WRAP_CONTENT));\n \tfor(String intentStr: action.split(\",\")){\n \t\tLog.d(TAG, intentStr);\n \t\tButton button = new Button(c);\n \t\tbutton.setText(\"????\");\n \t\tbutton.setTextColor(Color.BLUE);\n button.setHint(\"TOUCH TO CALL\");\n button.setHintTextColor(Color.CYAN);\n button.setText(\"Call Anbulance\");\n \t\ttry {\n \t\t\t\tIntent buttonAction = Intent.parseUri(intentStr, Intent.URI_INTENT_SCHEME);\n \t \t\tbutton.setTag(buttonAction);"}}},{"rowIdx":198739,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"72759cc75e1342fc3d836bd79f6c699fd8c330f1"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox"},"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.pdfbox.cos;\n\nimport static org.junit.Assert.fail;\n\nimport java.util.Calendar;\n\nimport org.apache.pdfbox.pdmodel.font.encoding.Encoding;\nimport org.junit.Test;\n\npublic class UnmodifiableCOSDictionaryTest\n{\n @Test\n public void testUnmodifiableCOSDictionary()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.clear();\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.removeItem(COSName.A);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.addAll(new COSDictionary());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.setFlag(COSName.A, 0, true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.setNeedToBeUpdated(true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.setNeedToBeUpdated(true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetItem()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setItem(COSName.A, COSName.A);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setItem(COSName.A, Encoding.getInstance(COSName.STANDARD_ENCODING));\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setItem(\"A\", COSName.A);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n try\n {\n unmodifiableCOSDictionary.setItem(\"A\", Encoding.getInstance(COSName.STANDARD_ENCODING));\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetBoolean()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setBoolean(COSName.A, true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setBoolean(\"A\", true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetName()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setName(COSName.A, \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setName(\"A\", \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetDate()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setDate(COSName.A, Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setDate(\"A\", Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetEmbeddedDate()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setEmbeddedDate(\"Embedded\", COSName.A, Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setEmbeddedDate(\"Embedded\", \"A\", Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetString()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setString(COSName.A, \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setString(\"A\", \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetEmbeddedString()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setEmbeddedString(\"Embedded\", COSName.A, \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setEmbeddedString(\"Embedded\", \"A\", \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetInt()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setInt(COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setInt(\"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetEmbeddedInt()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setEmbeddedInt(\"Embedded\", COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setEmbeddedInt(\"Embedded\", \"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetLong()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setLong(COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setLong(\"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetFloat()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setFloat(COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setFloat(\"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n}"},"new_file":{"kind":"string","value":"pdfbox/src/test/java/org/apache/pdfbox/cos/UnmodifiableCOSDictionaryTest.java"},"old_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.pdfbox.cos;\n\nimport static org.junit.Assert.fail;\n\nimport java.util.Calendar;\nimport java.util.function.BiConsumer;\n\nimport org.apache.pdfbox.pdmodel.common.COSObjectable;\nimport org.apache.pdfbox.pdmodel.font.encoding.Encoding;\nimport org.junit.Test;\n\npublic class UnmodifiableCOSDictionaryTest\n{\n @Test\n public void testUnmodifiableCOSDictionary()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.clear();\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.removeItem(COSName.A);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.addAll(new COSDictionary());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.setFlag(COSName.A, 0, true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.setNeedToBeUpdated(true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n\n try\n {\n unmodifiableCOSDictionary.setNeedToBeUpdated(true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetItem()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setItem(COSName.A, COSName.A);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setItem(COSName.A, Encoding.getInstance(COSName.STANDARD_ENCODING));\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setItem(\"A\", COSName.A);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n try\n {\n unmodifiableCOSDictionary.setItem(\"A\", Encoding.getInstance(COSName.STANDARD_ENCODING));\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch(UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetBoolean()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setBoolean(COSName.A, true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setBoolean(\"A\", true);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetName()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setName(COSName.A, \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setName(\"A\", \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetDate()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setDate(COSName.A, Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setDate(\"A\", Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetEmbeddedDate()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setEmbeddedDate(\"Embedded\", COSName.A, Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setEmbeddedDate(\"Embedded\", \"A\", Calendar.getInstance());\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetString()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setString(COSName.A, \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setString(\"A\", \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetEmbeddedString()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setEmbeddedString(\"Embedded\", COSName.A, \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setEmbeddedString(\"Embedded\", \"A\", \"A\");\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetInt()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setInt(COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setInt(\"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetEmbeddedInt()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setEmbeddedInt(\"Embedded\", COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setEmbeddedInt(\"Embedded\", \"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetLong()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setLong(COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setLong(\"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n @Test\n public void testSetFloat()\n {\n COSDictionary unmodifiableCOSDictionary = new COSDictionary().asUnmodifiableDictionary();\n try\n {\n unmodifiableCOSDictionary.setFloat(COSName.A, 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n \n try\n {\n unmodifiableCOSDictionary.setFloat(\"A\", 0);\n fail(\"An UnsupportedOperationException should have been thrown\");\n }\n catch (UnsupportedOperationException exception)\n {\n // nothing to do\n }\n }\n\n}"},"message":{"kind":"string","value":"PDFBOX-4892: remove unused imports\n\ngit-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1882837 13f79535-47bb-0310-9956-ffa450edef68\n"},"old_file":{"kind":"string","value":"pdfbox/src/test/java/org/apache/pdfbox/cos/UnmodifiableCOSDictionaryTest.java"},"subject":{"kind":"string","value":"PDFBOX-4892: remove unused imports"},"git_diff":{"kind":"string","value":"dfbox/src/test/java/org/apache/pdfbox/cos/UnmodifiableCOSDictionaryTest.java\n import static org.junit.Assert.fail;\n \n import java.util.Calendar;\nimport java.util.function.BiConsumer;\n\nimport org.apache.pdfbox.pdmodel.common.COSObjectable;\n\n import org.apache.pdfbox.pdmodel.font.encoding.Encoding;\n import org.junit.Test;\n "}}},{"rowIdx":198740,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"02cd39ae4e52d530e2ccb9883bb5b85053b62126"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"YiiGuxing/TranslationPlugin,YiiGuxing/TranslationPlugin"},"new_contents":{"kind":"string","value":"package cn.yiiguxing.plugin.translate.action;\n\nimport cn.yiiguxing.plugin.translate.TranslationUiManager;\nimport cn.yiiguxing.plugin.translate.Utils;\nimport com.intellij.codeInsight.documentation.DocumentationManager;\nimport com.intellij.codeInsight.hint.HintManagerImpl;\nimport com.intellij.openapi.actionSystem.*;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.project.DumbAware;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.ui.popup.JBPopup;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport javax.swing.text.JTextComponent;\n\n/**\n * 文本组件(如快速文档、提示气泡、输入框……)翻译动作\n */\npublic class TranslateTextComponentAction extends AnAction implements DumbAware, HintManagerImpl.ActionToIgnore {\n\n public TranslateTextComponentAction() {\n setEnabledInModalContext(true);\n }\n\n @Nullable\n public static String getSelectedText(@NotNull AnActionEvent event) {\n final DataContext dataContext = event.getDataContext();\n\n String selectedQuickDocText = DocumentationManager.SELECTED_QUICK_DOC_TEXT.getData(dataContext);\n if (selectedQuickDocText != null) {\n return selectedQuickDocText;\n }\n\n final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);\n if (editor != null) {\n return editor.getSelectionModel().getSelectedText();\n }\n\n final Object data = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);\n if (data instanceof JTextComponent) {\n return ((JTextComponent) data).getSelectedText();\n }\n\n return null;\n }\n\n @Override\n public void update(AnActionEvent e) {\n final String selected = getSelectedText(e);\n e.getPresentation().setEnabledAndVisible(!Utils.isEmptyOrBlankString(Utils.splitWord(selected)));\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n if (ApplicationManager.getApplication().isHeadlessEnvironment()) {\n return;\n }\n\n final String selected = Utils.splitWord(getSelectedText(e));\n if (Utils.isEmptyOrBlankString(selected)) {\n return;\n }\n\n final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());\n final JBPopup docInfoHint = project == null ? null : DocumentationManager.getInstance(project).getDocInfoHint();\n if (docInfoHint != null) {\n docInfoHint.cancel();\n }\n\n TranslationUiManager.getInstance().showTranslationDialog(e.getProject()).query(selected);\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/cn/yiiguxing/plugin/translate/action/TranslateTextComponentAction.java"},"old_contents":{"kind":"string","value":"package cn.yiiguxing.plugin.translate.action;\n\nimport cn.yiiguxing.plugin.translate.TranslationUiManager;\nimport cn.yiiguxing.plugin.translate.Utils;\nimport com.intellij.codeInsight.documentation.DocumentationManager;\nimport com.intellij.codeInsight.hint.HintManagerImpl;\nimport com.intellij.openapi.actionSystem.*;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.editor.textarea.TextComponentEditorImpl;\nimport com.intellij.openapi.project.DumbAware;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.ui.popup.JBPopup;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport javax.swing.text.JTextComponent;\n\n/**\n * 文本组件(如快速文档、提示气泡、输入框……)翻译动作\n */\npublic class TranslateTextComponentAction extends AnAction implements DumbAware, HintManagerImpl.ActionToIgnore {\n\n public TranslateTextComponentAction() {\n setEnabledInModalContext(true);\n }\n\n @Nullable\n public static Editor getEditorFromContext(@NotNull DataContext dataContext) {\n final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);\n if (editor != null) return editor;\n\n final Object data = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);\n if (data instanceof JTextComponent) {\n return new TextComponentEditorImpl(CommonDataKeys.PROJECT.getData(dataContext), (JTextComponent) data);\n }\n\n return null;\n }\n\n @Override\n public void update(AnActionEvent e) {\n final String selected = getSelectedText(e);\n e.getPresentation().setEnabledAndVisible(!Utils.isEmptyOrBlankString(Utils.splitWord(selected)));\n }\n\n @Nullable\n private String getSelectedText(AnActionEvent e) {\n String selected = e.getData(DocumentationManager.SELECTED_QUICK_DOC_TEXT);\n if (selected == null) {\n final Editor editor = getEditorFromContext(e.getDataContext());\n if (editor != null) {\n selected = editor.getSelectionModel().getSelectedText();\n }\n }\n\n return selected;\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n if (ApplicationManager.getApplication().isHeadlessEnvironment()) {\n return;\n }\n\n final String selected = Utils.splitWord(getSelectedText(e));\n if (Utils.isEmptyOrBlankString(selected)) {\n return;\n }\n\n final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());\n final JBPopup docInfoHint = project == null ? null : DocumentationManager.getInstance(project).getDocInfoHint();\n if (docInfoHint != null) {\n docInfoHint.cancel();\n }\n\n TranslationUiManager.getInstance().showTranslationDialog(e.getProject()).query(selected);\n }\n\n}\n"},"message":{"kind":"string","value":":ambulance: 低版本兼容\n"},"old_file":{"kind":"string","value":"src/cn/yiiguxing/plugin/translate/action/TranslateTextComponentAction.java"},"subject":{"kind":"string","value":":ambulance: 低版本兼容"},"git_diff":{"kind":"string","value":"rc/cn/yiiguxing/plugin/translate/action/TranslateTextComponentAction.java\n import com.intellij.openapi.actionSystem.*;\n import com.intellij.openapi.application.ApplicationManager;\n import com.intellij.openapi.editor.Editor;\nimport com.intellij.openapi.editor.textarea.TextComponentEditorImpl;\n import com.intellij.openapi.project.DumbAware;\n import com.intellij.openapi.project.Project;\n import com.intellij.openapi.ui.popup.JBPopup;\n }\n \n @Nullable\n public static Editor getEditorFromContext(@NotNull DataContext dataContext) {\n public static String getSelectedText(@NotNull AnActionEvent event) {\n final DataContext dataContext = event.getDataContext();\n\n String selectedQuickDocText = DocumentationManager.SELECTED_QUICK_DOC_TEXT.getData(dataContext);\n if (selectedQuickDocText != null) {\n return selectedQuickDocText;\n }\n\n final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);\n if (editor != null) return editor;\n if (editor != null) {\n return editor.getSelectionModel().getSelectedText();\n }\n \n final Object data = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);\n if (data instanceof JTextComponent) {\n return new TextComponentEditorImpl(CommonDataKeys.PROJECT.getData(dataContext), (JTextComponent) data);\n return ((JTextComponent) data).getSelectedText();\n }\n \n return null;\n public void update(AnActionEvent e) {\n final String selected = getSelectedText(e);\n e.getPresentation().setEnabledAndVisible(!Utils.isEmptyOrBlankString(Utils.splitWord(selected)));\n }\n\n @Nullable\n private String getSelectedText(AnActionEvent e) {\n String selected = e.getData(DocumentationManager.SELECTED_QUICK_DOC_TEXT);\n if (selected == null) {\n final Editor editor = getEditorFromContext(e.getDataContext());\n if (editor != null) {\n selected = editor.getSelectionModel().getSelectedText();\n }\n }\n\n return selected;\n }\n \n @Override"}}},{"rowIdx":198741,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"0ff586badf276c575e5215d0020e37aff9b1bc78"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ronnyfriedland/Knowledgebase-2.0,ronnyfriedland/Knowledgebase-2.0,ronnyfriedland/Knowledgebase-2.0,ronnyfriedland/Knowledgebase-2.0"},"new_contents":{"kind":"string","value":"package de.ronnyfriedland.knowledgebase.entity;\n\nimport java.util.Collections;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\nimport de.ronnyfriedland.knowledgebase.repository.jcr.JCRTextDocument;\n\n/**\n * @author ronnyfriedland\n */\npublic class DocumentTest {\n\n @Test\n public void testConstructor() throws Exception {\n Document subject = new Document<>(\"key\", \"header\", \"message\", false, \"tag1\", \"tag2\");\n Assert.assertNotNull(subject);\n\n Assert.assertEquals(\"key\", subject.getKey());\n Assert.assertEquals(\"header\", subject.getHeader());\n Assert.assertEquals(\"message\", subject.getMessage());\n Assert.assertArrayEquals(new String[] { \"tag1\", \"tag2\" }, subject.getTags());\n\n subject = new Document<>(\"key\", \"header\", \"message\", false);\n Assert.assertArrayEquals(new String[0], subject.getTags());\n }\n\n @Test\n public void testFromJcrDocument() throws Exception {\n Document subject = new JCRTextDocument(\"path\", \"header\", \"message\", false,\n Collections.singletonList(\" tag1 withwithspaces \")).toDocument();\n Assert.assertNotNull(subject);\n Assert.assertNotNull(subject.getKey());\n Assert.assertEquals(\"path\", subject.getKey());\n Assert.assertNotNull(subject.getHeader());\n Assert.assertEquals(\"header\", subject.getHeader());\n Assert.assertNotNull(subject.getMessage());\n Assert.assertEquals(\"message\", subject.getMessage());\n Assert.assertNotNull(subject.getTags());\n Assert.assertArrayEquals(new String[] { \"tag1 withwithspaces\" }, subject.getTags()); // trimmed tags\n }\n}\n"},"new_file":{"kind":"string","value":"src/test/java/de/ronnyfriedland/knowledgebase/entity/DocumentTest.java"},"old_contents":{"kind":"string","value":"package de.ronnyfriedland.knowledgebase.entity;\n\nimport java.util.Collections;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\nimport de.ronnyfriedland.knowledgebase.repository.jcr.JCRTextDocument;\n\n/**\n * @author ronnyfriedland\n */\npublic class DocumentTest {\n\n @Test\n public void testConstructor() throws Exception {\n Document subject = new Document<>(\"key\", \"header\", \"message\", false, \"tag1\", \"tag2\");\n Assert.assertNotNull(subject);\n\n Assert.assertEquals(\"key\", subject.getKey());\n Assert.assertEquals(\"header\", subject.getHeader());\n Assert.assertEquals(\"message\", subject.getMessage());\n Assert.assertArrayEquals(new String[] { \"tag1\", \"tag2\" }, subject.getTags());\n\n subject = new Document<>(\"key\", \"header\", \"message\", false);\n Assert.assertArrayEquals(new String[0], subject.getTags());\n }\n\n @Test\n public void testFromJcrDocument() throws Exception {\n Document subject = new JCRTextDocument(\"path\", \"header\", \"message\", false,\n Collections.singletonList(\" tag1 withwithspaces \")).toDocument();\n Assert.assertNotNull(subject);\n Assert.assertNotNull(subject.getKey());\n Assert.assertEquals(\"/path\", subject.getKey());\n Assert.assertNotNull(subject.getHeader());\n Assert.assertEquals(\"header\", subject.getHeader());\n Assert.assertNotNull(subject.getMessage());\n Assert.assertEquals(\"message\", subject.getMessage());\n Assert.assertNotNull(subject.getTags());\n Assert.assertArrayEquals(new String[] { \"tag1 withwithspaces\" }, subject.getTags()); // trimmed tags\n }\n}\n"},"message":{"kind":"string","value":"fix test"},"old_file":{"kind":"string","value":"src/test/java/de/ronnyfriedland/knowledgebase/entity/DocumentTest.java"},"subject":{"kind":"string","value":"fix test"},"git_diff":{"kind":"string","value":"rc/test/java/de/ronnyfriedland/knowledgebase/entity/DocumentTest.java\n Collections.singletonList(\" tag1 withwithspaces \")).toDocument();\n Assert.assertNotNull(subject);\n Assert.assertNotNull(subject.getKey());\n Assert.assertEquals(\"/path\", subject.getKey());\n Assert.assertEquals(\"path\", subject.getKey());\n Assert.assertNotNull(subject.getHeader());\n Assert.assertEquals(\"header\", subject.getHeader());\n Assert.assertNotNull(subject.getMessage());"}}},{"rowIdx":198742,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f4db45f608adcfca25aa678f5fb643a8e72e5fcb"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"antonio-fasolato/jfmigrate"},"new_contents":{"kind":"string","value":"package net.fasolato.jfmigrate.internal;\n\nimport net.fasolato.jfmigrate.JFMigrationClass;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLDecoder;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.List;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\n\npublic class ReflectionHelper {\n private static Logger log = LogManager.getLogger(ReflectionHelper.class);\n\n public static List getAllMigrations(String pkg) throws Exception {\n if (pkg == null || pkg.trim().length() == 0) {\n throw new Exception(\"Null or empty package passed\");\n }\n List classNames = listClassesInPackage(pkg);\n\n List migrations = new ArrayList();\n for (String n : classNames) {\n Class c = Class.forName((pkg + \".\" + n).replaceAll(\"/\", \"\"));\n if (!JFMigrationClass.class.isAssignableFrom(c)) {\n log.debug(\"class {} does not implement IMigration. Class is ignored\", c.getSimpleName());\n } else {\n log.debug(\"class {} implements IMigration. Class is added as a migration\", c.getSimpleName());\n migrations.add((JFMigrationClass) c.newInstance());\n }\n }\n\n return migrations;\n }\n\n // Inspiration and code taken from https://stackoverflow.com/a/7461653\n public static List listClassesInPackage(String packageName) throws IOException, URISyntaxException {\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n URL url;\n List toReturn = new ArrayList();\n\n packageName = packageName.replaceAll(\"\\\\.\", \"/\");\n url = cl.getResource(packageName);\n\n if (url.getProtocol().equals(\"jar\")) {\n //Jar files\n String jarFile = URLDecoder.decode(url.getFile(), \"UTF-8\");\n String fileName = jarFile.substring(5, jarFile.indexOf(\"!\"));\n JarFile jf = new JarFile(fileName);\n Enumeration entries = jf.entries();\n while (entries.hasMoreElements()) {\n JarEntry jar = entries.nextElement();\n String entryName = jar.getName();\n if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {\n entryName = entryName.substring(packageName.length(), entryName.lastIndexOf('.'));\n toReturn.add(entryName);\n }\n }\n } else {\n //class files\n File dir = new File(new URI(url.toString()).getPath());\n for (File f : dir.listFiles()) {\n if (f.isFile()) {\n toReturn.add(f.getName().substring(0, f.getName().lastIndexOf('.')));\n }\n }\n }\n\n return toReturn;\n }\n}\n"},"new_file":{"kind":"string","value":"JFMigrate/src/main/java/net/fasolato/jfmigrate/internal/ReflectionHelper.java"},"old_contents":{"kind":"string","value":"package net.fasolato.jfmigrate.internal;\n\nimport net.fasolato.jfmigrate.JFMigrationClass;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLDecoder;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.List;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\n\npublic class ReflectionHelper {\n private static Logger log = LogManager.getLogger(ReflectionHelper.class);\n\n public static List getAllMigrations(String pkg) throws Exception {\n if (pkg == null || pkg.trim().length() == 0) {\n throw new Exception(\"Null or empty package passed\");\n }\n List classNames = listClassesInPackage(pkg);\n\n List migrations = new ArrayList();\n for (String n : classNames) {\n Class c = Class.forName(pkg + \".\" + n);\n if (!JFMigrationClass.class.isAssignableFrom(c)) {\n log.debug(\"class {} does not implement IMigration. Class is ignored\", c.getSimpleName());\n } else {\n log.debug(\"class {} implements IMigration. Class is added as a migration\", c.getSimpleName());\n migrations.add((JFMigrationClass) c.newInstance());\n }\n }\n\n return migrations;\n }\n\n // Inspiration and code taken from https://stackoverflow.com/a/7461653\n public static List listClassesInPackage(String packageName) throws IOException, URISyntaxException {\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n URL url;\n List toReturn = new ArrayList();\n\n packageName = packageName.replaceAll(\"\\\\.\", \"/\");\n url = cl.getResource(packageName);\n\n if (url.getProtocol().equals(\"jar\")) {\n //Jar files\n String jarFile = URLDecoder.decode(url.getFile(), \"UTF-8\");\n String fileName = jarFile.substring(5, jarFile.indexOf(\"!\"));\n JarFile jf = new JarFile(fileName);\n Enumeration entries = jf.entries();\n while (entries.hasMoreElements()) {\n JarEntry jar = entries.nextElement();\n String entryName = jar.getName();\n if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {\n entryName = entryName.substring(packageName.length(), entryName.lastIndexOf('.'));\n toReturn.add(entryName);\n }\n }\n } else {\n //class files\n File dir = new File(new URI(url.toString()).getPath());\n for (File f : dir.listFiles()) {\n if (f.isFile()) {\n toReturn.add(f.getName().substring(0, f.getName().lastIndexOf('.')));\n }\n }\n }\n\n return toReturn;\n }\n}\n"},"message":{"kind":"string","value":"Fixed an error reading classes names\n"},"old_file":{"kind":"string","value":"JFMigrate/src/main/java/net/fasolato/jfmigrate/internal/ReflectionHelper.java"},"subject":{"kind":"string","value":"Fixed an error reading classes names"},"git_diff":{"kind":"string","value":"FMigrate/src/main/java/net/fasolato/jfmigrate/internal/ReflectionHelper.java\n \n List migrations = new ArrayList();\n for (String n : classNames) {\n Class c = Class.forName(pkg + \".\" + n);\n Class c = Class.forName((pkg + \".\" + n).replaceAll(\"/\", \"\"));\n if (!JFMigrationClass.class.isAssignableFrom(c)) {\n log.debug(\"class {} does not implement IMigration. Class is ignored\", c.getSimpleName());\n } else {"}}},{"rowIdx":198743,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"4c56fce5c4c953d54ce621fb8b0382baa224e422"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"vladikoff/p,rkatic/p,vladikoff/p,rkatic/p"},"new_contents":{"kind":"string","value":"(function(){\r\n\"use strict\";\r\n\r\nvar opt_tracing = typeof TRACE_FUNCTIONS !== \"undefined\";\r\n\r\nif ( typeof P === \"undefined\" ) {\r\n\tglobal.P = require(opt_tracing ? \"./p\" : \"../p\");\r\n\tglobal.expect = require(\"expect.js\");\r\n\t//require(\"mocha\");\r\n}\r\n\r\nif ( opt_tracing ) {\r\n\tTRACE_FUNCTIONS.stopAdding();\r\n\r\n\tbeforeEach(function() {\r\n\t\tTRACE_FUNCTIONS.optimize();\r\n\t});\r\n\r\n\tafterEach(function() {\r\n\t\tTRACE_FUNCTIONS.optimize();\r\n\t});\r\n}\r\n\r\nvar isNodeJS = typeof process === \"object\" && process &&\r\n\t({}).toString.call(process) === \"[object process]\";\r\n\r\n\r\nfunction fail() {\r\n\texpect(true).to.be(false);\r\n}\r\n\r\nfunction thenableSyncFulfillment( value ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\tcb( value );\r\n\t\t}\r\n\t};\r\n}\r\n\r\nfunction thenableSyncRejection( reason ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\teb( reason );\r\n\t\t}\r\n\t};\r\n}\r\n\r\nfunction thenableFulfillment( value ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\tsetTimeout(function() {\r\n\t\t\t\tcb( value );\r\n\t\t\t}, 0)\r\n\t\t}\r\n\t};\r\n}\r\n\r\nfunction thenableRejection( reason ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\tsetTimeout(function() {\r\n\t\t\t\teb( reason );\r\n\t\t\t}, 0)\r\n\t\t}\r\n\t};\r\n}\r\n\r\nvar VALUES = [\"\", true, false, 0, 1, 2, -1, -2, {}, [], {x: 1}, [1,2,3], null, void 0, new Error()];\r\n\r\nvar FULLFILMENTS = VALUES.concat(\r\n\tVALUES.map( P ),\r\n\tVALUES.map( thenableFulfillment ),\r\n\tVALUES.map( thenableSyncFulfillment )\r\n);\r\n\r\nvar REJECTIONS = [].concat(\r\n\tVALUES.map( P.reject ),\r\n\tVALUES.map( thenableRejection ),\r\n\tVALUES.map( thenableSyncRejection )\r\n);\r\n\r\nvar FULLFILMENTS_AND_REJECTIONS = FULLFILMENTS.concat( REJECTIONS );\r\n\r\nfunction map( array, f ) {\r\n\tvar array2 = new Array(array.length|0);\r\n\tfor ( var i = 0, l = array.length; i < l; ++i ) {\r\n\t\tif ( i in array ) {\r\n\t\t\tarray2[i] = f( array[i], i, array );\r\n\t\t}\r\n\t}\r\n\treturn array2;\r\n}\r\n\r\nfunction allValues( func ) {\r\n\treturn P.all( map(VALUES, func) );\r\n}\r\n\r\ndescribe(\"P function\", function() {\r\n\r\n\tit(\"should return a promise\", function() {\r\n\t\tvar Promise = P().constructor;\r\n\r\n\t\texpect(\r\n\t\t\tPromise.constructor.name === \"Promise\" ||\r\n\t\t\tPromise.toString().lastIndexOf(\"function Promise\", 0) === 0\r\n\t\t).to.be(true);\r\n\r\n\t\tmap(FULLFILMENTS_AND_REJECTIONS, function( value ) {\r\n\t\t\texpect( P(value) instanceof Promise ).to.be(true);\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should return input itself if it is a promise\", function() {\r\n\t\tvar p = P();\r\n\t\texpect( P(p) ).to.be( p );\r\n\t});\r\n\r\n\tit(\"should fulfill with input if not a promise\", function() {\r\n\t\treturn allValues(function( value ) {\r\n\t\t\treturn P( value ).then(function( fulfilledValue ) {\r\n\t\t\t\texpect( fulfilledValue ).to.be( value );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"inspect\", function() {\r\n\r\n\tit(\"on fulfillment\", function() {\r\n\t\treturn allValues(function( value ) {\r\n\t\t\tvar p = P( value );\r\n\t\t\treturn p.then(function() {\r\n\t\t\t\texpect( p.inspect() ).to.be.eql( {state: \"fulfilled\", value: value} );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"on rejection\", function() {\r\n\t\treturn allValues(function( reason ) {\r\n\t\t\tvar d = P.defer();\r\n\t\t\tvar p = d.promise;\r\n\t\t\texpect( p.inspect() ).to.be.eql( {state: \"pending\"} );\r\n\t\t\td.reject( reason );\r\n\t\t\treturn p.then( fail, function() {\r\n\t\t\t\texpect( p.inspect() ).to.be.eql( {state: \"rejected\", reason: reason} );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"reject\", function() {\r\n\r\n\tit(\"returns a rejected promise\", function() {\r\n\t\treturn allValues(function( reason ) {\r\n\t\t\treturn P.reject( reason ).then( fail, function( rejectedReason ) {\r\n\t\t\t\texpect( rejectedReason ).to.be( reason );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n\r\nfunction deep( func ) {\r\n\tvar d = P.defer();\r\n\tvar p = d.promise;\r\n\tvar n = 10000;\r\n\twhile ( n-- ) {\r\n\t\tp = func([ p ]);\r\n\t}\r\n\td.promise = p;\r\n\treturn d;\r\n}\r\n\r\ndescribe(\"all\", function() {\r\n\r\n\tit(\"resolves when passed an empty array\", function() {\r\n\t\treturn P.all([]);\r\n\t});\r\n\r\n\tit(\"resolves when passed an array\", function() {\r\n\t\tvar toResolve = P.defer();\r\n\t\tvar array = VALUES.concat( toResolve.promise );\r\n\t\tvar array2 = array.slice();\r\n\t\tarray2[ array2.length - 1 ] = 12;\r\n\t\tvar promise = P.all( array );\r\n\r\n\t\ttoResolve.resolve(12);\r\n\r\n\t\treturn promise.then(function( values ) {\r\n\t\t\texpect( values ).to.be.eql( array2 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"rejects if any consituent promise is rejectd\", function() {\r\n\t\tvar toReject = P.defer();\r\n\t\tvar theReason = new Error();\r\n\t\ttoReject.reject( theReason );\r\n\t\tvar array = FULLFILMENTS.concat( toReject.promise )\r\n\r\n\t\treturn P.all( array )\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theReason );\r\n\t\t})\r\n\t\t.then(function() {\r\n\t\t\tvar toRejectLater = P.defer();\r\n\t\t\tvar array = FULLFILMENTS.concat( toRejectLater.promise );\r\n\t\t\tvar promise = P.all( array );\r\n\t\t\ttoRejectLater.reject( theReason );\r\n\t\t\treturn promise;\r\n\t\t})\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theReason );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should resolve on deep resolved promise\", function() {\r\n\t\tvar d = deep( P.all );\r\n\t\td.resolve( 1 );\r\n\t\treturn d.promise;\r\n\t});\r\n\r\n\tit(\"should reject on deep rejected promise\", function() {\r\n\t\tvar d = deep( P.all );\r\n\t\td.reject( 7 );\r\n\t\treturn d.promise.then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( 7 );\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"allSettled\", function() {\r\n\r\n\tit(\"resolves when passed an empty array\", function() {\r\n\t\treturn P.allSettled([]);\r\n\t});\r\n\r\n\tit(\"resolves when passed an array\", function() {\r\n\t\tvar array = FULLFILMENTS_AND_REJECTIONS;\r\n\t\tvar promise = P.allSettled( array );\r\n\r\n\t\treturn promise.then(function( settled ) {\r\n\t\t\tfor ( var i = 0; i < settled.length; ++i ) {\r\n\t\t\t\tvar expectedValue = VALUES[ i % VALUES.length ];\r\n\r\n\t\t\t\tif ( i < FULLFILMENTS.length ) {\r\n\t\t\t\t\texpect( settled[i] ).to.be.eql( {state: \"fulfilled\", value: expectedValue} );\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\texpect( settled[i] ).to.be.eql( {state: \"rejected\", reason: expectedValue} );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should resolve on deep resolved promise\", function() {\r\n\t\tvar d = deep( P.allSettled );\r\n\t\td.resolve( 1 );\r\n\t\treturn d.promise;\r\n\t});\r\n\r\n\tit(\"should resolve on deep rejected promise\", function() {\r\n\t\tvar d = deep( P.allSettled );\r\n\t\td.reject( new Error(\"foo\") );\r\n\t\treturn d.promise;\r\n\t});\r\n});\r\n\r\ndescribe(\"spread\", function() {\r\n\r\n\tit(\"spreads values across arguments\", function() {\r\n\t\treturn P([1, P(2), 3]).spread(function( one, two, three ) {\r\n\t\t\texpect( one ).to.be( 1 );\r\n\t\t\texpect( two ).to.be( 2 );\r\n\t\t\texpect( three ).to.be( 3 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should call the errback in case of a rejected promise\", function() {\r\n\t\tvar toReject = P.defer();\r\n\t\tvar theReason = new Error();\r\n\t\ttoReject.reject( theReason );\r\n\r\n\t\treturn P([ 1, P(2), toReject.promise]).spread(\r\n\t\t\tfail,\r\n\t\t\tfunction( reason ) {\r\n\t\t\t\texpect( reason ).to.be( theReason );\r\n\t\t\t}\r\n\t\t);\r\n\t});\r\n});\r\n\r\ndescribe(\"done\", function() {\r\n\r\n\tafterEach(function() {\r\n\t\tP.onerror = null;\r\n\t});\r\n\r\n\t// TODO: cover other cases too!\r\n\r\n\tdescribe(\"when the promise is rejected\", function() {\r\n\t\tdescribe(\"and there is no errback\", function() {\r\n\r\n\t\t\tit(\"should throw the reason in a next turn\", function( done ) {\r\n\t\t\t\tvar turn = 0;\r\n\t\t\t\tvar toReject = P.defer();\r\n\t\t\t\ttoReject.reject(\"foo\");\r\n\t\t\t\tvar promise = toReject.promise;\r\n\r\n\t\t\t\texpect( promise.done() ).to.be( undefined );\r\n\r\n\t\t\t\tP.onerror = function( error ) {\r\n\t\t\t\t\texpect( turn ).to.be( 1 );\r\n\t\t\t\t\texpect( error ).to.be(\"foo\");\r\n\t\t\t\t\tdone();\r\n\t\t\t\t};\r\n\r\n\t\t\t\t++turn;\r\n\t\t\t});\r\n\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"fin\", function() {\r\n\r\n\tdescribe(\"when the promise is fulfilled\", function() {\r\n\r\n\t\tit(\"should call the callback and fulfill with the original value\", function() {\r\n\t\t\tvar called = false;\r\n\r\n\t\t\treturn P(\"foo\")\r\n\t\t\t.fin(function() {\r\n\t\t\t\tcalled = true;\r\n\t\t\t\treturn \"boo\";\r\n\t\t\t})\r\n\t\t\t.then(function( value ) {\r\n\t\t\t\texpect( called ).to.be( true );\r\n\t\t\t\texpect( value ).to.be(\"foo\");\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback returns a promise\", function() {\r\n\r\n\t\t\tdescribe(\"that is fulfilled\", function() {\r\n\t\t\t\tit(\"should fulfill with the original value after the promise is settled\", function() {\r\n\t\t\t\t\tvar delayed = P(\"boo\").delay(50);\r\n\r\n\t\t\t\t\treturn P(\"foo\")\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn delayed;\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(function( value ) {\r\n\t\t\t\t\t\texpect( delayed.inspect() ).to.be.eql({ state: \"fulfilled\", value: \"boo\" });\r\n\t\t\t\t\t\texpect( value ).to.be(\"foo\");\r\n\t\t\t\t\t});\r\n\t\t\t\t})\r\n\t\t\t});\r\n\r\n\t\t\tdescribe(\"that is rejected\", function() {\r\n\t\t\t\tit(\"should reject with this new reason\", function() {\r\n\t\t\t\t\tvar theError = new Error(\"boo\");\r\n\r\n\t\t\t\t\treturn P(\"foo\")\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn P.reject( theError );\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t});\r\n\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback throws an exception\", function() {\r\n\t\t\tit(\"should reject with this new exception\", function() {\r\n\t\t\t\tvar theError = new Error(\"boo\");\r\n\r\n\t\t\t\treturn P(\"foo\")\r\n\t\t\t\t.fin(function() {\r\n\t\t\t\t\tthrow theError;\r\n\t\t\t\t})\r\n\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t});\r\n\r\n\tdescribe(\"when the promise is rejected\", function () {\r\n\r\n\t\tvar theError = new Error(\"nooo\");\r\n\r\n\t\tit(\"should call the callback and reject with the original reason\", function() {\r\n\t\t\tvar called = false;\r\n\r\n\t\t\treturn P.reject( theError )\r\n\t\t\t.fin(function() {\r\n\t\t\t\tcalled = true;\r\n\t\t\t\treturn \"boo\";\r\n\t\t\t})\r\n\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\texpect( called ).to.be( true );\r\n\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback returns a promise\", function() {\r\n\r\n\t\t\tdescribe(\"that is fulfilled\", function() {\r\n\t\t\t\tit(\"should reject with the original reason after the promise is settled\", function() {\r\n\t\t\t\t\tvar delayed = P(\"boo\").delay(50);\r\n\r\n\t\t\t\t\treturn P.reject( theError )\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn delayed;\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\t\texpect( delayed.inspect() ).to.be.eql({ state: \"fulfilled\", value: \"boo\" });\r\n\t\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t\t});\r\n\t\t\t\t})\r\n\t\t\t});\r\n\r\n\t\t\tdescribe(\"that is rejected\", function() {\r\n\t\t\t\tit(\"should reject with this new reason\", function() {\r\n\t\t\t\t\treturn P.reject( new Error(\"boo\") )\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn P.reject( theError );\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t});\r\n\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback throws an exception\", function() {\r\n\t\t\tit(\"should reject with this new exception\", function() {\r\n\t\t\t\tvar theError = new Error(\"boo\");\r\n\r\n\t\t\t\treturn P.reject( new Error(\"boo\") )\r\n\t\t\t\t.fin(function() {\r\n\t\t\t\t\tthrow theError;\r\n\t\t\t\t})\r\n\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t});\r\n\r\n});\r\n\r\ndescribe(\"timeout\", function() {\r\n\r\n\t// This part is based on the respective part of the Q spec.\r\n\r\n\tit(\"should do nothing if the promise fulfills quickly\", function() {\r\n\t\treturn P().delay( 10 ).timeout( 100 );\r\n\t});\r\n\r\n\tit(\"should do nothing if the promise rejects quickly\", function() {\r\n\t\tvar error = new Error();\r\n\r\n\t\treturn P().delay( 10 )\r\n\t\t.then(function() {\r\n\t\t\tthrow error;\r\n\t\t})\r\n\t\t.timeout( 100 )\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( error );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject within a timeout error if the promise is too slow\", function() {\r\n\t\treturn P().delay( 100 )\r\n\t\t.timeout( 10 )\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason.message ).to.match(/time/i);\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject with a custom timeout message if the promise is too slow\", function() {\r\n\t\treturn P().delay( 100 )\r\n\t\t.timeout(10, \"custom\")\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason.message ).to.match(/custom/i);\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"delay\", function() {\r\n\r\n\t// This part is based on the respective part of the Q spec.\r\n\r\n\tit(\"should dealy fulfillment\", function() {\r\n\t\tvar promise = P(1).delay( 50 );\r\n\r\n\t\tsetTimeout(function() {\r\n\t\t\texpect( promise.inspect().state ).to.be(\"pending\");\r\n\t\t}, 30);\r\n\r\n\t\treturn promise;\r\n\t});\r\n\r\n\tit(\"should not dealy rejection\", function() {\r\n\t\tvar d = P.defer();\r\n\t\td.reject(1);\r\n\t\tvar promise = d.promise.delay( 50 );\r\n\r\n\t\tsetTimeout(function() {\r\n\t\t\texpect( promise.inspect().state ).to.be(\"rejected\");\r\n\t\t}, 30);\r\n\r\n\t\treturn promise.then( fail, function(){} );\r\n\t});\r\n\r\n\tit(\"should delay after fulfillment\", function() {\r\n\t\tvar p1 = P(\"foo\").delay( 30 );\r\n\t\tvar p2 = p1.delay( 30 );\r\n\r\n\t\tsetTimeout(function() {\r\n\t\t\texpect( p1.inspect().state ).to.be(\"fulfilled\");\r\n\t\t\texpect( p2.inspect().state ).to.be(\"pending\");\r\n\t\t}, 45);\r\n\r\n\t\treturn p2.then(function( value ) {\r\n\t\t\texpect( value ).to.be(\"foo\");\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"nodeify\", function() {\r\n\r\n\tit(\"calls back with a resolution\", function( done ) {\r\n\t\tP( 7 ).nodeify(function( error, value ) {\r\n\t\t\texpect( error ).to.be( null );\r\n\t\t\texpect( value ).to.be( 7 );\r\n\t\t\tdone();\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"calls back with an error\", function( done ) {\r\n\t\tP.reject( 13 ).nodeify(function( error, value ) {\r\n\t\t\texpect( error ).to.be( 13 );\r\n\t\t\texpect( value ).to.be( void 0 );\r\n\t\t\tdone();\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"forwards a fullfilment\", function() {\r\n\t\treturn P( 5 ).nodeify( void 0 ).then(function( value ) {\r\n\t\t\texpect( value ).to.be( 5 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"forwards a rejection\", function() {\r\n\t\treturn P.reject( 3 ).nodeify( void 0 ).then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( 3 );\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"promised\", function() {\r\n\r\n\tvar sum = P.promised(function( a, b ) {\r\n\t\treturn a + b;\r\n\t});\r\n\r\n\tvar inc = P.promised(function( n ) {\r\n\t\treturn this + n;\r\n\t});\r\n\r\n\tit(\"resolves promised arguments\", function() {\r\n\t\treturn sum( P(1), 2 ).then(function( res ) {\r\n\t\t\texpect( res ).to.be( 3 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"resolves promised `this`\", function() {\r\n\t\treturn inc.call( P(4), 1 ).then(function( res ) {\r\n\t\t\texpect( res ).to.be( 5 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"is rejected if an argument is rejected\", function() {\r\n\t\treturn sum( P.reject(1), 2 ).then(fail, function( e ) {\r\n\t\t\texpect( e ).to.be( 1 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"is rejected if `this` is rejected\", function() {\r\n\t\treturn inc.call( P.reject(1), P(2) ).then(fail, function( e ) {\r\n\t\t\texpect( e ).to.be( 1 );\r\n\t\t});\r\n\t});\r\n\r\n});\r\n\r\ndescribe(\"denodeify\", function() {\r\n\r\n\tit(\"should fulfill if no error\", function() {\r\n\t\tvar f = P.denodeify(function( a, b, c, d, callback ) {\r\n\t\t\tcallback( null, a + b + c + d );\r\n\t\t});\r\n\r\n\t\treturn f( 1, 2, 3, 4 ).then(function( value ) {\r\n\t\t\texpect( value ).to.be( 10 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject on error\", function() {\r\n\t\tvar theError = new Error();\r\n\r\n\t\tvar f = P.denodeify(function( a, b, c, d, callback ) {\r\n\t\t\tcallback( theError );\r\n\t\t});\r\n\r\n\t\treturn f( 1, 2, 3, 4 ).then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theError );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject on thrown error\", function() {\r\n\t\tvar theError = new Error();\r\n\r\n\t\tvar f = P.denodeify(function( a, b, c, d, callback ) {\r\n\t\t\tthrow theError;\r\n\t\t});\r\n\r\n\t\treturn f( 1, 2, 3, 4 ).then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theError );\r\n\t\t});\r\n\t});\r\n\r\n});\r\n\r\n!opt_tracing && describe(\"longStackSupport\", function() {\r\n\r\n\tError.stackTraceLimit = Infinity;\r\n\r\n\tbeforeEach(function() {\r\n\t\tP.longStackSupport = true;\r\n\t});\r\n\r\n\tafterEach(function() {\r\n\t\tP.longStackSupport = false;\r\n\t});\r\n\r\n\tfunction createError( msg ) {\r\n\t\ttry {\r\n\t\t\tthrow new Error( msg );\r\n\r\n\t\t} catch ( e ) {\r\n\t\t\treturn e;\r\n\t\t}\r\n\t}\r\n\r\n\tfunction checkError( error, expectedNamesStr ) {\r\n\t\texpect( error instanceof Error ).to.be( true );\r\n\r\n\t\tvar stacks = error.stack\r\n\t\t\t.split(\"_it_\")[0]\r\n\t\t\t.split(\"\\nFrom previous event:\\n\");\r\n\r\n\t\tvar str = map(stacks, function( stack ) {\r\n\t\t\treturn ( stack.match(/_(\\w+)_/g) || [] )\r\n\t\t\t\t.join(\"\")\r\n\t\t\t\t.split(\"__\").join(\"-\")\r\n\t\t\t\t.slice(1, -1);\r\n\t\t})\r\n\t\t.join(\" \")\r\n\t\t.replace(/^\\s+|\\s+$/g, \"\")\r\n\t\t.replace(/\\s+/g, \" \");\r\n\r\n\t\texpect( str ).to.be( expectedNamesStr );\r\n\t}\r\n\r\n\tit(\"should make trace long on sync rejected thenable\", function _it_() {\r\n\t\treturn P().then(function _5_() {\r\n\t\t\treturn P().then(function _4_() {\r\n\t\t\t\treturn P().then(function _3_() {\r\n\t\t\t\t\treturn {then: function _2_( cb, eb ) {\r\n\t\t\t\t\t cb({then: function _1_( cb, eb ) {\r\n\t\t\t\t\t\teb( createError() );\r\n\t\t\t\t\t }});\r\n\t\t\t\t\t}};\r\n\t\t\t\t});\r\n\t\t\t})\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"1-2 4 5\");\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should make trace long on async rejected thenable\", function _it_() {\r\n\t\treturn P().then(function _5_() {\r\n\t\t\treturn P().then(function _4_() {\r\n\t\t\t\treturn P().then(function _3_() {\r\n\t\t\t\t\treturn {then: function _2_( cb, eb ) {\r\n\t\t\t\t\t\tsetTimeout(function _b_() {\r\n\t\t\t\t\t\t\tcb({then: function _1_( cb, eb ) {\r\n\t\t\t\t\t\t\t\tcb({then: function( cb, eb ) {\r\n\t\t\t\t\t\t\t\t\tsetTimeout(function _a_() {\r\n\t\t\t\t\t\t\t\t\t\teb( new Error() );\r\n\t\t\t\t\t\t\t\t\t}, 0);\r\n\t\t\t\t\t\t\t\t}});\r\n\t\t\t\t\t\t\t}});\r\n\r\n\t\t\t\t\t\t\tP().then(function _c_() {\r\n\t\t\t\t\t\t\t\tthrow new Error();\r\n\t\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\t.done(null, function( error ) {\r\n\t\t\t\t\t\t\t\tcheckError(error, \"c b\");\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}, 0);\r\n\t\t\t\t\t}};\r\n\t\t\t\t});\r\n\t\t\t})\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"a 1-b 4 5\");\r\n\t\t});\r\n\t});\r\n\r\n\r\n\tit(\"should make trace long if denodeifed function rejects\", function _it_() {\r\n\r\n\t\tvar rejection = P.denodeify(function( nodeback ) {\r\n\t\t\tsetTimeout(function _0_() {\r\n\t\t\t\tnodeback( new Error() );\r\n\t\t\t}, 0);\r\n\t\t});\r\n\r\n\t\treturn P().then(function _2_() {\r\n\t\t\treturn P().then(function _1_() {\r\n\t\t\t\treturn rejection();\r\n\t\t\t});\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"0 1 2\");\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should make trace long on timeouted promise\", function _it_() {\r\n\t\treturn P().then(function _2_() {\r\n\t\t\treturn P().then(function _1_() {\r\n\t\t\t\treturn P.defer().promise.timeout(1);\r\n\t\t\t});\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"1 2\");\r\n\t\t});\r\n\t});\r\n\r\n});\r\n\r\nif ( isNodeJS ) describe(\"domain\", function() {\r\n\r\n\tvar domain = require(\"domain\");\r\n\r\n\tit(\"should work with domains\", function() {\r\n\t\tvar d = P.defer();\r\n\t\tvar theValue = 0;\r\n\t\tvar theError = new Error();\r\n\r\n\t\tP(47).then(function( value ) { theValue = value; });\r\n\r\n\t\tvar theDomain = domain.create();\r\n\t\ttheDomain.on(\"error\", function( error ) {\r\n\t\t\texpect( theValue ).to.be( 47 );\r\n\t\t\texpect( error ).to.be( theError );\r\n\t\t\tP().then( d.resolve );\r\n\t\t})\r\n\t\t.run(function() {\r\n\t\t\tP().then(function() {\r\n\t\t\t\texpect( domain.active ).to.be( theDomain );\r\n\t\t\t}).done();\r\n\r\n\t\t\tP.reject( theError ).done();\r\n\t\t});\r\n\r\n\t\treturn d.promise.then(function() {\r\n\t\t\texpect( domain.active ).to.be( theDomain );\r\n\t\t}, fail);\r\n\t});\r\n\r\n\tit(\"should not evaluate promises in disposed domains\", function() {\r\n\t\tvar theDomain = domain.create();\r\n\t\tvar called = false;\r\n\r\n\t\ttheDomain.on(\"error\", function( e ) {\r\n\t\t\tP().then(function() { called = true; });\r\n\t\t\ttheDomain.dispose();\r\n\t\t})\r\n\t\t.run(function() {\r\n\t\t\tP.reject( new Error() ).done();\r\n\t\t});\r\n\r\n\t\treturn P().delay(10).then(function() {\r\n\t\t\texpect( called ).to.be( false );\r\n\t\t});\r\n\t});\r\n});\r\n\r\n})();\r\n"},"new_file":{"kind":"string","value":"test/test.js"},"old_contents":{"kind":"string","value":"(function(){\r\n\"use strict\";\r\n\r\nvar opt_tracing = typeof TRACE_FUNCTIONS !== \"undefined\";\r\n\r\nif ( typeof P === \"undefined\" ) {\r\n\tglobal.P = require(opt_tracing ? \"./p\" : \"../p\");\r\n\tglobal.expect = require(\"expect.js\");\r\n\t//require(\"mocha\");\r\n}\r\n\r\nif ( opt_tracing ) {\r\n\tTRACE_FUNCTIONS.stopAdding();\r\n\r\n\tbeforeEach(function() {\r\n\t\tTRACE_FUNCTIONS.optimize();\r\n\t});\r\n\r\n\tafterEach(function() {\r\n\t\tTRACE_FUNCTIONS.optimize();\r\n\t});\r\n}\r\n\r\nvar isNodeJS = typeof process === \"object\" && process &&\r\n\t({}).toString.call(process) === \"[object process]\";\r\n\r\n\r\nfunction fail() {\r\n\texpect(true).to.be(false);\r\n}\r\n\r\nfunction thenableSyncFulfillment( value ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\tcb( value );\r\n\t\t}\r\n\t};\r\n}\r\n\r\nfunction thenableSyncRejection( reason ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\teb( reason );\r\n\t\t}\r\n\t};\r\n}\r\n\r\nfunction thenableFulfillment( value ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\tsetTimeout(function() {\r\n\t\t\t\tcb( value );\r\n\t\t\t}, 0)\r\n\t\t}\r\n\t};\r\n}\r\n\r\nfunction thenableRejection( reason ) {\r\n\treturn {\r\n\t\tthen: function( cb, eb ) {\r\n\t\t\tsetTimeout(function() {\r\n\t\t\t\teb( reason );\r\n\t\t\t}, 0)\r\n\t\t}\r\n\t};\r\n}\r\n\r\nvar VALUES = [\"\", true, false, 0, 1, 2, -1, -2, {}, [], {x: 1}, [1,2,3], null, void 0, new Error()];\r\n\r\nvar FULLFILMENTS = VALUES.concat(\r\n\tVALUES.map( P ),\r\n\tVALUES.map( thenableFulfillment ),\r\n\tVALUES.map( thenableSyncFulfillment )\r\n);\r\n\r\nvar REJECTIONS = [].concat(\r\n\tVALUES.map( P.reject ),\r\n\tVALUES.map( thenableRejection ),\r\n\tVALUES.map( thenableSyncRejection )\r\n);\r\n\r\nvar FULLFILMENTS_AND_REJECTIONS = FULLFILMENTS.concat( REJECTIONS );\r\n\r\nfunction map( array, f ) {\r\n\tvar array2 = new Array(array.length|0);\r\n\tfor ( var i = 0, l = array.length; i < l; ++i ) {\r\n\t\tif ( i in array ) {\r\n\t\t\tarray2[i] = f( array[i], i, array );\r\n\t\t}\r\n\t}\r\n\treturn array2;\r\n}\r\n\r\nfunction allValues( func ) {\r\n\treturn P.all( map(VALUES, func) );\r\n}\r\n\r\ndescribe(\"P function\", function() {\r\n\r\n\tit(\"should return a promise\", function() {\r\n\t\tvar Promise = P().constructor;\r\n\r\n\t\texpect(\r\n\t\t\tPromise.constructor.name === \"Promise\" ||\r\n\t\t\tPromise.toString().lastIndexOf(\"function Promise\", 0) === 0\r\n\t\t).to.be(true);\r\n\r\n\t\tmap(FULLFILMENTS_AND_REJECTIONS, function( value ) {\r\n\t\t\texpect( P(value) instanceof Promise ).to.be(true);\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should return input itself if it is a promise\", function() {\r\n\t\tvar p = P();\r\n\t\texpect( P(p) ).to.be( p );\r\n\t});\r\n\r\n\tit(\"should fulfill with input if not a promise\", function() {\r\n\t\treturn allValues(function( value ) {\r\n\t\t\treturn P( value ).then(function( fulfilledValue ) {\r\n\t\t\t\texpect( fulfilledValue ).to.be( value );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"inspect\", function() {\r\n\r\n\tit(\"on fulfillment\", function() {\r\n\t\treturn allValues(function( value ) {\r\n\t\t\tvar p = P( value );\r\n\t\t\treturn p.then(function() {\r\n\t\t\t\texpect( p.inspect() ).to.be.eql( {state: \"fulfilled\", value: value} );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"on rejection\", function() {\r\n\t\treturn allValues(function( reason ) {\r\n\t\t\tvar d = P.defer();\r\n\t\t\tvar p = d.promise;\r\n\t\t\texpect( p.inspect() ).to.be.eql( {state: \"pending\"} );\r\n\t\t\td.reject( reason );\r\n\t\t\treturn p.then( fail, function() {\r\n\t\t\t\texpect( p.inspect() ).to.be.eql( {state: \"rejected\", reason: reason} );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"reject\", function() {\r\n\r\n\tit(\"returns a rejected promise\", function() {\r\n\t\treturn allValues(function( reason ) {\r\n\t\t\treturn P.reject( reason ).then( fail, function( rejectedReason ) {\r\n\t\t\t\texpect( rejectedReason ).to.be( reason );\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n\r\nfunction deep( func ) {\r\n\tvar d = P.defer();\r\n\tvar p = d.promise;\r\n\tvar n = 10000;\r\n\twhile ( n-- ) {\r\n\t\tp = func([ p ]);\r\n\t}\r\n\td.promise = p;\r\n\treturn d;\r\n}\r\n\r\ndescribe(\"all\", function() {\r\n\r\n\tit(\"resolves when passed an empty array\", function() {\r\n\t\treturn P.all([]);\r\n\t});\r\n\r\n\tit(\"resolves when passed an array\", function() {\r\n\t\tvar toResolve = P.defer();\r\n\t\tvar array = VALUES.concat( toResolve.promise );\r\n\t\tvar array2 = array.slice();\r\n\t\tarray2[ array2.length - 1 ] = 12;\r\n\t\tvar promise = P.all( array );\r\n\r\n\t\ttoResolve.resolve(12);\r\n\r\n\t\treturn promise.then(function( values ) {\r\n\t\t\texpect( values ).to.be.eql( array2 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"rejects if any consituent promise is rejectd\", function() {\r\n\t\tvar toReject = P.defer();\r\n\t\tvar theReason = new Error();\r\n\t\ttoReject.reject( theReason );\r\n\t\tvar array = FULLFILMENTS.concat( toReject.promise )\r\n\r\n\t\treturn P.all( array )\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theReason );\r\n\t\t})\r\n\t\t.then(function() {\r\n\t\t\tvar toRejectLater = P.defer();\r\n\t\t\tvar array = FULLFILMENTS.concat( toRejectLater.promise );\r\n\t\t\tvar promise = P.all( array );\r\n\t\t\ttoRejectLater.reject( theReason );\r\n\t\t\treturn promise;\r\n\t\t})\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theReason );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should resolve on deep resolved promise\", function() {\r\n\t\tvar d = deep( P.all );\r\n\t\td.resolve( 1 );\r\n\t\treturn d.promise;\r\n\t});\r\n\r\n\tit(\"should reject on deep rejected promise\", function() {\r\n\t\tvar d = deep( P.all );\r\n\t\td.reject( 7 );\r\n\t\treturn d.promise.then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( 7 );\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"allSettled\", function() {\r\n\r\n\tit(\"resolves when passed an empty array\", function() {\r\n\t\treturn P.allSettled([]);\r\n\t});\r\n\r\n\tit(\"resolves when passed an array\", function() {\r\n\t\tvar array = FULLFILMENTS_AND_REJECTIONS;\r\n\t\tvar promise = P.allSettled( array );\r\n\r\n\t\treturn promise.then(function( settled ) {\r\n\t\t\tfor ( var i = 0; i < settled.length; ++i ) {\r\n\t\t\t\tvar expectedValue = VALUES[ i % VALUES.length ];\r\n\r\n\t\t\t\tif ( i < FULLFILMENTS.length ) {\r\n\t\t\t\t\texpect( settled[i] ).to.be.eql( {state: \"fulfilled\", value: expectedValue} );\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\texpect( settled[i] ).to.be.eql( {state: \"rejected\", reason: expectedValue} );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should resolve on deep resolved promise\", function() {\r\n\t\tvar d = deep( P.allSettled );\r\n\t\td.resolve( 1 );\r\n\t\treturn d.promise;\r\n\t});\r\n\r\n\tit(\"should resolve on deep rejected promise\", function() {\r\n\t\tvar d = deep( P.allSettled );\r\n\t\td.reject( new Error(\"foo\") );\r\n\t\treturn d.promise;\r\n\t});\r\n});\r\n\r\ndescribe(\"spread\", function() {\r\n\r\n\tit(\"spreads values across arguments\", function() {\r\n\t\treturn P([1, P(2), 3]).spread(function( one, two, three ) {\r\n\t\t\texpect( one ).to.be( 1 );\r\n\t\t\texpect( two ).to.be( 2 );\r\n\t\t\texpect( three ).to.be( 3 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should call the errback in case of a rejected promise\", function() {\r\n\t\tvar toReject = P.defer();\r\n\t\tvar theReason = new Error();\r\n\t\ttoReject.reject( theReason );\r\n\r\n\t\treturn P([ 1, P(2), toReject.promise]).spread(\r\n\t\t\tfail,\r\n\t\t\tfunction( reason ) {\r\n\t\t\t\texpect( reason ).to.be( theReason );\r\n\t\t\t}\r\n\t\t);\r\n\t});\r\n});\r\n\r\ndescribe(\"done\", function() {\r\n\r\n\tafterEach(function() {\r\n\t\tP.onerror = null;\r\n\t});\r\n\r\n\t// TODO: cover other cases too!\r\n\r\n\tdescribe(\"when the promise is rejected\", function() {\r\n\t\tdescribe(\"and there is no errback\", function() {\r\n\r\n\t\t\tit(\"should throw the reason in a next turn\", function( done ) {\r\n\t\t\t\tvar turn = 0;\r\n\t\t\t\tvar toReject = P.defer();\r\n\t\t\t\ttoReject.reject(\"foo\");\r\n\t\t\t\tvar promise = toReject.promise;\r\n\r\n\t\t\t\texpect( promise.done() ).to.be( undefined );\r\n\r\n\t\t\t\tP.onerror = function( error ) {\r\n\t\t\t\t\texpect( turn ).to.be( 1 );\r\n\t\t\t\t\texpect( error ).to.be(\"foo\");\r\n\t\t\t\t\tdone();\r\n\t\t\t\t};\r\n\r\n\t\t\t\t++turn;\r\n\t\t\t});\r\n\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"fin\", function() {\r\n\r\n\tdescribe(\"when the promise is fulfilled\", function() {\r\n\r\n\t\tit(\"should call the callback and fulfill with the original value\", function() {\r\n\t\t\tvar called = false;\r\n\r\n\t\t\treturn P(\"foo\")\r\n\t\t\t.fin(function() {\r\n\t\t\t\tcalled = true;\r\n\t\t\t\treturn \"boo\";\r\n\t\t\t})\r\n\t\t\t.then(function( value ) {\r\n\t\t\t\texpect( called ).to.be( true );\r\n\t\t\t\texpect( value ).to.be(\"foo\");\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback returns a promise\", function() {\r\n\r\n\t\t\tdescribe(\"that is fulfilled\", function() {\r\n\t\t\t\tit(\"should fulfill with the original value after the promise is settled\", function() {\r\n\t\t\t\t\tvar delayed = P(\"boo\").delay(50);\r\n\r\n\t\t\t\t\treturn P(\"foo\")\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn delayed;\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(function( value ) {\r\n\t\t\t\t\t\texpect( delayed.inspect() ).to.be.eql({ state: \"fulfilled\", value: \"boo\" });\r\n\t\t\t\t\t\texpect( value ).to.be(\"foo\");\r\n\t\t\t\t\t});\r\n\t\t\t\t})\r\n\t\t\t});\r\n\r\n\t\t\tdescribe(\"that is rejected\", function() {\r\n\t\t\t\tit(\"should reject with this new reason\", function() {\r\n\t\t\t\t\tvar theError = new Error(\"boo\");\r\n\r\n\t\t\t\t\treturn P(\"foo\")\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn P.reject( theError );\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t});\r\n\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback throws an exception\", function() {\r\n\t\t\tit(\"should reject with this new exception\", function() {\r\n\t\t\t\tvar theError = new Error(\"boo\");\r\n\r\n\t\t\t\treturn P(\"foo\")\r\n\t\t\t\t.fin(function() {\r\n\t\t\t\t\tthrow theError;\r\n\t\t\t\t})\r\n\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t});\r\n\r\n\tdescribe(\"when the promise is rejected\", function () {\r\n\r\n\t\tvar theError = new Error(\"nooo\");\r\n\r\n\t\tit(\"should call the callback and reject with the original reason\", function() {\r\n\t\t\tvar called = false;\r\n\r\n\t\t\treturn P.reject( theError )\r\n\t\t\t.fin(function() {\r\n\t\t\t\tcalled = true;\r\n\t\t\t\treturn \"boo\";\r\n\t\t\t})\r\n\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\texpect( called ).to.be( true );\r\n\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback returns a promise\", function() {\r\n\r\n\t\t\tdescribe(\"that is fulfilled\", function() {\r\n\t\t\t\tit(\"should reject with the original reason after the promise is settled\", function() {\r\n\t\t\t\t\tvar delayed = P(\"boo\").delay(50);\r\n\r\n\t\t\t\t\treturn P.reject( theError )\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn delayed;\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\t\texpect( delayed.inspect() ).to.be.eql({ state: \"fulfilled\", value: \"boo\" });\r\n\t\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t\t});\r\n\t\t\t\t})\r\n\t\t\t});\r\n\r\n\t\t\tdescribe(\"that is rejected\", function() {\r\n\t\t\t\tit(\"should reject with this new reason\", function() {\r\n\t\t\t\t\treturn P.reject( new Error(\"boo\") )\r\n\t\t\t\t\t.fin(function() {\r\n\t\t\t\t\t\treturn P.reject( theError );\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t});\r\n\r\n\t\t});\r\n\r\n\t\tdescribe(\"when the callback throws an exception\", function() {\r\n\t\t\tit(\"should reject with this new exception\", function() {\r\n\t\t\t\tvar theError = new Error(\"boo\");\r\n\r\n\t\t\t\treturn P.reject( new Error(\"boo\") )\r\n\t\t\t\t.fin(function() {\r\n\t\t\t\t\tthrow theError;\r\n\t\t\t\t})\r\n\t\t\t\t.then(fail, function( reason ) {\r\n\t\t\t\t\texpect( reason ).to.be( theError );\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t});\r\n\r\n});\r\n\r\ndescribe(\"timeout\", function() {\r\n\r\n\t// This part is based on the respective part of the Q spec.\r\n\r\n\tit(\"should do nothing if the promise fulfills quickly\", function() {\r\n\t\treturn P().delay( 10 ).timeout( 100 );\r\n\t});\r\n\r\n\tit(\"should do nothing if the promise rejects quickly\", function() {\r\n\t\tvar error = new Error();\r\n\r\n\t\treturn P().delay( 10 )\r\n\t\t.then(function() {\r\n\t\t\tthrow error;\r\n\t\t})\r\n\t\t.timeout( 100 )\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( error );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject within a timeout error if the promise is too slow\", function() {\r\n\t\treturn P().delay( 100 )\r\n\t\t.timeout( 10 )\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason.message ).to.match(/time/i);\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject with a custom timeout message if the promise is too slow\", function() {\r\n\t\treturn P().delay( 100 )\r\n\t\t.timeout(10, \"custom\")\r\n\t\t.then( fail, function( reason ) {\r\n\t\t\texpect( reason.message ).to.match(/custom/i);\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"delay\", function() {\r\n\r\n\t// This part is based on the respective part of the Q spec.\r\n\r\n\tit(\"should dealy fulfillment\", function() {\r\n\t\tvar promise = P(1).delay( 50 );\r\n\r\n\t\tsetTimeout(function() {\r\n\t\t\texpect( promise.inspect().state ).to.be(\"pending\");\r\n\t\t}, 30);\r\n\r\n\t\treturn promise;\r\n\t});\r\n\r\n\tit(\"should not dealy rejection\", function() {\r\n\t\tvar d = P.defer();\r\n\t\td.reject(1);\r\n\t\tvar promise = d.promise.delay( 50 );\r\n\r\n\t\tsetTimeout(function() {\r\n\t\t\texpect( promise.inspect().state ).to.be(\"rejected\");\r\n\t\t}, 30);\r\n\r\n\t\treturn promise.then( fail, function(){} );\r\n\t});\r\n\r\n\tit(\"should delay after fulfillment\", function() {\r\n\t\tvar p1 = P(\"foo\").delay( 30 );\r\n\t\tvar p2 = p1.delay( 30 );\r\n\r\n\t\tsetTimeout(function() {\r\n\t\t\texpect( p1.inspect().state ).to.be(\"fulfilled\");\r\n\t\t\texpect( p2.inspect().state ).to.be(\"pending\");\r\n\t\t}, 45);\r\n\r\n\t\treturn p2.then(function( value ) {\r\n\t\t\texpect( value ).to.be(\"foo\");\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"nodeify\", function() {\r\n\r\n\tit(\"calls back with a resolution\", function( done ) {\r\n\t\tP( 7 ).nodeify(function( error, value ) {\r\n\t\t\texpect( error ).to.be( null );\r\n\t\t\texpect( value ).to.be( 7 );\r\n\t\t\tdone();\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"calls back with an error\", function( done ) {\r\n\t\tP.reject( 13 ).nodeify(function( error, value ) {\r\n\t\t\texpect( error ).to.be( 13 );\r\n\t\t\texpect( value ).to.be( void 0 );\r\n\t\t\tdone();\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"forwards a fullfilment\", function() {\r\n\t\treturn P( 5 ).nodeify( void 0 ).then(function( value ) {\r\n\t\t\texpect( value ).to.be( 5 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"forwards a rejection\", function() {\r\n\t\treturn P.reject( 3 ).nodeify( void 0 ).then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( 3 );\r\n\t\t});\r\n\t});\r\n});\r\n\r\ndescribe(\"promised\", function() {\r\n\r\n\tvar sum = P.promised(function( a, b ) {\r\n\t\treturn a + b;\r\n\t});\r\n\r\n\tvar inc = P.promised(function( n ) {\r\n\t\treturn this + n;\r\n\t});\r\n\r\n\tit(\"resolves promised arguments\", function() {\r\n\t\treturn sum( P(1), 2 ).then(function( res ) {\r\n\t\t\texpect( res ).to.be( 3 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"resolves promised `this`\", function() {\r\n\t\treturn inc.call( P(4), 1 ).then(function( res ) {\r\n\t\t\texpect( res ).to.be( 5 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"is rejected if an argument is rejected\", function() {\r\n\t\treturn sum( P.reject(1), 2 ).then(fail, function( e ) {\r\n\t\t\texpect( e ).to.be( 1 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"is rejected if `this` is rejected\", function() {\r\n\t\treturn inc.call( P.reject(1), P(2) ).then(fail, function( e ) {\r\n\t\t\texpect( e ).to.be( 1 );\r\n\t\t});\r\n\t});\r\n\r\n});\r\n\r\ndescribe(\"denodeify\", function() {\r\n\r\n\tit(\"should fulfill if no error\", function() {\r\n\t\tvar f = P.denodeify(function( a, b, c, d, callback ) {\r\n\t\t\tcallback( null, a + b + c + d );\r\n\t\t});\r\n\r\n\t\treturn f( 1, 2, 3, 4 ).then(function( value ) {\r\n\t\t\texpect( value ).to.be( 10 );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject on error\", function() {\r\n\t\tvar theError = new Error();\r\n\r\n\t\tvar f = P.denodeify(function( a, b, c, d, callback ) {\r\n\t\t\tcallback( theError );\r\n\t\t});\r\n\r\n\t\treturn f( 1, 2, 3, 4 ).then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theError );\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should reject on thrown error\", function() {\r\n\t\tvar theError = new Error();\r\n\r\n\t\tvar f = P.denodeify(function( a, b, c, d, callback ) {\r\n\t\t\tthrow theError;\r\n\t\t});\r\n\r\n\t\treturn f( 1, 2, 3, 4 ).then(fail, function( reason ) {\r\n\t\t\texpect( reason ).to.be( theError );\r\n\t\t});\r\n\t});\r\n\r\n});\r\n\r\n!opt_tracing && describe(\"longStackSupport\", function() {\r\n\r\n\tError.stackTraceLimit = Infinity;\r\n\r\n\tbeforeEach(function() {\r\n\t\tP.longStackSupport = true;\r\n\t});\r\n\r\n\tafterEach(function() {\r\n\t\tP.longStackSupport = false;\r\n\t});\r\n\r\n\tfunction createError( msg ) {\r\n\t\ttry {\r\n\t\t\tthrow new Error( msg );\r\n\r\n\t\t} catch ( e ) {\r\n\t\t\treturn e;\r\n\t\t}\r\n\t}\r\n\r\n\tfunction checkError( error, expectedNamesStr ) {\r\n\t\texpect( error instanceof Error ).to.be( true );\r\n\r\n\t\tvar stacks = error.stack\r\n\t\t\t.split(\"_it_\")[0]\r\n\t\t\t.split(\"\\nFrom previous event:\\n\");\r\n\r\n\t\tvar str = map(stacks, function( stack ) {\r\n\t\t\treturn ( stack.match(/_(\\w+)_/g) || [] )\r\n\t\t\t\t.join(\"\")\r\n\t\t\t\t.split(\"__\").join(\"-\")\r\n\t\t\t\t.slice(1, -1);\r\n\t\t})\r\n\t\t.join(\" \")\r\n\t\t.replace(/^\\s+|\\s+$/g, \"\")\r\n\t\t.replace(/\\s+/g, \" \");\r\n\r\n\t\texpect( str ).to.be( expectedNamesStr );\r\n\t}\r\n\r\n\tit(\"should make trace long on sync rejected thenable\", function _it_() {\r\n\t\treturn P().then(function _5_() {\r\n\t\t\treturn P().then(function _4_() {\r\n\t\t\t\treturn P().then(function _3_() {\r\n\t\t\t\t\treturn {then: function _2_( cb, eb ) {\r\n\t\t\t\t\t cb({then: function _1_( cb, eb ) {\r\n\t\t\t\t\t\teb( createError() );\r\n\t\t\t\t\t }});\r\n\t\t\t\t\t}};\r\n\t\t\t\t});\r\n\t\t\t})\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"1-2 4 5\");\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should make trace long on async rejected thenable\", function _it_() {\r\n\t\treturn P().then(function _5_() {\r\n\t\t\treturn P().then(function _4_() {\r\n\t\t\t\treturn P().then(function _3_() {\r\n\t\t\t\t\treturn {then: function _2_( cb, eb ) {\r\n\t\t\t\t\t\tsetTimeout(function _b_() {\r\n\t\t\t\t\t\t\tcb({then: function _1_( cb, eb ) {\r\n\t\t\t\t\t\t\t\tcb({then: function( cb, eb ) {\r\n\t\t\t\t\t\t\t\t\tsetTimeout(function _a_() {\r\n\t\t\t\t\t\t\t\t\t\teb( new Error() );\r\n\t\t\t\t\t\t\t\t\t}, 0);\r\n\t\t\t\t\t\t\t\t}});\r\n\t\t\t\t\t\t\t}});\r\n\r\n\t\t\t\t\t\t\tP().then(function _c_() {\r\n\t\t\t\t\t\t\t\tthrow new Error();\r\n\t\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\t.done(null, function( error ) {\r\n\t\t\t\t\t\t\t\tcheckError(error, \"c b\");\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}, 0);\r\n\t\t\t\t\t}};\r\n\t\t\t\t});\r\n\t\t\t})\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"a 1-b 4 5\");\r\n\t\t});\r\n\t});\r\n\r\n\r\n\tit(\"should make trace long if denodeifed function rejects\", function _it_() {\r\n\r\n\t\tvar rejection = P.denodeify(function( nodeback ) {\r\n\t\t\tsetTimeout(function _0_() {\r\n\t\t\t\tnodeback( new Error() );\r\n\t\t\t}, 0);\r\n\t\t});\r\n\r\n\t\treturn P().then(function _2_() {\r\n\t\t\treturn P().then(function _1_() {\r\n\t\t\t\treturn rejection();\r\n\t\t\t});\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"0 1 2\");\r\n\t\t});\r\n\t});\r\n\r\n\tit(\"should make trace long on timeouted promise\", function _it_() {\r\n\t\treturn P().then(function _2_() {\r\n\t\t\treturn P().then(function _1_() {\r\n\t\t\t\treturn P.defer().promise.timeout(1);\r\n\t\t\t});\r\n\t\t})\r\n\t\t.then(fail, function( error ) {\r\n\t\t\tcheckError(error, \"1 2\");\r\n\t\t});\r\n\t});\r\n\r\n});\r\n\r\nif ( isNodeJS ) describe(\"domain\", function() {\r\n\r\n\tvar domain = require(\"domain\");\r\n\r\n\tit(\"should work with domains\", function() {\r\n\t\tvar d = P.defer();\r\n\t\tvar theValue = 0;\r\n\t\tvar theError = new Error();\r\n\r\n\t\tP(47).then(function( value ) { theValue = value; });\r\n\r\n\t\tvar theDomain = domain.create();\r\n\t\ttheDomain.on(\"error\", function( error ) {\r\n\t\t\texpect( theValue ).to.be( 47 );\r\n\t\t\texpect( error ).to.be( theError );\r\n\t\t\tP().then( d.resolve );\r\n\t\t})\r\n\t\t.run(function() {\r\n\t\t\tP().then(function() {\r\n\t\t\t\texpect( domain.active ).to.be( theDomain );\r\n\t\t\t}).done();\r\n\r\n\t\t\tP.reject( theError ).done();\r\n\t\t});\r\n\r\n\t\treturn d.promise.then(function() {\r\n\t\t\texpect( domain.active ).not.to.be( theDomain );\r\n\t\t}, fail);\r\n\t});\r\n\r\n\tit(\"should not evaluate promises in disposed domains\", function() {\r\n\t\tvar theDomain = domain.create();\r\n\t\tvar called = false;\r\n\r\n\t\ttheDomain.on(\"error\", function( e ) {\r\n\t\t\tP().then(function() { called = true; });\r\n\t\t\ttheDomain.dispose();\r\n\t\t})\r\n\t\t.run(function() {\r\n\t\t\tP.reject( new Error() ).done();\r\n\t\t});\r\n\r\n\t\treturn P().delay(10).then(function() {\r\n\t\t\texpect( called ).to.be( false );\r\n\t\t});\r\n\t});\r\n});\r\n\r\n})();\r\n"},"message":{"kind":"string","value":"Fix domain test"},"old_file":{"kind":"string","value":"test/test.js"},"subject":{"kind":"string","value":"Fix domain test"},"git_diff":{"kind":"string","value":"est/test.js\n \t\t});\n \n \t\treturn d.promise.then(function() {\n\t\t\texpect( domain.active ).not.to.be( theDomain );\n\t\t\texpect( domain.active ).to.be( theDomain );\n \t\t}, fail);\n \t});\n "}}},{"rowIdx":198744,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"fe43a364c84d92209af2c1e60a6af80870009213"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tylerrinnan-wf/java-nats,cloudfoundry-community/java-nats"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) 2012 Mike Heath. 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 implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage nats.codec;\n\nimport nats.NatsException;\nimport org.codehaus.jackson.annotate.JsonCreator;\nimport org.codehaus.jackson.annotate.JsonProperty;\nimport org.codehaus.jackson.map.DeserializationConfig;\nimport org.codehaus.jackson.map.ObjectMapper;\n\nimport java.io.IOException;\n\n/**\n * @author Mike Heath \n */\npublic class ConnectBody {\n\n\tprivate final String user;\n\tprivate final String password;\n\tprivate final boolean pedantic;\n\tprivate final boolean verbose;\n\n\t@JsonCreator\n\tpublic ConnectBody(\n\t\t\t@JsonProperty(\"user\")\n\t\t\tString user,\n\t\t\t@JsonProperty(\"pass\")\n\t\t\tString password,\n\t\t\t@JsonProperty(\"pedantic\")\n\t\t\tboolean pedantic,\n\t\t\t@JsonProperty(\"verbose\")\n\t\t\tboolean verbose) {\n\t\tthis.user = user;\n\t\tthis.password = password;\n\t\tthis.pedantic = pedantic;\n\t\tthis.verbose = verbose;\n\t}\n\n\t@JsonProperty(\"pass\")\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic boolean isPedantic() {\n\t\treturn pedantic;\n\t}\n\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\n\tpublic boolean isVerbose() {\n\t\treturn verbose;\n\t}\n\n\tpublic static ConnectBody parse(String body) {\n\t\tfinal ObjectMapper mapper = new ObjectMapper();\n\t\tmapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\t\ttry {\n\t\t\treturn mapper.readValue(body, ConnectBody.class);\n\t\t} catch (IOException e) {\n\t\t\tthrow new NatsException(e);\n\t\t}\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"client/src/main/java/nats/codec/ConnectBody.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2012 Mike Heath. 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 implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage nats.codec;\n\nimport nats.NatsException;\nimport org.codehaus.jackson.annotate.JsonCreator;\nimport org.codehaus.jackson.annotate.JsonProperty;\nimport org.codehaus.jackson.map.DeserializationConfig;\nimport org.codehaus.jackson.map.ObjectMapper;\n\nimport java.io.IOException;\n\n/**\n * @author Mike Heath \n */\npublic class ConnectBody {\n\n\tprivate final String user;\n\tprivate final String password;\n\tprivate final boolean pedantic;\n\tprivate final boolean verbose;\n\n\t@JsonCreator\n\tpublic ConnectBody(\n\t\t\t@JsonProperty(\"user\")\n\t\t\tString user,\n\t\t\t@JsonProperty(\"password\")\n\t\t\tString password,\n\t\t\t@JsonProperty(\"pedantic\")\n\t\t\tboolean pedantic,\n\t\t\t@JsonProperty(\"verbose\")\n\t\t\tboolean verbose) {\n\t\tthis.user = user;\n\t\tthis.password = password;\n\t\tthis.pedantic = pedantic;\n\t\tthis.verbose = verbose;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic boolean isPedantic() {\n\t\treturn pedantic;\n\t}\n\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\n\tpublic boolean isVerbose() {\n\t\treturn verbose;\n\t}\n\n\tpublic static ConnectBody parse(String body) {\n\t\tfinal ObjectMapper mapper = new ObjectMapper();\n\t\tmapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\t\ttry {\n\t\t\treturn mapper.readValue(body, ConnectBody.class);\n\t\t} catch (IOException e) {\n\t\t\tthrow new NatsException(e);\n\t\t}\n\t}\n\n}\n"},"message":{"kind":"string","value":"Fixed #19 - Body of connect message isn't JSON encoded properly for authentication.\n"},"old_file":{"kind":"string","value":"client/src/main/java/nats/codec/ConnectBody.java"},"subject":{"kind":"string","value":"Fixed #19 - Body of connect message isn't JSON encoded properly for authentication."},"git_diff":{"kind":"string","value":"lient/src/main/java/nats/codec/ConnectBody.java\n \tpublic ConnectBody(\n \t\t\t@JsonProperty(\"user\")\n \t\t\tString user,\n\t\t\t@JsonProperty(\"password\")\n\t\t\t@JsonProperty(\"pass\")\n \t\t\tString password,\n \t\t\t@JsonProperty(\"pedantic\")\n \t\t\tboolean pedantic,\n \t\tthis.verbose = verbose;\n \t}\n \n\t@JsonProperty(\"pass\")\n \tpublic String getPassword() {\n \t\treturn password;\n \t}"}}},{"rowIdx":198745,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"0d4722c5f2379da05a6041d2834e1098db852d6b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"fqqb/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,yamcs/yamcs"},"new_contents":{"kind":"string","value":"package org.yamcs.yarch.rocksdb;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.rocksdb.ReadOptions;\nimport org.rocksdb.RocksDBException;\nimport org.rocksdb.RocksIterator;\nimport org.rocksdb.Snapshot;\nimport org.rocksdb.WriteBatch;\nimport org.rocksdb.WriteOptions;\nimport org.yamcs.utils.StringConverter;\nimport org.yamcs.yarch.AbstractTableWalker;\nimport org.yamcs.yarch.DbRange;\nimport org.yamcs.yarch.Partition;\nimport org.yamcs.yarch.PartitionManager;\nimport org.yamcs.yarch.RawTuple;\nimport org.yamcs.yarch.TableDefinition;\nimport org.yamcs.yarch.TableVisitor;\nimport org.yamcs.yarch.YarchDatabaseInstance;\nimport org.yamcs.yarch.YarchException;\nimport org.yamcs.yarch.streamsql.StreamSqlException;\nimport org.yamcs.yarch.streamsql.StreamSqlException.ErrCode;\n\npublic class RdbTableWalker extends AbstractTableWalker {\n private final Tablespace tablespace;\n\n static AtomicInteger count = new AtomicInteger(0);\n\n boolean batchUpdates = false;\n Snapshot snapshot = null;\n protected TableVisitor visitor;\n\n protected RdbTableWalker(Tablespace tablespace, YarchDatabaseInstance ydb, TableDefinition tableDefinition,\n boolean ascending, boolean follow) {\n super(ydb, tableDefinition, ascending, follow);\n\n this.tablespace = tablespace;\n }\n\n /**\n * \n * Iterate data through the given interval taking into account also the tableRange.\n *

\n * tableRange has to be non-null but can be unbounded at one or both ends.\n * itList = new ArrayList<>(interval.size());\n // create an iterator for each partitions\n for (Partition p : interval) {\n p1 = (RdbPartition) p;\n if (!ascending) {\n readOptions.setTotalOrderSeek(true);\n }\n RocksIterator rocksIt = rdb.getDb().newIterator(readOptions);\n DbIterator it = getPartitionIterator(rocksIt, p1.tbsIndex, ascending, tableRange);\n if (it.isValid()) {\n itList.add(it);\n } else {\n it.close();\n }\n }\n\n if (itList.size() == 0) {\n return false;\n } else if (itList.size() == 1) {\n iterator = itList.get(0);\n } else {\n iterator = new MergingIterator(itList,\n ascending ? new SuffixAscendingComparator(4) : new SuffixDescendingComparator(4));\n }\n boolean endReached;\n if (ascending) {\n endReached = runAscending(rdb, iterator, writeBatch, tableRange.rangeEnd);\n } else {\n endReached = runDescending(rdb, iterator, writeBatch, tableRange.rangeStart);\n }\n if (writeBatch != null) {\n WriteOptions wo = new WriteOptions();\n rdb.getDb().write(wo, writeBatch);\n wo.close();\n }\n return endReached;\n } finally {\n if (iterator != null) {\n iterator.close();\n }\n if (snapshot != null) {\n rdb.getDb().releaseSnapshot(snapshot);\n snapshot.close();\n snapshot = null;\n }\n readOptions.close();\n tablespace.dispose(rdb);\n\n if (writeBatch != null) {\n writeBatch.close();\n }\n }\n }\n\n /**\n * If set, the snapshot will be used to iterate the database but only if the follow = false\n *

\n * The snapshot will be release at the end\n * \n * @param snapshot\n */\n public void setSnapshot(Snapshot snapshot) {\n this.snapshot = snapshot;\n }\n\n // return true if the end condition has been reached\n boolean runAscending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeEnd)\n throws RocksDBException, StreamSqlException {\n\n while (isRunning() && iterator.isValid()) {\n byte[] dbKey = iterator.key();\n byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length);\n byte[] value = iterator.value();\n numRecordsRead++;\n\n if (iAscendingFinished(key, value, rangeEnd)) {\n return true;\n }\n TableVisitor.Action action = visitor.visit(key, iterator.value());\n if (writeBatch == null) {\n executeAction(rdb, action, dbKey);\n } else {\n executeAction(rdb, writeBatch, action, dbKey);\n }\n if (action.stop()) {\n close();\n return false;\n }\n\n iterator.next();\n }\n return false;\n }\n\n boolean runDescending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeStart)\n throws RocksDBException, StreamSqlException {\n while (isRunning() && iterator.isValid()) {\n byte[] dbKey = iterator.key();\n byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length);\n numRecordsRead++;\n\n if (isDescendingFinished(key, iterator.value(), rangeStart)) {\n return true;\n }\n\n TableVisitor.Action action = visitor.visit(key, iterator.value());\n if (writeBatch == null) {\n executeAction(rdb, action, dbKey);\n } else {\n executeAction(rdb, writeBatch, action, dbKey);\n }\n\n if (action.stop()) {\n close();\n return false;\n }\n iterator.prev();\n }\n return false;\n }\n\n static void executeAction(YRDB rdb, WriteBatch writeBatch, TableVisitor.Action action, byte[] dbKey)\n throws RocksDBException, StreamSqlException {\n if (action.action() == TableVisitor.ActionType.DELETE) {\n writeBatch.delete(dbKey);\n } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) {\n writeBatch.put(dbKey, action.getUpdatedValue());\n } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) {\n // we only support updates on non partition tables\n int tbsIndex = RdbStorageEngine.tbsIndex(dbKey);\n byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey());\n if (rdb.get(updatedDbKey) != null) {\n throw new StreamSqlException(ErrCode.DUPLICATE_KEY,\n \"duplicate key in update: \" + StringConverter.arrayToHexString(updatedDbKey));\n }\n\n writeBatch.delete(dbKey);\n writeBatch.put(updatedDbKey, action.getUpdatedValue());\n\n }\n }\n\n static void executeAction(YRDB rdb, TableVisitor.Action action, byte[] dbKey)\n throws RocksDBException, StreamSqlException {\n if (action.action() == TableVisitor.ActionType.DELETE) {\n rdb.delete(dbKey);\n } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) {\n rdb.put(dbKey, action.getUpdatedValue());\n } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) {\n // we only support updates on non partition tables\n int tbsIndex = RdbStorageEngine.tbsIndex(dbKey);\n byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey());\n if (rdb.get(updatedDbKey) != null) {\n throw new StreamSqlException(ErrCode.DUPLICATE_KEY,\n \"duplicate key in update: \" + StringConverter.arrayToHexString(updatedDbKey));\n }\n rdb.delete(dbKey);\n rdb.put(updatedDbKey, action.getUpdatedValue());\n }\n }\n\n /*\n * create a ranging iterator for the given partition\n * TODO: check usage of RocksDB prefix iterators\n * \n */\n private DbIterator getPartitionIterator(RocksIterator it, int tbsIndex, boolean ascending, DbRange tableRange) {\n DbRange dbRange = getDbRange(tbsIndex, tableRange);\n if (ascending) {\n return new AscendingRangeIterator(it, dbRange);\n } else {\n return new DescendingRangeIterator(it, dbRange);\n }\n }\n\n public long getNumRecordsRead() {\n return numRecordsRead;\n }\n\n public boolean isBatchUpdates() {\n return batchUpdates;\n }\n\n public void setBatchUpdates(boolean batchUpdates) {\n this.batchUpdates = batchUpdates;\n }\n\n class RdbRawTuple extends RawTuple {\n RocksIterator iterator;\n byte[] partition;\n byte[] key;\n byte[] value;\n\n public RdbRawTuple(byte[] partition, byte[] key, byte[] value, RocksIterator iterator, int index) {\n super(index);\n this.partition = partition;\n this.key = key;\n this.value = value;\n this.iterator = iterator;\n }\n\n @Override\n protected byte[] getKey() {\n return key;\n }\n\n @Override\n protected byte[] getValue() {\n return value;\n }\n }\n\n static DbRange getDbRange(int tbsIndex, DbRange tableRange) {\n DbRange dbr = new DbRange();\n if (tableRange != null && tableRange.rangeStart != null) {\n dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeStart);\n } else {\n dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex);\n }\n\n if (tableRange != null && tableRange.rangeEnd != null) {\n dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeEnd);\n } else {\n dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex);\n }\n return dbr;\n }\n\n static class SuffixAscendingComparator implements Comparator {\n int prefixSize;\n\n public SuffixAscendingComparator(int prefixSize) {\n this.prefixSize = prefixSize;\n }\n\n @Override\n public int compare(byte[] b1, byte[] b2) {\n int minLength = Math.min(b1.length, b2.length);\n for (int i = prefixSize; i < minLength; i++) {\n int d = (b1[i] & 0xFF) - (b2[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n for (int i = 0; i < prefixSize; i++) {\n int d = (b1[i] & 0xFF) - (b2[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n return b1.length - b2.length;\n }\n }\n\n static class SuffixDescendingComparator implements Comparator {\n int prefixSize;\n\n public SuffixDescendingComparator(int prefixSize) {\n this.prefixSize = prefixSize;\n }\n\n @Override\n public int compare(byte[] b1, byte[] b2) {\n int minLength = Math.min(b1.length, b2.length);\n for (int i = prefixSize; i < minLength; i++) {\n int d = (b2[i] & 0xFF) - (b1[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n for (int i = 0; i < prefixSize; i++) {\n int d = (b2[i] & 0xFF) - (b1[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n return b2.length - b1.length;\n }\n }\n}\n"},"new_file":{"kind":"string","value":"yamcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbTableWalker.java"},"old_contents":{"kind":"string","value":"package org.yamcs.yarch.rocksdb;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.rocksdb.ReadOptions;\nimport org.rocksdb.RocksDBException;\nimport org.rocksdb.RocksIterator;\nimport org.rocksdb.Snapshot;\nimport org.rocksdb.WriteBatch;\nimport org.rocksdb.WriteOptions;\nimport org.yamcs.utils.StringConverter;\nimport org.yamcs.yarch.AbstractTableWalker;\nimport org.yamcs.yarch.DbRange;\nimport org.yamcs.yarch.Partition;\nimport org.yamcs.yarch.PartitionManager;\nimport org.yamcs.yarch.RawTuple;\nimport org.yamcs.yarch.TableDefinition;\nimport org.yamcs.yarch.TableVisitor;\nimport org.yamcs.yarch.YarchDatabaseInstance;\nimport org.yamcs.yarch.YarchException;\nimport org.yamcs.yarch.streamsql.StreamSqlException;\nimport org.yamcs.yarch.streamsql.StreamSqlException.ErrCode;\n\npublic class RdbTableWalker extends AbstractTableWalker {\n private final Tablespace tablespace;\n\n static AtomicInteger count = new AtomicInteger(0);\n\n boolean batchUpdates = false;\n Snapshot snapshot = null;\n protected TableVisitor visitor;\n\n protected RdbTableWalker(Tablespace tablespace, YarchDatabaseInstance ydb, TableDefinition tableDefinition,\n boolean ascending, boolean follow) {\n super(ydb, tableDefinition, ascending, follow);\n\n this.tablespace = tablespace;\n }\n\n /**\n * \n * Iterate data through the given interval taking into account also the tableRange.\n *

\n * tableRange has to be non-null but can be unbounded at one or both ends.\n * itList = new ArrayList<>(interval.size());\n // create an iterator for each partitions\n for (Partition p : interval) {\n p1 = (RdbPartition) p;\n if (!ascending) {\n readOptions.setTotalOrderSeek(true);\n }\n RocksIterator rocksIt = rdb.getDb().newIterator(readOptions);\n DbIterator it = getPartitionIterator(rocksIt, p1.tbsIndex, ascending, tableRange);\n if (it.isValid()) {\n itList.add(it);\n } else {\n it.close();\n }\n }\n\n if (itList.size() == 0) {\n return false;\n } else if (itList.size() == 1) {\n iterator = itList.get(0);\n } else {\n iterator = new MergingIterator(itList,\n ascending ? new SuffixAscendingComparator(4) : new SuffixDescendingComparator(4));\n }\n boolean endReached;\n if (ascending) {\n endReached = runAscending(rdb, iterator, writeBatch, tableRange.rangeEnd);\n } else {\n endReached = runDescending(rdb, iterator, writeBatch, tableRange.rangeStart);\n }\n if (writeBatch != null) {\n WriteOptions wo = new WriteOptions();\n rdb.getDb().write(wo, writeBatch);\n wo.close();\n }\n return endReached;\n } finally {\n if (iterator != null) {\n iterator.close();\n }\n if (snapshot != null) {\n snapshot.close();\n rdb.getDb().releaseSnapshot(snapshot);\n snapshot = null;\n }\n readOptions.close();\n tablespace.dispose(rdb);\n\n if (writeBatch != null) {\n writeBatch.close();\n }\n }\n }\n\n /**\n * If set, the snapshot will be used to iterate the database but only if the follow = false\n *

\n * The snapshot will be release at the end\n * \n * @param snapshot\n */\n public void setSnapshot(Snapshot snapshot) {\n this.snapshot = snapshot;\n }\n\n // return true if the end condition has been reached\n boolean runAscending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeEnd)\n throws RocksDBException, StreamSqlException {\n\n while (isRunning() && iterator.isValid()) {\n byte[] dbKey = iterator.key();\n byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length);\n byte[] value = iterator.value();\n numRecordsRead++;\n\n if (iAscendingFinished(key, value, rangeEnd)) {\n return true;\n }\n TableVisitor.Action action = visitor.visit(key, iterator.value());\n if (writeBatch == null) {\n executeAction(rdb, action, dbKey);\n } else {\n executeAction(rdb, writeBatch, action, dbKey);\n }\n if (action.stop()) {\n close();\n return false;\n }\n\n iterator.next();\n }\n return false;\n }\n\n boolean runDescending(YRDB rdb, DbIterator iterator, WriteBatch writeBatch, byte[] rangeStart)\n throws RocksDBException, StreamSqlException {\n while (isRunning() && iterator.isValid()) {\n byte[] dbKey = iterator.key();\n byte[] key = Arrays.copyOfRange(dbKey, 4, dbKey.length);\n numRecordsRead++;\n\n if (isDescendingFinished(key, iterator.value(), rangeStart)) {\n return true;\n }\n\n TableVisitor.Action action = visitor.visit(key, iterator.value());\n if (writeBatch == null) {\n executeAction(rdb, action, dbKey);\n } else {\n executeAction(rdb, writeBatch, action, dbKey);\n }\n\n if (action.stop()) {\n close();\n return false;\n }\n iterator.prev();\n }\n return false;\n }\n\n static void executeAction(YRDB rdb, WriteBatch writeBatch, TableVisitor.Action action, byte[] dbKey)\n throws RocksDBException, StreamSqlException {\n if (action.action() == TableVisitor.ActionType.DELETE) {\n writeBatch.delete(dbKey);\n } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) {\n writeBatch.put(dbKey, action.getUpdatedValue());\n } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) {\n // we only support updates on non partition tables\n int tbsIndex = RdbStorageEngine.tbsIndex(dbKey);\n byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey());\n if (rdb.get(updatedDbKey) != null) {\n throw new StreamSqlException(ErrCode.DUPLICATE_KEY,\n \"duplicate key in update: \" + StringConverter.arrayToHexString(updatedDbKey));\n }\n\n writeBatch.delete(dbKey);\n writeBatch.put(updatedDbKey, action.getUpdatedValue());\n\n }\n }\n\n static void executeAction(YRDB rdb, TableVisitor.Action action, byte[] dbKey)\n throws RocksDBException, StreamSqlException {\n if (action.action() == TableVisitor.ActionType.DELETE) {\n rdb.delete(dbKey);\n } else if (action.action() == TableVisitor.ActionType.UPDATE_VAL) {\n rdb.put(dbKey, action.getUpdatedValue());\n } else if (action.action() == TableVisitor.ActionType.UPDATE_ROW) {\n // we only support updates on non partition tables\n int tbsIndex = RdbStorageEngine.tbsIndex(dbKey);\n byte[] updatedDbKey = RdbStorageEngine.dbKey(tbsIndex, action.getUpdatedKey());\n if (rdb.get(updatedDbKey) != null) {\n throw new StreamSqlException(ErrCode.DUPLICATE_KEY,\n \"duplicate key in update: \" + StringConverter.arrayToHexString(updatedDbKey));\n }\n rdb.delete(dbKey);\n rdb.put(updatedDbKey, action.getUpdatedValue());\n }\n }\n\n /*\n * create a ranging iterator for the given partition\n * TODO: check usage of RocksDB prefix iterators\n * \n */\n private DbIterator getPartitionIterator(RocksIterator it, int tbsIndex, boolean ascending, DbRange tableRange) {\n DbRange dbRange = getDbRange(tbsIndex, tableRange);\n if (ascending) {\n return new AscendingRangeIterator(it, dbRange);\n } else {\n return new DescendingRangeIterator(it, dbRange);\n }\n }\n\n public long getNumRecordsRead() {\n return numRecordsRead;\n }\n\n public boolean isBatchUpdates() {\n return batchUpdates;\n }\n\n public void setBatchUpdates(boolean batchUpdates) {\n this.batchUpdates = batchUpdates;\n }\n\n class RdbRawTuple extends RawTuple {\n RocksIterator iterator;\n byte[] partition;\n byte[] key;\n byte[] value;\n\n public RdbRawTuple(byte[] partition, byte[] key, byte[] value, RocksIterator iterator, int index) {\n super(index);\n this.partition = partition;\n this.key = key;\n this.value = value;\n this.iterator = iterator;\n }\n\n @Override\n protected byte[] getKey() {\n return key;\n }\n\n @Override\n protected byte[] getValue() {\n return value;\n }\n }\n\n static DbRange getDbRange(int tbsIndex, DbRange tableRange) {\n DbRange dbr = new DbRange();\n if (tableRange != null && tableRange.rangeStart != null) {\n dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeStart);\n } else {\n dbr.rangeStart = RdbStorageEngine.dbKey(tbsIndex);\n }\n\n if (tableRange != null && tableRange.rangeEnd != null) {\n dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex, tableRange.rangeEnd);\n } else {\n dbr.rangeEnd = RdbStorageEngine.dbKey(tbsIndex);\n }\n return dbr;\n }\n\n static class SuffixAscendingComparator implements Comparator {\n int prefixSize;\n\n public SuffixAscendingComparator(int prefixSize) {\n this.prefixSize = prefixSize;\n }\n\n @Override\n public int compare(byte[] b1, byte[] b2) {\n int minLength = Math.min(b1.length, b2.length);\n for (int i = prefixSize; i < minLength; i++) {\n int d = (b1[i] & 0xFF) - (b2[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n for (int i = 0; i < prefixSize; i++) {\n int d = (b1[i] & 0xFF) - (b2[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n return b1.length - b2.length;\n }\n }\n\n static class SuffixDescendingComparator implements Comparator {\n int prefixSize;\n\n public SuffixDescendingComparator(int prefixSize) {\n this.prefixSize = prefixSize;\n }\n\n @Override\n public int compare(byte[] b1, byte[] b2) {\n int minLength = Math.min(b1.length, b2.length);\n for (int i = prefixSize; i < minLength; i++) {\n int d = (b2[i] & 0xFF) - (b1[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n for (int i = 0; i < prefixSize; i++) {\n int d = (b2[i] & 0xFF) - (b1[i] & 0xFF);\n if (d != 0) {\n return d;\n }\n }\n return b2.length - b1.length;\n }\n }\n}\n"},"message":{"kind":"string","value":"fix crash with snapshot\n\nreleaseSnapshot has to be called before snapshot.close\n"},"old_file":{"kind":"string","value":"yamcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbTableWalker.java"},"subject":{"kind":"string","value":"fix crash with snapshot"},"git_diff":{"kind":"string","value":"amcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbTableWalker.java\n iterator.close();\n }\n if (snapshot != null) {\n rdb.getDb().releaseSnapshot(snapshot);\n snapshot.close();\n rdb.getDb().releaseSnapshot(snapshot);\n snapshot = null;\n }\n readOptions.close();"}}},{"rowIdx":198746,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":"error: pathspec 'src/com/opengamma/id/UniqueIdentifierFudgeType.java' did not match any file(s) known to git\n"},"commit":{"kind":"string","value":"4d5602f87edb7e38444fe670c999532f099c45b6"},"returncode":{"kind":"number","value":1,"string":"1"},"repos":{"kind":"string","value":"nssales/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling"},"new_contents":{"kind":"string","value":"/**\n * Copyright (C) 2009 - 2010 by OpenGamma Inc.\n *\n * Please see distribution for license.\n */\npackage com.opengamma.id;\n\nimport org.fudgemsg.types.SecondaryFieldType;\nimport org.fudgemsg.types.StringFieldType;\n\n/**\n * Defines a UniqueIdentifier as a Fudge type, based on String. The UniqueIdentifier is typically encoded as a \n * submessage using its toFudgeMsg and fromFudgeMsg methods, but there may be cases where a string is required.\n */\npublic final class UniqueIdentifierFudgeType extends SecondaryFieldType {\n\n /**\n * Singleton instance of the type.\n */\n public static final UniqueIdentifierFudgeType INSTANCE = new UniqueIdentifierFudgeType();\n\n private UniqueIdentifierFudgeType() {\n super(StringFieldType.INSTANCE, UniqueIdentifier.class);\n }\n\n @Override\n public String secondaryToPrimary(final UniqueIdentifier identifier) {\n return identifier.toString();\n }\n\n @Override\n public UniqueIdentifier primaryToSecondary(final String string) {\n return UniqueIdentifier.parse(string);\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/com/opengamma/id/UniqueIdentifierFudgeType.java"},"old_contents":{"kind":"string","value":""},"message":{"kind":"string","value":"Secondary Fudge type for UniqueIdentifiers that are encoded as strings.\n"},"old_file":{"kind":"string","value":"src/com/opengamma/id/UniqueIdentifierFudgeType.java"},"subject":{"kind":"string","value":"Secondary Fudge type for UniqueIdentifiers that are encoded as strings."},"git_diff":{"kind":"string","value":"rc/com/opengamma/id/UniqueIdentifierFudgeType.java\n/**\n * Copyright (C) 2009 - 2010 by OpenGamma Inc.\n *\n * Please see distribution for license.\n */\npackage com.opengamma.id;\n\nimport org.fudgemsg.types.SecondaryFieldType;\nimport org.fudgemsg.types.StringFieldType;\n\n/**\n * Defines a UniqueIdentifier as a Fudge type, based on String. The UniqueIdentifier is typically encoded as a \n * submessage using its toFudgeMsg and fromFudgeMsg methods, but there may be cases where a string is required.\n */\npublic final class UniqueIdentifierFudgeType extends SecondaryFieldType {\n\n /**\n * Singleton instance of the type.\n */\n public static final UniqueIdentifierFudgeType INSTANCE = new UniqueIdentifierFudgeType();\n\n private UniqueIdentifierFudgeType() {\n super(StringFieldType.INSTANCE, UniqueIdentifier.class);\n }\n\n @Override\n public String secondaryToPrimary(final UniqueIdentifier identifier) {\n return identifier.toString();\n }\n\n @Override\n public UniqueIdentifier primaryToSecondary(final String string) {\n return UniqueIdentifier.parse(string);\n }\n\n}"}}},{"rowIdx":198747,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"7a83bd3496e1d98ca493169576948ae02d574372"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"linkedgeodesy/opossum,linkedgeodesy/opossum"},"new_contents":{"kind":"string","value":"import \"./style/style.css\";\nimport * as $ from \"jquery\";\nimport * as L from \"leaflet\";\nimport * as wellknown from \"wellknown\";\nimport * as turf from \"@turf/turf\";\nimport \"materialize-css\";\n\nlet ors_key = \"58d904a497c67e00015b45fcd2e10661dfa14f2d46c679d259b00197\";\n\nlet lat = 39.4699075;\nlet lon = -0.3762881000000107;\nlet radius = 10000;\n\nlet lat_mz = 50.0;\nlet lon_mz = 8.271111;\nlet radius_mz = 10;\nlet lgdtype = \"PlaceOfWorship\"; //Museum School PlaceOfWorship Restaurant\nlet lgdtype2 = \"Restaurant\"; //Museum School PlaceOfWorship Restaurant\nlet range_mz_min = 25;\nlet range_mz = range_mz_min*60;\n\n// set tile layer\nlet hotMap = L.tileLayer(\"http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png\", {\n maxZoom: 19,\n attribution: \"&copy; OpenStreetMap, Tiles courtesy of Humanitarian OpenStreetMap Team\"\n});\n\nlet osmMap = L.tileLayer(\"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\", {\n maxZoom: 19,\n attribution: \"&copy; OpenStreetMap Contributors\"\n});\n\n// add circle\nlet buffer = L.circle([lat, lon], {\n color: \"#000\",\n fillOpacity: 0.0,\n radius: radius\n});\n\nlet buffer2 = L.circle([lat_mz, lon_mz], {\n color: \"#000\",\n fillOpacity: 0.0,\n radius: radius\n});\n\nlet wikipedia = L.layerGroup();\nlet PlaceOfWorship = L.layerGroup();\nlet Restaurant = L.layerGroup();\nlet walkingArea = L.layerGroup();\n\nlet getTypesFromDBpedia = (json) => {\n let types = \"

types
\";\n $.ajax({\n type: \"GET\",\n url: \"http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+*+WHERE+%7B+%3Fs+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FwikiPageID%3E+%22\"+json.pageid+\"%22%5E%5Exsd%3Ainteger+.+%3Fs+%3Fp+%3Fo+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&run=+Run+Query+\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let bindings = data.results.bindings;\n for (var item in bindings) {\n if (bindings[item].p.value.includes(\"#type\")) {\n if (bindings[item].o.value.includes(\"http://dbpedia.org/ontology/\")) {\n let split = bindings[item].o.value.split(\"/\");\n types += split[split.length-1]+\"
\";\n }\n }\n }\n }\n });\n return types;\n};\n\nvar styleValencia = {\n \"color\": \"#0000FF\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// read valencia data from wikipedia api\n$.ajax({\n type: \"GET\",\n url: \"https://en.wikipedia.org/w/api.php?action=query&gsmaxdim=10000&list=geosearch&gslimit=1000&gsradius=\"+radius+\"&gscoord=\"+lat+\"|\"+lon+\"&continue&format=json&origin=*\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let geosearch = data.query.geosearch;\n for (var item in geosearch) {\n let point = turf.point([geosearch[item].lon, geosearch[item].lat]);\n let buffer = turf.buffer(point, 20, \"meters\");\n let envelope = turf.envelope(buffer);\n let marker = L.geoJson(envelope, {style: styleValencia});\n marker.properties = {};\n marker.properties.wiki1 = geosearch[item];\n marker.bindPopup(\"\"+marker.properties.wiki1.title+\"\"+getTypesFromDBpedia(geosearch[item]));\n wikipedia.addLayer(marker);\n }\n }\n});\n\nvar stylePlaceOfWorship = {\n \"color\": \"#ff7800\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// load place of worships via linkedgeodata.org\n$.ajax({\n type: \"GET\",\n url: \"http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A\"+lgdtype+\"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28\"+lon_mz+\"%2C+\"+lat_mz+\"%29%2C+\"+radius_mz+\"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let bindings = data.results.bindings;\n for (var item in bindings) {\n // WKT TO GEOJSON via\n let geojson = wellknown.parse(bindings[item].geo.value);\n // LINESTRING TO POLYGON VIA turf\n if (bindings[item].geo.value.includes(\"LINESTRING\")) {\n var coord = turf.getCoords(geojson);\n var line = turf.lineString(coord);\n var polygon = turf.lineStringToPolygon(line);\n geojson = polygon;\n } else if (bindings[item].geo.value.includes(\"POINT\")) {\n let coord = turf.getCoords(geojson);\n let point = turf.point(coord);\n let buffer = turf.buffer(point, 10, \"meters\");\n let envelope = turf.envelope(buffer);\n geojson = envelope;\n }\n let marker = L.geoJson(geojson, {style: stylePlaceOfWorship});\n marker.properties = {};\n marker.properties.item = bindings[item].item.value;\n marker.properties.label = bindings[item].label.value;\n marker.bindPopup(\"

\"+marker.properties.label);\n PlaceOfWorship.addLayer(marker);\n }\n }\n});\n\nvar styleRestaurant = {\n \"color\": \"#447550\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// load restaurants via linkedgeodata.org\n$.ajax({\n type: \"GET\",\n url: \"http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A\"+lgdtype2+\"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28\"+lon_mz+\"%2C+\"+lat_mz+\"%29%2C+\"+radius_mz+\"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let bindings = data.results.bindings;\n for (var item in bindings) {\n // WKT TO GEOJSON via\n let geojson = wellknown.parse(bindings[item].geo.value);\n // LINESTRING TO POLYGON VIA turf\n if (bindings[item].geo.value.includes(\"LINESTRING\")) {\n let coord = turf.getCoords(geojson);\n let line = turf.lineString(coord);\n let polygon = turf.lineStringToPolygon(line);\n geojson = polygon;\n } else if (bindings[item].geo.value.includes(\"POINT\")) {\n let coord = turf.getCoords(geojson);\n let point = turf.point(coord);\n let buffer = turf.buffer(point, 10, \"meters\");\n let envelope = turf.envelope(buffer);\n geojson = envelope;\n }\n let marker = L.geoJson(geojson, {style: styleRestaurant});\n marker.properties = {};\n marker.properties.item = bindings[item].item.value;\n marker.properties.label = bindings[item].label.value;\n marker.bindPopup(\"

\"+marker.properties.label);\n Restaurant.addLayer(marker);\n }\n }\n});\n\nvar styleWalkingArea = {\n \"color\": \"grey\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// load waking area via openrouteservice.org\n$.ajax({\n type: \"GET\",\n url: \"https://api.openrouteservice.org/isochrones?locations=\"+lon_mz+\"%2C\"+lat_mz+\"&profile=foot-walking&range_type=time&range=\"+range_mz+\"&location_type=start&api_key=\"+ors_key,\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let marker = L.geoJson(data, {style: styleWalkingArea});\n marker.bindPopup();\n walkingArea.addLayer(marker);\n }\n});\n\n// init map\nlet mymap = L.map(\"mapid\", {\n center: [45.5, 4.8],\n zoom: 6,\n layers: [osmMap, buffer, wikipedia, buffer2, walkingArea, PlaceOfWorship, Restaurant]\n});\n\nlet baseMaps = {\n \"Hot\": hotMap,\n \"OSM Mapnik\": osmMap\n};\n\nlet overlays ={\n \"Buffer Wikipedia\": buffer,\n \"wikipedia\": wikipedia,\n \"Buffer LGD\": buffer2,\n \"LGD PlaceOfWorship\": PlaceOfWorship,\n \"LGD Restaurant\": Restaurant,\n \"ORS WalkingArea 25min\": walkingArea\n};\n\nL.control.layers(baseMaps, overlays).addTo(mymap);\n"},"new_file":{"kind":"string","value":"src/app.js"},"old_contents":{"kind":"string","value":"import \"./style/style.css\";\nimport * as $ from \"jquery\";\nimport * as L from \"leaflet\";\nimport * as wellknown from \"wellknown\";\nimport * as turf from \"@turf/turf\";\nimport \"materialize-css\";\n\nlet lat = 39.4699075;\nlet lon = -0.3762881000000107;\nlet radius = 10000;\n\nlet lat_mz = 50.0;\nlet lon_mz = 8.271111;\nlet radius_mz = 10;\nlet lgdtype = \"PlaceOfWorship\"; //Museum School PlaceOfWorship Restaurant\nlet lgdtype2 = \"Restaurant\"; //Museum School PlaceOfWorship Restaurant\n\n// set tile layer\nlet hotMap = L.tileLayer(\"http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png\", {\n maxZoom: 19,\n attribution: \"&copy; OpenStreetMap, Tiles courtesy of Humanitarian OpenStreetMap Team\"\n});\n\nlet osmMap = L.tileLayer(\"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\", {\n maxZoom: 19,\n attribution: \"&copy; OpenStreetMap Contributors\"\n});\n\n// add circle\nlet buffer = L.circle([lat, lon], {\n color: \"#000\",\n fillOpacity: 0.0,\n radius: radius\n});\n\nlet buffer2 = L.circle([lat_mz, lon_mz], {\n color: \"#000\",\n fillOpacity: 0.0,\n radius: radius\n});\n\nlet wikipedia = L.layerGroup();\nlet PlaceOfWorship = L.layerGroup();\nlet Restaurant = L.layerGroup();\n\nlet getTypesFromDBpedia = (json) => {\n let types = \"

types
\";\n $.ajax({\n type: \"GET\",\n url: \"http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+*+WHERE+%7B+%3Fs+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FwikiPageID%3E+%22\"+json.pageid+\"%22%5E%5Exsd%3Ainteger+.+%3Fs+%3Fp+%3Fo+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&run=+Run+Query+\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let bindings = data.results.bindings;\n for (var item in bindings) {\n if (bindings[item].p.value.includes(\"#type\")) {\n if (bindings[item].o.value.includes(\"http://dbpedia.org/ontology/\")) {\n let split = bindings[item].o.value.split(\"/\");\n types += split[split.length-1]+\"
\";\n }\n }\n }\n }\n });\n return types;\n};\n\nvar styleValencia = {\n \"color\": \"#0000FF\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// read valencia data from wikipedia api\n$.ajax({\n type: \"GET\",\n url: \"https://en.wikipedia.org/w/api.php?action=query&gsmaxdim=10000&list=geosearch&gslimit=1000&gsradius=\"+radius+\"&gscoord=\"+lat+\"|\"+lon+\"&continue&format=json&origin=*\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let geosearch = data.query.geosearch;\n for (var item in geosearch) {\n let point = turf.point([geosearch[item].lon, geosearch[item].lat]);\n let buffer = turf.buffer(point, 20, \"meters\");\n let envelope = turf.envelope(buffer);\n let marker = L.geoJson(envelope, {style: styleValencia});\n marker.properties = {};\n marker.properties.wiki1 = geosearch[item];\n marker.bindPopup(\"\"+marker.properties.wiki1.title+\"\"+getTypesFromDBpedia(geosearch[item]));\n wikipedia.addLayer(marker);\n }\n }\n});\n\nvar stylePlaceOfWorship = {\n \"color\": \"#ff7800\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// load place of worships via linkedgeodata.org\n$.ajax({\n type: \"GET\",\n url: \"http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A\"+lgdtype+\"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28\"+lon_mz+\"%2C+\"+lat_mz+\"%29%2C+\"+radius_mz+\"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let bindings = data.results.bindings;\n for (var item in bindings) {\n // WKT TO GEOJSON via\n let geojson = wellknown.parse(bindings[item].geo.value);\n // LINESTRING TO POLYGON VIA turf\n if (bindings[item].geo.value.includes(\"LINESTRING\")) {\n var coord = turf.getCoords(geojson);\n var line = turf.lineString(coord);\n var polygon = turf.lineStringToPolygon(line);\n geojson = polygon;\n } else if (bindings[item].geo.value.includes(\"POINT\")) {\n let coord = turf.getCoords(geojson);\n let point = turf.point(coord);\n let buffer = turf.buffer(point, 10, \"meters\");\n let envelope = turf.envelope(buffer);\n geojson = envelope;\n }\n let marker = L.geoJson(geojson, {style: stylePlaceOfWorship});\n marker.properties = {};\n marker.properties.item = bindings[item].item.value;\n marker.properties.label = bindings[item].label.value;\n marker.bindPopup(\"

\"+marker.properties.label);\n PlaceOfWorship.addLayer(marker);\n }\n }\n});\n\nvar styleRestaurant = {\n \"color\": \"#447550\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// load restaurants via linkedgeodata.org\n$.ajax({\n type: \"GET\",\n url: \"http://linkedgeodata.org/sparql?default-graph-uri=http%3A%2F%2Flinkedgeodata.org&query=Prefix+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APrefix+ogc%3A+%3Chttp%3A%2F%2Fwww.opengis.net%2Font%2Fgeosparql%23%3E%0D%0APrefix+geom%3A+%3Chttp%3A%2F%2Fgeovocab.org%2Fgeometry%23%3E%0D%0APrefix+lgdo%3A+%3Chttp%3A%2F%2Flinkedgeodata.org%2Fontology%2F%3E%0D%0A%0D%0ASelect+%3Fitem+%3Flabel+%3Fgeo%0D%0AFrom+%3Chttp%3A%2F%2Flinkedgeodata.org%3E+%7B%0D%0A++%3Fitem%0D%0A++++a+lgdo%3A\"+lgdtype2+\"+%3B%0D%0A++++rdfs%3Alabel+%3Flabel+%3B%0D%0A++++geom%3Ageometry+%5B%0D%0A++++++ogc%3AasWKT+%3Fgeo%0D%0A++++%5D+.%0D%0A+++%0D%0A++Filter+%28%0D%0A++++bif%3Ast_intersects+%28%3Fgeo%2C+bif%3Ast_point+%28\"+lon_mz+\"%2C+\"+lat_mz+\"%29%2C+\"+radius_mz+\"%29%0D%0A++%29+.%0D%0A%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on\",\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let bindings = data.results.bindings;\n for (var item in bindings) {\n // WKT TO GEOJSON via\n let geojson = wellknown.parse(bindings[item].geo.value);\n // LINESTRING TO POLYGON VIA turf\n if (bindings[item].geo.value.includes(\"LINESTRING\")) {\n let coord = turf.getCoords(geojson);\n let line = turf.lineString(coord);\n let polygon = turf.lineStringToPolygon(line);\n geojson = polygon;\n } else if (bindings[item].geo.value.includes(\"POINT\")) {\n let coord = turf.getCoords(geojson);\n let point = turf.point(coord);\n let buffer = turf.buffer(point, 10, \"meters\");\n let envelope = turf.envelope(buffer);\n geojson = envelope;\n }\n let marker = L.geoJson(geojson, {style: styleRestaurant});\n marker.properties = {};\n marker.properties.item = bindings[item].item.value;\n marker.properties.label = bindings[item].label.value;\n marker.bindPopup(\"

\"+marker.properties.label);\n Restaurant.addLayer(marker);\n }\n }\n});\n\n// init map\nlet mymap = L.map(\"mapid\", {\n center: [45.5, 4.8],\n zoom: 6,\n layers: [osmMap, buffer, wikipedia, buffer2, PlaceOfWorship, Restaurant]\n});\n\nlet baseMaps = {\n \"Hot\": hotMap,\n \"OSM Mapnik\": osmMap\n};\n\nlet overlays ={\n \"Buffer Wikipedia\": buffer,\n \"wikipedia\": wikipedia,\n \"Buffer LGD\": buffer2,\n \"LGD PlaceOfWorship\": PlaceOfWorship,\n \"LGD Restaurant\": Restaurant\n};\n\nL.control.layers(baseMaps, overlays).addTo(mymap);\n"},"message":{"kind":"string","value":"add openroutemap and walking area for mainz\n"},"old_file":{"kind":"string","value":"src/app.js"},"subject":{"kind":"string","value":"add openroutemap and walking area for mainz"},"git_diff":{"kind":"string","value":"rc/app.js\n import * as turf from \"@turf/turf\";\n import \"materialize-css\";\n \nlet ors_key = \"58d904a497c67e00015b45fcd2e10661dfa14f2d46c679d259b00197\";\n\n let lat = 39.4699075;\n let lon = -0.3762881000000107;\n let radius = 10000;\n let radius_mz = 10;\n let lgdtype = \"PlaceOfWorship\"; //Museum School PlaceOfWorship Restaurant\n let lgdtype2 = \"Restaurant\"; //Museum School PlaceOfWorship Restaurant\nlet range_mz_min = 25;\nlet range_mz = range_mz_min*60;\n \n // set tile layer\n let hotMap = L.tileLayer(\"http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png\", {\n let wikipedia = L.layerGroup();\n let PlaceOfWorship = L.layerGroup();\n let Restaurant = L.layerGroup();\nlet walkingArea = L.layerGroup();\n \n let getTypesFromDBpedia = (json) => {\n let types = \"

types
\";\n }\n });\n \nvar styleWalkingArea = {\n \"color\": \"grey\",\n \"weight\": 5,\n \"opacity\": 1.0,\n \"fillOpacity\": 0.8\n};\n\n// load waking area via openrouteservice.org\n$.ajax({\n type: \"GET\",\n url: \"https://api.openrouteservice.org/isochrones?locations=\"+lon_mz+\"%2C\"+lat_mz+\"&profile=foot-walking&range_type=time&range=\"+range_mz+\"&location_type=start&api_key=\"+ors_key,\n async: false,\n error: function (jqXHR, textStatus, errorThrown) {\n alert(errorThrown);\n },\n success: function (data) {\n let marker = L.geoJson(data, {style: styleWalkingArea});\n marker.bindPopup();\n walkingArea.addLayer(marker);\n }\n});\n\n // init map\n let mymap = L.map(\"mapid\", {\n center: [45.5, 4.8],\n zoom: 6,\n layers: [osmMap, buffer, wikipedia, buffer2, PlaceOfWorship, Restaurant]\n layers: [osmMap, buffer, wikipedia, buffer2, walkingArea, PlaceOfWorship, Restaurant]\n });\n \n let baseMaps = {\n \"wikipedia\": wikipedia,\n \"Buffer LGD\": buffer2,\n \"LGD PlaceOfWorship\": PlaceOfWorship,\n \"LGD Restaurant\": Restaurant\n \"LGD Restaurant\": Restaurant,\n \"ORS WalkingArea 25min\": walkingArea\n };\n \n L.control.layers(baseMaps, overlays).addTo(mymap);"}}},{"rowIdx":198748,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ee1b6d0a29d7c50b56ede85fa9c8d0e502dcc986"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"leomoldo/bunkerwar"},"new_contents":{"kind":"string","value":"package fr.leomoldo.android.bunkerwar;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.util.AttributeSet;\nimport android.view.View;\n\nimport fr.leomoldo.android.bunkerwar.game.Bunker;\nimport fr.leomoldo.android.bunkerwar.game.Landscape;\n\n/**\n * Created by leomoldo on 16/05/2016.\n */\npublic class GameView extends View {\n\n private final static float MAX_HEIGHT_RATIO_FOR_LANDSCAPE = 0.5f;\n\n private final static Double BUNKER_CANON_LENGTH = 30.0;\n public final static Float BUNKER_RADIUS = 17f;\n private final static Float BUNKER_STROKE_WIDTH = 10f;\n\n public final static Float BOMBSHELL_RADIUS = 5f;\n\n\n // Context.\n private Context mContext;\n\n // Model.\n private Landscape mLandscape;\n private Bunker mPlayerOneBunker;\n private Bunker mPlayerTwoBunker;\n\n private Float mBunkerPlayerOneX;\n private Float mBunkerPlayerOneY;\n private Float mBunkerPlayerTwoX;\n private Float mBunkerPlayerTwoY;\n\n private Float mBombShellX;\n private Float mBombShellY;\n\n // Paints.\n private Paint mLandscapePaint;\n private Paint mPlayerOneBunkerPaint;\n private Paint mPlayerTwoBunkerPaint;\n private Paint mBombShellPaint;\n\n\n public GameView(Context context) {\n this(context, null);\n }\n\n public GameView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public GameView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n\n mContext = context;\n\n this.setWillNotDraw(false);\n\n initializePaints();\n }\n\n public void initializeNewGame(Landscape landscape, Bunker playerOneBunker, Bunker playerTwoBunker) {\n mLandscape = landscape;\n mPlayerOneBunker = playerOneBunker;\n mPlayerTwoBunker = playerTwoBunker;\n }\n\n public void showBombShell(float x, float y) {\n mBombShellX = x;\n mBombShellY = y;\n }\n\n public void hideBombShell() {\n mBombShellY = null;\n mBombShellY = null;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n\n super.onDraw(canvas);\n\n if (canvas == null) return;\n\n if (mPlayerOneBunker != null) {\n drawPlayerOneBunker(canvas);\n }\n\n if (mPlayerTwoBunker != null) {\n drawPlayerTwoBunker(canvas);\n }\n\n if (mLandscape != null) {\n drawLandscape(canvas);\n }\n\n // TODO Draw BombShell if necessary (after Landscape).\n\n if (mBombShellX != null && mBombShellY != null) {\n drawBombShell(canvas, mBombShellX, mBombShellY);\n }\n }\n\n private void drawLandscape(Canvas canvas) {\n\n for (int i = 0; i < mLandscape.getNumberOfLandscapeSlices(); i++) {\n canvas.drawRect(i * getWidth() / mLandscape.getNumberOfLandscapeSlices(),\n getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(i),\n (i + 1) * getWidth() / mLandscape.getNumberOfLandscapeSlices(),\n getHeight(),\n mLandscapePaint);\n }\n }\n\n private void drawPlayerOneBunker(Canvas canvas) {\n if (mBunkerPlayerOneX == null) {\n setBunkerOneX();\n }\n if (mBunkerPlayerOneY == null) {\n setBunkerOneY();\n }\n drawBunker(canvas, mPlayerOneBunkerPaint, mBunkerPlayerOneX, mBunkerPlayerOneY, mPlayerOneBunker.getCanonAngleRadian(), true);\n }\n\n private void drawPlayerTwoBunker(Canvas canvas) {\n if (mBunkerPlayerTwoX == null) {\n setBunkerTwoX();\n }\n if (mBunkerPlayerTwoY == null) {\n setBunkerTwoY();\n }\n drawBunker(canvas, mPlayerTwoBunkerPaint, mBunkerPlayerTwoX, mBunkerPlayerTwoY, mPlayerTwoBunker.getCanonAngleRadian(), false);\n }\n\n private void drawBunker(Canvas canvas, Paint paint, float x, float y, double canonAngleRadian, boolean isCanonSetLeftToRight) {\n\n // Draw a circle and a rectangle for the bunker.\n canvas.drawCircle(x, y, BUNKER_RADIUS, paint);\n canvas.drawRect(x - BUNKER_RADIUS, y, x + BUNKER_RADIUS, getHeight(), paint);\n\n // Draw the canon of the bunker.\n float lengthX = (float) (BUNKER_CANON_LENGTH * Math.cos(canonAngleRadian));\n float lengthY = (float) (-BUNKER_CANON_LENGTH * Math.sin(canonAngleRadian));\n\n if (!isCanonSetLeftToRight) {\n lengthX = -lengthX;\n }\n\n canvas.drawLine(x, y, x + lengthX, y + lengthY, paint);\n }\n\n private void drawBombShell(Canvas canvas, float x, float y) {\n canvas.drawCircle(x, y, BOMBSHELL_RADIUS, mBombShellPaint);\n }\n\n private void initializePaints() {\n\n // Landscape.\n mLandscapePaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n mLandscapePaint.setColor(mContext.getResources().getColor(R.color.green_land_slice));\n\n // Bunker One.\n mPlayerOneBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n mPlayerOneBunkerPaint.setColor(Color.RED);\n mPlayerOneBunkerPaint.setStyle(Paint.Style.FILL);\n mPlayerOneBunkerPaint.setStrokeCap(Paint.Cap.BUTT);\n mPlayerOneBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH);\n\n // Bunker Two.\n mPlayerTwoBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n mPlayerTwoBunkerPaint.setColor(Color.YELLOW);\n mPlayerTwoBunkerPaint.setStyle(Paint.Style.FILL);\n mPlayerTwoBunkerPaint.setStrokeCap(Paint.Cap.BUTT);\n mPlayerTwoBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH);\n\n // Bombshell.\n mBombShellPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n /*if (mBunker.isPlayerOne()) {\n mBombShellPaint.setColor(Color.RED);\n\t\t} else {\n\t\t\tmBombShellPaint.setColor(Color.YELLOW);\n\t\t}*/\n mBombShellPaint.setColor(Color.BLACK); // TODO Debug only.\n mBombShellPaint.setStyle(Paint.Style.FILL);\n }\n\n\n private void setBunkerOneX() {\n float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices();\n mBunkerPlayerOneX = Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth;\n }\n\n private void setBunkerOneY() {\n mBunkerPlayerOneY = getHeight()\n - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER)\n - BUNKER_RADIUS;\n }\n\n private void setBunkerTwoX() {\n float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices();\n mBunkerPlayerTwoX = getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER;\n }\n\n private void setBunkerTwoY() {\n mBunkerPlayerTwoY = getHeight()\n - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER)\n - BUNKER_RADIUS;\n }\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/fr/leomoldo/android/bunkerwar/GameView.java"},"old_contents":{"kind":"string","value":"package fr.leomoldo.android.bunkerwar;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.util.AttributeSet;\nimport android.view.View;\n\nimport fr.leomoldo.android.bunkerwar.game.Bunker;\nimport fr.leomoldo.android.bunkerwar.game.Landscape;\n\n/**\n * Created by leomoldo on 16/05/2016.\n */\npublic class GameView extends View {\n\n private final static float MAX_HEIGHT_RATIO_FOR_LANDSCAPE = 0.5f;\n\n private final static Double BUNKER_CANON_LENGTH = 30.0;\n public final static Float BUNKER_RADIUS = 17f;\n private final static Float BUNKER_STROKE_WIDTH = 10f;\n\n public final static Float BOMBSHELL_RADIUS = 5f;\n\n\n // Context.\n private Context mContext;\n\n // Model.\n private Landscape mLandscape;\n private Bunker mPlayerOneBunker;\n private Bunker mPlayerTwoBunker;\n\n private Float mBunkerPlayerOneX;\n private Float mBunkerPlayerOneY;\n private Float mBunkerPlayerTwoX;\n private Float mBunkerPlayerTwoY;\n\n // Paints.\n private Paint mLandscapePaint;\n private Paint mPlayerOneBunkerPaint;\n private Paint mPlayerTwoBunkerPaint;\n private Paint mBombShellPaint;\n\n\n public GameView(Context context) {\n this(context, null);\n }\n\n public GameView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public GameView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n\n mContext = context;\n\n this.setWillNotDraw(false);\n\n initializePaints();\n }\n\n public void initializeNewGame(Landscape landscape, Bunker playerOneBunker, Bunker playerTwoBunker) {\n mLandscape = landscape;\n mPlayerOneBunker = playerOneBunker;\n mPlayerTwoBunker = playerTwoBunker;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n\n super.onDraw(canvas);\n\n if (canvas == null) return;\n\n if (mPlayerOneBunker != null) {\n drawPlayerOneBunker(canvas);\n }\n\n if (mPlayerTwoBunker != null) {\n drawPlayerTwoBunker(canvas);\n }\n\n if (mLandscape != null) {\n drawLandscape(canvas);\n }\n\n // TODO Draw BombShell if necessary (after Landscape).\n }\n\n private void drawLandscape(Canvas canvas) {\n\n for (int i = 0; i < mLandscape.getNumberOfLandscapeSlices(); i++) {\n canvas.drawRect(i * getWidth() / mLandscape.getNumberOfLandscapeSlices(),\n getHeight() - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(i),\n (i + 1) * getWidth() / mLandscape.getNumberOfLandscapeSlices(),\n getHeight(),\n mLandscapePaint);\n }\n }\n\n private void drawPlayerOneBunker(Canvas canvas) {\n if (mBunkerPlayerOneX == null) {\n setBunkerOneX();\n }\n if (mBunkerPlayerOneY == null) {\n setBunkerOneY();\n }\n drawBunker(canvas, mPlayerOneBunkerPaint, mBunkerPlayerOneX, mBunkerPlayerOneY, mPlayerOneBunker.getCanonAngleRadian(), true);\n }\n\n private void drawPlayerTwoBunker(Canvas canvas) {\n if (mBunkerPlayerTwoX == null) {\n setBunkerTwoX();\n }\n if (mBunkerPlayerTwoY == null) {\n setBunkerTwoY();\n }\n drawBunker(canvas, mPlayerTwoBunkerPaint, mBunkerPlayerTwoX, mBunkerPlayerTwoY, mPlayerTwoBunker.getCanonAngleRadian(), false);\n }\n\n private void drawBunker(Canvas canvas, Paint paint, float x, float y, double canonAngleRadian, boolean isCanonSetLeftToRight) {\n\n // Draw a circle and a rectangle for the bunker.\n canvas.drawCircle(x, y, BUNKER_RADIUS, paint);\n canvas.drawRect(x - BUNKER_RADIUS, y, x + BUNKER_RADIUS, getHeight(), paint);\n\n // Draw the canon of the bunker.\n float lengthX = (float) (BUNKER_CANON_LENGTH * Math.cos(canonAngleRadian));\n float lengthY = (float) (-BUNKER_CANON_LENGTH * Math.sin(canonAngleRadian));\n\n if (!isCanonSetLeftToRight) {\n lengthX = -lengthX;\n }\n\n canvas.drawLine(x, y, x + lengthX, y + lengthY, paint);\n }\n\n private void drawBombShell(Canvas canvas, float x, float y) {\n canvas.drawCircle(x, y, BOMBSHELL_RADIUS, mBombShellPaint);\n }\n\n private void initializePaints() {\n\n // Landscape.\n mLandscapePaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n mLandscapePaint.setColor(mContext.getResources().getColor(R.color.green_land_slice));\n\n // Bunker One.\n mPlayerOneBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n mPlayerOneBunkerPaint.setColor(Color.RED);\n mPlayerOneBunkerPaint.setStyle(Paint.Style.FILL);\n mPlayerOneBunkerPaint.setStrokeCap(Paint.Cap.BUTT);\n mPlayerOneBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH);\n\n // Bunker Two.\n mPlayerTwoBunkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n mPlayerTwoBunkerPaint.setColor(Color.YELLOW);\n mPlayerTwoBunkerPaint.setStyle(Paint.Style.FILL);\n mPlayerTwoBunkerPaint.setStrokeCap(Paint.Cap.BUTT);\n mPlayerTwoBunkerPaint.setStrokeWidth(BUNKER_STROKE_WIDTH);\n\n // Bombshell.\n mBombShellPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n /*if (mBunker.isPlayerOne()) {\n mBombShellPaint.setColor(Color.RED);\n\t\t} else {\n\t\t\tmBombShellPaint.setColor(Color.YELLOW);\n\t\t}*/\n mBombShellPaint.setColor(Color.BLACK); // TODO Debug only.\n mBombShellPaint.setStyle(Paint.Style.FILL);\n }\n\n\n private void setBunkerOneX() {\n float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices();\n mBunkerPlayerOneX = Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth;\n }\n\n private void setBunkerOneY() {\n mBunkerPlayerOneY = getHeight()\n - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER)\n - BUNKER_RADIUS;\n }\n\n private void setBunkerTwoX() {\n float landSliceWidth = getWidth() / mLandscape.getNumberOfLandscapeSlices();\n mBunkerPlayerTwoX = getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER;\n }\n\n private void setBunkerTwoY() {\n mBunkerPlayerTwoY = getHeight()\n - getHeight() * MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER)\n - BUNKER_RADIUS;\n }\n}\n"},"message":{"kind":"string","value":"Implemented bombshell drawing management interface in GameView.\n"},"old_file":{"kind":"string","value":"app/src/main/java/fr/leomoldo/android/bunkerwar/GameView.java"},"subject":{"kind":"string","value":"Implemented bombshell drawing management interface in GameView."},"git_diff":{"kind":"string","value":"pp/src/main/java/fr/leomoldo/android/bunkerwar/GameView.java\n private Float mBunkerPlayerTwoX;\n private Float mBunkerPlayerTwoY;\n \n private Float mBombShellX;\n private Float mBombShellY;\n\n // Paints.\n private Paint mLandscapePaint;\n private Paint mPlayerOneBunkerPaint;\n mPlayerTwoBunker = playerTwoBunker;\n }\n \n public void showBombShell(float x, float y) {\n mBombShellX = x;\n mBombShellY = y;\n }\n\n public void hideBombShell() {\n mBombShellY = null;\n mBombShellY = null;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n \n }\n \n // TODO Draw BombShell if necessary (after Landscape).\n\n if (mBombShellX != null && mBombShellY != null) {\n drawBombShell(canvas, mBombShellX, mBombShellY);\n }\n }\n \n private void drawLandscape(Canvas canvas) {"}}},{"rowIdx":198749,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d35966755d63d774a2ddbcdabdf76cfa3d23939d"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"mapzen/documentation,mapzen/documentation,mapzen/mapzen-docs-generator,mapzen/documentation,mapzen/mapzen-docs-generator,mapzen/mapzen-docs-generator,mapzen/mapzen-docs-generator,mapzen/documentation"},"new_contents":{"kind":"string","value":"\nfunction getSearchTerm()\n{\n var sPageURL = window.location.search.substring(1);\n var sURLVariables = sPageURL.split('&');\n for (var i = 0; i < sURLVariables.length; i++)\n {\n var sParameterName = sURLVariables[i].split('=');\n if (sParameterName[0] == 'q')\n {\n return sParameterName[1];\n }\n }\n}\n\n$(document).ready(function () {\n var search_term = getSearchTerm()\n var $search_modal = $('#mkdocs_search_modal')\n var $docContainer = $('.documentation-container')\n var $searchResults = $('#mkdocs-search-results')\n var $searchInput = $('#mkdocs-search-query')\n var $nav = $('nav')\n var $toc = $('#toc')\n var $docContent = $('.documentation-content').parent()\n var affixState = false\n\n if (search_term) {\n $searchInput.val(search_term)\n }\n\n var selectedPosition\n\n $searchInput.on('keyup', function (e) {\n // Need to wait a bit for search function to finish populating our results\n setTimeout(function () {\n // See if anything is inside the search results\n if ($.trim($searchResults.html()) !== '') {\n $searchResults.show()\n $searchResults.css('max-height', window.innerHeight - $searchResults[0].getBoundingClientRect().top - 100)\n\n var input = $searchInput.val().trim()\n var list = $searchResults.find('article')\n\n if (list.length > 0) {\n // var highlight = function (text, focus) {\n // var r = RegExp('(' + focus + ')', 'gi');\n // return text.replace(r, '$1');\n // }\n\n // var html = $searchResults.html()\n // $searchResults.html(highlight(html, input))\n\n // Now reapply selection\n if (selectedPosition) {\n list[selectedPosition].addClass('selected')\n }\n }\n } else {\n $searchResults.hide()\n }\n }, 0)\n })\n /* DISABLED, this doesn't work well because other search JS overwrites selection\n $searchInput.on('keydown', function (e) {\n // Ignore key results are not visible\n if (!$searchResults.is(':visible')) {\n return;\n }\n\n var selected = $searchResults.find('article.selected')[0]\n var list = $searchResults.find('article')\n\n for (var i = 0; i < list.length; i++) {\n if (list[i] === selected) {\n selectedPosition = i;\n break;\n }\n }\n\n switch (e.keyCode) {\n // 13 = enter\n case 13:\n e.preventDefault()\n if (selected) {\n findAndOpenLink(selected)\n }\n break;\n // 38 = up arrow\n case 38:\n e.preventDefault()\n\n if (selected) {\n $(selected).removeClass('selected')\n }\n\n var previousItem = list[selectedPosition - 1];\n\n if (selected && previousItem) {\n $(previousItem).addClass('selected');\n } else {\n $(list[list.length - 1]).addClass('selected');\n }\n break;\n // 40 = down arrow\n case 40:\n e.preventDefault()\n\n if (selected) {\n $(selected).removeClass('selected');\n }\n\n var nextItem = list[selectedPosition + 1];\n\n if (selected && nextItem) {\n $(nextItem).addClass('selected');\n } else {\n $(list[0]).addClass('selected');\n }\n break;\n // all other keys\n default:\n break;\n }\n })\n */\n $search_modal.on('blur', function () {\n resetSearchResults();\n })\n $searchResults.on('click', 'article', function (e) {\n findAndOpenLink(this);\n // In case it just jumps down the page\n resetSearchResults();\n })\n\n function findAndOpenLink (articleEl) {\n var link = $(articleEl).find('a').attr('href')\n window.location.href = link;\n }\n\n function resetSearchResults () {\n $searchResults.empty();\n $searchResults.hide();\n }\n\n // Highlight.js\n hljs.initHighlightingOnLoad();\n $('table').addClass('table');\n\n // Affix for side nav bar\n // Don't turn on affix if the TOC height is greater than\n // document content, to prevent positioning bugs\n if ($toc.height() < $docContent.height()) {\n $toc.affix({\n offset: {\n top: function () {\n return $docContainer.offset().top - $nav.height()\n },\n bottom: function () {\n return $(document).height() - $docContainer.offset().top - $docContainer.outerHeight(true)\n }\n }\n })\n // Record that affix is on\n affixState = true\n }\n\n $('.toc-subnav-toggle').on('click', function (e) {\n e.preventDefault()\n var $el = $(this).next('ul')\n $el.toggleClass('toc-expand')\n\n // Recalc affix position after expand transition finishes\n if (affixState === true) {\n $el.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (e) {\n $toc.affix('checkPosition')\n })\n }\n })\n\n // Guarantee only one active thing is up\n\n var activeEls = $('.toc li.active')\n activeEls.each(function (index) {\n if (index + 1 !== activeEls.length) {\n $(activeEls[index]).removeClass('active')\n }\n })\n});\n\n\n$('body').scrollspy({\n target: '.toc',\n offset: 10\n});\n\n/* Prevent disabled links from causing a page reload */\n$('li.disabled a').click(function(event) {\n event.preventDefault();\n})\n"},"new_file":{"kind":"string","value":"theme/js/base.js"},"old_contents":{"kind":"string","value":"\nfunction getSearchTerm()\n{\n var sPageURL = window.location.search.substring(1);\n var sURLVariables = sPageURL.split('&');\n for (var i = 0; i < sURLVariables.length; i++)\n {\n var sParameterName = sURLVariables[i].split('=');\n if (sParameterName[0] == 'q')\n {\n return sParameterName[1];\n }\n }\n}\n\n$(document).ready(function () {\n var search_term = getSearchTerm()\n var $search_modal = $('#mkdocs_search_modal')\n var $docContainer = $('.documentation-container')\n var $searchResults = $('#mkdocs-search-results')\n var $searchInput = $('#mkdocs-search-query')\n var $nav = $('nav')\n var $toc = $('#toc')\n var $docContent = $('.documentation-content').parent()\n var affixState = false\n\n if (search_term) {\n $searchInput.val(search_term)\n }\n\n var selectedPosition\n\n $searchInput.on('keyup', function (e) {\n // Need to wait a bit for search function to finish populating our results\n setTimeout(function () {\n // See if anything is inside the search results\n if ($.trim($searchResults.html()) !== '') {\n $searchResults.show()\n $searchResults.css('max-height', window.innerHeight - $searchResults[0].getBoundingClientRect().top - 100)\n\n var input = $searchInput.val().trim()\n var list = $searchResults.find('article')\n\n if (list.length > 0) {\n var highlight = function (text, focus) {\n var r = RegExp('(' + focus + ')', 'gi');\n return text.replace(r, '$1');\n }\n\n var html = $searchResults.html()\n $searchResults.html(highlight(html, input))\n\n // Now reapply selection\n if (selectedPosition) {\n list[selectedPosition].addClass('selected')\n }\n }\n } else {\n $searchResults.hide()\n }\n }, 0)\n })\n /* DISABLED, this doesn't work well because other search JS overwrites selection\n $searchInput.on('keydown', function (e) {\n // Ignore key results are not visible\n if (!$searchResults.is(':visible')) {\n return;\n }\n\n var selected = $searchResults.find('article.selected')[0]\n var list = $searchResults.find('article')\n\n for (var i = 0; i < list.length; i++) {\n if (list[i] === selected) {\n selectedPosition = i;\n break;\n }\n }\n\n switch (e.keyCode) {\n // 13 = enter\n case 13:\n e.preventDefault()\n if (selected) {\n findAndOpenLink(selected)\n }\n break;\n // 38 = up arrow\n case 38:\n e.preventDefault()\n\n if (selected) {\n $(selected).removeClass('selected')\n }\n\n var previousItem = list[selectedPosition - 1];\n\n if (selected && previousItem) {\n $(previousItem).addClass('selected');\n } else {\n $(list[list.length - 1]).addClass('selected');\n }\n break;\n // 40 = down arrow\n case 40:\n e.preventDefault()\n\n if (selected) {\n $(selected).removeClass('selected');\n }\n\n var nextItem = list[selectedPosition + 1];\n\n if (selected && nextItem) {\n $(nextItem).addClass('selected');\n } else {\n $(list[0]).addClass('selected');\n }\n break;\n // all other keys\n default:\n break;\n }\n })\n */\n $search_modal.on('blur', function () {\n resetSearchResults();\n })\n $searchResults.on('click', 'article', function (e) {\n findAndOpenLink(this);\n // In case it just jumps down the page\n resetSearchResults();\n })\n\n function findAndOpenLink (articleEl) {\n var link = $(articleEl).find('a').attr('href')\n window.location.href = link;\n }\n\n function resetSearchResults () {\n $searchResults.empty();\n $searchResults.hide();\n }\n\n // Highlight.js\n hljs.initHighlightingOnLoad();\n $('table').addClass('table');\n\n // Affix for side nav bar\n // Don't turn on affix if the TOC height is greater than\n // document content, to prevent positioning bugs\n if ($toc.height() < $docContent.height()) {\n $toc.affix({\n offset: {\n top: function () {\n return $docContainer.offset().top - $nav.height()\n },\n bottom: function () {\n return $(document).height() - $docContainer.offset().top - $docContainer.outerHeight(true)\n }\n }\n })\n // Record that affix is on\n affixState = true\n }\n\n $('.toc-subnav-toggle').on('click', function (e) {\n e.preventDefault()\n var $el = $(this).next('ul')\n $el.toggleClass('toc-expand')\n\n // Recalc affix position after expand transition finishes\n if (affixState === true) {\n $el.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (e) {\n $toc.affix('checkPosition')\n })\n }\n })\n\n // Guarantee only one active thing is up\n\n var activeEls = $('.toc li.active')\n activeEls.each(function (index) {\n if (index + 1 !== activeEls.length) {\n $(activeEls[index]).removeClass('active')\n }\n })\n});\n\n\n$('body').scrollspy({\n target: '.toc',\n offset: 10\n});\n\n/* Prevent disabled links from causing a page reload */\n$('li.disabled a').click(function(event) {\n event.preventDefault();\n})\n"},"message":{"kind":"string","value":"Do not highlight search results because it is buggy. (#62)\n"},"old_file":{"kind":"string","value":"theme/js/base.js"},"subject":{"kind":"string","value":"Do not highlight search results because it is buggy. (#62)"},"git_diff":{"kind":"string","value":"heme/js/base.js\n var list = $searchResults.find('article')\n \n if (list.length > 0) {\n var highlight = function (text, focus) {\n var r = RegExp('(' + focus + ')', 'gi');\n return text.replace(r, '$1');\n }\n // var highlight = function (text, focus) {\n // var r = RegExp('(' + focus + ')', 'gi');\n // return text.replace(r, '$1');\n // }\n \n var html = $searchResults.html()\n $searchResults.html(highlight(html, input))\n // var html = $searchResults.html()\n // $searchResults.html(highlight(html, input))\n \n // Now reapply selection\n if (selectedPosition) {"}}},{"rowIdx":198750,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"epl-1.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"4adf8e3bd55dff49a76c8e010fa6b3798d7f077a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse"},"new_contents":{"kind":"string","value":"package org.eclipse.scanning.example.scannable;\n\nimport java.text.MessageFormat;\n\nimport org.eclipse.dawnsci.nexus.INexusDevice;\nimport org.eclipse.dawnsci.nexus.NXobject;\nimport org.eclipse.dawnsci.nexus.NXpositioner;\nimport org.eclipse.dawnsci.nexus.NexusException;\nimport org.eclipse.dawnsci.nexus.NexusNodeFactory;\nimport org.eclipse.dawnsci.nexus.NexusScanInfo;\nimport org.eclipse.dawnsci.nexus.builder.NexusObjectProvider;\nimport org.eclipse.dawnsci.nexus.builder.NexusObjectWrapper;\nimport org.eclipse.january.dataset.Dataset;\nimport org.eclipse.january.dataset.DatasetFactory;\nimport org.eclipse.january.dataset.ILazyWriteableDataset;\nimport org.eclipse.january.dataset.SliceND;\nimport org.eclipse.scanning.api.IScanAttributeContainer;\nimport org.eclipse.scanning.api.points.IPosition;\nimport org.eclipse.scanning.api.points.Scalar;\nimport org.eclipse.scanning.api.scan.rank.IScanRankService;\nimport org.eclipse.scanning.api.scan.rank.IScanSlice;\n\n/**\n * \n * A class to wrap any IScannable as a positioner and then write to a nexus file\n * as the positions are set during the scan.\n * \n * @author Matthew Gerring\n *\n */\npublic class MockNeXusScannable extends MockScannable implements INexusDevice {\n\t\n\tpublic static final String FIELD_NAME_DEMAND_VALUE = NXpositioner.NX_VALUE + \"_demand\";\n\t\n\tprivate ILazyWriteableDataset lzDemand;\n\tprivate ILazyWriteableDataset lzValue;\n\n\tpublic MockNeXusScannable() {\n\t\tsuper();\n\t}\n\t\n\tpublic MockNeXusScannable(String name, double d, int level) {\n\t\tsuper(name, d, level);\n\t}\n\tpublic MockNeXusScannable(String name, double d, int level, String unit) {\n\t\tsuper(name, d, level, unit);\n\t}\n\n\tpublic NexusObjectProvider getNexusProvider(NexusScanInfo info) throws NexusException {\n\t\tfinal NXpositioner positioner = NexusNodeFactory.createNXpositioner();\n\t\tpositioner.setNameScalar(getName());\n\n\t\tif (info.isMetadataScannable(getName())) {\n\t\t\tpositioner.setField(FIELD_NAME_DEMAND_VALUE, getPosition().doubleValue());\n\t\t\tpositioner.setValueScalar(getPosition().doubleValue());\n\t\t} else {\n\t\t\tthis.lzDemand = positioner.initializeLazyDataset(FIELD_NAME_DEMAND_VALUE, 1, Double.class);\n\t\t\tlzDemand.setChunking(new int[]{1});\n\t\t\t\n\t\t\tthis.lzValue = positioner.initializeLazyDataset(NXpositioner.NX_VALUE, info.getRank(), Double.class);\n\t\t\tlzValue.setChunking(info.createChunk(1)); // TODO Might be slow, need to check this\n\t\t}\n\n\t\tregisterAttributes(positioner, this);\n\t\t\n\t\tNexusObjectWrapper nexusDelegate = new NexusObjectWrapper<>(\n\t\t\t\tgetName(), positioner, NXpositioner.NX_VALUE);\n\t\tnexusDelegate.setDefaultAxisDataFieldName(FIELD_NAME_DEMAND_VALUE);\n\t\treturn nexusDelegate;\n\t}\t\n\n\tpublic void setPosition(Number value, IPosition position) throws Exception {\n\t\t\n\t\tif (value!=null) {\n\t\t\tint index = position!=null ? position.getIndex(getName()) : -1;\n\t\t\tif (isRealisticMove()) {\n\t\t\t\tvalue = doRealisticMove(value, index, -1);\n\t\t\t}\n\t\t\tthis.position = value;\n\t\t\tdelegate.firePositionPerformed(-1, new Scalar(getName(), index, value.doubleValue()));\n\t\t}\n\n\t\tif (position!=null) write(value, getPosition(), position);\n\t}\n\n\tprivate void write(Number demand, Number actual, IPosition loc) throws Exception {\n\t\t\n\t\tif (lzValue==null) return;\n\t\tif (actual!=null) {\n\t\t\t// write actual position\n\t\t\tfinal Dataset newActualPositionData = DatasetFactory.createFromObject(actual);\n\t\t\tIScanSlice rslice = IScanRankService.getScanRankService().createScanSlice(loc);\n\t\t\tSliceND sliceND = new SliceND(lzValue.getShape(), lzValue.getMaxShape(), rslice.getStart(), rslice.getStop(), rslice.getStep());\n\t\t\tlzValue.setSlice(null, newActualPositionData, sliceND);\n\t\t}\n\n\t\tif (lzDemand==null) return;\n\t\tif (demand!=null) {\n\t\t\tint index = loc.getIndex(getName());\n\t\t\tif (index<0) {\n\t\t\t\tthrow new Exception(\"Incorrect data index for scan for value of '\"+getName()+\"'. The index is \"+index);\n\t\t\t}\n\t\t\tfinal int[] startPos = new int[] { index };\n\t\t\tfinal int[] stopPos = new int[] { index + 1 };\n\n\t\t\t// write demand position\n\t\t\tfinal Dataset newDemandPositionData = DatasetFactory.createFromObject(demand);\n\t\t\tlzDemand.setSlice(null, newDemandPositionData, startPos, stopPos, null);\n\t\t}\n\t}\n\t\n\t/**\n\t * Add the attributes for the given attribute container into the given nexus object.\n\t * @param positioner\n\t * @param container\n\t * @throws NexusException if the attributes could not be added for any reason \n\t */\n\tprivate static void registerAttributes(NXobject nexusObject, IScanAttributeContainer container) throws NexusException {\n\t\t// We create the attributes, if any\n\t\tnexusObject.setField(\"name\", container.getName());\n\t\tif (container.getScanAttributeNames()!=null) for(String attrName : container.getScanAttributeNames()) {\n\t\t\ttry {\n\t\t\t\tnexusObject.setField(attrName, container.getScanAttribute(attrName));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new NexusException(MessageFormat.format(\n\t\t\t\t\t\t\"An exception occurred attempting to get the value of the attribute ''{0}'' for the device ''{1}''\",\n\t\t\t\t\t\tcontainer.getName(), attrName));\n\t\t\t}\n\t\t}\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"org.eclipse.scanning.example/src/org/eclipse/scanning/example/scannable/MockNeXusScannable.java"},"old_contents":{"kind":"string","value":"package org.eclipse.scanning.example.scannable;\n\nimport java.text.MessageFormat;\n\nimport org.eclipse.dawnsci.nexus.INexusDevice;\nimport org.eclipse.dawnsci.nexus.NXobject;\nimport org.eclipse.dawnsci.nexus.NXpositioner;\nimport org.eclipse.dawnsci.nexus.NexusException;\nimport org.eclipse.dawnsci.nexus.NexusNodeFactory;\nimport org.eclipse.dawnsci.nexus.NexusScanInfo;\nimport org.eclipse.dawnsci.nexus.builder.NexusObjectProvider;\nimport org.eclipse.dawnsci.nexus.builder.NexusObjectWrapper;\nimport org.eclipse.january.dataset.Dataset;\nimport org.eclipse.january.dataset.DatasetFactory;\nimport org.eclipse.january.dataset.ILazyWriteableDataset;\nimport org.eclipse.january.dataset.SliceND;\nimport org.eclipse.scanning.api.IScanAttributeContainer;\nimport org.eclipse.scanning.api.points.IPosition;\nimport org.eclipse.scanning.api.points.Scalar;\nimport org.eclipse.scanning.api.scan.rank.IScanRankService;\nimport org.eclipse.scanning.api.scan.rank.IScanSlice;\n\n/**\n * \n * A class to wrap any IScannable as a positioner and then write to a nexus file\n * as the positions are set during the scan.\n * \n * @author Matthew Gerring\n *\n */\npublic class MockNeXusScannable extends MockScannable implements INexusDevice {\n\t\n\tprivate ILazyWriteableDataset lzDemand;\n\tprivate ILazyWriteableDataset lzValue;\n\n\tpublic MockNeXusScannable() {\n\t\tsuper();\n\t}\n\t\n\tpublic MockNeXusScannable(String name, double d, int level) {\n\t\tsuper(name, d, level);\n\t}\n\tpublic MockNeXusScannable(String name, double d, int level, String unit) {\n\t\tsuper(name, d, level, unit);\n\t}\n\n\tpublic NexusObjectProvider getNexusProvider(NexusScanInfo info) throws NexusException {\n\t\tfinal NXpositioner positioner = NexusNodeFactory.createNXpositioner();\n\t\tpositioner.setNameScalar(getName());\n\n\t\tString fieldNameDemand = getName() + \"_demand\";\n\n\t\tif (info.isMetadataScannable(getName())) {\n\t\t\tpositioner.setField(fieldNameDemand, getPosition().doubleValue());\n\t\t\tpositioner.setValueScalar(getPosition().doubleValue());\n\t\t} else {\n\t\t\tthis.lzDemand = positioner.initializeLazyDataset(fieldNameDemand, 1, Double.class);\n\t\t\tlzDemand.setChunking(new int[]{1});\n\t\t\t\n\t\t\tthis.lzValue = positioner.initializeLazyDataset(NXpositioner.NX_VALUE, info.getRank(), Double.class);\n\t\t\tlzValue.setChunking(info.createChunk(1)); // TODO Might be slow, need to check this\n\t\t}\n\n\t\tregisterAttributes(positioner, this);\n\t\t\n\t\tNexusObjectWrapper nexusDelegate = new NexusObjectWrapper<>(\n\t\t\t\tgetName(), positioner, NXpositioner.NX_VALUE);\n\t\tnexusDelegate.setDefaultAxisDataFieldName(fieldNameDemand);\n\t\treturn nexusDelegate;\n\t}\t\n\n\tpublic void setPosition(Number value, IPosition position) throws Exception {\n\t\t\n\t\tif (value!=null) {\n\t\t\tint index = position!=null ? position.getIndex(getName()) : -1;\n\t\t\tif (isRealisticMove()) {\n\t\t\t\tvalue = doRealisticMove(value, index, -1);\n\t\t\t}\n\t\t\tthis.position = value;\n\t\t\tdelegate.firePositionPerformed(-1, new Scalar(getName(), index, value.doubleValue()));\n\t\t}\n\n\t\tif (position!=null) write(value, getPosition(), position);\n\t}\n\n\tprivate void write(Number demand, Number actual, IPosition loc) throws Exception {\n\t\t\n\t\tif (lzValue==null) return;\n\t\tif (actual!=null) {\n\t\t\t// write actual position\n\t\t\tfinal Dataset newActualPositionData = DatasetFactory.createFromObject(actual);\n\t\t\tIScanSlice rslice = IScanRankService.getScanRankService().createScanSlice(loc);\n\t\t\tSliceND sliceND = new SliceND(lzValue.getShape(), lzValue.getMaxShape(), rslice.getStart(), rslice.getStop(), rslice.getStep());\n\t\t\tlzValue.setSlice(null, newActualPositionData, sliceND);\n\t\t}\n\n\t\tif (lzDemand==null) return;\n\t\tif (demand!=null) {\n\t\t\tint index = loc.getIndex(getName());\n\t\t\tif (index<0) {\n\t\t\t\tthrow new Exception(\"Incorrect data index for scan for value of '\"+getName()+\"'. The index is \"+index);\n\t\t\t}\n\t\t\tfinal int[] startPos = new int[] { index };\n\t\t\tfinal int[] stopPos = new int[] { index + 1 };\n\n\t\t\t// write demand position\n\t\t\tfinal Dataset newDemandPositionData = DatasetFactory.createFromObject(demand);\n\t\t\tlzDemand.setSlice(null, newDemandPositionData, startPos, stopPos, null);\n\t\t}\n\t}\n\t\n\t/**\n\t * Add the attributes for the given attribute container into the given nexus object.\n\t * @param positioner\n\t * @param container\n\t * @throws NexusException if the attributes could not be added for any reason \n\t */\n\tprivate static void registerAttributes(NXobject nexusObject, IScanAttributeContainer container) throws NexusException {\n\t\t// We create the attributes, if any\n\t\tnexusObject.setField(\"name\", container.getName());\n\t\tif (container.getScanAttributeNames()!=null) for(String attrName : container.getScanAttributeNames()) {\n\t\t\ttry {\n\t\t\t\tnexusObject.setField(attrName, container.getScanAttribute(attrName));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new NexusException(MessageFormat.format(\n\t\t\t\t\t\t\"An exception occurred attempting to get the value of the attribute ''{0}'' for the device ''{1}''\",\n\t\t\t\t\t\tcontainer.getName(), attrName));\n\t\t\t}\n\t\t}\n\t}\n\n}\n"},"message":{"kind":"string","value":"Reverted scannable value name change\n\nhttp://jira.diamond.ac.uk/browse/DAQ-244"},"old_file":{"kind":"string","value":"org.eclipse.scanning.example/src/org/eclipse/scanning/example/scannable/MockNeXusScannable.java"},"subject":{"kind":"string","value":"Reverted scannable value name change"},"git_diff":{"kind":"string","value":"rg.eclipse.scanning.example/src/org/eclipse/scanning/example/scannable/MockNeXusScannable.java\n */\n public class MockNeXusScannable extends MockScannable implements INexusDevice {\n \t\n\tpublic static final String FIELD_NAME_DEMAND_VALUE = NXpositioner.NX_VALUE + \"_demand\";\n\t\n \tprivate ILazyWriteableDataset lzDemand;\n \tprivate ILazyWriteableDataset lzValue;\n \n \t\tfinal NXpositioner positioner = NexusNodeFactory.createNXpositioner();\n \t\tpositioner.setNameScalar(getName());\n \n\t\tString fieldNameDemand = getName() + \"_demand\";\n\n \t\tif (info.isMetadataScannable(getName())) {\n\t\t\tpositioner.setField(fieldNameDemand, getPosition().doubleValue());\n\t\t\tpositioner.setField(FIELD_NAME_DEMAND_VALUE, getPosition().doubleValue());\n \t\t\tpositioner.setValueScalar(getPosition().doubleValue());\n \t\t} else {\n\t\t\tthis.lzDemand = positioner.initializeLazyDataset(fieldNameDemand, 1, Double.class);\n\t\t\tthis.lzDemand = positioner.initializeLazyDataset(FIELD_NAME_DEMAND_VALUE, 1, Double.class);\n \t\t\tlzDemand.setChunking(new int[]{1});\n \t\t\t\n \t\t\tthis.lzValue = positioner.initializeLazyDataset(NXpositioner.NX_VALUE, info.getRank(), Double.class);\n \t\t\n \t\tNexusObjectWrapper nexusDelegate = new NexusObjectWrapper<>(\n \t\t\t\tgetName(), positioner, NXpositioner.NX_VALUE);\n\t\tnexusDelegate.setDefaultAxisDataFieldName(fieldNameDemand);\n\t\tnexusDelegate.setDefaultAxisDataFieldName(FIELD_NAME_DEMAND_VALUE);\n \t\treturn nexusDelegate;\n \t}\t\n "}}},{"rowIdx":198751,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"6c2b5c72040ba8e49bbf907459ef616bc2d4363d"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon"},"new_contents":{"kind":"string","value":"/*\r\n * $Id: LockssRepositoryImpl.java,v 1.53 2004-04-27 19:40:12 tlipkis Exp $\r\n */\r\n\r\n/*\r\n\r\nCopyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,\r\nall rights reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\nSTANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\r\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\nExcept as contained in this notice, the name of Stanford University shall not\r\nbe used in advertising or otherwise to promote the sale, use or other dealings\r\nin this Software without prior written authorization from Stanford University.\r\n\r\n*/\r\n\r\npackage org.lockss.repository;\r\n\r\nimport java.io.*;\r\nimport java.net.*;\r\nimport java.util.*;\r\nimport org.lockss.app.*;\r\nimport org.lockss.daemon.*;\r\nimport org.lockss.plugin.*;\r\nimport org.lockss.util.*;\r\nimport org.apache.commons.collections.LRUMap;\r\nimport org.apache.commons.collections.ReferenceMap;\r\n\r\n/**\r\n * LockssRepository is used to organize the urls being cached.\r\n * It keeps a memory cache of the most recently used nodes as a\r\n * least-recently-used map, and also caches weak references to the instances\r\n * as they're doled out. This ensures that two instances of the same node are\r\n * never created, as the weak references only disappear when the object is\r\n * finalized (they go to null when the last hard reference is gone, then are\r\n * removed from the cache on finalize()).\r\n */\r\npublic class LockssRepositoryImpl\r\n extends BaseLockssManager implements LockssRepository {\r\n\r\n /**\r\n * Configuration parameter name for Lockss cache location.\r\n */\r\n public static final String PARAM_CACHE_LOCATION =\r\n Configuration.PREFIX + \"cache.location\";\r\n /**\r\n * Name of top directory in which the urls are cached.\r\n */\r\n public static final String CACHE_ROOT_NAME = \"cache\";\r\n\r\n // needed only for unit tests\r\n static String cacheLocation = null;\r\n\r\n // used for name mapping\r\n static HashMap nameMap = null;\r\n\r\n // starts with a '#' so no possibility of clashing with a URL\r\n static final String AU_ID_FILE = \"#au_id_file\";\r\n static final String AU_ID_PROP = \"au.id\";\r\n static final String PLUGIN_ID_PROP = \"plugin.id\";\r\n static final char ESCAPE_CHAR = '#';\r\n static final String ESCAPE_STR = \"#\";\r\n static final char ENCODED_SEPARATOR_CHAR = 's';\r\n static final String INITIAL_PLUGIN_DIR = String.valueOf((char)('a'-1));\r\n static String lastPluginDir = INITIAL_PLUGIN_DIR;\r\n\r\n /**\r\n * Parameter for maximum number of node instances to cache. This can be\r\n * fairly small because there typically isn't need for repeated access to\r\n * the same nodes over a short time.\r\n */\r\n public static final String PARAM_MAX_LRUMAP_SIZE = Configuration.PREFIX +\r\n \"cache.max.lrumap.size\";\r\n private static final int DEFAULT_MAX_LRUMAP_SIZE = 100;\r\n\r\n // this contains a '#' so that it's not defeatable by strings which\r\n // match the prefix in a url (like '../tmp/')\r\n private static final String TEST_PREFIX = \"/#tmp\";\r\n\r\n private String rootLocation;\r\n private LRUMap nodeCache;\r\n private int nodeCacheSize = DEFAULT_MAX_LRUMAP_SIZE;\r\n private ReferenceMap refMap;\r\n private int cacheHits = 0;\r\n private int cacheMisses = 0;\r\n private int refHits = 0;\r\n private int refMisses = 0;\r\n private static Logger logger = Logger.getLogger(\"LockssRepository\");\r\n\r\n LockssRepositoryImpl(String rootPath) {\r\n rootLocation = rootPath;\r\n if (!rootLocation.endsWith(File.separator)) {\r\n // this shouldn't happen\r\n rootLocation += File.separator;\r\n }\r\n nodeCache = new LRUMap(nodeCacheSize);\r\n refMap = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK);\r\n }\r\n\r\n public void stopService() {\r\n // mainly important in testing to blank this\r\n lastPluginDir = INITIAL_PLUGIN_DIR;\r\n nameMap = null;\r\n super.stopService();\r\n }\r\n\r\n protected void setConfig(Configuration newConfig, Configuration prevConfig,\r\n Set changedKeys) {\r\n // at some point we'll have to respond to changes in the available disk\r\n // space list\r\n\r\n nodeCacheSize = newConfig.getInt(PARAM_MAX_LRUMAP_SIZE,\r\n\t\t\t\t DEFAULT_MAX_LRUMAP_SIZE);\r\n if (nodeCache.getMaximumSize() != nodeCacheSize) {\r\n nodeCache.setMaximumSize(nodeCacheSize);\r\n }\r\n }\r\n\r\n /** Called between initService() and startService(), then whenever the\r\n * AU's config changes.\r\n * @param auConfig the new configuration\r\n */\r\n public void setAuConfig(Configuration auConfig) {\r\n }\r\n\r\n public RepositoryNode getNode(String url) throws MalformedURLException {\r\n return getNode(url, false);\r\n }\r\n\r\n public RepositoryNode createNewNode(String url) throws MalformedURLException {\r\n return getNode(url, true);\r\n }\r\n\r\n public void deleteNode(String url) throws MalformedURLException {\r\n RepositoryNode node = getNode(url, false);\r\n if (node!=null) {\r\n node.markAsDeleted();\r\n }\r\n }\r\n\r\n public void deactivateNode(String url) throws MalformedURLException {\r\n RepositoryNode node = getNode(url, false);\r\n if (node!=null) {\r\n node.deactivateContent();\r\n }\r\n }\r\n\r\n /**\r\n * This function returns a RepositoryNode with a canonicalized path.\r\n * @param url the url in String form\r\n * @param create true iff the node should be created if absent\r\n * @return RepositoryNode the node\r\n * @throws MalformedURLException\r\n */\r\n private synchronized RepositoryNode getNode(String url, boolean create)\r\n throws MalformedURLException {\r\n String urlKey;\r\n boolean isAuUrl = false;\r\n if (AuUrl.isAuUrl(url)) {\r\n // path information is lost here, but is unimportant if it's an AuUrl\r\n urlKey = AuUrl.PROTOCOL;\r\n isAuUrl = true;\r\n } else {\r\n // create a canonical path, handling all illegal path traversal\r\n urlKey = canonicalizePath(url);\r\n }\r\n\r\n // check LRUMap cache for node\r\n RepositoryNode node = (RepositoryNode)nodeCache.get(urlKey);\r\n if (node!=null) {\r\n cacheHits++;\r\n return node;\r\n } else {\r\n cacheMisses++;\r\n }\r\n\r\n // check weak reference map for node\r\n node = (RepositoryNode)refMap.get(urlKey);\r\n if (node!=null) {\r\n refHits++;\r\n nodeCache.put(urlKey, node);\r\n return node;\r\n } else {\r\n refMisses++;\r\n }\r\n\r\n String nodeLocation;\r\n if (isAuUrl) {\r\n // base directory of ArchivalUnit\r\n nodeLocation = rootLocation;\r\n node = new AuNodeImpl(urlKey, nodeLocation, this);\r\n } else {\r\n // determine proper node location\r\n nodeLocation = LockssRepositoryImpl.mapUrlToFileLocation(rootLocation,\r\n urlKey);\r\n node = new RepositoryNodeImpl(urlKey, nodeLocation, this);\r\n }\r\n\r\n if (!create) {\r\n // if not creating, check for existence\r\n File nodeDir = new File(nodeLocation);\r\n if (!nodeDir.exists()) {\r\n // return null if the node doesn't exist and shouldn't be created\r\n return null;\r\n }\r\n if (!nodeDir.isDirectory()) {\r\n logger.error(\"Cache file not a directory: \"+nodeLocation);\r\n throw new LockssRepository.RepositoryStateException(\"Invalid cache file.\");\r\n }\r\n }\r\n\r\n // add to node cache and weak reference cache\r\n nodeCache.put(urlKey, node);\r\n refMap.put(urlKey, node);\r\n return node;\r\n }\r\n\r\n // functions for testing\r\n int getCacheHits() { return cacheHits; }\r\n int getCacheMisses() { return cacheMisses; }\r\n int getRefHits() { return refHits; }\r\n int getRefMisses() { return refMisses; }\r\n\r\n /**\r\n * This is called when a node is in an inconsistent state. It simply creates\r\n * some necessary directories and deactivates the node. Future polls should\r\n * restore it properly.\r\n * @param node the inconsistent node\r\n */\r\n void deactivateInconsistentNode(RepositoryNodeImpl node) {\r\n logger.warning(\"Inconsistent node state found; node content deactivated.\");\r\n if (!node.contentDir.exists()) {\r\n node.contentDir.mkdirs();\r\n }\r\n // manually deactivate\r\n node.deactivateContent();\r\n }\r\n\r\n /**\r\n * A method to remove any non-canonical '..' or '.' elements in the path,\r\n * as well as protecting against illegal path traversal.\r\n * @param url the raw url\r\n * @return String the canonicalized url\r\n * @throws MalformedURLException\r\n */\r\n public static String canonicalizePath(String url)\r\n throws MalformedURLException {\r\n String canonUrl;\r\n try {\r\n URL testUrl = new URL(url);\r\n String path = testUrl.getPath();\r\n // look for '.' or '..' elements\r\n if (path.indexOf(\"/.\")>=0) {\r\n // check if path traversal is legal\r\n if (FileUtil.isLegalPath(path)) {\r\n // canonicalize to remove urls including '..' and '.'\r\n path = TEST_PREFIX + path;\r\n File testFile = new File(path);\r\n String canonPath = testFile.getCanonicalPath();\r\n String sysDepPrefix = FileUtil.sysDepPath(TEST_PREFIX);\r\n int pathIndex = canonPath.indexOf(sysDepPrefix) +\r\n sysDepPrefix.length();\r\n // reconstruct the url\r\n canonUrl = testUrl.getProtocol() + \"://\" +\r\n testUrl.getHost().toLowerCase() +\r\n FileUtil.sysIndepPath(canonPath.substring(pathIndex));\r\n // restore the query, if any\r\n String query = testUrl.getQuery();\r\n if (query!=null) {\r\n canonUrl += \"?\" + query;\r\n }\r\n } else {\r\n logger.error(\"Illegal URL detected: \"+url);\r\n throw new MalformedURLException(\"Illegal URL detected.\");\r\n }\r\n } else {\r\n // clean path, no testing needed\r\n canonUrl = url;\r\n }\r\n } catch (MalformedURLException e) {\r\n logger.warning(\"Can't canonicalize path: \" + e);\r\n throw e;\r\n } catch (IOException e) {\r\n logger.warning(\"Can't canonicalize path: \" + e);\r\n throw new MalformedURLException(url);\r\n }\r\n\r\n // canonicalize \"dir\" and \"dir/\"\r\n // XXX if these are ever two separate nodes, this is wrong\r\n if (canonUrl.endsWith(UrlUtil.URL_PATH_SEPARATOR)) {\r\n canonUrl = canonUrl.substring(0, canonUrl.length()-1);\r\n }\r\n\r\n return canonUrl;\r\n }\r\n\r\n // static calls\r\n\r\n /**\r\n * Factory method to create new LockssRepository instances.\r\n * @param au the {@link ArchivalUnit}\r\n * @return the new LockssRepository instance\r\n */\r\n public static LockssRepository createNewLockssRepository(ArchivalUnit au) {\r\n // XXX needs to handle multiple disks/repository locations\r\n\r\n cacheLocation = Configuration.getParam(PARAM_CACHE_LOCATION);\r\n if (cacheLocation == null) {\r\n logger.error(\"Couldn't get \" + PARAM_CACHE_LOCATION +\r\n\t\t \" from Configuration\");\r\n throw new LockssRepository.RepositoryStateException(\r\n \"Couldn't load param.\");\r\n }\r\n cacheLocation = extendCacheLocation(cacheLocation);\r\n\r\n return new LockssRepositoryImpl(\r\n LockssRepositoryImpl.mapAuToFileLocation(cacheLocation, au));\r\n }\r\n\r\n /**\r\n * Adds the 'cache' directory to the HD location.\r\n * @param cacheDir the root location.\r\n * @return String the extended location\r\n */\r\n static String extendCacheLocation(String cacheDir) {\r\n StringBuffer buffer = new StringBuffer(cacheDir);\r\n if (!cacheDir.endsWith(File.separator)) {\r\n buffer.append(File.separator);\r\n }\r\n buffer.append(CACHE_ROOT_NAME);\r\n buffer.append(File.separator);\r\n return buffer.toString();\r\n }\r\n\r\n /**\r\n * mapAuToFileLocation() is the method used to resolve {@link ArchivalUnit}s\r\n * into directory names. This maps a given au to directories, using the\r\n * cache root as the base. Given an au with PluginId of 'plugin' and AuId\r\n * of 'au', it would return the string '/plugin/au/'.\r\n * @param rootLocation the root for all ArchivalUnits\r\n * @param au the ArchivalUnit to resolve\r\n * @return the directory location\r\n */\r\n public static String mapAuToFileLocation(String rootLocation, ArchivalUnit au) {\r\n StringBuffer buffer = new StringBuffer(rootLocation);\r\n if (!rootLocation.endsWith(File.separator)) {\r\n buffer.append(File.separator);\r\n }\r\n getAuDir(au, buffer);\r\n buffer.append(File.separator);\r\n return buffer.toString();\r\n }\r\n\r\n /**\r\n * mapUrlToFileLocation() is the method used to resolve urls into file names.\r\n * This maps a given url to a file location, using the au top directory as\r\n * the base. It creates directories which mirror the html string, so\r\n * 'http://www.journal.org/issue1/index.html' would be cached in the file:\r\n * /www.journal.org/http/issue1/index.html\r\n * @param rootLocation the top directory for ArchivalUnit this URL is in\r\n * @param urlStr the url to translate\r\n * @return the url file location\r\n * @throws java.net.MalformedURLException\r\n */\r\n public static String mapUrlToFileLocation(String rootLocation, String urlStr)\r\n throws MalformedURLException {\r\n int totalLength = rootLocation.length() + urlStr.length();\r\n URL url = new URL(urlStr);\r\n StringBuffer buffer = new StringBuffer(totalLength);\r\n buffer.append(rootLocation);\r\n if (!rootLocation.endsWith(File.separator)) {\r\n buffer.append(File.separator);\r\n }\r\n buffer.append(url.getHost().toLowerCase());\r\n buffer.append(File.separator);\r\n buffer.append(url.getProtocol());\r\n buffer.append(escapePath(StringUtil.replaceString(url.getPath(),\r\n UrlUtil.URL_PATH_SEPARATOR, File.separator)));\r\n String query = url.getQuery();\r\n if (query!=null) {\r\n buffer.append(\"?\");\r\n buffer.append(escapeQuery(query));\r\n }\r\n return buffer.toString();\r\n }\r\n\r\n // name mapping functions\r\n\r\n /**\r\n * Finds the directory for this AU. If none found in the map, designates\r\n * a new dir for it.\r\n * @param au the AU\r\n * @param buffer a StringBuffer to add the dir name to.\r\n */\r\n static void getAuDir(ArchivalUnit au, StringBuffer buffer) {\r\n if (nameMap == null) {\r\n loadNameMap(buffer.toString());\r\n }\r\n String auKey = au.getAuId();\r\n String auDir = (String)nameMap.get(auKey);\r\n if (auDir == null) {\r\n logger.debug3(\"Creating new au directory for '\" + auKey + \"'.\");\r\n while (true) {\r\n // loop through looking for an available dir\r\n auDir = getNewPluginDir();\r\n File testDir = new File(buffer.toString() + auDir);\r\n if (!testDir.exists()) {\r\n break;\r\n } else {\r\n logger.debug3(\"Existing directory found at '\"+auDir+\r\n \"'. Creating another...\");\r\n }\r\n }\r\n logger.debug3(\"New au directory: \"+auDir);\r\n nameMap.put(auKey, auDir);\r\n String auLocation = buffer.toString() + auDir;\r\n // write the new au property file to the new dir\r\n // XXX this data should be backed up elsewhere to avoid single-point\r\n // corruption\r\n Properties idProps = new Properties();\r\n idProps.setProperty(AU_ID_PROP, au.getAuId());\r\n saveAuIdProperties(auLocation, idProps);\r\n }\r\n buffer.append(auDir);\r\n }\r\n\r\n /**\r\n * Loads the name map by recursing through the current dirs and reading\r\n * the AU prop file at each location.\r\n * @param rootLocation the repository HD root location\r\n */\r\n static void loadNameMap(String rootLocation) {\r\n logger.debug3(\"Loading name map for '\" + rootLocation + \"'.\");\r\n nameMap = new HashMap();\r\n File rootFile = new File(rootLocation);\r\n if (!rootFile.exists()) {\r\n rootFile.mkdirs();\r\n logger.debug3(\"Creating root directory at '\" + rootLocation + \"'.\");\r\n return;\r\n }\r\n File[] pluginAus = rootFile.listFiles();\r\n for (int ii = 0; ii < pluginAus.length; ii++) {\r\n // loop through reading each property and storing the id with that dir\r\n String dirName = pluginAus[ii].getName();\r\n if (dirName.compareTo(lastPluginDir) == 1) {\r\n // adjust the 'lastPluginDir' upwards if necessary\r\n lastPluginDir = dirName;\r\n }\r\n\r\n Properties idProps = getAuIdProperties(pluginAus[ii].getAbsolutePath());\r\n if (idProps==null) {\r\n // if no properties were found, just continue\r\n continue;\r\n }\r\n // store the id, dirName pair in our map\r\n nameMap.put(idProps.getProperty(AU_ID_PROP), dirName);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the next dir name, from 'a'->'z', then 'aa'->'az', then 'ba'->etc.\r\n * @return String the next dir\r\n */\r\n static String getNewPluginDir() {\r\n String newPluginDir = \"\";\r\n boolean charChanged = false;\r\n // go through and increment the first non-'z' char\r\n // counts back from the last char, so 'aa'->'ab', not 'ba'\r\n for (int ii=lastPluginDir.length()-1; ii>=0; ii--) {\r\n char curChar = lastPluginDir.charAt(ii);\r\n if (!charChanged) {\r\n if (curChar < 'z') {\r\n curChar++;\r\n charChanged = true;\r\n newPluginDir = curChar + newPluginDir;\r\n } else {\r\n newPluginDir += 'a';\r\n }\r\n } else {\r\n newPluginDir = curChar + newPluginDir;\r\n }\r\n }\r\n if (!charChanged) {\r\n newPluginDir += 'a';\r\n }\r\n lastPluginDir = newPluginDir;\r\n return newPluginDir;\r\n }\r\n\r\n static Properties getAuIdProperties(String location) {\r\n File propFile = new File(location + File.separator + AU_ID_FILE);\r\n try {\r\n InputStream is = new BufferedInputStream(new FileInputStream(propFile));\r\n Properties idProps = new Properties();\r\n idProps.load(is);\r\n is.close();\r\n return idProps;\r\n } catch (Exception e) {\r\n logger.warning(\"Error loading au id from \" + propFile.getPath() + \".\");\r\n return null;\r\n }\r\n }\r\n\r\n static void saveAuIdProperties(String location, Properties props) {\r\n //XXX these AU_ID_FILE entries need to be backed up elsewhere to avoid\r\n // single-point corruption\r\n File propDir = new File(location);\r\n if (!propDir.exists()) {\r\n logger.debug(\"Creating directory '\"+propDir.getAbsolutePath()+\"'\");\r\n propDir.mkdirs();\r\n }\r\n File propFile = new File(propDir, AU_ID_FILE);\r\n try {\r\n logger.debug3(\"Saving au id properties at '\" + location + \"'.\");\r\n OutputStream os = new BufferedOutputStream(new FileOutputStream(propFile));\r\n props.store(os, \"ArchivalUnit id info\");\r\n os.close();\r\n propFile.setReadOnly();\r\n } catch (IOException ioe) {\r\n logger.error(\"Couldn't write properties for \" + propFile.getPath() + \".\",\r\n ioe);\r\n throw new LockssRepository.RepositoryStateException(\r\n \"Couldn't write au id properties file.\");\r\n }\r\n }\r\n\r\n // lockss filename-specific encoding methods\r\n\r\n /**\r\n * Escapes instances of the ESCAPE_CHAR from the path. This avoids name\r\n * conflicts with the repository files, such as '#nodestate.xml'.\r\n * @param path the path\r\n * @return the escaped path\r\n */\r\n static String escapePath(String path) {\r\n //XXX escaping disabled because of URL encoding\r\n if (false && path.indexOf(ESCAPE_CHAR) >= 0) {\r\n return StringUtil.replaceString(path, ESCAPE_STR, ESCAPE_STR+ESCAPE_STR);\r\n } else {\r\n return path;\r\n }\r\n }\r\n\r\n /**\r\n * Escapes instances of File.separator from the query. These are safe from\r\n * filename overlap, but can't convert into extended paths and directories.\r\n * @param query the query\r\n * @return the escaped query\r\n */\r\n static String escapeQuery(String query) {\r\n if (query.indexOf(File.separator) >= 0) {\r\n return StringUtil.replaceString(query, File.separator, ESCAPE_STR +\r\n ENCODED_SEPARATOR_CHAR);\r\n } else {\r\n return query;\r\n }\r\n }\r\n\r\n /**\r\n * Extracts '#x' encoding and converts back to 'x'.\r\n * @param orig the original\r\n * @return the unescaped version.\r\n */\r\n static String unescape(String orig) {\r\n if (orig.indexOf(ESCAPE_CHAR) < 0) {\r\n // fast treatment of non-escaped strings\r\n return orig;\r\n }\r\n int index = -1;\r\n StringBuffer buffer = new StringBuffer(orig.length());\r\n String oldStr = orig;\r\n while ((index = oldStr.indexOf(ESCAPE_CHAR)) >= 0) {\r\n buffer.append(oldStr.substring(0, index));\r\n buffer.append(convertCode(oldStr.substring(index, index+2)));\r\n if (oldStr.length() > 2) {\r\n oldStr = oldStr.substring(index + 2);\r\n } else {\r\n oldStr = \"\";\r\n }\r\n }\r\n buffer.append(oldStr);\r\n return buffer.toString();\r\n }\r\n\r\n /**\r\n * Returns the second char in the escaped segment, unless it is 's', which\r\n * is a stand-in for the File.separatorChar.\r\n * @param code the code segment (length 2)\r\n * @return the encoded char\r\n */\r\n static char convertCode(String code) {\r\n char encodedChar = code.charAt(1);\r\n if (encodedChar == ENCODED_SEPARATOR_CHAR) {\r\n return File.separatorChar;\r\n } else {\r\n return encodedChar;\r\n }\r\n }\r\n\r\n public static class Factory implements LockssAuManager.Factory {\r\n public LockssAuManager createAuManager(ArchivalUnit au) {\r\n return createNewLockssRepository(au);\r\n }\r\n }\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"src/org/lockss/repository/LockssRepositoryImpl.java"},"old_contents":{"kind":"string","value":"/*\r\n * $Id: LockssRepositoryImpl.java,v 1.52 2004-04-14 23:46:17 eaalto Exp $\r\n */\r\n\r\n/*\r\n\r\nCopyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,\r\nall rights reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\nSTANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\r\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\nExcept as contained in this notice, the name of Stanford University shall not\r\nbe used in advertising or otherwise to promote the sale, use or other dealings\r\nin this Software without prior written authorization from Stanford University.\r\n\r\n*/\r\n\r\npackage org.lockss.repository;\r\n\r\nimport java.io.*;\r\nimport java.net.*;\r\nimport java.util.*;\r\nimport org.lockss.app.*;\r\nimport org.lockss.daemon.*;\r\nimport org.lockss.plugin.*;\r\nimport org.lockss.util.*;\r\nimport org.apache.commons.collections.LRUMap;\r\nimport org.apache.commons.collections.ReferenceMap;\r\n\r\n/**\r\n * LockssRepository is used to organize the urls being cached.\r\n * It keeps a memory cache of the most recently used nodes as a\r\n * least-recently-used map, and also caches weak references to the instances\r\n * as they're doled out. This ensures that two instances of the same node are\r\n * never created, as the weak references only disappear when the object is\r\n * finalized (they go to null when the last hard reference is gone, then are\r\n * removed from the cache on finalize()).\r\n */\r\npublic class LockssRepositoryImpl\r\n extends BaseLockssManager implements LockssRepository {\r\n\r\n /**\r\n * Configuration parameter name for Lockss cache location.\r\n */\r\n public static final String PARAM_CACHE_LOCATION =\r\n Configuration.PREFIX + \"cache.location\";\r\n /**\r\n * Name of top directory in which the urls are cached.\r\n */\r\n public static final String CACHE_ROOT_NAME = \"cache\";\r\n\r\n // needed only for unit tests\r\n static String cacheLocation = null;\r\n\r\n // used for name mapping\r\n static HashMap nameMap = null;\r\n\r\n // starts with a '#' so no possibility of clashing with a URL\r\n static final String AU_ID_FILE = \"#au_id_file\";\r\n static final String AU_ID_PROP = \"au.id\";\r\n static final String PLUGIN_ID_PROP = \"plugin.id\";\r\n static final char ESCAPE_CHAR = '#';\r\n static final String ESCAPE_STR = \"#\";\r\n static final char ENCODED_SEPARATOR_CHAR = 's';\r\n static final String INITIAL_PLUGIN_DIR = String.valueOf((char)('a'-1));\r\n static String lastPluginDir = INITIAL_PLUGIN_DIR;\r\n\r\n /**\r\n * Parameter for maximum number of node instances to cache. This can be\r\n * fairly small because there typically isn't need for repeated access to\r\n * the same nodes over a short time.\r\n */\r\n public static final String PARAM_MAX_LRUMAP_SIZE = Configuration.PREFIX +\r\n \"cache.max.lrumap.size\";\r\n private static final int DEFAULT_MAX_LRUMAP_SIZE = 100;\r\n\r\n // this contains a '#' so that it's not defeatable by strings which\r\n // match the prefix in a url (like '../tmp/')\r\n private static final String TEST_PREFIX = \"/#tmp\";\r\n\r\n private String rootLocation;\r\n private LRUMap nodeCache;\r\n private int nodeCacheSize = DEFAULT_MAX_LRUMAP_SIZE;\r\n private ReferenceMap refMap;\r\n private int cacheHits = 0;\r\n private int cacheMisses = 0;\r\n private int refHits = 0;\r\n private int refMisses = 0;\r\n private static Logger logger = Logger.getLogger(\"LockssRepository\");\r\n\r\n LockssRepositoryImpl(String rootPath) {\r\n rootLocation = rootPath;\r\n if (!rootLocation.endsWith(File.separator)) {\r\n // this shouldn't happen\r\n rootLocation += File.separator;\r\n }\r\n nodeCache = new LRUMap(nodeCacheSize);\r\n refMap = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK);\r\n }\r\n\r\n public void stopService() {\r\n // mainly important in testing to blank this\r\n lastPluginDir = INITIAL_PLUGIN_DIR;\r\n nameMap = null;\r\n super.stopService();\r\n }\r\n\r\n protected void setConfig(Configuration newConfig, Configuration prevConfig,\r\n Set changedKeys) {\r\n // at some point we'll have to respond to changes in the available disk\r\n // space list\r\n\r\n nodeCacheSize = newConfig.getInt(PARAM_MAX_LRUMAP_SIZE,\r\n\t\t\t\t DEFAULT_MAX_LRUMAP_SIZE);\r\n if (nodeCache.getMaximumSize() != nodeCacheSize) {\r\n nodeCache.setMaximumSize(nodeCacheSize);\r\n }\r\n }\r\n\r\n /** Called between initService() and startService(), then whenever the\r\n * AU's config changes.\r\n * @param auConfig the new configuration\r\n */\r\n public void setAuConfig(Configuration auConfig) {\r\n }\r\n\r\n public RepositoryNode getNode(String url) throws MalformedURLException {\r\n return getNode(url, false);\r\n }\r\n\r\n public RepositoryNode createNewNode(String url) throws MalformedURLException {\r\n return getNode(url, true);\r\n }\r\n\r\n public void deleteNode(String url) throws MalformedURLException {\r\n RepositoryNode node = getNode(url, false);\r\n if (node!=null) {\r\n node.markAsDeleted();\r\n }\r\n }\r\n\r\n public void deactivateNode(String url) throws MalformedURLException {\r\n RepositoryNode node = getNode(url, false);\r\n if (node!=null) {\r\n node.deactivateContent();\r\n }\r\n }\r\n\r\n /**\r\n * This function returns a RepositoryNode with a canonicalized path.\r\n * @param url the url in String form\r\n * @param create true iff the node should be created if absent\r\n * @return RepositoryNode the node\r\n * @throws MalformedURLException\r\n */\r\n private synchronized RepositoryNode getNode(String url, boolean create)\r\n throws MalformedURLException {\r\n String urlKey;\r\n boolean isAuUrl = false;\r\n if (AuUrl.isAuUrl(url)) {\r\n // path information is lost here, but is unimportant if it's an AuUrl\r\n urlKey = AuUrl.PROTOCOL;\r\n isAuUrl = true;\r\n } else {\r\n // create a canonical path, handling all illegal path traversal\r\n urlKey = canonicalizePath(url);\r\n }\r\n\r\n // check LRUMap cache for node\r\n RepositoryNode node = (RepositoryNode)nodeCache.get(urlKey);\r\n if (node!=null) {\r\n cacheHits++;\r\n return node;\r\n } else {\r\n cacheMisses++;\r\n }\r\n\r\n // check weak reference map for node\r\n node = (RepositoryNode)refMap.get(urlKey);\r\n if (node!=null) {\r\n refHits++;\r\n nodeCache.put(urlKey, node);\r\n return node;\r\n } else {\r\n refMisses++;\r\n }\r\n\r\n String nodeLocation;\r\n if (isAuUrl) {\r\n // base directory of ArchivalUnit\r\n nodeLocation = rootLocation;\r\n node = new AuNodeImpl(urlKey, nodeLocation, this);\r\n } else {\r\n // determine proper node location\r\n nodeLocation = LockssRepositoryImpl.mapUrlToFileLocation(rootLocation,\r\n urlKey);\r\n node = new RepositoryNodeImpl(urlKey, nodeLocation, this);\r\n }\r\n\r\n if (!create) {\r\n // if not creating, check for existence\r\n File nodeDir = new File(nodeLocation);\r\n if (!nodeDir.exists()) {\r\n // return null if the node doesn't exist and shouldn't be created\r\n return null;\r\n }\r\n if (!nodeDir.isDirectory()) {\r\n logger.error(\"Cache file not a directory: \"+nodeLocation);\r\n throw new LockssRepository.RepositoryStateException(\"Invalid cache file.\");\r\n }\r\n }\r\n\r\n // add to node cache and weak reference cache\r\n nodeCache.put(urlKey, node);\r\n refMap.put(urlKey, node);\r\n return node;\r\n }\r\n\r\n // functions for testing\r\n int getCacheHits() { return cacheHits; }\r\n int getCacheMisses() { return cacheMisses; }\r\n int getRefHits() { return refHits; }\r\n int getRefMisses() { return refMisses; }\r\n\r\n /**\r\n * This is called when a node is in an inconsistent state. It simply creates\r\n * some necessary directories and deactivates the node. Future polls should\r\n * restore it properly.\r\n * @param node the inconsistent node\r\n */\r\n void deactivateInconsistentNode(RepositoryNodeImpl node) {\r\n logger.warning(\"Inconsistent node state found; node content deactivated.\");\r\n if (!node.contentDir.exists()) {\r\n node.contentDir.mkdirs();\r\n }\r\n // manually deactivate\r\n node.deactivateContent();\r\n }\r\n\r\n /**\r\n * A method to remove any non-canonical '..' or '.' elements in the path,\r\n * as well as protecting against illegal path traversal.\r\n * @param url the raw url\r\n * @return String the canonicalized url\r\n * @throws MalformedURLException\r\n */\r\n public static String canonicalizePath(String url)\r\n throws MalformedURLException {\r\n String canonUrl;\r\n try {\r\n URL testUrl = new URL(url);\r\n String path = testUrl.getPath();\r\n // look for '.' or '..' elements\r\n if (path.indexOf(\"/.\")>=0) {\r\n // check if path traversal is legal\r\n if (FileUtil.isLegalPath(path)) {\r\n // canonicalize to remove urls including '..' and '.'\r\n path = TEST_PREFIX + path;\r\n File testFile = new File(path);\r\n String canonPath = testFile.getCanonicalPath();\r\n String sysDepPrefix = FileUtil.sysDepPath(TEST_PREFIX);\r\n int pathIndex = canonPath.indexOf(sysDepPrefix) +\r\n sysDepPrefix.length();\r\n // reconstruct the url\r\n canonUrl = testUrl.getProtocol() + \"://\" +\r\n testUrl.getHost().toLowerCase() +\r\n FileUtil.sysIndepPath(canonPath.substring(pathIndex));\r\n // restore the query, if any\r\n String query = testUrl.getQuery();\r\n if (query!=null) {\r\n canonUrl += \"?\" + query;\r\n }\r\n } else {\r\n logger.error(\"Illegal URL detected: \"+url);\r\n throw new MalformedURLException(\"Illegal URL detected.\");\r\n }\r\n } else {\r\n // clean path, no testing needed\r\n canonUrl = url;\r\n }\r\n } catch (IOException ie) {\r\n logger.error(\"Error testing URL: \"+ie);\r\n throw new MalformedURLException (\"Error testing URL.\");\r\n }\r\n\r\n // canonicalize \"dir\" and \"dir/\"\r\n // XXX if these are ever two separate nodes, this is wrong\r\n if (canonUrl.endsWith(UrlUtil.URL_PATH_SEPARATOR)) {\r\n canonUrl = canonUrl.substring(0, canonUrl.length()-1);\r\n }\r\n\r\n return canonUrl;\r\n }\r\n\r\n // static calls\r\n\r\n /**\r\n * Factory method to create new LockssRepository instances.\r\n * @param au the {@link ArchivalUnit}\r\n * @return the new LockssRepository instance\r\n */\r\n public static LockssRepository createNewLockssRepository(ArchivalUnit au) {\r\n // XXX needs to handle multiple disks/repository locations\r\n\r\n cacheLocation = Configuration.getParam(PARAM_CACHE_LOCATION);\r\n if (cacheLocation == null) {\r\n logger.error(\"Couldn't get \" + PARAM_CACHE_LOCATION +\r\n\t\t \" from Configuration\");\r\n throw new LockssRepository.RepositoryStateException(\r\n \"Couldn't load param.\");\r\n }\r\n cacheLocation = extendCacheLocation(cacheLocation);\r\n\r\n return new LockssRepositoryImpl(\r\n LockssRepositoryImpl.mapAuToFileLocation(cacheLocation, au));\r\n }\r\n\r\n /**\r\n * Adds the 'cache' directory to the HD location.\r\n * @param cacheDir the root location.\r\n * @return String the extended location\r\n */\r\n static String extendCacheLocation(String cacheDir) {\r\n StringBuffer buffer = new StringBuffer(cacheDir);\r\n if (!cacheDir.endsWith(File.separator)) {\r\n buffer.append(File.separator);\r\n }\r\n buffer.append(CACHE_ROOT_NAME);\r\n buffer.append(File.separator);\r\n return buffer.toString();\r\n }\r\n\r\n /**\r\n * mapAuToFileLocation() is the method used to resolve {@link ArchivalUnit}s\r\n * into directory names. This maps a given au to directories, using the\r\n * cache root as the base. Given an au with PluginId of 'plugin' and AuId\r\n * of 'au', it would return the string '/plugin/au/'.\r\n * @param rootLocation the root for all ArchivalUnits\r\n * @param au the ArchivalUnit to resolve\r\n * @return the directory location\r\n */\r\n public static String mapAuToFileLocation(String rootLocation, ArchivalUnit au) {\r\n StringBuffer buffer = new StringBuffer(rootLocation);\r\n if (!rootLocation.endsWith(File.separator)) {\r\n buffer.append(File.separator);\r\n }\r\n getAuDir(au, buffer);\r\n buffer.append(File.separator);\r\n return buffer.toString();\r\n }\r\n\r\n /**\r\n * mapUrlToFileLocation() is the method used to resolve urls into file names.\r\n * This maps a given url to a file location, using the au top directory as\r\n * the base. It creates directories which mirror the html string, so\r\n * 'http://www.journal.org/issue1/index.html' would be cached in the file:\r\n * /www.journal.org/http/issue1/index.html\r\n * @param rootLocation the top directory for ArchivalUnit this URL is in\r\n * @param urlStr the url to translate\r\n * @return the url file location\r\n * @throws java.net.MalformedURLException\r\n */\r\n public static String mapUrlToFileLocation(String rootLocation, String urlStr)\r\n throws MalformedURLException {\r\n int totalLength = rootLocation.length() + urlStr.length();\r\n URL url = new URL(urlStr);\r\n StringBuffer buffer = new StringBuffer(totalLength);\r\n buffer.append(rootLocation);\r\n if (!rootLocation.endsWith(File.separator)) {\r\n buffer.append(File.separator);\r\n }\r\n buffer.append(url.getHost().toLowerCase());\r\n buffer.append(File.separator);\r\n buffer.append(url.getProtocol());\r\n buffer.append(escapePath(StringUtil.replaceString(url.getPath(),\r\n UrlUtil.URL_PATH_SEPARATOR, File.separator)));\r\n String query = url.getQuery();\r\n if (query!=null) {\r\n buffer.append(\"?\");\r\n buffer.append(escapeQuery(query));\r\n }\r\n return buffer.toString();\r\n }\r\n\r\n // name mapping functions\r\n\r\n /**\r\n * Finds the directory for this AU. If none found in the map, designates\r\n * a new dir for it.\r\n * @param au the AU\r\n * @param buffer a StringBuffer to add the dir name to.\r\n */\r\n static void getAuDir(ArchivalUnit au, StringBuffer buffer) {\r\n if (nameMap == null) {\r\n loadNameMap(buffer.toString());\r\n }\r\n String auKey = au.getAuId();\r\n String auDir = (String)nameMap.get(auKey);\r\n if (auDir == null) {\r\n logger.debug3(\"Creating new au directory for '\" + auKey + \"'.\");\r\n while (true) {\r\n // loop through looking for an available dir\r\n auDir = getNewPluginDir();\r\n File testDir = new File(buffer.toString() + auDir);\r\n if (!testDir.exists()) {\r\n break;\r\n } else {\r\n logger.debug3(\"Existing directory found at '\"+auDir+\r\n \"'. Creating another...\");\r\n }\r\n }\r\n logger.debug3(\"New au directory: \"+auDir);\r\n nameMap.put(auKey, auDir);\r\n String auLocation = buffer.toString() + auDir;\r\n // write the new au property file to the new dir\r\n // XXX this data should be backed up elsewhere to avoid single-point\r\n // corruption\r\n Properties idProps = new Properties();\r\n idProps.setProperty(AU_ID_PROP, au.getAuId());\r\n saveAuIdProperties(auLocation, idProps);\r\n }\r\n buffer.append(auDir);\r\n }\r\n\r\n /**\r\n * Loads the name map by recursing through the current dirs and reading\r\n * the AU prop file at each location.\r\n * @param rootLocation the repository HD root location\r\n */\r\n static void loadNameMap(String rootLocation) {\r\n logger.debug3(\"Loading name map for '\" + rootLocation + \"'.\");\r\n nameMap = new HashMap();\r\n File rootFile = new File(rootLocation);\r\n if (!rootFile.exists()) {\r\n rootFile.mkdirs();\r\n logger.debug3(\"Creating root directory at '\" + rootLocation + \"'.\");\r\n return;\r\n }\r\n File[] pluginAus = rootFile.listFiles();\r\n for (int ii = 0; ii < pluginAus.length; ii++) {\r\n // loop through reading each property and storing the id with that dir\r\n String dirName = pluginAus[ii].getName();\r\n if (dirName.compareTo(lastPluginDir) == 1) {\r\n // adjust the 'lastPluginDir' upwards if necessary\r\n lastPluginDir = dirName;\r\n }\r\n\r\n Properties idProps = getAuIdProperties(pluginAus[ii].getAbsolutePath());\r\n if (idProps==null) {\r\n // if no properties were found, just continue\r\n continue;\r\n }\r\n // store the id, dirName pair in our map\r\n nameMap.put(idProps.getProperty(AU_ID_PROP), dirName);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the next dir name, from 'a'->'z', then 'aa'->'az', then 'ba'->etc.\r\n * @return String the next dir\r\n */\r\n static String getNewPluginDir() {\r\n String newPluginDir = \"\";\r\n boolean charChanged = false;\r\n // go through and increment the first non-'z' char\r\n // counts back from the last char, so 'aa'->'ab', not 'ba'\r\n for (int ii=lastPluginDir.length()-1; ii>=0; ii--) {\r\n char curChar = lastPluginDir.charAt(ii);\r\n if (!charChanged) {\r\n if (curChar < 'z') {\r\n curChar++;\r\n charChanged = true;\r\n newPluginDir = curChar + newPluginDir;\r\n } else {\r\n newPluginDir += 'a';\r\n }\r\n } else {\r\n newPluginDir = curChar + newPluginDir;\r\n }\r\n }\r\n if (!charChanged) {\r\n newPluginDir += 'a';\r\n }\r\n lastPluginDir = newPluginDir;\r\n return newPluginDir;\r\n }\r\n\r\n static Properties getAuIdProperties(String location) {\r\n File propFile = new File(location + File.separator + AU_ID_FILE);\r\n try {\r\n InputStream is = new BufferedInputStream(new FileInputStream(propFile));\r\n Properties idProps = new Properties();\r\n idProps.load(is);\r\n is.close();\r\n return idProps;\r\n } catch (Exception e) {\r\n logger.warning(\"Error loading au id from \" + propFile.getPath() + \".\");\r\n return null;\r\n }\r\n }\r\n\r\n static void saveAuIdProperties(String location, Properties props) {\r\n //XXX these AU_ID_FILE entries need to be backed up elsewhere to avoid\r\n // single-point corruption\r\n File propDir = new File(location);\r\n if (!propDir.exists()) {\r\n logger.debug(\"Creating directory '\"+propDir.getAbsolutePath()+\"'\");\r\n propDir.mkdirs();\r\n }\r\n File propFile = new File(propDir, AU_ID_FILE);\r\n try {\r\n logger.debug3(\"Saving au id properties at '\" + location + \"'.\");\r\n OutputStream os = new BufferedOutputStream(new FileOutputStream(propFile));\r\n props.store(os, \"ArchivalUnit id info\");\r\n os.close();\r\n propFile.setReadOnly();\r\n } catch (IOException ioe) {\r\n logger.error(\"Couldn't write properties for \" + propFile.getPath() + \".\",\r\n ioe);\r\n throw new LockssRepository.RepositoryStateException(\r\n \"Couldn't write au id properties file.\");\r\n }\r\n }\r\n\r\n // lockss filename-specific encoding methods\r\n\r\n /**\r\n * Escapes instances of the ESCAPE_CHAR from the path. This avoids name\r\n * conflicts with the repository files, such as '#nodestate.xml'.\r\n * @param path the path\r\n * @return the escaped path\r\n */\r\n static String escapePath(String path) {\r\n //XXX escaping disabled because of URL encoding\r\n if (false && path.indexOf(ESCAPE_CHAR) >= 0) {\r\n return StringUtil.replaceString(path, ESCAPE_STR, ESCAPE_STR+ESCAPE_STR);\r\n } else {\r\n return path;\r\n }\r\n }\r\n\r\n /**\r\n * Escapes instances of File.separator from the query. These are safe from\r\n * filename overlap, but can't convert into extended paths and directories.\r\n * @param query the query\r\n * @return the escaped query\r\n */\r\n static String escapeQuery(String query) {\r\n if (query.indexOf(File.separator) >= 0) {\r\n return StringUtil.replaceString(query, File.separator, ESCAPE_STR +\r\n ENCODED_SEPARATOR_CHAR);\r\n } else {\r\n return query;\r\n }\r\n }\r\n\r\n /**\r\n * Extracts '#x' encoding and converts back to 'x'.\r\n * @param orig the original\r\n * @return the unescaped version.\r\n */\r\n static String unescape(String orig) {\r\n if (orig.indexOf(ESCAPE_CHAR) < 0) {\r\n // fast treatment of non-escaped strings\r\n return orig;\r\n }\r\n int index = -1;\r\n StringBuffer buffer = new StringBuffer(orig.length());\r\n String oldStr = orig;\r\n while ((index = oldStr.indexOf(ESCAPE_CHAR)) >= 0) {\r\n buffer.append(oldStr.substring(0, index));\r\n buffer.append(convertCode(oldStr.substring(index, index+2)));\r\n if (oldStr.length() > 2) {\r\n oldStr = oldStr.substring(index + 2);\r\n } else {\r\n oldStr = \"\";\r\n }\r\n }\r\n buffer.append(oldStr);\r\n return buffer.toString();\r\n }\r\n\r\n /**\r\n * Returns the second char in the escaped segment, unless it is 's', which\r\n * is a stand-in for the File.separatorChar.\r\n * @param code the code segment (length 2)\r\n * @return the encoded char\r\n */\r\n static char convertCode(String code) {\r\n char encodedChar = code.charAt(1);\r\n if (encodedChar == ENCODED_SEPARATOR_CHAR) {\r\n return File.separatorChar;\r\n } else {\r\n return encodedChar;\r\n }\r\n }\r\n\r\n public static class Factory implements LockssAuManager.Factory {\r\n public LockssAuManager createAuManager(ArchivalUnit au) {\r\n return createNewLockssRepository(au);\r\n }\r\n }\r\n\r\n}\r\n"},"message":{"kind":"string","value":"Minor error log improvement.\n\n\ngit-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@2848 4f837ed2-42f5-46e7-a7a5-fa17313484d4\n"},"old_file":{"kind":"string","value":"src/org/lockss/repository/LockssRepositoryImpl.java"},"subject":{"kind":"string","value":"Minor error log improvement."},"git_diff":{"kind":"string","value":"rc/org/lockss/repository/LockssRepositoryImpl.java\n /*\n * $Id: LockssRepositoryImpl.java,v 1.52 2004-04-14 23:46:17 eaalto Exp $\n * $Id: LockssRepositoryImpl.java,v 1.53 2004-04-27 19:40:12 tlipkis Exp $\n */\n \n /*\n // clean path, no testing needed\n canonUrl = url;\n }\n } catch (IOException ie) {\n logger.error(\"Error testing URL: \"+ie);\n throw new MalformedURLException (\"Error testing URL.\");\n } catch (MalformedURLException e) {\n logger.warning(\"Can't canonicalize path: \" + e);\n throw e;\n } catch (IOException e) {\n logger.warning(\"Can't canonicalize path: \" + e);\n throw new MalformedURLException(url);\n }\n \n // canonicalize \"dir\" and \"dir/\""}}},{"rowIdx":198752,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"c32c3973a508fbbd570a72c8c94b8007c365afa3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"SirWellington/alchemy-http,SirWellington/alchemy-http"},"new_contents":{"kind":"string","value":"/*\n * Copyright © 2018. Sir Wellington.\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 *\n * You may obtain a copy of the License at\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 tech.sirwellington.alchemy.http.exceptions;\n\nimport tech.sirwellington.alchemy.http.*;\n\n/**\n * Thrown when an error occurs trying to parse JSON, or unwrap JSON into a\n * {@linkplain AlchemyRequest.Step3#expecting(java.lang.Class) POJO}.\n *\n * @author SirWellington\n */\npublic class JsonException extends AlchemyHttpException\n{\n\n public JsonException()\n {\n }\n\n public JsonException(String message)\n {\n super(message);\n }\n\n public JsonException(String message, Throwable cause)\n {\n super(message, cause);\n }\n\n public JsonException(Throwable cause)\n {\n super(cause);\n }\n\n public JsonException(HttpRequest request)\n {\n super(request);\n }\n\n public JsonException(HttpRequest request, String message)\n {\n super(request, message);\n }\n\n public JsonException(HttpRequest request, String message, Throwable cause)\n {\n super(request, message, cause);\n }\n\n public JsonException(HttpRequest request, Throwable cause)\n {\n super(request, cause);\n }\n\n public JsonException(HttpResponse response)\n {\n super(response);\n }\n\n public JsonException(HttpResponse response, String message)\n {\n super(response, message);\n }\n\n public JsonException(HttpResponse response, String message, Throwable cause)\n {\n super(response, message, cause);\n }\n\n public JsonException(HttpResponse response, Throwable cause)\n {\n super(response, cause);\n }\n\n public JsonException(HttpRequest request, HttpResponse response)\n {\n super(request, response);\n }\n\n public JsonException(HttpRequest request, HttpResponse response, String message)\n {\n super(request, response, message);\n }\n\n public JsonException(HttpRequest request, HttpResponse response, String message, Throwable cause)\n {\n super(request, response, message, cause);\n }\n\n public JsonException(HttpRequest request, HttpResponse response, Throwable cause)\n {\n super(request, response, cause);\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/tech/sirwellington/alchemy/http/exceptions/JsonException.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright © 2018. Sir Wellington.\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 *\n * You may obtain a copy of the License at\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 tech.sirwellington.alchemy.http.exceptions;\n\nimport tech.sirwellington.alchemy.http.AlchemyRequest;\nimport tech.sirwellington.alchemy.http.HttpRequest;\nimport tech.sirwellington.alchemy.http.HttpResponse;\n\n/**\n * Thrown when an error occurs trying to parse JSON, or unwrap JSON into a\n * {@linkplain AlchemyRequest.Step3#expecting(java.lang.Class) POJO}.\n *\n * @author SirWellington\n */\npublic class JsonException extends AlchemyHttpException\n{\n\n public JsonException()\n {\n }\n\n public JsonException(String message)\n {\n super(message);\n }\n\n public JsonException(String message, Throwable cause)\n {\n super(message, cause);\n }\n\n public JsonException(Throwable cause)\n {\n super(cause);\n }\n\n public JsonException(HttpRequest request)\n {\n super(request);\n }\n\n public JsonException(HttpRequest request, String message)\n {\n super(request, message);\n }\n\n public JsonException(HttpRequest request, String message, Throwable cause)\n {\n super(request, message, cause);\n }\n\n public JsonException(HttpRequest request, Throwable cause)\n {\n super(request, cause);\n }\n\n public JsonException(HttpResponse response)\n {\n super(response);\n }\n\n public JsonException(HttpResponse response, String message)\n {\n super(response, message);\n }\n\n public JsonException(HttpResponse response, String message, Throwable cause)\n {\n super(response, message, cause);\n }\n\n public JsonException(HttpResponse response, Throwable cause)\n {\n super(response, cause);\n }\n\n public JsonException(HttpRequest request, HttpResponse response)\n {\n super(request, response);\n }\n\n public JsonException(HttpRequest request, HttpResponse response, String message)\n {\n super(request, response, message);\n }\n\n public JsonException(HttpRequest request, HttpResponse response, String message, Throwable cause)\n {\n super(request, response, message, cause);\n }\n\n public JsonException(HttpRequest request, HttpResponse response, Throwable cause)\n {\n super(request, response, cause);\n }\n\n}\n"},"message":{"kind":"string","value":"Optimizes imports\n"},"old_file":{"kind":"string","value":"src/main/java/tech/sirwellington/alchemy/http/exceptions/JsonException.java"},"subject":{"kind":"string","value":"Optimizes imports"},"git_diff":{"kind":"string","value":"rc/main/java/tech/sirwellington/alchemy/http/exceptions/JsonException.java\n */\n package tech.sirwellington.alchemy.http.exceptions;\n \nimport tech.sirwellington.alchemy.http.AlchemyRequest;\nimport tech.sirwellington.alchemy.http.HttpRequest;\nimport tech.sirwellington.alchemy.http.HttpResponse;\nimport tech.sirwellington.alchemy.http.*;\n \n /**\n * Thrown when an error occurs trying to parse JSON, or unwrap JSON into a"}}},{"rowIdx":198753,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"fee3a4ba14e40f564a385e9b4f2a8b223ffaba30"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"skyscreamer/yoga,skyscreamer/yoga"},"new_contents":{"kind":"string","value":"package org.skyscreamer.yoga.demo.view;\n\nimport org.skyscreamer.yoga.controller.ControllerResponse;\nimport org.skyscreamer.yoga.populator.ObjectFieldPopulator;\nimport org.skyscreamer.yoga.selector.Selector;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.core.annotation.AnnotationUtils;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;\nimport org.springframework.http.server.ServletServerHttpRequest;\nimport org.springframework.http.server.ServletServerHttpResponse;\nimport org.springframework.ui.ExtendedModelMap;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.context.request.NativeWebRequest;\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.View;\nimport org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\npublic class SelectorModelAndViewResolver implements ModelAndViewResolver\n{\n @Autowired\n ObjectFieldPopulator _objectFieldPopulator;\n\n MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();\n\n @SuppressWarnings(\"rawtypes\")\n public ModelAndView resolveModelAndView( Method handlerMethod, Class handlerType, Object returnValue,\n ExtendedModelMap implicitModel, NativeWebRequest webRequest )\n {\n if ( returnValue instanceof ControllerResponse )\n {\n ControllerResponse controllerResponse = (ControllerResponse)returnValue;\n if ( controllerResponse.getData() != null &&\n AnnotationUtils.findAnnotation( handlerMethod, ResponseBody.class ) != null )\n {\n return render( controllerResponse, webRequest );\n }\n }\n return UNRESOLVED;\n }\n\n protected ModelAndView render( final ControllerResponse controllerResponse, NativeWebRequest webRequest )\n {\n final MediaType accept = getAcceptableAcccept( controllerResponse.getData().getClass(), webRequest );\n\n if ( accept == null )\n {\n return null;\n }\n\n return new ModelAndView( new View()\n {\n public void render( Map input, HttpServletRequest request, HttpServletResponse response )\n throws Exception\n {\n Object toRender = getModel( input.values().iterator().next(), controllerResponse.getSelector() );\n mappingJacksonHttpMessageConverter.write( toRender, accept, new ServletServerHttpResponse( response ) );\n }\n\n public String getContentType()\n {\n return accept.toString();\n }\n } ).addObject( controllerResponse.getData() );\n }\n\n protected Object getModel( Object returnValue, Selector selector )\n {\n if ( returnValue instanceof Collection )\n {\n return _objectFieldPopulator.populate( (Collection) returnValue, selector );\n }\n else\n {\n return _objectFieldPopulator.populate( returnValue, selector );\n }\n }\n\n protected MediaType getAcceptableAcccept( Class returnType, NativeWebRequest nativeWebRequest )\n {\n HttpServletRequest req = nativeWebRequest.getNativeRequest( HttpServletRequest.class );\n ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest( req );\n List accepts = servletServerHttpRequest.getHeaders().getAccept();\n for ( MediaType mediaType : accepts )\n {\n if ( mappingJacksonHttpMessageConverter.canWrite( returnType, mediaType ) )\n {\n return mediaType;\n }\n }\n return null;\n }\n}\n"},"new_file":{"kind":"string","value":"demos/yoga-springmvc/src/main/java/org/skyscreamer/yoga/demo/view/SelectorModelAndViewResolver.java"},"old_contents":{"kind":"string","value":"package org.skyscreamer.yoga.demo.view;\n\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.skyscreamer.yoga.populator.ObjectFieldPopulator;\nimport org.skyscreamer.yoga.selector.CombinedSelector;\nimport org.skyscreamer.yoga.selector.CoreSelector;\nimport org.skyscreamer.yoga.selector.ParseSelectorException;\nimport org.skyscreamer.yoga.selector.Selector;\nimport org.skyscreamer.yoga.selector.SelectorParser;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.core.annotation.AnnotationUtils;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;\nimport org.springframework.http.server.ServletServerHttpRequest;\nimport org.springframework.http.server.ServletServerHttpResponse;\nimport org.springframework.ui.ExtendedModelMap;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.context.request.NativeWebRequest;\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.View;\nimport org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;\n\npublic class SelectorModelAndViewResolver implements ModelAndViewResolver {\n\n\t@Autowired\n\tObjectFieldPopulator _objectFieldPopulator;\n\n\tMappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();\n\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) {\n\t\tif (returnValue == null || AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn render(returnValue, webRequest);\n\t}\n\n\tprotected ModelAndView render(final Object returnValue, NativeWebRequest webRequest) {\n\t\tHttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);\n\t\tfinal MediaType accept = getAcceptableAcccept(returnValue.getClass(), req);\n\t\t\n\t\tif (accept == null) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\treturn new ModelAndView(new View() {\n\t\t\t@Override\n\t\t\tpublic void render(Map input, HttpServletRequest request, HttpServletResponse response) throws Exception {\n\t\t\t\tObject toRender = getModel(input.values().iterator().next(), request);\n\t\t\t\tmappingJacksonHttpMessageConverter.write(toRender, accept, new ServletServerHttpResponse(response));\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic String getContentType() {\n\t\t\t\treturn accept.toString();\n\t\t\t}\n\t\t}).addObject(returnValue);\n\t}\n\n\tprotected Object getModel(Object returnValue, HttpServletRequest req) {\n\t\tif (returnValue instanceof Collection) {\n\t\t\treturn _objectFieldPopulator.populate((Collection) returnValue, getSelector(req));\n\t\t} else {\n\t\t\treturn _objectFieldPopulator.populate(returnValue, getSelector(req));\n\t\t}\n\t}\n\n\tprotected Selector getSelector(HttpServletRequest req) {\n\t\tCoreSelector coreSelector = new CoreSelector();\n\t\tString selectorStr = req.getParameter(\"selector\");\n\t\tif (selectorStr != null) {\n\t\t\ttry {\n\t\t\t\treturn new CombinedSelector(coreSelector, SelectorParser.parse(selectorStr));\n\t\t\t} catch (ParseSelectorException e) {\n\t\t\t\t// TODO: Add logging here. Spring spits out\n\t\t\t\t// \"no matching editors or conversion strategy found\", which\n\t\t\t\t// is vague and misleading. (ie, A URL typo looks like a\n\t\t\t\t// configuration error)\n\t\t\t\tthrow new IllegalArgumentException(\"Could not parse selector\", e);\n\t\t\t}\n\t\t}\n\t\treturn coreSelector;\n\t}\n\n\tprotected MediaType getAcceptableAcccept(Class returnType, HttpServletRequest req) {\n\t\tServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(req);\n\t\tList accepts = servletServerHttpRequest.getHeaders().getAccept();\n\t\tfor (MediaType mediaType : accepts) {\n\t\t\tif (mappingJacksonHttpMessageConverter.canWrite(returnType, mediaType)) {\n\t\t\t\treturn mediaType;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}\n"},"message":{"kind":"string","value":"Binding the selector at the beginning of the controller method to enable DTO population\n"},"old_file":{"kind":"string","value":"demos/yoga-springmvc/src/main/java/org/skyscreamer/yoga/demo/view/SelectorModelAndViewResolver.java"},"subject":{"kind":"string","value":"Binding the selector at the beginning of the controller method to enable DTO population"},"git_diff":{"kind":"string","value":"emos/yoga-springmvc/src/main/java/org/skyscreamer/yoga/demo/view/SelectorModelAndViewResolver.java\n package org.skyscreamer.yoga.demo.view;\n \nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.skyscreamer.yoga.controller.ControllerResponse;\n import org.skyscreamer.yoga.populator.ObjectFieldPopulator;\nimport org.skyscreamer.yoga.selector.CombinedSelector;\nimport org.skyscreamer.yoga.selector.CoreSelector;\nimport org.skyscreamer.yoga.selector.ParseSelectorException;\n import org.skyscreamer.yoga.selector.Selector;\nimport org.skyscreamer.yoga.selector.SelectorParser;\n import org.springframework.beans.factory.annotation.Autowired;\n import org.springframework.core.annotation.AnnotationUtils;\n import org.springframework.http.MediaType;\n import org.springframework.web.servlet.View;\n import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;\n \npublic class SelectorModelAndViewResolver implements ModelAndViewResolver {\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n \n\t@Autowired\n\tObjectFieldPopulator _objectFieldPopulator;\npublic class SelectorModelAndViewResolver implements ModelAndViewResolver\n{\n @Autowired\n ObjectFieldPopulator _objectFieldPopulator;\n \n\tMappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();\n MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();\n \n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) {\n\t\tif (returnValue == null || AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn render(returnValue, webRequest);\n\t}\n @SuppressWarnings(\"rawtypes\")\n public ModelAndView resolveModelAndView( Method handlerMethod, Class handlerType, Object returnValue,\n ExtendedModelMap implicitModel, NativeWebRequest webRequest )\n {\n if ( returnValue instanceof ControllerResponse )\n {\n ControllerResponse controllerResponse = (ControllerResponse)returnValue;\n if ( controllerResponse.getData() != null &&\n AnnotationUtils.findAnnotation( handlerMethod, ResponseBody.class ) != null )\n {\n return render( controllerResponse, webRequest );\n }\n }\n return UNRESOLVED;\n }\n \n\tprotected ModelAndView render(final Object returnValue, NativeWebRequest webRequest) {\n\t\tHttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);\n\t\tfinal MediaType accept = getAcceptableAcccept(returnValue.getClass(), req);\n\t\t\n\t\tif (accept == null) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\treturn new ModelAndView(new View() {\n\t\t\t@Override\n\t\t\tpublic void render(Map input, HttpServletRequest request, HttpServletResponse response) throws Exception {\n\t\t\t\tObject toRender = getModel(input.values().iterator().next(), request);\n\t\t\t\tmappingJacksonHttpMessageConverter.write(toRender, accept, new ServletServerHttpResponse(response));\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic String getContentType() {\n\t\t\t\treturn accept.toString();\n\t\t\t}\n\t\t}).addObject(returnValue);\n\t}\n protected ModelAndView render( final ControllerResponse controllerResponse, NativeWebRequest webRequest )\n {\n final MediaType accept = getAcceptableAcccept( controllerResponse.getData().getClass(), webRequest );\n \n\tprotected Object getModel(Object returnValue, HttpServletRequest req) {\n\t\tif (returnValue instanceof Collection) {\n\t\t\treturn _objectFieldPopulator.populate((Collection) returnValue, getSelector(req));\n\t\t} else {\n\t\t\treturn _objectFieldPopulator.populate(returnValue, getSelector(req));\n\t\t}\n\t}\n if ( accept == null )\n {\n return null;\n }\n \n\tprotected Selector getSelector(HttpServletRequest req) {\n\t\tCoreSelector coreSelector = new CoreSelector();\n\t\tString selectorStr = req.getParameter(\"selector\");\n\t\tif (selectorStr != null) {\n\t\t\ttry {\n\t\t\t\treturn new CombinedSelector(coreSelector, SelectorParser.parse(selectorStr));\n\t\t\t} catch (ParseSelectorException e) {\n\t\t\t\t// TODO: Add logging here. Spring spits out\n\t\t\t\t// \"no matching editors or conversion strategy found\", which\n\t\t\t\t// is vague and misleading. (ie, A URL typo looks like a\n\t\t\t\t// configuration error)\n\t\t\t\tthrow new IllegalArgumentException(\"Could not parse selector\", e);\n\t\t\t}\n\t\t}\n\t\treturn coreSelector;\n\t}\n return new ModelAndView( new View()\n {\n public void render( Map input, HttpServletRequest request, HttpServletResponse response )\n throws Exception\n {\n Object toRender = getModel( input.values().iterator().next(), controllerResponse.getSelector() );\n mappingJacksonHttpMessageConverter.write( toRender, accept, new ServletServerHttpResponse( response ) );\n }\n \n\tprotected MediaType getAcceptableAcccept(Class returnType, HttpServletRequest req) {\n\t\tServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(req);\n\t\tList accepts = servletServerHttpRequest.getHeaders().getAccept();\n\t\tfor (MediaType mediaType : accepts) {\n\t\t\tif (mappingJacksonHttpMessageConverter.canWrite(returnType, mediaType)) {\n\t\t\t\treturn mediaType;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n public String getContentType()\n {\n return accept.toString();\n }\n } ).addObject( controllerResponse.getData() );\n }\n\n protected Object getModel( Object returnValue, Selector selector )\n {\n if ( returnValue instanceof Collection )\n {\n return _objectFieldPopulator.populate( (Collection) returnValue, selector );\n }\n else\n {\n return _objectFieldPopulator.populate( returnValue, selector );\n }\n }\n\n protected MediaType getAcceptableAcccept( Class returnType, NativeWebRequest nativeWebRequest )\n {\n HttpServletRequest req = nativeWebRequest.getNativeRequest( HttpServletRequest.class );\n ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest( req );\n List accepts = servletServerHttpRequest.getHeaders().getAccept();\n for ( MediaType mediaType : accepts )\n {\n if ( mappingJacksonHttpMessageConverter.canWrite( returnType, mediaType ) )\n {\n return mediaType;\n }\n }\n return null;\n }\n }"}}},{"rowIdx":198754,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"2eef5ad197e4477b47f080d99c22a5379d257cc9"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"bradparks/mamute,GEBIT/mamute,csokol/mamute,c2tarun/mamute,superm1a3/mamute,khajavi/mamute,JamesSullivan/mamute,cristianospsp/mamute,jasonwjones/mamute,bradparks/mamute,dhieugo/mamute,shomabegoo/shomabegoo,bradparks/mamute,dhieugo/mamute,MatejBalantic/mamute,c2tarun/mamute,caelum/mamute,jasonwjones/mamute,csokol/mamute,caelum/mamute,xdarklight/mamute,MatejBalantic/mamute,GEBIT/mamute,MatejBalantic/mamute,khajavi/mamute,superm1a3/mamute,khajavi/mamute,caelum/mamute,xdarklight/mamute,shomabegoo/shomabegoo,cristianospsp/mamute,jasonwjones/mamute,cristianospsp/mamute,GEBIT/mamute,csokol/mamute,xdarklight/mamute,shomabegoo/shomabegoo,superm1a3/mamute,JamesSullivan/mamute,c2tarun/mamute,dhieugo/mamute,shomabegoo/shomabegoo,JamesSullivan/mamute"},"new_contents":{"kind":"string","value":"package org.mamute.auth;\n\nimport static org.apache.commons.lang.StringUtils.isEmpty;\nimport static org.apache.commons.lang.StringUtils.isNotEmpty;\nimport static org.mamute.model.SanitizedText.fromTrustedText;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.annotation.PostConstruct;\nimport javax.inject.Inject;\n\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Attribute;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.entry.Value;\nimport org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\nimport org.mamute.dao.LoginMethodDAO;\nimport org.mamute.dao.UserDAO;\nimport org.mamute.model.LoginMethod;\nimport org.mamute.model.User;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport br.com.caelum.vraptor.environment.Environment;\n\n/**\n * LDAP authentication API\n */\npublic class LDAPApi {\n\tprivate static final Logger logger = LoggerFactory.getLogger(LDAPApi.class);\n\n\tpublic static final String LDAP_AUTH = \"ldap\";\n\tpublic static final String LDAP_HOST = \"ldap.host\";\n\tpublic static final String LDAP_PORT = \"ldap.port\";\n\tpublic static final String LDAP_USER = \"ldap.user\";\n\tpublic static final String LDAP_PASS = \"ldap.pass\";\n\tpublic static final String LDAP_USER_DN = \"ldap.userDn\";\n\tpublic static final String LDAP_EMAIL = \"ldap.emailAttr\";\n\tpublic static final String LDAP_NAME = \"ldap.nameAttr\";\n\tpublic static final String LDAP_SURNAME = \"ldap.surnameAttr\";\n\tpublic static final String LDAP_GROUP = \"ldap.groupAttr\";\n\tpublic static final String LDAP_LOOKUP = \"ldap.lookupAttr\";\n\tpublic static final String LDAP_MODERATOR_GROUP = \"ldap.moderatorGroup\";\n\tpublic static final String PLACHOLDER_PASSWORD = \"ldap-password-ignore-me\";\n\n\t@Inject private Environment env;\n\t@Inject private UserDAO users;\n\t@Inject private LoginMethodDAO loginMethods;\n\n\tprivate String host;\n\tprivate Integer port;\n\tprivate String user;\n\tprivate String pass;\n\tprivate String userDn;\n\tprivate String emailAttr;\n\tprivate String nameAttr;\n\tprivate String surnameAttr;\n\tprivate String groupAttr;\n\tprivate String[] lookupAttrs;\n\tprivate String moderatorGroup;\n\n\t/**\n\t * Ensure that required variables are set if LDAP auth\n\t * is enabled\n\t */\n\t@PostConstruct\n\tpublic void init() {\n\t\tif (env.supports(\"feature.auth.ldap\")) {\n\t\t\t//required\n\t\t\thost = assertValuePresent(LDAP_HOST);\n\t\t\tport = Integer.parseInt(assertValuePresent(LDAP_PORT));\n\t\t\tuser = assertValuePresent(LDAP_USER);\n\t\t\tpass = assertValuePresent(LDAP_PASS);\n\t\t\tuserDn = assertValuePresent(LDAP_USER_DN);\n\t\t\temailAttr = assertValuePresent(LDAP_EMAIL);\n\t\t\tnameAttr = assertValuePresent(LDAP_NAME);\n\n\t\t\t//optional\n\t\t\tsurnameAttr = env.get(LDAP_SURNAME, \"\");\n\t\t\tgroupAttr = env.get(LDAP_GROUP, \"\");\n\t\t\tmoderatorGroup = env.get(LDAP_MODERATOR_GROUP, \"\");\n\t\t\tlookupAttrs = env.get(LDAP_LOOKUP, \"\").split(\",\");\n\t\t}\n\t}\n\n\t/**\n\t * Attempt to authenticate against LDAP directory. Accepts email addresses\n\t * as well as plain usernames; emails will have the '@mail.com' portion\n\t * stripped off before read.\n\t *\n\t * @param username\n\t * @param password\n\t * @return\n\t */\n\tpublic boolean authenticate(String username, String password) {\n\t\ttry (LDAPResource ldap = new LDAPResource()) {\n\t\t\tString cn = userCn(username);\n\t\t\tldap.verifyCredentials(cn, password);\n\t\t\tcreateUserIfNeeded(ldap, cn);\n\n\t\t\treturn true;\n\t\t} catch (LdapAuthenticationException e) {\n\t\t\tlogger.debug(\"LDAP auth attempt failed\");\n\t\t\treturn false;\n\t\t} catch (LdapException | IOException e) {\n\t\t\tlogger.debug(\"LDAP connection error\", e);\n\t\t\tthrow new AuthenticationException(LDAP_AUTH, \"LDAP connection error\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Find the email address for a given username\n\t *\n\t * @param username\n\t * @return\n\t */\n\tpublic String getEmail(String username) {\n\t\ttry (LDAPResource ldap = new LDAPResource()) {\n\t\t\tEntry ldapUser = ldap.getUser(userCn(username));\n\t\t\treturn ldap.getAttribute(ldapUser, emailAttr);\n\t\t} catch (LdapException | IOException e) {\n\t\t\tlogger.debug(\"LDAP connection error\", e);\n\t\t\tthrow new AuthenticationException(LDAP_AUTH, \"LDAP connection error\", e);\n\t\t}\n\t}\n\n\tprivate String userCn(String username) {\n\t\tif (lookupAttrs.length > 0) {\n\t\t\ttry (LDAPResource ldap = new LDAPResource()) {\n\t\t\t\tEntry user = ldap.lookupUser(username);\n\t\t\t\tif (user != null) {\n\t\t\t\t\treturn user.getDn().getName();\n\t\t\t\t}\n\t\t\t} catch (LdapException | IOException e) {\n\t\t\t\tlogger.debug(\"LDAP connection error\", e);\n\t\t\t\tthrow new AuthenticationException(LDAP_AUTH, \"LDAP connection error\", e);\n\t\t\t}\n\t\t}\n\n\t\t// fallback: assume lookup by CN\n\t\tString sanitizedUser = username.replaceAll(\"[,=]\", \"\");\n\t\tString cn = \"cn=\" + sanitizedUser + \",\" + userDn;\n\t\treturn cn;\n\t}\n\n\tprivate void createUserIfNeeded(LDAPResource ldap, String cn) throws LdapException {\n\t\tEntry ldapUser = ldap.getUser(cn);\n\t\tString email = ldap.getAttribute(ldapUser, emailAttr);\n\t\tUser user = users.findByEmail(email);\n\t\tif (user == null) {\n\t\t\tString fullName = ldap.getAttribute(ldapUser, nameAttr);\n\t\t\tif (isNotEmpty(surnameAttr)) {\n\t\t\t\tfullName += \" \" + ldap.getAttribute(ldapUser, surnameAttr);\n\t\t\t}\n\n\t\t\tuser = new User(fromTrustedText(fullName.trim()), email);\n\n\n\t\t\tLoginMethod brutalLogin = LoginMethod.brutalLogin(user, email, PLACHOLDER_PASSWORD);\n\t\t\tuser.add(brutalLogin);\n\n\t\t\tusers.save(user);\n\t\t\tloginMethods.save(brutalLogin);\n\t\t}\n\n\t\t//update moderator status\n\t\tif (isNotEmpty(moderatorGroup) && ldap.getGroups(ldapUser).contains(moderatorGroup)) {\n\t\t\tuser = user.asModerator();\n\t\t} else {\n\t\t\tuser.removeModerator();\n\t\t}\n\n\t\tusers.save(user);\n\t}\n\n\tprivate String assertValuePresent(String field) {\n\t\tString value = env.get(field, \"\");\n\t\tif (isEmpty(value)) {\n\t\t\tthrow new RuntimeException(\"Field [\" + field + \"] is required when using LDAP authentication\");\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Acts as a session-level LDAP connection.\n\t */\n\tprivate class LDAPResource implements AutoCloseable {\n\t\tLdapConnection connection;\n\n\t\tprivate LDAPResource() throws LdapException {\n\t\t\tconnection = connection(user, pass);\n\t\t}\n\n\t\tprivate void verifyCredentials(String userCn, String password) throws LdapException, IOException {\n\t\t\ttry (LdapConnection conn = connection(userCn, password)) {\n\t\t\t\tlogger.debug(\"LDAP login from [\" + userCn + \"]\");\n\t\t\t}\n\t\t}\n\n\t\tprivate LdapConnection connection(String username, String password) throws LdapException {\n\t\t\tLdapNetworkConnection conn = new LdapNetworkConnection(host, port);\n\t\t\tconn.bind(username, password);\n\t\t\treturn conn;\n\t\t}\n\n\t\tprivate List getGroups(Entry user) {\n\t\t\tList groupCns = new ArrayList<>();\n\t\t\tif (isNotEmpty(groupAttr)) {\n\t\t\t\tAttribute grpEntry = user.get(groupAttr);\n\t\t\t\tif (grpEntry != null) {\n\t\t\t\t\tfor (Value grp : grpEntry) {\n\t\t\t\t\t\tgroupCns.add(grp.getString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn groupCns;\n\t\t}\n\n\t\tprivate Entry getUser(String cn) throws LdapException {\n\t\t\treturn connection.lookup(cn);\n\t\t}\n\n\t\tprivate Entry lookupUser(String username) throws LdapException {\n\t\t\tStringBuilder userQuery = new StringBuilder();\n\t\t\tuserQuery.append(\"(&(objectclass=user)(|\");\n\t\t\tboolean hasCondition = false;\n\t\t\tfor (String lookupAttr : lookupAttrs) {\n\t\t\t\tString attrName = lookupAttr.trim();\n\t\t\t\tif (!attrName.isEmpty()) {\n\t\t\t\t\tuserQuery.append('(').append(attrName).append('=').append(username).append(')');\n\t\t\t\t\thasCondition = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tuserQuery.append(\"))\");\n\n\t\t\tif (!hasCondition) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tfor (String lookupAttr : lookupAttrs) {\n\t\t\t\tString attrName = lookupAttr.trim();\n\t\t\t\tif (!attrName.isEmpty()) {\n\t\t\t\t\tEntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE);\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (responseCursor != null && responseCursor.next()) {\n\t\t\t\t\t\t\t\treturn responseCursor.get();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (CursorException e) {\n\t\t\t\t\t\t\tlogger.debug(\"LDAP search error\", e);\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tresponseCursor.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate String getAttribute(Entry entry, String attribute) throws LdapException {\n\t\t\treturn entry.get(attribute).getString();\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() throws IOException {\n\t\t\tconnection.close();\n\t\t}\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/mamute/auth/LDAPApi.java"},"old_contents":{"kind":"string","value":"package org.mamute.auth;\n\nimport static org.apache.commons.lang.StringUtils.isEmpty;\nimport static org.apache.commons.lang.StringUtils.isNotEmpty;\nimport static org.mamute.model.SanitizedText.fromTrustedText;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.annotation.PostConstruct;\nimport javax.inject.Inject;\n\nimport org.apache.directory.api.ldap.model.cursor.CursorException;\nimport org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Entry;\nimport org.apache.directory.api.ldap.model.entry.Value;\nimport org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.api.ldap.model.message.SearchScope;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\nimport org.mamute.dao.LoginMethodDAO;\nimport org.mamute.dao.UserDAO;\nimport org.mamute.model.LoginMethod;\nimport org.mamute.model.User;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport br.com.caelum.vraptor.environment.Environment;\n\n/**\n * LDAP authentication API\n */\npublic class LDAPApi {\n\tprivate static final Logger logger = LoggerFactory.getLogger(LDAPApi.class);\n\n\tpublic static final String LDAP_AUTH = \"ldap\";\n\tpublic static final String LDAP_HOST = \"ldap.host\";\n\tpublic static final String LDAP_PORT = \"ldap.port\";\n\tpublic static final String LDAP_USER = \"ldap.user\";\n\tpublic static final String LDAP_PASS = \"ldap.pass\";\n\tpublic static final String LDAP_USER_DN = \"ldap.userDn\";\n\tpublic static final String LDAP_EMAIL = \"ldap.emailAttr\";\n\tpublic static final String LDAP_NAME = \"ldap.nameAttr\";\n\tpublic static final String LDAP_SURNAME = \"ldap.surnameAttr\";\n\tpublic static final String LDAP_GROUP = \"ldap.groupAttr\";\n\tpublic static final String LDAP_LOOKUP = \"ldap.lookupAttr\";\n\tpublic static final String LDAP_MODERATOR_GROUP = \"ldap.moderatorGroup\";\n\tpublic static final String PLACHOLDER_PASSWORD = \"ldap-password-ignore-me\";\n\n\t@Inject private Environment env;\n\t@Inject private UserDAO users;\n\t@Inject private LoginMethodDAO loginMethods;\n\n\tprivate String host;\n\tprivate Integer port;\n\tprivate String user;\n\tprivate String pass;\n\tprivate String userDn;\n\tprivate String emailAttr;\n\tprivate String nameAttr;\n\tprivate String surnameAttr;\n\tprivate String groupAttr;\n\tprivate String[] lookupAttrs;\n\tprivate String moderatorGroup;\n\n\t/**\n\t * Ensure that required variables are set if LDAP auth\n\t * is enabled\n\t */\n\t@PostConstruct\n\tpublic void init() {\n\t\tif (env.supports(\"feature.auth.ldap\")) {\n\t\t\t//required\n\t\t\thost = assertValuePresent(LDAP_HOST);\n\t\t\tport = Integer.parseInt(assertValuePresent(LDAP_PORT));\n\t\t\tuser = assertValuePresent(LDAP_USER);\n\t\t\tpass = assertValuePresent(LDAP_PASS);\n\t\t\tuserDn = assertValuePresent(LDAP_USER_DN);\n\t\t\temailAttr = assertValuePresent(LDAP_EMAIL);\n\t\t\tnameAttr = assertValuePresent(LDAP_NAME);\n\n\t\t\t//optional\n\t\t\tsurnameAttr = env.get(LDAP_SURNAME, \"\");\n\t\t\tgroupAttr = env.get(LDAP_GROUP, \"\");\n\t\t\tmoderatorGroup = env.get(LDAP_MODERATOR_GROUP, \"\");\n\t\t\tlookupAttrs = env.get(LDAP_LOOKUP, \"\").split(\",\");\n\t\t}\n\t}\n\n\t/**\n\t * Attempt to authenticate against LDAP directory. Accepts email addresses\n\t * as well as plain usernames; emails will have the '@mail.com' portion\n\t * stripped off before read.\n\t *\n\t * @param username\n\t * @param password\n\t * @return\n\t */\n\tpublic boolean authenticate(String username, String password) {\n\t\ttry (LDAPResource ldap = new LDAPResource()) {\n\t\t\tString cn = userCn(username);\n\t\t\tldap.verifyCredentials(cn, password);\n\t\t\tcreateUserIfNeeded(ldap, cn);\n\n\t\t\treturn true;\n\t\t} catch (LdapAuthenticationException e) {\n\t\t\tlogger.debug(\"LDAP auth attempt failed\");\n\t\t\treturn false;\n\t\t} catch (LdapException | IOException e) {\n\t\t\tlogger.debug(\"LDAP connection error\", e);\n\t\t\tthrow new AuthenticationException(LDAP_AUTH, \"LDAP connection error\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Find the email address for a given username\n\t *\n\t * @param username\n\t * @return\n\t */\n\tpublic String getEmail(String username) {\n\t\ttry (LDAPResource ldap = new LDAPResource()) {\n\t\t\tEntry ldapUser = ldap.getUser(userCn(username));\n\t\t\treturn ldap.getAttribute(ldapUser, emailAttr);\n\t\t} catch (LdapException | IOException e) {\n\t\t\tlogger.debug(\"LDAP connection error\", e);\n\t\t\tthrow new AuthenticationException(LDAP_AUTH, \"LDAP connection error\", e);\n\t\t}\n\t}\n\n\tprivate String userCn(String username) {\n\t\tif (lookupAttrs.length > 0) {\n\t\t\ttry (LDAPResource ldap = new LDAPResource()) {\n\t\t\t\tEntry user = ldap.lookupUser(username);\n\t\t\t\tif (user != null) {\n\t\t\t\t\treturn user.getDn().getName();\n\t\t\t\t}\n\t\t\t} catch (LdapException | IOException e) {\n\t\t\t\tlogger.debug(\"LDAP connection error\", e);\n\t\t\t\tthrow new AuthenticationException(LDAP_AUTH, \"LDAP connection error\", e);\n\t\t\t}\n\t\t}\n\n\t\t// fallback: assume lookup by CN\n\t\tString sanitizedUser = username.replaceAll(\"[,=]\", \"\");\n\t\tString cn = \"cn=\" + sanitizedUser + \",\" + userDn;\n\t\treturn cn;\n\t}\n\n\tprivate void createUserIfNeeded(LDAPResource ldap, String cn) throws LdapException {\n\t\tEntry ldapUser = ldap.getUser(cn);\n\t\tString email = ldap.getAttribute(ldapUser, emailAttr);\n\t\tUser user = users.findByEmail(email);\n\t\tif (user == null) {\n\t\t\tString fullName = ldap.getAttribute(ldapUser, nameAttr);\n\t\t\tif (isNotEmpty(surnameAttr)) {\n\t\t\t\tfullName += \" \" + ldap.getAttribute(ldapUser, surnameAttr);\n\t\t\t}\n\n\t\t\tuser = new User(fromTrustedText(fullName.trim()), email);\n\n\n\t\t\tLoginMethod brutalLogin = LoginMethod.brutalLogin(user, email, PLACHOLDER_PASSWORD);\n\t\t\tuser.add(brutalLogin);\n\n\t\t\tusers.save(user);\n\t\t\tloginMethods.save(brutalLogin);\n\t\t}\n\n\t\t//update moderator status\n\t\tif (isNotEmpty(moderatorGroup) && ldap.getGroups(ldapUser).contains(moderatorGroup)) {\n\t\t\tuser = user.asModerator();\n\t\t} else {\n\t\t\tuser.removeModerator();\n\t\t}\n\n\t\tusers.save(user);\n\t}\n\n\tprivate String assertValuePresent(String field) {\n\t\tString value = env.get(field, \"\");\n\t\tif (isEmpty(value)) {\n\t\t\tthrow new RuntimeException(\"Field [\" + field + \"] is required when using LDAP authentication\");\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Acts as a session-level LDAP connection.\n\t */\n\tprivate class LDAPResource implements AutoCloseable {\n\t\tLdapConnection connection;\n\n\t\tprivate LDAPResource() throws LdapException {\n\t\t\tconnection = connection(user, pass);\n\t\t}\n\n\t\tprivate void verifyCredentials(String userCn, String password) throws LdapException, IOException {\n\t\t\ttry (LdapConnection conn = connection(userCn, password)) {\n\t\t\t\tlogger.debug(\"LDAP login from [\" + userCn + \"]\");\n\t\t\t}\n\t\t}\n\n\t\tprivate LdapConnection connection(String username, String password) throws LdapException {\n\t\t\tLdapNetworkConnection conn = new LdapNetworkConnection(host, port);\n\t\t\tconn.bind(username, password);\n\t\t\treturn conn;\n\t\t}\n\n\t\tprivate List getGroups(Entry user) {\n\t\t\tList groupCns = new ArrayList<>();\n\t\t\tif (isNotEmpty(groupAttr)) {\n\t\t\t\tfor (Value grp : user.get(groupAttr)) {\n\t\t\t\t\tgroupCns.add(grp.getString());\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn groupCns;\n\t\t}\n\n\t\tprivate Entry getUser(String cn) throws LdapException {\n\t\t\treturn connection.lookup(cn);\n\t\t}\n\n\t\tprivate Entry lookupUser(String username) throws LdapException {\n\t\t\tStringBuilder userQuery = new StringBuilder();\n\t\t\tuserQuery.append(\"(&(objectclass=user)(|\");\n\t\t\tboolean hasCondition = false;\n\t\t\tfor (String lookupAttr : lookupAttrs) {\n\t\t\t\tString attrName = lookupAttr.trim();\n\t\t\t\tif (!attrName.isEmpty()) {\n\t\t\t\t\tuserQuery.append('(').append(attrName).append('=').append(username).append(')');\n\t\t\t\t\thasCondition = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tuserQuery.append(\"))\");\n\n\t\t\tif (!hasCondition) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tfor (String lookupAttr : lookupAttrs) {\n\t\t\t\tString attrName = lookupAttr.trim();\n\t\t\t\tif (!attrName.isEmpty()) {\n\t\t\t\t\tEntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE);\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (responseCursor != null && responseCursor.next()) {\n\t\t\t\t\t\t\t\treturn responseCursor.get();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (CursorException e) {\n\t\t\t\t\t\t\tlogger.debug(\"LDAP search error\", e);\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tresponseCursor.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate String getAttribute(Entry entry, String attribute) throws LdapException {\n\t\t\treturn entry.get(attribute).getString();\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() throws IOException {\n\t\t\tconnection.close();\n\t\t}\n\t}\n}\n"},"message":{"kind":"string","value":"Fixed NPE in group lookup if attribute is not present\n"},"old_file":{"kind":"string","value":"src/main/java/org/mamute/auth/LDAPApi.java"},"subject":{"kind":"string","value":"Fixed NPE in group lookup if attribute is not present"},"git_diff":{"kind":"string","value":"rc/main/java/org/mamute/auth/LDAPApi.java\n \n import org.apache.directory.api.ldap.model.cursor.CursorException;\n import org.apache.directory.api.ldap.model.cursor.EntryCursor;\nimport org.apache.directory.api.ldap.model.entry.Attribute;\n import org.apache.directory.api.ldap.model.entry.Entry;\n import org.apache.directory.api.ldap.model.entry.Value;\n import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;\n \t\tprivate List getGroups(Entry user) {\n \t\t\tList groupCns = new ArrayList<>();\n \t\t\tif (isNotEmpty(groupAttr)) {\n\t\t\t\tfor (Value grp : user.get(groupAttr)) {\n\t\t\t\t\tgroupCns.add(grp.getString());\n\t\t\t\tAttribute grpEntry = user.get(groupAttr);\n\t\t\t\tif (grpEntry != null) {\n\t\t\t\t\tfor (Value grp : grpEntry) {\n\t\t\t\t\t\tgroupCns.add(grp.getString());\n\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\treturn groupCns;"}}},{"rowIdx":198755,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"c7759d1a9191fabc6877a736df1307c81290aec5"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"rowhit/tagspaces,cbop-dev/tagspaces,cbop-dev/tagspaces,rowhit/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,rowhit/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,cbop-dev/tagspaces,rowhit/tagspaces"},"new_contents":{"kind":"string","value":"/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.\n * Use of this source code is governed by a AGPL3 license that\n * can be found in the LICENSE file. */\n/* undef: true, unused: false */\n/* global define, Mousetrap, Handlebars */\ndefine(function(require, exports, module) {\n 'use strict';\n console.log('Loading fileopener...');\n var TSCORE = require('tscore');\n var _openedFilePath;\n var _openedFileProperties;\n var _isFileOpened = false;\n var _isFileChanged = false;\n var _tsEditor;\n var generatedTagButtons;\n // Backup cancel button \n $.fn.editableform.buttons = '';\n // If a file is currently opened for editing, this var should be true\n var _isEditMode = false;\n\n window.onbeforeunload = function() {\n if (_isFileChanged) {\n return \"Confirm close\";\n }\n };\n\n function initUI() {\n $('#editDocument').click(function() {\n editFile(_openedFilePath);\n });\n $('#saveDocument').click(function() {\n saveFile();\n });\n $('#closeOpenedFile').click(function() {\n closeFile();\n });\n $('#nextFileButton').click(function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath));\n });\n $('#prevFileButton').click(function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath));\n });\n $('#closeFile').click(function() {\n closeFile();\n });\n $('#reloadFile').click(function() {\n TSCORE.FileOpener.openFile(_openedFilePath);\n });\n $('#sendFile').click(function() {\n TSCORE.IO.sendFile(_openedFilePath);\n });\n $('#openFileInNewWindow').click(function() {\n if (isWeb) {\n if (location.port === '') {\n window.open(location.protocol + '//' + location.hostname + _openedFilePath);\n } else {\n window.open(location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath);\n }\n } else {\n window.open('file:///' + _openedFilePath);\n }\n });\n $('#printFile').click(function() {\n $('iframe').get(0).contentWindow.print();\n });\n $('#tagFile').click(function() {\n if (_isFileChanged) {\n TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert'));\n } else {\n TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.selectedFiles.push(_openedFilePath);\n TSCORE.showAddTagsDialog();\n }\n });\n $('#suggestTagsFile').click(function() {\n $('tagSuggestionsMenu').dropdown('toggle');\n });\n $('#renameFile').click(function() {\n if (_isFileChanged) {\n TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert'));\n } else {\n TSCORE.showFileRenameDialog(_openedFilePath);\n }\n });\n $('#duplicateFile').click(function() {\n var currentDateTime = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true);\n var fileNameWithOutExt = TSCORE.TagUtils.extractFileNameWithoutExt(_openedFilePath);\n var fileExt = TSCORE.TagUtils.extractFileExtension(_openedFilePath);\n var newFilePath = TSCORE.currentPath + TSCORE.dirSeparator + fileNameWithOutExt + '_' + currentDateTime + '.' + fileExt;\n TSCORE.IO.copyFile(_openedFilePath, newFilePath);\n });\n $('#toggleFullWidthButton').click(function() {\n TSCORE.toggleFullWidth();\n });\n $('#deleteFile').click(function() {\n TSCORE.showFileDeleteDialog(_openedFilePath);\n });\n $('#openNatively').click(function() {\n TSCORE.IO.openFile(_openedFilePath);\n });\n $('#openDirectory').click(function() {\n TSCORE.IO.openDirectory(TSCORE.TagUtils.extractParentDirectoryPath(_openedFilePath));\n });\n $('#fullscreenFile').click(function() {\n var docElm = $('#viewer')[0];\n if (docElm.requestFullscreen) {\n docElm.requestFullscreen();\n } else if (docElm.mozRequestFullScreen) {\n docElm.mozRequestFullScreen();\n } else if (docElm.webkitRequestFullScreen) {\n docElm.webkitRequestFullScreen();\n }\n });\n $('#openProperties').click(function() {\n showFilePropertiesDialog();\n });\n }\n\n function isFileChanged() {\n return _isFileChanged;\n }\n\n function setFileChanged(value) {\n var $fileExt = $('#fileExtText');\n var $fileTitle = $('#fileTitle');\n if (value && !_isFileChanged) {\n $fileExt.text($fileExt.text() + '*');\n $fileTitle.editable('disable');\n $('#fileTags').find('button').prop('disabled', true);\n $('#addTagFileViewer').prop('disabled', true);\n }\n if (!value) {\n $fileExt.text(TSCORE.TagUtils.extractFileExtension(_openedFilePath));\n $fileTitle.editable('enable');\n $('#fileTags').find('button').prop('disabled', false);\n $('#addTagFileViewer').prop('disabled', false);\n }\n _isFileChanged = value;\n }\n\n function isFileEdited() {\n return _isEditMode;\n }\n\n function isFileOpened() {\n return _isFileOpened;\n }\n\n function getOpenedFilePath() {\n return _openedFilePath;\n }\n\n function closeFile(forceClose) {\n if (isFileChanged()) {\n if (forceClose) {\n cleanViewer();\n } else {\n TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:closingEditedFileTitleConfirm'), $.i18n.t('ns.dialogs:closingEditedFileContentConfirm'), function() {\n cleanViewer();\n });\n }\n } else {\n cleanViewer();\n }\n }\n\n function cleanViewer() {\n //TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.closeFileViewer();\n // Cleaning the viewer/editor\n //document.getElementById(\"viewer\").innerHTML = \"\";\n $('#viewer').find('*').off().unbind();\n $('#viewer').find('iframe').remove();\n $('#viewer').find('*').children().remove();\n _isFileOpened = false;\n _isEditMode = false;\n _isFileChanged = false;\n Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding());\n }\n\n function openFileOnStartup(filePath) {\n TSCORE.Config.setLastOpenedLocation(undefined);\n // quick and dirty solution, should use flag later\n TSCORE.toggleFullWidth();\n TSCORE.FileOpener.openFile(filePath);\n TSCORE.openLocation(TSCORE.TagUtils.extractContainingDirectoryPath(filePath));\n }\n\n function openFile(filePath, editMode) {\n console.log('Opening file: ' + filePath);\n if (filePath === undefined) {\n return false;\n }\n if (TSCORE.FileOpener.isFileChanged()) {\n // TODO use closeFile method\n if (confirm($.i18n.t('ns.dialogs:closingEditedFileConfirm'))) {\n $('#saveDocument').hide();\n _isEditMode = false;\n } else {\n return false;\n }\n }\n\n $('#fileTags').find('button').prop('disabled', false);\n $('#addTagFileViewer').prop('disabled', false);\n\n _isEditMode = false;\n _isFileChanged = false;\n _openedFilePath = filePath;\n //$(\"#selectedFilePath\").val(_openedFilePath.replace(\"\\\\\\\\\",\"\\\\\"));\n if (isWeb) {\n var downloadLink;\n if (location.port === '') {\n downloadLink = location.protocol + '//' + location.hostname + _openedFilePath;\n } else {\n downloadLink = location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath;\n }\n $('#downloadFile').attr('href', downloadLink).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath));\n } else {\n $('#downloadFile').attr('href', 'file:///' + _openedFilePath).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath));\n }\n var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);\n // Getting the viewer for the file extension/type\n var viewerExt = TSCORE.Config.getFileTypeViewer(fileExt);\n var editorExt = TSCORE.Config.getFileTypeEditor(fileExt);\n console.log('File Viewer: ' + viewerExt + ' File Editor: ' + editorExt);\n // Handling the edit button depending on existense of an editor\n if (editorExt === false || editorExt === 'false' || editorExt === '') {\n $('#editDocument').hide();\n } else {\n $('#editDocument').show();\n }\n var $viewer = $('#viewer');\n $viewer.find('*').off();\n $viewer.find('*').unbind();\n $viewer.find('*').remove();\n TSCORE.IO.checkAccessFileURLAllowed();\n TSCORE.IO.getFileProperties(filePath.replace('\\\\\\\\', '\\\\'));\n updateUI();\n if (editMode) {\n // opening file for editing\n editFile(filePath);\n } else {\n // opening file for viewing\n if (!viewerExt) {\n require([TSCORE.Config.getExtensionPath() + '/viewerText/extension.js'], function(viewer) {\n _tsEditor = viewer;\n _tsEditor.init(filePath, 'viewer', true);\n });\n } else {\n require([TSCORE.Config.getExtensionPath() + '/' + viewerExt + '/extension.js'], function(viewer) {\n _tsEditor = viewer;\n _tsEditor.init(filePath, 'viewer', true);\n });\n }\n }\n initTagSuggestionMenu(filePath);\n // Clearing file selection on file load and adding the current file path to the selection\n TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.selectedFiles.push(filePath);\n _isFileOpened = true;\n TSCORE.openFileViewer();\n // Handling the keybindings\n Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getSaveDocumentKeyBinding(), function() {\n saveFile();\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getCloseViewerKeyBinding(), function() {\n closeFile();\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getReloadDocumentKeyBinding(), function() {\n reloadFile();\n return false;\n });\n /*Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding());\n Mousetrap.bind(TSCORE.Config.getDeleteDocumentKeyBinding(), function() {\n TSCORE.showFileDeleteDialog(_openedFilePath);\n return false;\n });*/\n Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getPropertiesDocumentKeyBinding(), function() {\n showFilePropertiesDialog();\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding());\n Mousetrap.bind(TSCORE.Config.getPrevDocumentKeyBinding(), function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath));\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding());\n Mousetrap.bind(TSCORE.Config.getNextDocumentKeyBinding(), function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath));\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getEditDocumentKeyBinding(), function() {\n editFile(_openedFilePath);\n return false;\n });\n }\n\n function setFileProperties(fileProperties) {\n _openedFileProperties = fileProperties;\n }\n\n function updateEditorContent(fileContent) {\n console.log('Updating editor');\n // with data: \"+fileContent);\n _tsEditor.setContent(fileContent);\n }\n // Should return false if no editor found\n function getFileEditor(filePath) {\n var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);\n // Getting the editor for the file extension/type\n var editorExt = TSCORE.Config.getFileTypeEditor(fileExt);\n console.log('File Editor: ' + editorExt);\n return editorExt;\n }\n\n function editFile(filePath) {\n console.log('Editing file: ' + filePath);\n $('#viewer').children().remove();\n var editorExt = getFileEditor(filePath);\n try {\n require([TSCORE.Config.getExtensionPath() + '/' + editorExt + '/extension.js'], function(editr) {\n _tsEditor = editr;\n _tsEditor.init(filePath, 'viewer', false);\n });\n _isEditMode = true;\n $('#editDocument').hide();\n $('#saveDocument').show();\n } catch (ex) {\n console.error('Loading editing extension failed: ' + ex);\n }\n }\n\n function reloadFile() {\n console.log('Reloading current file.');\n TSCORE.FileOpener.openFile(_openedFilePath);\n }\n\n function saveFile() {\n console.log('Save current file: ' + _openedFilePath);\n var content = _tsEditor.getContent();\n /*var title = TSCORE.TagUtils.extractTitle(_openedFilePath);\n if(title.length < 1 && content.length > 1) {\n title = content.substring(0,content.indexOf(\"\\n\"));\n if(title.length > 100) {\n title = title.substring(0,99);\n }\n }*/\n TSCORE.IO.saveTextFile(_openedFilePath, content);\n }\n\n function updateUI() {\n $('#saveDocument').hide();\n // Initialize File Extension\n var fileExtension = TSCORE.TagUtils.extractFileExtension(_openedFilePath);\n $('#fileExtText').text(fileExtension);\n // Initialize File Title Editor\n var title = TSCORE.TagUtils.extractTitle(_openedFilePath);\n var $fileTitle = $('#fileTitle');\n $fileTitle.editable('destroy');\n $fileTitle.text(title);\n $fileTitle.editable({\n type: 'text',\n //placement: 'bottom',\n title: 'Change Title',\n mode: 'inline',\n success: function(response, newValue) {\n TSCORE.TagUtils.changeTitle(_openedFilePath, newValue);\n }\n });\n // Generate tag & ext buttons\n // Appending tag buttons\n var tags = TSCORE.TagUtils.extractTags(_openedFilePath);\n var tagString = '';\n tags.forEach(function(value, index) {\n if (index === 0) {\n tagString = value;\n } else {\n tagString = tagString + ',' + value;\n }\n });\n generatedTagButtons = TSCORE.generateTagButtons(tagString, _openedFilePath);\n var $fileTags = $('#fileTags');\n $fileTags.children().remove();\n $fileTags.append(generatedTagButtons);\n $('#tagsContainer').droppable({\n greedy: 'true',\n accept: '.tagButton',\n hoverClass: 'activeRow',\n drop: function(event, ui) {\n if (_isFileChanged) {\n TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert'));\n } else {\n console.log('Tagging file: ' + TSCORE.selectedTag + ' to ' + _openedFilePath);\n TSCORE.TagUtils.addTag([_openedFilePath], [TSCORE.selectedTag]); //$(ui.helper).remove();\n }\n }\n });\n // Init Tag Context Menus\n $fileTags.on('contextmenu click', '.tagButton', function() {\n TSCORE.hideAllDropDownMenus();\n TSCORE.openTagMenu(this, $(this).attr('tag'), $(this).attr('filepath'));\n TSCORE.showContextMenu('#tagMenu', $(this));\n return false;\n });\n }\n\n function initTagSuggestionMenu(filePath) {\n var tags = TSCORE.TagUtils.extractTags(filePath);\n var suggTags = TSCORE.TagUtils.suggestTags(filePath);\n var tsMenu = $('#tagSuggestionsMenu');\n tsMenu.children().remove();\n tsMenu.attr('style', 'overflow-y: auto; max-height: 500px;');\n tsMenu.append($('

  • ', {\n class: 'dropdown-header',\n text: $.i18n.t('ns.common:tagOperations')\n }).append(''));\n tsMenu.append($('
  • ').append($('', {\n title: $.i18n.t('ns.common:addRemoveTagsTooltip'),\n filepath: filePath,\n text: ' ' + $.i18n.t('ns.common:addRemoveTags')\n }).prepend('').click(function() {\n TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.selectedFiles.push(filePath);\n TSCORE.showAddTagsDialog();\n })));\n tsMenu.append($('
  • ', {\n class: 'dropdown-header',\n text: $.i18n.t('ns.common:suggestedTags')\n }));\n // Add tag suggestion based on the last modified date\n if (_openedFileProperties !== undefined && _openedFileProperties.lmdt !== undefined) {\n suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt));\n suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt, true));\n }\n // Adding context menu entries for creating tags according to the suggested tags\n for (var i = 0; i < suggTags.length; i++) {\n // Ignoring the tags already assigned to a file\n if (tags.indexOf(suggTags[i]) < 0) {\n tsMenu.append($('
  • ', {\n name: suggTags[i]\n }).append($('', {}).append($('';\n // If a file is currently opened for editing, this var should be true\n var _isEditMode = false;\n\n window.onbeforeunload = function() {\n if (_isFileChanged) {\n return \"Confirm close\";\n }\n };\n\n function initUI() {\n $('#editDocument').click(function() {\n editFile(_openedFilePath);\n });\n $('#saveDocument').click(function() {\n saveFile();\n });\n $('#closeOpenedFile').click(function() {\n closeFile();\n });\n $('#nextFileButton').click(function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath));\n });\n $('#prevFileButton').click(function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath));\n });\n $('#closeFile').click(function() {\n closeFile();\n });\n $('#reloadFile').click(function() {\n TSCORE.FileOpener.openFile(_openedFilePath);\n });\n $('#sendFile').click(function() {\n TSCORE.IO.sendFile(_openedFilePath);\n });\n $('#openFileInNewWindow').click(function() {\n if (isWeb) {\n if (location.port === '') {\n window.open(location.protocol + '//' + location.hostname + _openedFilePath);\n } else {\n window.open(location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath);\n }\n } else {\n window.open('file:///' + _openedFilePath);\n }\n });\n $('#printFile').click(function() {\n $('iframe').get(0).contentWindow.print();\n });\n $('#tagFile').click(function() {\n if (_isFileChanged) {\n TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert'));\n } else {\n TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.selectedFiles.push(_openedFilePath);\n TSCORE.showAddTagsDialog();\n }\n });\n $('#suggestTagsFile').click(function() {\n $('tagSuggestionsMenu').dropdown('toggle');\n });\n $('#renameFile').click(function() {\n if (_isFileChanged) {\n TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert'));\n } else {\n TSCORE.showFileRenameDialog(_openedFilePath);\n }\n });\n $('#duplicateFile').click(function() {\n var currentDateTime = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true);\n var fileNameWithOutExt = TSCORE.TagUtils.extractFileNameWithoutExt(_openedFilePath);\n var fileExt = TSCORE.TagUtils.extractFileExtension(_openedFilePath);\n var newFilePath = TSCORE.currentPath + TSCORE.dirSeparator + fileNameWithOutExt + '_' + currentDateTime + '.' + fileExt;\n TSCORE.IO.copyFile(_openedFilePath, newFilePath);\n });\n $('#toggleFullWidthButton').click(function() {\n TSCORE.toggleFullWidth();\n });\n $('#deleteFile').click(function() {\n TSCORE.showFileDeleteDialog(_openedFilePath);\n });\n $('#openNatively').click(function() {\n TSCORE.IO.openFile(_openedFilePath);\n });\n $('#openDirectory').click(function() {\n TSCORE.IO.openDirectory(TSCORE.TagUtils.extractParentDirectoryPath(_openedFilePath));\n });\n $('#fullscreenFile').click(function() {\n var docElm = $('#viewer')[0];\n if (docElm.requestFullscreen) {\n docElm.requestFullscreen();\n } else if (docElm.mozRequestFullScreen) {\n docElm.mozRequestFullScreen();\n } else if (docElm.webkitRequestFullScreen) {\n docElm.webkitRequestFullScreen();\n }\n });\n $('#openProperties').click(function() {\n showFilePropertiesDialog();\n });\n }\n\n function isFileChanged() {\n return _isFileChanged;\n }\n\n function setFileChanged(value) {\n var $fileExt = $('#fileExtText');\n var $fileTitle = $('#fileTitle');\n if (value && !_isFileChanged) {\n $fileExt.text($fileExt.text() + '*');\n $fileTitle.editable('disable');\n $('#fileTags').find('button').prop('disabled', true);\n $('#addTagFileViewer').prop('disabled', true);\n }\n if (!value) {\n $fileExt.text(TSCORE.TagUtils.extractFileExtension(_openedFilePath));\n $fileTitle.editable('enable');\n $('#fileTags').find('button').prop('disabled', false);\n $('#addTagFileViewer').prop('disabled', false);\n }\n _isFileChanged = value;\n }\n\n function isFileEdited() {\n return _isEditMode;\n }\n\n function isFileOpened() {\n return _isFileOpened;\n }\n\n function getOpenedFilePath() {\n return _openedFilePath;\n }\n\n function closeFile(forceClose) {\n if (isFileChanged()) {\n if (forceClose) {\n cleanViewer();\n } else {\n TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:closingEditedFileTitleConfirm'), $.i18n.t('ns.dialogs:closingEditedFileContentConfirm'), function() {\n cleanViewer();\n });\n }\n } else {\n cleanViewer();\n }\n }\n\n function cleanViewer() {\n //TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.closeFileViewer();\n // Cleaning the viewer/editor\n //document.getElementById(\"viewer\").innerHTML = \"\";\n $('#viewer').find('*').off().unbind();\n $('#viewer').find('iframe').remove();\n $('#viewer').find('*').children().remove();\n _isFileOpened = false;\n _isEditMode = false;\n _isFileChanged = false;\n Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding());\n Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding());\n }\n\n function openFileOnStartup(filePath) {\n TSCORE.Config.setLastOpenedLocation(undefined);\n // quick and dirty solution, should use flag later\n TSCORE.toggleFullWidth();\n TSCORE.FileOpener.openFile(filePath);\n TSCORE.openLocation(TSCORE.TagUtils.extractContainingDirectoryPath(filePath));\n }\n\n function openFile(filePath, editMode) {\n console.log('Opening file: ' + filePath);\n if (filePath === undefined) {\n return false;\n }\n if (TSCORE.FileOpener.isFileChanged()) {\n // TODO use closeFile method\n if (confirm($.i18n.t('ns.dialogs:closingEditedFileConfirm'))) {\n $('#saveDocument').hide();\n _isEditMode = false;\n } else {\n return false;\n }\n }\n _isEditMode = false;\n _isFileChanged = false;\n _openedFilePath = filePath;\n //$(\"#selectedFilePath\").val(_openedFilePath.replace(\"\\\\\\\\\",\"\\\\\"));\n if (isWeb) {\n var downloadLink;\n if (location.port === '') {\n downloadLink = location.protocol + '//' + location.hostname + _openedFilePath;\n } else {\n downloadLink = location.protocol + '//' + location.hostname + ':' + location.port + _openedFilePath;\n }\n $('#downloadFile').attr('href', downloadLink).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath));\n } else {\n $('#downloadFile').attr('href', 'file:///' + _openedFilePath).attr('download', TSCORE.TagUtils.extractFileName(_openedFilePath));\n }\n var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);\n // Getting the viewer for the file extension/type\n var viewerExt = TSCORE.Config.getFileTypeViewer(fileExt);\n var editorExt = TSCORE.Config.getFileTypeEditor(fileExt);\n console.log('File Viewer: ' + viewerExt + ' File Editor: ' + editorExt);\n // Handling the edit button depending on existense of an editor\n if (editorExt === false || editorExt === 'false' || editorExt === '') {\n $('#editDocument').hide();\n } else {\n $('#editDocument').show();\n }\n var $viewer = $('#viewer');\n $viewer.find('*').off();\n $viewer.find('*').unbind();\n $viewer.find('*').remove();\n TSCORE.IO.checkAccessFileURLAllowed();\n TSCORE.IO.getFileProperties(filePath.replace('\\\\\\\\', '\\\\'));\n updateUI();\n if (editMode) {\n // opening file for editing\n editFile(filePath);\n } else {\n // opening file for viewing\n if (!viewerExt) {\n require([TSCORE.Config.getExtensionPath() + '/viewerText/extension.js'], function(viewer) {\n _tsEditor = viewer;\n _tsEditor.init(filePath, 'viewer', true);\n });\n } else {\n require([TSCORE.Config.getExtensionPath() + '/' + viewerExt + '/extension.js'], function(viewer) {\n _tsEditor = viewer;\n _tsEditor.init(filePath, 'viewer', true);\n });\n }\n }\n initTagSuggestionMenu(filePath);\n // Clearing file selection on file load and adding the current file path to the selection\n TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.selectedFiles.push(filePath);\n _isFileOpened = true;\n TSCORE.openFileViewer();\n // Handling the keybindings\n Mousetrap.unbind(TSCORE.Config.getSaveDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getSaveDocumentKeyBinding(), function() {\n saveFile();\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getCloseViewerKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getCloseViewerKeyBinding(), function() {\n closeFile();\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getReloadDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getReloadDocumentKeyBinding(), function() {\n reloadFile();\n return false;\n });\n /*Mousetrap.unbind(TSCORE.Config.getDeleteDocumentKeyBinding());\n Mousetrap.bind(TSCORE.Config.getDeleteDocumentKeyBinding(), function() {\n TSCORE.showFileDeleteDialog(_openedFilePath);\n return false;\n });*/\n Mousetrap.unbind(TSCORE.Config.getPropertiesDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getPropertiesDocumentKeyBinding(), function() {\n showFilePropertiesDialog();\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getPrevDocumentKeyBinding());\n Mousetrap.bind(TSCORE.Config.getPrevDocumentKeyBinding(), function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getPrevFile(_openedFilePath));\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getNextDocumentKeyBinding());\n Mousetrap.bind(TSCORE.Config.getNextDocumentKeyBinding(), function() {\n TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(_openedFilePath));\n return false;\n });\n Mousetrap.unbind(TSCORE.Config.getEditDocumentKeyBinding());\n Mousetrap.bindGlobal(TSCORE.Config.getEditDocumentKeyBinding(), function() {\n editFile(_openedFilePath);\n return false;\n });\n }\n\n function setFileProperties(fileProperties) {\n _openedFileProperties = fileProperties;\n }\n\n function updateEditorContent(fileContent) {\n console.log('Updating editor');\n // with data: \"+fileContent);\n _tsEditor.setContent(fileContent);\n }\n // Should return false if no editor found\n function getFileEditor(filePath) {\n var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);\n // Getting the editor for the file extension/type\n var editorExt = TSCORE.Config.getFileTypeEditor(fileExt);\n console.log('File Editor: ' + editorExt);\n return editorExt;\n }\n\n function editFile(filePath) {\n console.log('Editing file: ' + filePath);\n $('#viewer').children().remove();\n var editorExt = getFileEditor(filePath);\n try {\n require([TSCORE.Config.getExtensionPath() + '/' + editorExt + '/extension.js'], function(editr) {\n _tsEditor = editr;\n _tsEditor.init(filePath, 'viewer', false);\n });\n _isEditMode = true;\n $('#editDocument').hide();\n $('#saveDocument').show();\n } catch (ex) {\n console.error('Loading editing extension failed: ' + ex);\n }\n }\n\n function reloadFile() {\n console.log('Reloading current file.');\n TSCORE.FileOpener.openFile(_openedFilePath);\n }\n\n function saveFile() {\n console.log('Save current file: ' + _openedFilePath);\n var content = _tsEditor.getContent();\n /*var title = TSCORE.TagUtils.extractTitle(_openedFilePath);\n if(title.length < 1 && content.length > 1) {\n title = content.substring(0,content.indexOf(\"\\n\"));\n if(title.length > 100) {\n title = title.substring(0,99);\n }\n }*/\n TSCORE.IO.saveTextFile(_openedFilePath, content);\n }\n\n function updateUI() {\n $('#saveDocument').hide();\n // Initialize File Extension\n var fileExtension = TSCORE.TagUtils.extractFileExtension(_openedFilePath);\n $('#fileExtText').text(fileExtension);\n // Initialize File Title Editor\n var title = TSCORE.TagUtils.extractTitle(_openedFilePath);\n var $fileTitle = $('#fileTitle');\n $fileTitle.editable('destroy');\n $fileTitle.text(title);\n $fileTitle.editable({\n type: 'text',\n //placement: 'bottom',\n title: 'Change Title',\n mode: 'inline',\n success: function(response, newValue) {\n TSCORE.TagUtils.changeTitle(_openedFilePath, newValue);\n }\n });\n // Generate tag & ext buttons\n // Appending tag buttons\n var tags = TSCORE.TagUtils.extractTags(_openedFilePath);\n var tagString = '';\n tags.forEach(function(value, index) {\n if (index === 0) {\n tagString = value;\n } else {\n tagString = tagString + ',' + value;\n }\n });\n generatedTagButtons = TSCORE.generateTagButtons(tagString, _openedFilePath);\n var $fileTags = $('#fileTags');\n $fileTags.children().remove();\n $fileTags.append(generatedTagButtons);\n $('#tagsContainer').droppable({\n greedy: 'true',\n accept: '.tagButton',\n hoverClass: 'activeRow',\n drop: function(event, ui) {\n if (_isFileChanged) {\n TSCORE.showAlertDialog($.i18n.t('ns.dialogs:operationNotPermittedInEditModeAlert'));\n } else {\n console.log('Tagging file: ' + TSCORE.selectedTag + ' to ' + _openedFilePath);\n TSCORE.TagUtils.addTag([_openedFilePath], [TSCORE.selectedTag]); //$(ui.helper).remove();\n }\n }\n });\n // Init Tag Context Menus\n $fileTags.on('contextmenu click', '.tagButton', function() {\n TSCORE.hideAllDropDownMenus();\n TSCORE.openTagMenu(this, $(this).attr('tag'), $(this).attr('filepath'));\n TSCORE.showContextMenu('#tagMenu', $(this));\n return false;\n });\n }\n\n function initTagSuggestionMenu(filePath) {\n var tags = TSCORE.TagUtils.extractTags(filePath);\n var suggTags = TSCORE.TagUtils.suggestTags(filePath);\n var tsMenu = $('#tagSuggestionsMenu');\n tsMenu.children().remove();\n tsMenu.attr('style', 'overflow-y: auto; max-height: 500px;');\n tsMenu.append($('
  • ', {\n class: 'dropdown-header',\n text: $.i18n.t('ns.common:tagOperations')\n }).append(''));\n tsMenu.append($('
  • ').append($('', {\n title: $.i18n.t('ns.common:addRemoveTagsTooltip'),\n filepath: filePath,\n text: ' ' + $.i18n.t('ns.common:addRemoveTags')\n }).prepend('').click(function() {\n TSCORE.PerspectiveManager.clearSelectedFiles();\n TSCORE.selectedFiles.push(filePath);\n TSCORE.showAddTagsDialog();\n })));\n tsMenu.append($('
  • ', {\n class: 'dropdown-header',\n text: $.i18n.t('ns.common:suggestedTags')\n }));\n // Add tag suggestion based on the last modified date\n if (_openedFileProperties !== undefined && _openedFileProperties.lmdt !== undefined) {\n suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt));\n suggTags.push(TSCORE.TagUtils.formatDateTime4Tag(_openedFileProperties.lmdt, true));\n }\n // Adding context menu entries for creating tags according to the suggested tags\n for (var i = 0; i < suggTags.length; i++) {\n // Ignoring the tags already assigned to a file\n if (tags.indexOf(suggTags[i]) < 0) {\n tsMenu.append($('
  • ', {\n name: suggTags[i]\n }).append($('', {}).append($('